use of com.cloud.network.rules.PortForwardingRuleVO in project cloudstack by apache.
the class ApiResponseHelper method createUsageResponse.
@Override
public UsageRecordResponse createUsageResponse(Usage usageRecord) {
UsageRecordResponse usageRecResponse = new UsageRecordResponse();
Account account = ApiDBUtils.findAccountById(usageRecord.getAccountId());
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
//find the project
Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId());
if (project != null) {
usageRecResponse.setProjectId(project.getUuid());
usageRecResponse.setProjectName(project.getName());
}
} else {
usageRecResponse.setAccountId(account.getUuid());
usageRecResponse.setAccountName(account.getAccountName());
}
Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId());
if (domain != null) {
usageRecResponse.setDomainId(domain.getUuid());
usageRecResponse.setDomainName(domain.getName());
}
if (usageRecord.getZoneId() != null) {
DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId());
if (zone != null) {
usageRecResponse.setZoneId(zone.getUuid());
}
}
usageRecResponse.setDescription(usageRecord.getDescription());
usageRecResponse.setUsage(usageRecord.getUsageDisplay());
usageRecResponse.setUsageType(usageRecord.getUsageType());
if (usageRecord.getVmInstanceId() != null) {
VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId());
if (vm != null) {
usageRecResponse.setVirtualMachineId(vm.getUuid());
}
}
usageRecResponse.setVmName(usageRecord.getVmName());
if (usageRecord.getTemplateId() != null) {
VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId());
if (template != null) {
usageRecResponse.setTemplateId(template.getUuid());
}
}
if (usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM) {
ServiceOfferingVO svcOffering = _entityMgr.findByIdIncludingRemoved(ServiceOfferingVO.class, usageRecord.getOfferingId().toString());
//Service Offering Id
usageRecResponse.setOfferingId(svcOffering.getUuid());
//VM Instance ID
VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
if (vm != null) {
usageRecResponse.setUsageId(vm.getUuid());
}
//Hypervisor Type
usageRecResponse.setType(usageRecord.getType());
//Dynamic compute offerings details
usageRecResponse.setCpuNumber(usageRecord.getCpuCores());
usageRecResponse.setCpuSpeed(usageRecord.getCpuSpeed());
usageRecResponse.setMemory(usageRecord.getMemory());
} else if (usageRecord.getUsageType() == UsageTypes.IP_ADDRESS) {
//isSourceNAT
usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat")) ? true : false);
//isSystem
usageRecResponse.setSystem((usageRecord.getSize() == 1) ? true : false);
//IP Address ID
IPAddressVO ip = _entityMgr.findByIdIncludingRemoved(IPAddressVO.class, usageRecord.getUsageId().toString());
if (ip != null) {
usageRecResponse.setUsageId(ip.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED) {
//Device Type
usageRecResponse.setType(usageRecord.getType());
if (usageRecord.getType().equals("DomainRouter")) {
//Domain Router Id
VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getUsageId().toString());
if (vm != null) {
usageRecResponse.setUsageId(vm.getUuid());
}
} else {
//External Device Host Id
HostVO host = _entityMgr.findByIdIncludingRemoved(HostVO.class, usageRecord.getUsageId().toString());
if (host != null) {
usageRecResponse.setUsageId(host.getUuid());
}
}
//Network ID
if ((usageRecord.getNetworkId() != null) && (usageRecord.getNetworkId() != 0)) {
NetworkVO network = _entityMgr.findByIdIncludingRemoved(NetworkVO.class, usageRecord.getNetworkId().toString());
if (network != null) {
usageRecResponse.setNetworkId(network.getUuid());
}
}
} else if (usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_IO_WRITE || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_READ || usageRecord.getUsageType() == UsageTypes.VM_DISK_BYTES_WRITE) {
//Device Type
usageRecResponse.setType(usageRecord.getType());
//VM Instance Id
VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
if (vm != null) {
usageRecResponse.setVirtualMachineId(vm.getUuid());
}
//Volume ID
VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
if (volume != null) {
usageRecResponse.setUsageId(volume.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.VOLUME) {
//Volume ID
VolumeVO volume = _entityMgr.findByIdIncludingRemoved(VolumeVO.class, usageRecord.getUsageId().toString());
if (volume != null) {
usageRecResponse.setUsageId(volume.getUuid());
}
//Volume Size
usageRecResponse.setSize(usageRecord.getSize());
//Disk Offering Id
if (usageRecord.getOfferingId() != null) {
DiskOfferingVO diskOff = _entityMgr.findByIdIncludingRemoved(DiskOfferingVO.class, usageRecord.getOfferingId().toString());
usageRecResponse.setOfferingId(diskOff.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.TEMPLATE || usageRecord.getUsageType() == UsageTypes.ISO) {
//Template/ISO ID
VMTemplateVO tmpl = _entityMgr.findByIdIncludingRemoved(VMTemplateVO.class, usageRecord.getUsageId().toString());
if (tmpl != null) {
usageRecResponse.setUsageId(tmpl.getUuid());
}
//Template/ISO Size
usageRecResponse.setSize(usageRecord.getSize());
if (usageRecord.getUsageType() == UsageTypes.ISO) {
usageRecResponse.setVirtualSize(usageRecord.getSize());
} else {
usageRecResponse.setVirtualSize(usageRecord.getVirtualSize());
}
} else if (usageRecord.getUsageType() == UsageTypes.SNAPSHOT) {
//Snapshot ID
SnapshotVO snap = _entityMgr.findByIdIncludingRemoved(SnapshotVO.class, usageRecord.getUsageId().toString());
if (snap != null) {
usageRecResponse.setUsageId(snap.getUuid());
}
//Snapshot Size
usageRecResponse.setSize(usageRecord.getSize());
} else if (usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY) {
//Load Balancer Policy ID
LoadBalancerVO lb = _entityMgr.findByIdIncludingRemoved(LoadBalancerVO.class, usageRecord.getUsageId().toString());
if (lb != null) {
usageRecResponse.setUsageId(lb.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE) {
//Port Forwarding Rule ID
PortForwardingRuleVO pf = _entityMgr.findByIdIncludingRemoved(PortForwardingRuleVO.class, usageRecord.getUsageId().toString());
if (pf != null) {
usageRecResponse.setUsageId(pf.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING) {
//Network Offering Id
NetworkOfferingVO netOff = _entityMgr.findByIdIncludingRemoved(NetworkOfferingVO.class, usageRecord.getOfferingId().toString());
usageRecResponse.setOfferingId(netOff.getUuid());
//is Default
usageRecResponse.setDefault((usageRecord.getUsageId() == 1) ? true : false);
} else if (usageRecord.getUsageType() == UsageTypes.VPN_USERS) {
//VPN User ID
VpnUserVO vpnUser = _entityMgr.findByIdIncludingRemoved(VpnUserVO.class, usageRecord.getUsageId().toString());
if (vpnUser != null) {
usageRecResponse.setUsageId(vpnUser.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP) {
//Security Group Id
SecurityGroupVO sg = _entityMgr.findByIdIncludingRemoved(SecurityGroupVO.class, usageRecord.getUsageId().toString());
if (sg != null) {
usageRecResponse.setUsageId(sg.getUuid());
}
} else if (usageRecord.getUsageType() == UsageTypes.VM_SNAPSHOT) {
VMInstanceVO vm = _entityMgr.findByIdIncludingRemoved(VMInstanceVO.class, usageRecord.getVmInstanceId().toString());
if (vm != null) {
usageRecResponse.setVmName(vm.getInstanceName());
usageRecResponse.setUsageId(vm.getUuid());
}
usageRecResponse.setSize(usageRecord.getSize());
if (usageRecord.getOfferingId() != null) {
usageRecResponse.setOfferingId(usageRecord.getOfferingId().toString());
}
}
if (usageRecord.getRawUsage() != null) {
DecimalFormat decimalFormat = new DecimalFormat("###########.######");
usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage()));
}
if (usageRecord.getStartDate() != null) {
usageRecResponse.setStartDate(getDateStringInternal(usageRecord.getStartDate()));
}
if (usageRecord.getEndDate() != null) {
usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate()));
}
return usageRecResponse;
}
use of com.cloud.network.rules.PortForwardingRuleVO in project cloudstack by apache.
the class UsageServiceImpl method getUsageRecords.
@Override
public Pair<List<? extends Usage>, Integer> getUsageRecords(GetUsageRecordsCmd cmd) {
Long accountId = cmd.getAccountId();
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
Account userAccount = null;
Account caller = CallContext.current().getCallingAccount();
Long usageType = cmd.getUsageType();
Long projectId = cmd.getProjectId();
String usageId = cmd.getUsageId();
if (projectId != null) {
if (accountId != null) {
throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
}
Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
accountId = project.getProjectAccountId();
}
//if accountId is not specified, use accountName and domainId
if ((accountId == null) && (accountName != null) && (domainId != null)) {
if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
if (accounts.size() > 0) {
userAccount = accounts.get(0);
}
if (userAccount != null) {
accountId = userAccount.getId();
} else {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
}
} else {
throw new PermissionDeniedException("Invalid Domain Id or Account");
}
}
boolean isAdmin = false;
boolean isDomainAdmin = false;
//If accountId couldn't be found using accountName and domainId, get it from userContext
if (accountId == null) {
accountId = caller.getId();
//If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
if (_accountService.isRootAdmin(caller.getId())) {
isAdmin = true;
} else if (_accountService.isDomainAdmin(caller.getId())) {
isDomainAdmin = true;
}
s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
}
Date startDate = cmd.getStartDate();
Date endDate = cmd.getEndDate();
if (startDate.after(endDate)) {
throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
}
TimeZone usageTZ = getUsageTimezone();
Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ);
Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ);
if (s_logger.isDebugEnabled()) {
s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
}
Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) {
sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
}
if (isDomainAdmin) {
SearchCriteria<DomainVO> sdc = _domainDao.createSearchCriteria();
sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
List<DomainVO> domains = _domainDao.search(sdc, null);
List<Long> domainIds = new ArrayList<Long>();
for (DomainVO domain : domains) domainIds.add(domain.getId());
sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray());
}
if (domainId != null) {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
if (usageType != null) {
sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
}
if (usageId != null) {
if (usageType == null) {
throw new InvalidParameterValueException("Usageid must be specified together with usageType");
}
Long usageDbId = null;
switch(usageType.intValue()) {
case UsageTypes.NETWORK_BYTES_RECEIVED:
case UsageTypes.NETWORK_BYTES_SENT:
case UsageTypes.RUNNING_VM:
case UsageTypes.ALLOCATED_VM:
case UsageTypes.VM_SNAPSHOT:
VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId);
if (vm != null) {
usageDbId = vm.getId();
}
if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) {
HostVO host = _hostDao.findByUuidIncludingRemoved(usageId);
if (host != null) {
usageDbId = host.getId();
}
}
break;
case UsageTypes.SNAPSHOT:
SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId);
if (snap != null) {
usageDbId = snap.getId();
}
break;
case UsageTypes.TEMPLATE:
case UsageTypes.ISO:
VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId);
if (tmpl != null) {
usageDbId = tmpl.getId();
}
break;
case UsageTypes.LOAD_BALANCER_POLICY:
LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId);
if (lb != null) {
usageDbId = lb.getId();
}
break;
case UsageTypes.PORT_FORWARDING_RULE:
PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId);
if (pf != null) {
usageDbId = pf.getId();
}
break;
case UsageTypes.VOLUME:
case UsageTypes.VM_DISK_IO_READ:
case UsageTypes.VM_DISK_IO_WRITE:
case UsageTypes.VM_DISK_BYTES_READ:
case UsageTypes.VM_DISK_BYTES_WRITE:
VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId);
if (volume != null) {
usageDbId = volume.getId();
}
break;
case UsageTypes.VPN_USERS:
VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId);
if (vpnUser != null) {
usageDbId = vpnUser.getId();
}
break;
case UsageTypes.SECURITY_GROUP:
SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId);
if (sg != null) {
usageDbId = sg.getId();
}
break;
case UsageTypes.IP_ADDRESS:
IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId);
if (ip != null) {
usageDbId = ip.getId();
}
break;
default:
break;
}
if (usageDbId != null) {
sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId);
} else {
// return an empty list if usageId was not found
return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
}
}
if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
} else {
// return an empty list if we fail to validate the dates
return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
}
Pair<List<UsageVO>, Integer> usageRecords = null;
TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
try {
usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter);
} finally {
txn.close();
// switch back to VMOPS_DB
TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
swap.close();
}
return new Pair<List<? extends Usage>, Integer>(usageRecords.first(), usageRecords.second());
}
use of com.cloud.network.rules.PortForwardingRuleVO in project cloudstack by apache.
the class NetworkOrchestrator method shutdownNetworkResources.
private boolean shutdownNetworkResources(final long networkId, final Account caller, final long callerUserId) {
// This method cleans up network rules on the backend w/o touching them in the DB
boolean success = true;
final Network network = _networksDao.findById(networkId);
// Mark all PF rules as revoked and apply them on the backend (not in the DB)
final List<PortForwardingRuleVO> pfRules = _portForwardingRulesDao.listByNetwork(networkId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
for (final PortForwardingRuleVO pfRule : pfRules) {
s_logger.trace("Marking pf rule " + pfRule + " with Revoke state");
pfRule.setState(FirewallRule.State.Revoke);
}
try {
if (!_firewallMgr.applyRules(pfRules, true, false)) {
s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
// Mark all static rules as revoked and apply them on the backend (not in the DB)
final List<FirewallRuleVO> firewallStaticNatRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.StaticNat);
final List<StaticNatRule> staticNatRules = new ArrayList<StaticNatRule>();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + firewallStaticNatRules.size() + " static nat rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
for (final FirewallRuleVO firewallStaticNatRule : firewallStaticNatRules) {
s_logger.trace("Marking static nat rule " + firewallStaticNatRule + " with Revoke state");
final IpAddress ip = _ipAddressDao.findById(firewallStaticNatRule.getSourceIpAddressId());
final FirewallRuleVO ruleVO = _firewallDao.findById(firewallStaticNatRule.getId());
if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) {
throw new InvalidParameterValueException("Source ip address of the rule id=" + firewallStaticNatRule.getId() + " is not static nat enabled");
}
//String dstIp = _networkModel.getIpInNetwork(ip.getAssociatedWithVmId(), firewallStaticNatRule.getNetworkId());
ruleVO.setState(FirewallRule.State.Revoke);
staticNatRules.add(new StaticNatRuleImpl(ruleVO, ip.getVmIp()));
}
try {
if (!_firewallMgr.applyRules(staticNatRules, true, false)) {
s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
try {
if (!_lbMgr.revokeLoadBalancersForNetwork(networkId, Scheme.Public)) {
s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
try {
if (!_lbMgr.revokeLoadBalancersForNetwork(networkId, Scheme.Internal)) {
s_logger.warn("Failed to cleanup internal lb rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
// revoke all firewall rules for the network w/o applying them on the DB
final List<FirewallRuleVO> firewallRules = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Ingress);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + firewallRules.size() + " firewall ingress rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
for (final FirewallRuleVO firewallRule : firewallRules) {
s_logger.trace("Marking firewall ingress rule " + firewallRule + " with Revoke state");
firewallRule.setState(FirewallRule.State.Revoke);
}
try {
if (!_firewallMgr.applyRules(firewallRules, true, false)) {
s_logger.warn("Failed to cleanup firewall ingress rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup firewall ingress rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
final List<FirewallRuleVO> firewallEgressRules = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Egress);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + firewallEgressRules.size() + " firewall egress rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
try {
// delete default egress rule
final DataCenter zone = _dcDao.findById(network.getDataCenterId());
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && (network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) {
// add default egress rule to accept the traffic
_firewallMgr.applyDefaultEgressFirewallRule(network.getId(), _networkModel.getNetworkEgressDefaultPolicy(networkId), false);
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup firewall default egress rule as a part of shutdownNetworkRules due to ", ex);
success = false;
}
for (final FirewallRuleVO firewallRule : firewallEgressRules) {
s_logger.trace("Marking firewall egress rule " + firewallRule + " with Revoke state");
firewallRule.setState(FirewallRule.State.Revoke);
}
try {
if (!_firewallMgr.applyRules(firewallEgressRules, true, false)) {
s_logger.warn("Failed to cleanup firewall egress rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup firewall egress rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
if (network.getVpcId() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing Network ACL Items for network id=" + networkId + " as a part of shutdownNetworkRules");
}
try {
//revoke all Network ACLs for the network w/o applying them in the DB
if (!_networkACLMgr.revokeACLItemsForNetwork(networkId)) {
s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex);
success = false;
}
}
//release all static nats for the network
if (!_rulesMgr.applyStaticNatForNetwork(networkId, false, caller, true)) {
s_logger.warn("Failed to disable static nats as part of shutdownNetworkRules for network id " + networkId);
success = false;
}
// Get all ip addresses, mark as releasing and release them on the backend
final List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(networkId, null);
final List<PublicIp> publicIpsToRelease = new ArrayList<PublicIp>();
if (userIps != null && !userIps.isEmpty()) {
for (final IPAddressVO userIp : userIps) {
userIp.setState(IpAddress.State.Releasing);
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
publicIpsToRelease.add(publicIp);
}
}
try {
if (!_ipAddrMgr.applyIpAssociations(network, true, true, publicIpsToRelease)) {
s_logger.warn("Unable to apply ip address associations for " + network + " as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException e) {
throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e);
}
return success;
}
use of com.cloud.network.rules.PortForwardingRuleVO in project cloudstack by apache.
the class ExternalGuestNetworkGuru method implement.
@Override
public Network implement(Network config, NetworkOffering offering, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapacityException {
assert (config.getState() == State.Implementing) : "Why are we implementing " + config;
if (_networkModel.areServicesSupportedInNetwork(config.getId(), Network.Service.Connectivity)) {
return null;
}
if (!_networkModel.networkIsConfiguredForExternalNetworking(config.getDataCenterId(), config.getId())) {
return super.implement(config, offering, dest, context);
}
DataCenter zone = dest.getDataCenter();
NetworkVO implemented = new NetworkVO(config.getTrafficType(), config.getMode(), config.getBroadcastDomainType(), config.getNetworkOfferingId(), State.Allocated, config.getDataCenterId(), config.getPhysicalNetworkId(), offering.getRedundantRouter());
// Get a vlan tag
int vlanTag;
if (config.getBroadcastUri() == null) {
String vnet = _dcDao.allocateVnet(zone.getId(), config.getPhysicalNetworkId(), config.getAccountId(), context.getReservationId(), UseSystemGuestVlans.valueIn(config.getAccountId()));
try {
// when supporting more types of networks this need to become
// int vlantag = Integer.parseInt(BroadcastDomainType.getValue(vnet));
vlanTag = Integer.parseInt(vnet);
} catch (NumberFormatException e) {
throw new CloudRuntimeException("Obtained an invalid guest vlan tag. Exception: " + e.getMessage());
}
implemented.setBroadcastUri(BroadcastDomainType.Vlan.toUri(vlanTag));
ActionEventUtils.onCompletedActionEvent(CallContext.current().getCallingUserId(), config.getAccountId(), EventVO.LEVEL_INFO, EventTypes.EVENT_ZONE_VLAN_ASSIGN, "Assigned Zone Vlan: " + vnet + " Network Id: " + config.getId(), 0);
} else {
vlanTag = Integer.parseInt(BroadcastDomainType.getValue(config.getBroadcastUri()));
implemented.setBroadcastUri(config.getBroadcastUri());
}
// Determine the new gateway and CIDR
String[] oldCidr = config.getCidr().split("/");
String oldCidrAddress = oldCidr[0];
int cidrSize = Integer.parseInt(oldCidr[1]);
long newCidrAddress = (NetUtils.ip2Long(oldCidrAddress));
// if the implementing network is for vpc, no need to generate newcidr, use the cidr that came from super cidr
if (config.getVpcId() != null) {
implemented.setGateway(config.getGateway());
implemented.setCidr(config.getCidr());
implemented.setState(State.Implemented);
} else {
// Determine the offset from the lowest vlan tag
int offset = getVlanOffset(config.getPhysicalNetworkId(), vlanTag);
cidrSize = getGloballyConfiguredCidrSize();
// If the offset has more bits than there is room for, return null
long bitsInOffset = 32 - Integer.numberOfLeadingZeros(offset);
if (bitsInOffset > (cidrSize - 8)) {
throw new CloudRuntimeException("The offset " + offset + " needs " + bitsInOffset + " bits, but only have " + (cidrSize - 8) + " bits to work with.");
}
newCidrAddress = (NetUtils.ip2Long(oldCidrAddress) & 0xff000000) | (offset << (32 - cidrSize));
implemented.setGateway(NetUtils.long2Ip(newCidrAddress + 1));
implemented.setCidr(NetUtils.long2Ip(newCidrAddress) + "/" + cidrSize);
implemented.setState(State.Implemented);
}
// Mask the Ipv4 address of all nics that use this network with the new guest VLAN offset
List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(config.getId());
for (NicVO nic : nicsInNetwork) {
if (nic.getIPv4Address() != null) {
long ipMask = getIpMask(nic.getIPv4Address(), cidrSize);
nic.setIPv4Address(NetUtils.long2Ip(newCidrAddress | ipMask));
_nicDao.persist(nic);
}
}
// Mask the destination address of all port forwarding rules in this network with the new guest VLAN offset
List<PortForwardingRuleVO> pfRulesInNetwork = _pfRulesDao.listByNetwork(config.getId());
for (PortForwardingRuleVO pfRule : pfRulesInNetwork) {
if (pfRule.getDestinationIpAddress() != null) {
long ipMask = getIpMask(pfRule.getDestinationIpAddress().addr(), cidrSize);
String maskedDestinationIpAddress = NetUtils.long2Ip(newCidrAddress | ipMask);
pfRule.setDestinationIpAddress(new Ip(maskedDestinationIpAddress));
_pfRulesDao.update(pfRule.getId(), pfRule);
}
}
// Mask the destination address of all static nat rules in this network with the new guest VLAN offset
// Here the private ip of the nic get updated. When secondary ip are present the gc will not triggered
List<IPAddressVO> ipAddrsOfNw = _ipAddressDao.listStaticNatPublicIps(config.getId());
for (IPAddressVO ip : ipAddrsOfNw) {
if (ip.getVmIp() != null) {
long ipMask = getIpMask(ip.getVmIp(), cidrSize);
String maskedVmIp = NetUtils.long2Ip(newCidrAddress | ipMask);
ip.setVmIp(maskedVmIp);
_ipAddressDao.update(ip.getId(), ip);
}
}
//Egress rules cidr is subset of guest nework cidr, we need to change
List<FirewallRuleVO> fwEgressRules = _fwRulesDao.listByNetworkPurposeTrafficType(config.getId(), FirewallRule.Purpose.Firewall, FirewallRule.TrafficType.Egress);
for (FirewallRuleVO rule : fwEgressRules) {
//get the cidr list for this rule
List<FirewallRulesCidrsVO> fwRuleCidrsVo = _fwRulesCidrDao.listByFirewallRuleId(rule.getId());
for (FirewallRulesCidrsVO ruleCidrvo : fwRuleCidrsVo) {
String cidr = ruleCidrvo.getCidr();
String cidrAddr = cidr.split("/")[0];
String size = cidr.split("/")[1];
long ipMask = getIpMask(cidrAddr, cidrSize);
String newIp = NetUtils.long2Ip(newCidrAddress | ipMask);
String updatedCidr = newIp + "/" + size;
ruleCidrvo.setSourceCidrList(updatedCidr);
_fwRulesCidrDao.update(ruleCidrvo.getId(), ruleCidrvo);
}
}
return implemented;
}
use of com.cloud.network.rules.PortForwardingRuleVO in project cloudstack by apache.
the class FirewallManagerImpl method revokeFirewallRulesForVm.
@Override
@ActionEvent(eventType = EventTypes.EVENT_FIREWALL_CLOSE, eventDescription = "revoking firewall rule", async = true)
public boolean revokeFirewallRulesForVm(long vmId) {
boolean success = true;
UserVmVO vm = _vmDao.findByIdIncludingRemoved(vmId);
if (vm == null) {
return false;
}
List<PortForwardingRuleVO> pfRules = _pfRulesDao.listByVm(vmId);
List<FirewallRuleVO> staticNatRules = _firewallDao.listStaticNatByVmId(vm.getId());
List<FirewallRuleVO> firewallRules = new ArrayList<FirewallRuleVO>();
// Make a list of firewall rules to reprogram
for (PortForwardingRuleVO pfRule : pfRules) {
FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(pfRule.getId());
if (relatedRule != null) {
firewallRules.add(relatedRule);
}
}
for (FirewallRuleVO staticNatRule : staticNatRules) {
FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(staticNatRule.getId());
if (relatedRule != null) {
firewallRules.add(relatedRule);
}
}
Set<Long> ipsToReprogram = new HashSet<Long>();
if (firewallRules.isEmpty()) {
s_logger.debug("No firewall rules are found for vm id=" + vmId);
return true;
} else {
s_logger.debug("Found " + firewallRules.size() + " to cleanup for vm id=" + vmId);
}
for (FirewallRuleVO rule : firewallRules) {
// Mark firewall rules as Revoked, but don't revoke it yet (apply=false)
revokeFirewallRule(rule.getId(), false, _accountMgr.getSystemAccount(), Account.ACCOUNT_ID_SYSTEM);
ipsToReprogram.add(rule.getSourceIpAddressId());
}
// apply rules for all ip addresses
for (Long ipId : ipsToReprogram) {
s_logger.debug("Applying firewall rules for ip address id=" + ipId + " as a part of vm expunge");
try {
success = success && applyIngressFirewallRules(ipId, _accountMgr.getSystemAccount());
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to apply port forwarding rules for ip id=" + ipId);
success = false;
}
}
return success;
}
Aggregations