Search in sources :

Example 81 with Network

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

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();
    final 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);
    final Network network = _networkModel.getNetwork(networkId);
    final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
    if (off.getElasticIp()) {
        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(final 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());
                final StaticNatRule staticNatRule = new StaticNatRuleImpl(newRule, dstIp);
                return staticNatRule;
            } catch (final 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.legacymodel.user.Account) NetworkOffering(com.cloud.offering.NetworkOffering) TransactionStatus(com.cloud.utils.db.TransactionStatus) StaticNatRule(com.cloud.legacymodel.network.StaticNatRule) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 82 with Network

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

the class RulesManagerImpl method createPortForwardingRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NET_RULE_ADD, eventDescription = "creating forwarding rule", create = true)
public PortForwardingRule createPortForwardingRule(final PortForwardingRule rule, final Long vmId, final Ip vmIp, final boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final Long ipAddrId = rule.getSourceIpAddressId();
    IPAddressVO ipAddress = _ipAddressDao.findById(ipAddrId);
    // Validate ip address
    if (ipAddress == null) {
        throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " doesn't exist in the system");
    } else if (ipAddress.isOneToOneNat()) {
        throw new InvalidParameterValueException("Unable to create port forwarding rule; ip id=" + ipAddrId + " has static nat enabled");
    }
    final Long networkId = rule.getNetworkId();
    final Network network = _networkModel.getNetwork(networkId);
    // associate ip address to network (if needed)
    boolean performedIpAssoc = false;
    final Nic guestNic;
    if (ipAddress.getAssociatedWithNetworkId() == null) {
        final boolean assignToVpcNtwk = network.getVpcId() != null && ipAddress.getVpcId() != null && ipAddress.getVpcId().longValue() == network.getVpcId();
        if (assignToVpcNtwk) {
            _networkModel.checkIpForService(ipAddress, Service.PortForwarding, networkId);
            s_logger.debug("The ip is not associated with the VPC network id=" + networkId + ", so assigning");
            try {
                ipAddress = _ipAddrMgr.associateIPToGuestNetwork(ipAddrId, networkId, false);
                performedIpAssoc = true;
            } catch (final Exception ex) {
                throw new CloudRuntimeException("Failed to associate ip to VPC network as " + "a part of port forwarding rule creation");
            }
        }
    } else {
        _networkModel.checkIpForService(ipAddress, Service.PortForwarding, null);
    }
    if (ipAddress.getAssociatedWithNetworkId() == null) {
        throw new InvalidParameterValueException("Ip address " + ipAddress + " is not assigned to the network " + network);
    }
    try {
        _firewallMgr.validateFirewallRule(caller, ipAddress, rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getProtocol(), Purpose.PortForwarding, FirewallRuleType.User, networkId, rule.getTrafficType());
        final Long accountId = ipAddress.getAllocatedToAccountId();
        final Long domainId = ipAddress.getAllocatedInDomainId();
        // start port can't be bigger than end port
        if (rule.getDestinationPortStart() > rule.getDestinationPortEnd()) {
            throw new InvalidParameterValueException("Start port can't be bigger than end port");
        }
        // check that the port ranges are of equal size
        if ((rule.getDestinationPortEnd() - rule.getDestinationPortStart()) != (rule.getSourcePortEnd() - rule.getSourcePortStart())) {
            throw new InvalidParameterValueException("Source port and destination port ranges should be of equal sizes.");
        }
        // validate user VM exists
        final UserVm vm = _vmDao.findById(vmId);
        if (vm == null) {
            throw new InvalidParameterValueException("Unable to create port forwarding rule on address " + ipAddress + ", invalid virtual machine id specified (" + vmId + ").");
        } else if (vm.getState() == VirtualMachine.State.Destroyed || vm.getState() == VirtualMachine.State.Expunging) {
            throw new InvalidParameterValueException("Invalid user vm: " + vm.getId());
        }
        // Verify that vm has nic in the network
        Ip dstIp = rule.getDestinationIpAddress();
        guestNic = _networkModel.getNicInNetwork(vmId, networkId);
        if (guestNic == null || guestNic.getIPv4Address() == null) {
            throw new InvalidParameterValueException("Vm doesn't belong to network associated with ipAddress");
        } else {
            dstIp = new Ip(NetUtils.ip2Long(guestNic.getIPv4Address()));
        }
        if (vmIp != null) {
            // vm ip is passed so it can be primary or secondary ip addreess.
            if (!dstIp.equals(vmIp)) {
                // the vm ip is secondary ip to the nic.
                // is vmIp is secondary ip or not
                final NicSecondaryIp secondaryIp = _nicSecondaryDao.findByIp4AddressAndNicId(vmIp.toString(), guestNic.getId());
                if (secondaryIp == null) {
                    throw new InvalidParameterValueException("IP Address is not in the VM nic's network ");
                }
                dstIp = vmIp;
            }
        }
        // if start port and end port are passed in, and they are not equal to each other, perform the validation
        boolean validatePortRange = false;
        if (rule.getSourcePortStart().intValue() != rule.getSourcePortEnd().intValue() || rule.getDestinationPortStart() != rule.getDestinationPortEnd()) {
            validatePortRange = true;
        }
        if (validatePortRange) {
            // source start port and source dest port should be the same. The same applies to dest ports
            if (rule.getSourcePortStart().intValue() != rule.getDestinationPortStart()) {
                throw new InvalidParameterValueException("Private port start should be equal to public port start");
            }
            if (rule.getSourcePortEnd().intValue() != rule.getDestinationPortEnd()) {
                throw new InvalidParameterValueException("Private port end should be equal to public port end");
            }
        }
        final Ip dstIpFinal = dstIp;
        final IPAddressVO ipAddressFinal = ipAddress;
        return Transaction.execute(new TransactionCallbackWithException<PortForwardingRuleVO, NetworkRuleConflictException>() {

            @Override
            public PortForwardingRuleVO doInTransaction(final TransactionStatus status) throws NetworkRuleConflictException {
                PortForwardingRuleVO newRule = new PortForwardingRuleVO(rule.getXid(), rule.getSourceIpAddressId(), rule.getSourcePortStart(), rule.getSourcePortEnd(), dstIpFinal, rule.getDestinationPortStart(), rule.getDestinationPortEnd(), rule.getProtocol().toLowerCase(), networkId, accountId, domainId, vmId);
                if (forDisplay != null) {
                    newRule.setDisplay(forDisplay);
                }
                newRule = _portForwardingDao.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());
                    return newRule;
                } catch (final 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);
                        removePFRule(newRule);
                    }
                    if (e instanceof NetworkRuleConflictException) {
                        throw (NetworkRuleConflictException) e;
                    }
                    throw new CloudRuntimeException("Unable to add rule for the ip id=" + ipAddrId, e);
                }
            }
        });
    } finally {
        // release ip address if ipassoc was perfored
        if (performedIpAssoc) {
            // if the rule is the last one for the ip address assigned to VPC, unassign it from the network
            final IpAddress ip = _ipAddressDao.findById(ipAddress.getId());
            _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), networkId);
        }
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) Ip(com.cloud.legacymodel.network.Ip) NicSecondaryIp(com.cloud.vm.NicSecondaryIp) Nic(com.cloud.legacymodel.network.Nic) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(com.cloud.context.CallContext) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.legacymodel.exceptions.NetworkRuleConflictException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) Network(com.cloud.legacymodel.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) IpAddress(com.cloud.network.IpAddress) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 83 with Network

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

