use of com.cloud.network.IpAddress in project cloudstack by apache.
the class AccountManagerImpl method cleanupAccount.
protected boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId();
boolean accountCleanupNeeded = false;
try {
// cleanup the users from the account
List<UserVO> users = _userDao.listByAccount(accountId);
for (UserVO user : users) {
if (!_userDao.remove(user.getId())) {
s_logger.error("Unable to delete user: " + user + " as a part of account " + account + " cleanup");
accountCleanupNeeded = true;
}
}
// delete global load balancer rules for the account.
List<org.apache.cloudstack.region.gslb.GlobalLoadBalancerRuleVO> gslbRules = _gslbRuleDao.listByAccount(accountId);
if (gslbRules != null && !gslbRules.isEmpty()) {
_gslbService.revokeAllGslbRulesForAccount(caller, accountId);
}
// delete the account from project accounts
_projectAccountDao.removeAccountFromProjects(accountId);
if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
// delete the account from group
_messageBus.publish(_name, MESSAGE_REMOVE_ACCOUNT_EVENT, PublishScope.LOCAL, accountId);
}
// delete all vm groups belonging to accont
List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (InstanceGroupVO group : groups) {
if (!_vmMgr.deleteVmGroup(group.getId())) {
s_logger.error("Unable to delete group: " + group.getId());
accountCleanupNeeded = true;
}
}
// Delete the snapshots dir for the account. Have to do this before destroying the VMs.
boolean success = _snapMgr.deleteSnapshotDirsForAccount(accountId);
if (success) {
s_logger.debug("Successfully deleted snapshots directories for all volumes under account " + accountId + " across all zones");
}
// clean up templates
List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(accountId);
boolean allTemplatesDeleted = true;
for (VMTemplateVO template : userTemplates) {
if (template.getRemoved() == null) {
try {
allTemplatesDeleted = _tmpltMgr.delete(callerUserId, template.getId(), null);
} catch (Exception e) {
s_logger.warn("Failed to delete template while removing account: " + template.getName() + " due to: ", e);
allTemplatesDeleted = false;
}
}
}
if (!allTemplatesDeleted) {
s_logger.warn("Failed to delete templates while removing account id=" + accountId);
accountCleanupNeeded = true;
}
// Destroy VM Snapshots
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(Long.valueOf(accountId));
for (VMSnapshot vmSnapshot : vmSnapshots) {
try {
_vmSnapshotMgr.deleteVMSnapshot(vmSnapshot.getId());
} catch (Exception e) {
s_logger.debug("Failed to cleanup vm snapshot " + vmSnapshot.getId() + " due to " + e.toString());
}
}
// Destroy the account's VMs
List<UserVmVO> vms = _userVmDao.listByAccountId(accountId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Expunging # of vms (accountId=" + accountId + "): " + vms.size());
}
for (UserVmVO vm : vms) {
if (vm.getState() != VirtualMachine.State.Destroyed && vm.getState() != VirtualMachine.State.Expunging) {
try {
_vmMgr.destroyVm(vm.getId(), false);
} catch (Exception e) {
e.printStackTrace();
s_logger.warn("Failed destroying instance " + vm.getUuid() + " as part of account deletion.");
}
}
// should pass in order to perform further cleanup
if (!_vmMgr.expunge(vm, callerUserId, caller)) {
s_logger.error("Unable to expunge vm: " + vm.getId());
accountCleanupNeeded = true;
}
}
// Mark the account's volumes as destroyed
List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
for (VolumeVO volume : volumes) {
if (!volume.getState().equals(Volume.State.Destroy)) {
try {
volumeService.deleteVolume(volume.getId(), caller);
} catch (Exception ex) {
s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true;
}
}
}
// delete remote access vpns and associated users
List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
for (VpnUserVO vpnUser : vpnUsers) {
_remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller);
}
try {
for (RemoteAccessVpnVO vpn : remoteAccessVpns) {
_remoteAccessVpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller, false);
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex);
accountCleanupNeeded = true;
}
// Cleanup security groups
int numRemoved = _securityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId);
// Cleanup affinity groups
int numAGRemoved = _affinityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numAGRemoved + " affinity groups for account " + accountId);
// Delete all the networks
boolean networksDeleted = true;
s_logger.debug("Deleting networks for account " + account.getId());
List<NetworkVO> networks = _networkDao.listByOwner(accountId);
if (networks != null) {
for (NetworkVO network : networks) {
ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller);
if (!_networkMgr.destroyNetwork(network.getId(), context, false)) {
s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
networksDeleted = false;
} else {
s_logger.debug("Network " + network.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
}
}
}
// Delete all VPCs
boolean vpcsDeleted = true;
s_logger.debug("Deleting vpcs for account " + account.getId());
List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(account.getId());
for (Vpc vpc : vpcs) {
if (!_vpcMgr.destroyVpc(vpc, caller, callerUserId)) {
s_logger.warn("Unable to destroy VPC " + vpc + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
vpcsDeleted = false;
} else {
s_logger.debug("VPC " + vpc.getId() + " successfully deleted as a part of account id=" + accountId + " cleanup.");
}
}
if (networksDeleted && vpcsDeleted) {
// release ip addresses belonging to the account
List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (IpAddress ip : ipsToRelease) {
s_logger.debug("Releasing ip " + ip + " as a part of account id=" + accountId + " cleanup");
if (!_ipAddrMgr.disassociatePublicIpAddress(ip.getId(), callerUserId, caller)) {
s_logger.warn("Failed to release ip address " + ip + " as a part of account id=" + accountId + " clenaup");
accountCleanupNeeded = true;
}
}
}
// Delete Site 2 Site VPN customer gateway
s_logger.debug("Deleting site-to-site VPN customer gateways for account " + accountId);
if (!_vpnMgr.deleteCustomerGatewayByAccount(accountId)) {
s_logger.warn("Fail to delete site-to-site VPN customer gateways for account " + accountId);
}
// Delete autoscale resources if any
try {
_autoscaleMgr.cleanUpAutoScaleResources(accountId);
} catch (CloudRuntimeException ex) {
s_logger.warn("Failed to cleanup AutoScale resources as a part of account id=" + accountId + " cleanup due to exception:", ex);
accountCleanupNeeded = true;
}
// up successfully
if (networksDeleted) {
if (!_configMgr.releaseAccountSpecificVirtualRanges(accountId)) {
accountCleanupNeeded = true;
} else {
s_logger.debug("Account specific Virtual IP ranges " + " are successfully released as a part of account id=" + accountId + " cleanup.");
}
}
// release account specific guest vlans
List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(accountId);
for (AccountGuestVlanMapVO map : maps) {
_dataCenterVnetDao.releaseDedicatedGuestVlans(map.getId());
}
int vlansReleased = _accountGuestVlanMapDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Released " + vlansReleased + " dedicated guest vlan ranges from account " + accountId);
// release account specific acquired portable IP's. Since all the portable IP's must have been already
// disassociated with VPC/guest network (due to deletion), so just mark portable IP as free.
List<? extends IpAddress> ipsToRelease = _ipAddressDao.listByAccount(accountId);
for (IpAddress ip : ipsToRelease) {
if (ip.isPortable()) {
s_logger.debug("Releasing portable ip " + ip + " as a part of account id=" + accountId + " cleanup");
_ipAddrMgr.releasePortableIpAddress(ip.getId());
}
}
// release dedication if any
List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByAccountId(accountId);
if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
s_logger.debug("Releasing dedicated resources for account " + accountId);
for (DedicatedResourceVO dr : dedicatedResources) {
if (!_dedicatedDao.remove(dr.getId())) {
s_logger.warn("Fail to release dedicated resources for account " + accountId);
}
}
}
// Updating and deleting the resourceLimit and resourceCount should be the last step in cleanupAccount
// process.
// Update resource count for this account and for parent domains.
List<ResourceCountVO> resourceCounts = _resourceCountDao.listByOwnerId(accountId, ResourceOwnerType.Account);
for (ResourceCountVO resourceCount : resourceCounts) {
_resourceLimitMgr.decrementResourceCount(accountId, resourceCount.getType(), resourceCount.getCount());
}
// Delete resource count and resource limits entries set for this account (if there are any).
_resourceCountDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
_resourceLimitDao.removeEntriesByOwner(accountId, ResourceOwnerType.Account);
return true;
} catch (Exception ex) {
s_logger.warn("Failed to cleanup account " + account + " due to ", ex);
accountCleanupNeeded = true;
return true;
} finally {
s_logger.info("Cleanup for account " + account.getId() + (accountCleanupNeeded ? " is needed." : " is not needed."));
if (accountCleanupNeeded) {
_accountDao.markForCleanup(accountId);
} else {
account.setNeedsCleanup(false);
_accountDao.update(accountId, account);
}
}
}
use of com.cloud.network.IpAddress in project cloudstack by apache.
the class CiscoVnmcElementTest method applyFWRulesTest.
@Test
public void applyFWRulesTest() throws ResourceUnavailableException {
URI uri = URI.create("vlan://123");
Network network = mock(Network.class);
when(network.getId()).thenReturn(1L);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
when(network.getDataCenterId()).thenReturn(1L);
when(network.getBroadcastUri()).thenReturn(uri);
when(network.getCidr()).thenReturn("1.1.1.0/24");
when(network.getState()).thenReturn(Network.State.Implemented);
Ip ip = mock(Ip.class);
when(ip.addr()).thenReturn("1.2.3.4");
IpAddress ipAddress = mock(IpAddress.class);
when(ipAddress.getAddress()).thenReturn(ip);
when(_networkModel.getIp(anyLong())).thenReturn(ipAddress);
when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, Provider.CiscoVnmc)).thenReturn(true);
List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
devices.add(mock(CiscoVnmcControllerVO.class));
when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
HostVO hostVO = mock(HostVO.class);
when(hostVO.getId()).thenReturn(1L);
when(_hostDao.findById(anyLong())).thenReturn(hostVO);
FirewallRule rule = mock(FirewallRule.class);
when(rule.getSourceIpAddressId()).thenReturn(1L);
List<FirewallRule> rules = new ArrayList<FirewallRule>();
rules.add(rule);
Answer answer = mock(Answer.class);
when(answer.getResult()).thenReturn(true);
when(_agentMgr.easySend(anyLong(), any(SetFirewallRulesCommand.class))).thenReturn(answer);
assertTrue(_element.applyFWRules(network, rules));
}
use of com.cloud.network.IpAddress in project cloudstack by apache.
the class CiscoVnmcElement method applyStaticNats.
@Override
public boolean applyStaticNats(Network network, List<? extends StaticNat> rules) throws ResourceUnavailableException {
if (!_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.StaticNat, Provider.CiscoVnmc)) {
s_logger.error("Static NAT service is not provided by Cisco Vnmc device on network " + network.getName());
return false;
}
// Find VNMC host for physical network
List<CiscoVnmcControllerVO> devices = _ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
if (devices.isEmpty()) {
s_logger.error("No Cisco Vnmc device on network " + network.getName());
return true;
}
// Find if ASA 1000v is associated with network
NetworkAsa1000vMapVO asaForNetwork = _networkAsa1000vMapDao.findByNetworkId(network.getId());
if (asaForNetwork == null) {
s_logger.debug("Cisco ASA 1000v device is not associated with network " + network.getName());
return true;
}
if (network.getState() == Network.State.Allocated) {
s_logger.debug("External firewall was asked to apply static NAT rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands.");
return true;
}
CiscoVnmcControllerVO ciscoVnmcDevice = devices.get(0);
HostVO ciscoVnmcHost = _hostDao.findById(ciscoVnmcDevice.getHostId());
List<StaticNatRuleTO> rulesTO = new ArrayList<StaticNatRuleTO>();
for (StaticNat rule : rules) {
IpAddress sourceIp = _networkModel.getIp(rule.getSourceIpAddressId());
StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule.getSourceIpAddressId(), sourceIp.getAddress().addr(), null, null, rule.getDestIpAddress(), null, null, null, rule.isForRevoke(), false);
rulesTO.add(ruleTO);
}
if (!rulesTO.isEmpty()) {
SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(rulesTO, null);
cmd.setContextParam(NetworkElementCommand.GUEST_VLAN_TAG, BroadcastDomainType.getValue(network.getBroadcastUri()));
cmd.setContextParam(NetworkElementCommand.GUEST_NETWORK_CIDR, network.getCidr());
Answer answer = _agentMgr.easySend(ciscoVnmcHost.getId(), cmd);
if (answer == null || !answer.getResult()) {
String details = (answer != null) ? answer.getDetails() : "details unavailable";
String msg = "Unable to apply static NAT rules to Cisco ASA 1000v appliance due to: " + details + ".";
s_logger.error(msg);
throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId());
}
}
return true;
}
use of com.cloud.network.IpAddress in project cloudstack by apache.
the class CiscoVnmcElementTest method applyStaticNatsTest.
@Test
public void applyStaticNatsTest() throws ResourceUnavailableException {
URI uri = URI.create("vlan://123");
Network network = mock(Network.class);
when(network.getId()).thenReturn(1L);
when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan);
when(network.getDataCenterId()).thenReturn(1L);
when(network.getBroadcastUri()).thenReturn(uri);
when(network.getCidr()).thenReturn("1.1.1.0/24");
when(network.getState()).thenReturn(Network.State.Implemented);
Ip ip = mock(Ip.class);
when(ip.addr()).thenReturn("1.2.3.4");
IpAddress ipAddress = mock(IpAddress.class);
when(ipAddress.getAddress()).thenReturn(ip);
when(ipAddress.getVlanId()).thenReturn(1L);
when(_networkModel.getIp(anyLong())).thenReturn(ipAddress);
when(_networkModel.isProviderSupportServiceInNetwork(network.getId(), Service.StaticNat, Provider.CiscoVnmc)).thenReturn(true);
List<CiscoVnmcControllerVO> devices = new ArrayList<CiscoVnmcControllerVO>();
devices.add(mock(CiscoVnmcControllerVO.class));
when(_ciscoVnmcDao.listByPhysicalNetwork(network.getPhysicalNetworkId())).thenReturn(devices);
when(_networkAsa1000vMapDao.findByNetworkId(network.getId())).thenReturn(mock(NetworkAsa1000vMapVO.class));
HostVO hostVO = mock(HostVO.class);
when(hostVO.getId()).thenReturn(1L);
when(_hostDao.findById(anyLong())).thenReturn(hostVO);
VlanVO vlanVO = mock(VlanVO.class);
when(vlanVO.getVlanTag()).thenReturn(null);
when(_vlanDao.findById(anyLong())).thenReturn(vlanVO);
StaticNat rule = mock(StaticNat.class);
when(rule.getSourceIpAddressId()).thenReturn(1L);
when(rule.getDestIpAddress()).thenReturn("1.2.3.4");
when(rule.isForRevoke()).thenReturn(false);
List<StaticNat> rules = new ArrayList<StaticNat>();
rules.add(rule);
Answer answer = mock(Answer.class);
when(answer.getResult()).thenReturn(true);
when(_agentMgr.easySend(anyLong(), any(SetStaticNatRulesCommand.class))).thenReturn(answer);
assertTrue(_element.applyStaticNats(network, rules));
}
use of com.cloud.network.IpAddress in project cloudstack by apache.
the class ApiResponseHelper method createPortForwardingRuleResponse.
@Override
public FirewallRuleResponse createPortForwardingRuleResponse(PortForwardingRule fwRule) {
FirewallRuleResponse response = new FirewallRuleResponse();
response.setId(fwRule.getUuid());
response.setPrivateStartPort(Integer.toString(fwRule.getDestinationPortStart()));
response.setPrivateEndPort(Integer.toString(fwRule.getDestinationPortEnd()));
response.setProtocol(fwRule.getProtocol());
response.setPublicStartPort(Integer.toString(fwRule.getSourcePortStart()));
response.setPublicEndPort(Integer.toString(fwRule.getSourcePortEnd()));
List<String> cidrs = ApiDBUtils.findFirewallSourceCidrs(fwRule.getId());
response.setCidrList(StringUtils.join(cidrs, ","));
Network guestNtwk = ApiDBUtils.findNetworkById(fwRule.getNetworkId());
response.setNetworkId(guestNtwk.getUuid());
IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId());
if (ip != null) {
response.setPublicIpAddressId(ip.getUuid());
response.setPublicIpAddress(ip.getAddress().addr());
if (fwRule.getDestinationIpAddress() != null) {
response.setDestNatVmIp(fwRule.getDestinationIpAddress().toString());
UserVm vm = ApiDBUtils.findUserVmById(fwRule.getVirtualMachineId());
if (vm != null) {
response.setVirtualMachineId(vm.getUuid());
response.setVirtualMachineName(vm.getHostName());
if (vm.getDisplayName() != null) {
response.setVirtualMachineDisplayName(vm.getDisplayName());
} else {
response.setVirtualMachineDisplayName(vm.getHostName());
}
}
}
}
FirewallRule.State state = fwRule.getState();
String stateToSet = state.toString();
if (state.equals(FirewallRule.State.Revoke)) {
stateToSet = "Deleting";
}
// set tag information
List<? extends ResourceTag> tags = ApiDBUtils.listByResourceTypeAndId(ResourceObjectType.PortForwardingRule, fwRule.getId());
List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
for (ResourceTag tag : tags) {
ResourceTagResponse tagResponse = createResourceTagResponse(tag, true);
CollectionUtils.addIgnoreNull(tagResponses, tagResponse);
}
response.setTags(tagResponses);
response.setState(stateToSet);
response.setForDisplay(fwRule.isDisplay());
response.setObjectName("portforwardingrule");
return response;
}
Aggregations