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);
}
}
});
}
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);
}
}
}
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;
}
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);
}
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");
}
}
Aggregations