the class NicPlugInOutRules method accept.

@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
    _router = router;
    final Pair<Map<String, PublicIpAddress>, Map<String, PublicIpAddress>> nicsToChange = getNicsToChangeOnRouter(visitor);
    final Map<String, PublicIpAddress> nicsToPlug = nicsToChange.first();
    final Map<String, PublicIpAddress> nicsToUnplug = nicsToChange.second();
    final NetworkModel networkModel = visitor.getVirtualNetworkApplianceFactory().getNetworkModel();
    final VirtualMachineManager itMgr = visitor.getVirtualNetworkApplianceFactory().getItMgr();
    // 1) Unplug the nics
    for (final Entry<String, PublicIpAddress> entry : nicsToUnplug.entrySet()) {
        Network publicNtwk = null;
        try {
            publicNtwk = networkModel.getNetwork(entry.getValue().getNetworkId());
            final URI broadcastUri = BroadcastDomainType.Vlan.toUri(entry.getKey());
            itMgr.removeVmFromNetwork(_router, publicNtwk, broadcastUri);
        } catch (final ConcurrentOperationException e) {
            s_logger.warn("Failed to remove router " + _router + " from vlan " + entry.getKey() + " in public network " + publicNtwk + " due to ", e);
            return false;
        }
    }
    _netUsageCommands = new Commands(Command.OnError.Continue);
    final VpcDao vpcDao = visitor.getVirtualNetworkApplianceFactory().getVpcDao();
    final VpcVO vpc = vpcDao.findById(_router.getVpcId());
    // 2) Plug the nics
    for (final String vlanTag : nicsToPlug.keySet()) {
        final PublicIpAddress ip = nicsToPlug.get(vlanTag);
        // have to plug the nic(s)
        final NicProfile defaultNic = new NicProfile();
        if (ip.isSourceNat()) {
            defaultNic.setDefaultNic(true);
        }
        defaultNic.setIPv4Address(ip.getAddress().addr());
        defaultNic.setIPv4Gateway(ip.getGateway());
        defaultNic.setIPv4Netmask(ip.getNetmask());
        defaultNic.setMacAddress(ip.getMacAddress());
        defaultNic.setBroadcastType(BroadcastDomainType.Vlan);
        defaultNic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(ip.getVlanTag()));
        defaultNic.setIsolationUri(IsolationType.Vlan.toUri(ip.getVlanTag()));
        NicProfile publicNic = null;
        Network publicNtwk = null;
        try {
            publicNtwk = networkModel.getNetwork(ip.getNetworkId());
            publicNic = itMgr.addVmToNetwork(_router, publicNtwk, defaultNic);
        } catch (final ConcurrentOperationException e) {
            s_logger.warn("Failed to add router " + _router + " to vlan " + vlanTag + " in public network " + publicNtwk + " due to ", e);
        } catch (final InsufficientCapacityException e) {
            s_logger.warn("Failed to add router " + _router + " to vlan " + vlanTag + " in public network " + publicNtwk + " due to ", e);
        } finally {
            if (publicNic == null) {
                s_logger.warn("Failed to add router " + _router + " to vlan " + vlanTag + " in public network " + publicNtwk);
                return false;
            }
        }
        // Create network usage commands. Send commands to router after
        // IPAssoc
        final NetworkUsageCommand netUsageCmd = new NetworkUsageCommand(_router.getPrivateIpAddress(), _router.getInstanceName(), true, defaultNic.getIPv4Address(), vpc.getCidr());
        _netUsageCommands.addCommand(netUsageCmd);
        final UserStatisticsDao userStatsDao = visitor.getVirtualNetworkApplianceFactory().getUserStatsDao();
        UserStatisticsVO stats = userStatsDao.findBy(_router.getAccountId(), _router.getDataCenterId(), publicNtwk.getId(), publicNic.getIPv4Address(), _router.getId(), _router.getType().toString());
        if (stats == null) {
            stats = new UserStatisticsVO(_router.getAccountId(), _router.getDataCenterId(), publicNic.getIPv4Address(), _router.getId(), _router.getType().toString(), publicNtwk.getId());
            userStatsDao.persist(stats);
        }
    }
    // VpcIpAssociation is done.
    return true;
}
Also used : NetworkUsageCommand(com.cloud.legacymodel.communication.command.NetworkUsageCommand) NicProfile(com.cloud.vm.NicProfile) URI(java.net.URI) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) UserStatisticsDao(com.cloud.user.dao.UserStatisticsDao) PublicIpAddress(com.cloud.network.PublicIpAddress) VpcDao(com.cloud.network.vpc.dao.VpcDao) VpcVO(com.cloud.network.vpc.VpcVO) Network(com.cloud.legacymodel.network.Network) Commands(com.cloud.agent.manager.Commands) NetworkModel(com.cloud.network.NetworkModel) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) HashMap(java.util.HashMap) Map(java.util.Map) UserStatisticsVO(com.cloud.user.UserStatisticsVO)

Example 84 with Network

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

the class ListNetworksCmd method execute.

@Override
public void execute() {
    final Pair<List<? extends Network>, Integer> networks = _networkService.searchForNetworks(this);
    final ListResponse<NetworkResponse> response = new ListResponse<>();
    final List<NetworkResponse> networkResponses = new ArrayList<>();
    for (final Network network : networks.first()) {
        final NetworkResponse networkResponse = _responseGenerator.createNetworkResponse(ResponseView.Restricted, network);
        networkResponses.add(networkResponse);
    }
    response.setResponses(networkResponses, networks.second());
    response.setResponseName(getCommandName());
    setResponseObject(response);
}
Also used : ListResponse(com.cloud.api.response.ListResponse) Network(com.cloud.legacymodel.network.Network) NetworkResponse(com.cloud.api.response.NetworkResponse) PhysicalNetworkResponse(com.cloud.api.response.PhysicalNetworkResponse) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 85 with Network

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

the class UpdateNetworkCmd method execute.

// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
@Override
public void execute() throws InsufficientCapacityException, ConcurrentOperationException {
    final User callerUser = _accountService.getActiveUser(CallContext.current().getCallingUserId());
    final Account callerAccount = _accountService.getActiveAccountById(callerUser.getAccountId());
    final Network network = _networkService.getNetwork(id);
    if (network == null) {
        throw new InvalidParameterValueException("Couldn't find network by ID");
    }
    final Network result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr(), getGuestVmCidr(), getDisplayNetwork(), getCustomId(), getDns1(), getDns2(), getIpExclusionList(), getDhcpTftpServer(), getDhcpBootfileName());
    if (result != null) {
        final NetworkResponse response = _responseGenerator.createNetworkResponse(ResponseView.Restricted, result);
        response.setResponseName(getCommandName());
        setResponseObject(response);
    } else {
        throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update network");
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) ServerApiException(com.cloud.api.ServerApiException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Network(com.cloud.legacymodel.network.Network) NetworkResponse(com.cloud.api.response.NetworkResponse)

Aggregations

Network (com.cloud.legacymodel.network.Network)160 ArrayList (java.util.ArrayList)57 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)56 Account (com.cloud.legacymodel.user.Account)46 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)42 NetworkOffering (com.cloud.offering.NetworkOffering)36 PhysicalNetwork (com.cloud.network.PhysicalNetwork)34 IPAddressVO (com.cloud.network.dao.IPAddressVO)32 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)30 NetworkVO (com.cloud.network.dao.NetworkVO)28 List (java.util.List)28 Zone (com.cloud.db.model.Zone)27 DB (com.cloud.utils.db.DB)27 NicProfile (com.cloud.vm.NicProfile)26 Nic (com.cloud.legacymodel.network.Nic)21 DataCenter (com.cloud.legacymodel.dc.DataCenter)20 ConcurrentOperationException (com.cloud.legacymodel.exceptions.ConcurrentOperationException)20 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)19 DomainRouterVO (com.cloud.vm.DomainRouterVO)18 ActionEvent (com.cloud.event.ActionEvent)17