use of com.cloud.vm.ReservationContext in project cloudstack by apache.
the class NetworkServiceImpl method createGuestNetwork.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NETWORK_CREATE, eventDescription = "creating network")
public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
Long networkOfferingId = cmd.getNetworkOfferingId();
String gateway = cmd.getGateway();
String startIP = cmd.getStartIp();
String endIP = cmd.getEndIp();
String netmask = cmd.getNetmask();
String networkDomain = cmd.getNetworkDomain();
String vlanId = null;
boolean bypassVlanOverlapCheck = false;
boolean hideIpAddressUsage = false;
String routerIp = null;
String routerIpv6 = null;
if (cmd instanceof CreateNetworkCmdByAdmin) {
vlanId = ((CreateNetworkCmdByAdmin) cmd).getVlan();
bypassVlanOverlapCheck = ((CreateNetworkCmdByAdmin) cmd).getBypassVlanOverlapCheck();
hideIpAddressUsage = ((CreateNetworkCmdByAdmin) cmd).getHideIpAddressUsage();
routerIp = ((CreateNetworkCmdByAdmin) cmd).getRouterIp();
routerIpv6 = ((CreateNetworkCmdByAdmin) cmd).getRouterIpv6();
}
String name = cmd.getNetworkName();
String displayText = cmd.getDisplayText();
Account caller = CallContext.current().getCallingAccount();
Long physicalNetworkId = cmd.getPhysicalNetworkId();
Long zoneId = cmd.getZoneId();
String aclTypeStr = cmd.getAclType();
Long domainId = cmd.getDomainId();
boolean isDomainSpecific = false;
Boolean subdomainAccess = cmd.getSubdomainAccess();
Long vpcId = cmd.getVpcId();
String startIPv6 = cmd.getStartIpv6();
String endIPv6 = cmd.getEndIpv6();
String ip6Gateway = cmd.getIp6Gateway();
String ip6Cidr = cmd.getIp6Cidr();
Boolean displayNetwork = cmd.getDisplayNetwork();
Long aclId = cmd.getAclId();
String isolatedPvlan = cmd.getIsolatedPvlan();
String externalId = cmd.getExternalId();
String isolatedPvlanType = cmd.getIsolatedPvlanType();
// Validate network offering
NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId);
if (ntwkOff == null || ntwkOff.isSystemOnly()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find network offering by specified id");
if (ntwkOff != null) {
ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId");
}
throw ex;
}
Account owner = null;
if ((cmd.getAccountName() != null && domainId != null) || cmd.getProjectId() != null) {
owner = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), domainId, cmd.getProjectId());
} else {
owner = caller;
}
// validate physical network and zone
// Check if physical network exists
PhysicalNetwork pNtwk = null;
if (physicalNetworkId != null) {
pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
throw new InvalidParameterValueException("Unable to find a physical network having the specified physical network id");
}
}
if (zoneId == null) {
zoneId = pNtwk.getDataCenterId();
}
if (displayNetwork == null) {
displayNetwork = true;
}
DataCenter zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Specified zone id was not found");
}
_accountMgr.checkAccess(owner, ntwkOff, zone);
if (Grouping.AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
// See DataCenterVO.java
PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
ex.addProxyObject(zone.getUuid(), "zoneId");
throw ex;
}
// Only domain and account ACL types are supported in Acton.
ACLType aclType = null;
if (aclTypeStr != null) {
if (aclTypeStr.equalsIgnoreCase(ACLType.Account.toString())) {
aclType = ACLType.Account;
} else if (aclTypeStr.equalsIgnoreCase(ACLType.Domain.toString())) {
aclType = ACLType.Domain;
} else {
throw new InvalidParameterValueException("Incorrect aclType specified. Check the API documentation for supported types");
}
// In 3.0 all Shared networks should have aclType == Domain, all Isolated networks aclType==Account
if (ntwkOff.getGuestType() == GuestType.Isolated) {
if (aclType != ACLType.Account) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Account + " for network of type " + Network.GuestType.Isolated);
}
} else if (ntwkOff.getGuestType() == GuestType.Shared) {
if (!(aclType == ACLType.Domain || aclType == ACLType.Account)) {
throw new InvalidParameterValueException("AclType should be " + ACLType.Domain + " or " + ACLType.Account + " for network of type " + Network.GuestType.Shared);
}
}
} else {
if (ntwkOff.getGuestType() == GuestType.Isolated || ntwkOff.getGuestType() == GuestType.L2) {
aclType = ACLType.Account;
} else if (ntwkOff.getGuestType() == GuestType.Shared) {
aclType = ACLType.Domain;
}
}
// Only Admin can create Shared networks
if ((ntwkOff.getGuestType() == GuestType.Shared) && !_accountMgr.isAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only Admins can create network with guest type " + GuestType.Shared);
}
if (ntwkOff.getGuestType() != GuestType.Shared && (!StringUtils.isAllBlank(routerIp, routerIpv6))) {
throw new InvalidParameterValueException("Router IP can be specified only for Shared networks");
}
if (ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.isProviderForNetworkOffering(Provider.VirtualRouter, networkOfferingId) && (!StringUtils.isAllBlank(routerIp, routerIpv6))) {
throw new InvalidParameterValueException("Virtual Router is not a supported provider for the Shared network, hence router ip should not be provided");
}
// Check if the network is domain specific
if (aclType == ACLType.Domain) {
// only Admin can create domain with aclType=Domain
if (!_accountMgr.isAdmin(caller.getId())) {
throw new PermissionDeniedException("Only admin can create networks with aclType=Domain");
}
// only shared networks can be Domain specific
if (ntwkOff.getGuestType() != GuestType.Shared) {
throw new InvalidParameterValueException("Only " + GuestType.Shared + " networks can have aclType=" + ACLType.Domain);
}
if (domainId != null) {
if (ntwkOff.getTrafficType() != TrafficType.Guest || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Domain level networks are supported just for traffic type " + TrafficType.Guest + " and guest type " + Network.GuestType.Shared);
}
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find domain by specified id");
}
_accountMgr.checkAccess(caller, domain);
}
isDomainSpecific = true;
} else if (subdomainAccess != null) {
throw new InvalidParameterValueException("Parameter subDomainAccess can be specified only with aclType=Domain");
}
if (aclType == ACLType.Domain) {
owner = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
}
// The network name is unique under the account
if (!AllowDuplicateNetworkName.valueIn(owner.getAccountId())) {
List<NetworkVO> existingNetwork = _networksDao.listByAccountIdNetworkName(owner.getId(), name);
if (!existingNetwork.isEmpty()) {
throw new InvalidParameterValueException("Another network with same name already exists within account: " + owner.getAccountName());
}
}
boolean ipv4 = false, ipv6 = false;
if (org.apache.commons.lang3.StringUtils.isNoneBlank(gateway, netmask)) {
ipv4 = true;
}
if (StringUtils.isNoneBlank(ip6Cidr, ip6Gateway)) {
ipv6 = true;
}
if (gateway != null) {
try {
// getByName on a literal representation will only check validity of the address
// http://docs.oracle.com/javase/6/docs/api/java/net/InetAddress.html#getByName(java.lang.String)
InetAddress gatewayAddress = InetAddress.getByName(gateway);
if (gatewayAddress instanceof Inet6Address) {
ipv6 = true;
} else {
ipv4 = true;
}
} catch (UnknownHostException e) {
s_logger.error("Unable to convert gateway IP to a InetAddress", e);
throw new InvalidParameterValueException("Gateway parameter is invalid");
}
}
// Start and end IP address are mandatory for shared networks.
if (ntwkOff.getGuestType() == GuestType.Shared && vpcId == null) {
if (!AllowEmptyStartEndIpAddress.valueIn(owner.getAccountId()) && (startIP == null && endIP == null) && (startIPv6 == null && endIPv6 == null)) {
throw new InvalidParameterValueException("Either IPv4 or IPv6 start and end address are mandatory");
}
}
String cidr = null;
if (ipv4) {
// if end ip is not specified, default it to startIp
if (startIP != null) {
if (!NetUtils.isValidIp4(startIP)) {
throw new InvalidParameterValueException("Invalid format for the startIp parameter");
}
if (endIP == null) {
endIP = startIP;
} else if (!NetUtils.isValidIp4(endIP)) {
throw new InvalidParameterValueException("Invalid format for the endIp parameter");
}
if (!(gateway != null && netmask != null)) {
throw new InvalidParameterValueException("gateway and netmask should be defined when startIP/endIP are passed in");
}
}
if (gateway != null && netmask != null) {
if (NetUtils.isNetworkorBroadcastIP(gateway, netmask)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("The gateway IP provided is " + gateway + " and netmask is " + netmask + ". The IP is either broadcast or network IP.");
}
throw new InvalidParameterValueException("Invalid gateway IP provided. Either the IP is broadcast or network IP.");
}
if (!NetUtils.isValidIp4(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidIp4Netmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
}
}
if (ipv6) {
if (endIPv6 == null) {
endIPv6 = startIPv6;
}
_networkModel.checkIp6Parameters(startIPv6, endIPv6, ip6Gateway, ip6Cidr);
if (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() != Network.GuestType.Shared) {
throw new InvalidParameterValueException("Can only support create IPv6 network with advance shared network!");
}
if (StringUtils.isAllBlank(zone.getIp6Dns1(), zone.getIp6Dns2())) {
throw new InvalidParameterValueException("Can only create IPv6 network if the zone has IPv6 DNS! Please configure the zone IPv6 DNS1 and/or IPv6 DNS2.");
}
if (!ipv4 && ntwkOff.getGuestType() == GuestType.Shared && _networkModel.isProviderForNetworkOffering(Provider.VirtualRouter, networkOfferingId)) {
throw new InvalidParameterValueException("Currently IPv6-only Shared network with Virtual Router provider is not supported.");
}
}
validateRouterIps(routerIp, routerIpv6, startIP, endIP, gateway, netmask, startIPv6, endIPv6, ip6Cidr);
if (StringUtils.isNotBlank(isolatedPvlan) && (zone.getNetworkType() != NetworkType.Advanced || ntwkOff.getGuestType() == GuestType.Isolated)) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with advanced shared or L2 network!");
}
if (StringUtils.isNotBlank(isolatedPvlan) && ipv6) {
throw new InvalidParameterValueException("Can only support create Private VLAN network with IPv4!");
}
Pair<String, PVlanType> pvlanPair = getPrivateVlanPair(isolatedPvlan, isolatedPvlanType, vlanId);
String secondaryVlanId = pvlanPair.first();
PVlanType privateVlanType = pvlanPair.second();
if ((StringUtils.isNotBlank(secondaryVlanId) || privateVlanType != null) && StringUtils.isBlank(vlanId)) {
throw new InvalidParameterValueException("VLAN ID has to be set in order to configure a Private VLAN");
}
performBasicPrivateVlanChecks(vlanId, secondaryVlanId, privateVlanType);
if (!_accountMgr.isRootAdmin(caller.getId())) {
validateNetworkOfferingForNonRootAdminUser(ntwkOff);
}
// Don't allow to specify vlan if the caller is not ROOT admin
if (!_accountMgr.isRootAdmin(caller.getId()) && (ntwkOff.isSpecifyVlan() || vlanId != null || bypassVlanOverlapCheck)) {
throw new InvalidParameterValueException("Only ROOT admin is allowed to specify vlanId or bypass vlan overlap check");
}
if (ipv4) {
// For non-root admins check cidr limit - if it's allowed by global config value
if (!_accountMgr.isRootAdmin(caller.getId()) && cidr != null) {
String[] cidrPair = cidr.split("\\/");
int cidrSize = Integer.parseInt(cidrPair[1]);
if (cidrSize < _cidrLimit) {
throw new InvalidParameterValueException("Cidr size can't be less than " + _cidrLimit);
}
}
}
Collection<String> ntwkProviders = _networkMgr.finalizeServicesAndProvidersForNetwork(ntwkOff, physicalNetworkId).values();
if (ipv6 && providersConfiguredForExternalNetworking(ntwkProviders)) {
throw new InvalidParameterValueException("Cannot support IPv6 on network offering with external devices!");
}
if (StringUtils.isNotBlank(secondaryVlanId) && providersConfiguredForExternalNetworking(ntwkProviders)) {
throw new InvalidParameterValueException("Cannot support private vlan on network offering with external devices!");
}
if (cidr != null && providersConfiguredForExternalNetworking(ntwkProviders)) {
if (ntwkOff.getGuestType() == GuestType.Shared && (zone.getNetworkType() == NetworkType.Advanced) && isSharedNetworkOfferingWithServices(networkOfferingId)) {
// validate if CIDR specified overlaps with any of the CIDR's allocated for isolated networks and shared networks in the zone
checkSharedNetworkCidrOverlap(zoneId, pNtwk.getId(), cidr);
} else {
// if cidr is not null and network is not part of vpc then throw the exception
if (vpcId == null) {
throw new InvalidParameterValueException("Cannot specify CIDR when using network offering with external devices!");
}
}
}
// Vlan is created in 1 cases - works in Advance zone only:
// 1) GuestType is Shared
boolean createVlan = (startIP != null && endIP != null && zone.getNetworkType() == NetworkType.Advanced && ((ntwkOff.getGuestType() == Network.GuestType.Shared) || (ntwkOff.getGuestType() == GuestType.Isolated && !areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))));
if (!createVlan) {
// Only support advance shared network in IPv6, which means createVlan is a must
if (ipv6) {
createVlan = true;
}
}
// Can add vlan range only to the network which allows it
if (createVlan && !ntwkOff.isSpecifyIpRanges()) {
throwInvalidIdException("Network offering with specified id doesn't support adding multiple ip ranges", ntwkOff.getUuid(), "networkOfferingId");
}
Network network = commitNetwork(networkOfferingId, gateway, startIP, endIP, netmask, networkDomain, vlanId, bypassVlanOverlapCheck, name, displayText, caller, physicalNetworkId, zoneId, domainId, isDomainSpecific, subdomainAccess, vpcId, startIPv6, endIPv6, ip6Gateway, ip6Cidr, displayNetwork, aclId, secondaryVlanId, privateVlanType, ntwkOff, pNtwk, aclType, owner, cidr, createVlan, externalId, routerIp, routerIpv6);
if (hideIpAddressUsage) {
_networkDetailsDao.persist(new NetworkDetailVO(network.getId(), Network.hideIpAddressUsage, String.valueOf(hideIpAddressUsage), false));
}
// if the network offering has persistent set to true, implement the network
if (ntwkOff.isPersistent()) {
try {
DeployDestination dest = new DeployDestination(zone, null, null, null);
UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
Journal journal = new Journal.LogJournal("Implementing " + network, s_logger);
ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
s_logger.debug("Implementing network " + network + " as a part of network provision for persistent network");
Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(network.getId(), dest, context);
if (implementedNetwork == null || implementedNetwork.first() == null) {
s_logger.warn("Failed to provision the network " + network);
}
network = implementedNetwork.second();
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to implement persistent guest network " + network + "due to ", ex);
CloudRuntimeException e = new CloudRuntimeException("Failed to implement persistent guest network");
e.addProxyObject(network.getUuid(), "networkId");
throw e;
}
}
return network;
}
use of com.cloud.vm.ReservationContext in project cloudstack by apache.
the class GloboDnsElementTest method testReleaseMethodCallResource.
@Test
public void testReleaseMethodCallResource() throws Exception {
Network network = mock(Network.class);
when(network.getDataCenterId()).thenReturn(zoneId);
when(network.getId()).thenReturn(1l);
NicProfile nic = new NicProfile();
nic.setIPv4Address("10.11.12.13");
VirtualMachineProfile vm = mock(VirtualMachineProfile.class);
when(vm.getHostName()).thenReturn("vm-name");
when(vm.getType()).thenReturn(VirtualMachine.Type.User);
DataCenterVO dataCenterVO = mock(DataCenterVO.class);
when(dataCenterVO.getId()).thenReturn(zoneId);
when(_datacenterDao.findById(zoneId)).thenReturn(dataCenterVO);
ReservationContext context = new ReservationContextImpl(null, null, user);
HostVO hostVO = mock(HostVO.class);
when(hostVO.getId()).thenReturn(globoDnsHostId);
when(_hostDao.findByTypeNameAndZoneId(eq(zoneId), eq(Provider.GloboDns.getName()), eq(Type.L2Networking))).thenReturn(hostVO);
when(_agentMgr.easySend(eq(globoDnsHostId), isA(RemoveRecordCommand.class))).then(new org.mockito.stubbing.Answer<Answer>() {
@Override
public Answer answer(InvocationOnMock invocation) throws Throwable {
Command cmd = (Command) invocation.getArguments()[1];
return new Answer(cmd);
}
});
_globodnsElement.release(network, nic, vm, context);
verify(_agentMgr, times(1)).easySend(eq(globoDnsHostId), isA(RemoveRecordCommand.class));
}
use of com.cloud.vm.ReservationContext 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) {
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);
// Delete ssh keypairs
List<SSHKeyPairVO> sshkeypairs = _sshKeyPairDao.listKeyPairs(accountId, account.getDomainId());
for (SSHKeyPairVO keypair : sshkeypairs) {
_sshKeyPairDao.remove(keypair.getId());
}
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.vm.ReservationContext in project cloudstack by apache.
the class BrocadeVcsGuestNetworkGuruTest method testImplementFail.
@Test
public void testImplementFail() throws InsufficientVirtualNetworkCapacityException, URISyntaxException {
final PhysicalNetworkVO physnet = mock(PhysicalNetworkVO.class);
when(physnetdao.findById((Long) any())).thenReturn(physnet);
when(physnet.getIsolationMethods()).thenReturn(Arrays.asList(new String[] { "VCS" }));
when(physnet.getId()).thenReturn(NETWORK_ID);
final NetworkOffering offering = mock(NetworkOffering.class);
when(offering.getId()).thenReturn(NETWORK_ID);
when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
when(offering.getGuestType()).thenReturn(GuestType.Isolated);
when(nosd.areServicesSupportedByNetworkOffering(NETWORK_ID, Service.Connectivity)).thenReturn(false);
mock(DeploymentPlan.class);
final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(State.Implementing);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
when(network.getBroadcastUri()).thenReturn(new URI("vlan://14"));
final DeployDestination dest = mock(DeployDestination.class);
final DataCenter dc = mock(DataCenter.class);
when(dest.getDataCenter()).thenReturn(dc);
final HostVO brocadeHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(brocadeHost);
when(brocadeHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(NETWORK_ID);
final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class);
when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID);
final List<BrocadeVcsDeviceVO> devices = mock(List.class);
when(devices.isEmpty()).thenReturn(true);
when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices);
final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain");
final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname");
final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc);
when(guestGuru.implement(network, offering, dest, res)).thenReturn(network);
final CreateNetworkAnswer answer = mock(CreateNetworkAnswer.class);
when(answer.getResult()).thenReturn(true);
when(agentmgr.easySend(eq(NETWORK_ID), (Command) any())).thenReturn(answer);
final Network implementednetwork = guru.implement(network, offering, dest, res);
assertTrue(implementednetwork == null);
verify(agentmgr, times(0)).easySend(eq(NETWORK_ID), (Command) any());
}
use of com.cloud.vm.ReservationContext in project cloudstack by apache.
the class BrocadeVcsGuestNetworkGuruTest method testReserveFail.
@Test
public void testReserveFail() throws InsufficientVirtualNetworkCapacityException, URISyntaxException, InsufficientAddressCapacityException {
final NetworkVO network = mock(NetworkVO.class);
when(network.getName()).thenReturn("testnetwork");
when(network.getState()).thenReturn(State.Implementing);
when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
when(network.getBroadcastUri()).thenReturn(new URI("vlan://14"));
when(network.getDataCenterId()).thenReturn(NETWORK_ID);
final NicProfile nic = mock(NicProfile.class);
when(nic.getMacAddress()).thenReturn("macaddress");
when(nic.getReservationStrategy()).thenReturn(ReservationStrategy.Start);
final VirtualMachineProfile vmProfile = mock(VirtualMachineProfile.class);
final DeployDestination dest = mock(DeployDestination.class);
final DataCenterVO dc = mock(DataCenterVO.class);
when(dest.getDataCenter()).thenReturn(dc);
when(dcdao.findById((long) anyInt())).thenReturn(dc);
final HostVO brocadeHost = mock(HostVO.class);
when(hostdao.findById(anyLong())).thenReturn(brocadeHost);
when(brocadeHost.getId()).thenReturn(NETWORK_ID);
when(netmodel.findPhysicalNetworkId(anyLong(), (String) any(), (TrafficType) any())).thenReturn(NETWORK_ID);
final BrocadeVcsDeviceVO brocadeDevice = mock(BrocadeVcsDeviceVO.class);
when(brocadeDevice.getHostId()).thenReturn(NETWORK_ID);
final List<BrocadeVcsDeviceVO> devices = mock(List.class);
when(devices.isEmpty()).thenReturn(true);
when(vcsdao.listByPhysicalNetwork(anyLong())).thenReturn(devices);
final Domain dom = mock(Domain.class);
when(dom.getName()).thenReturn("domain");
final Account acc = mock(Account.class);
when(acc.getAccountName()).thenReturn("accountname");
final ReservationContext res = mock(ReservationContext.class);
when(res.getDomain()).thenReturn(dom);
when(res.getAccount()).thenReturn(acc);
final AssociateMacToNetworkAnswer answer = mock(AssociateMacToNetworkAnswer.class);
when(answer.getResult()).thenReturn(true);
when(agentmgr.easySend(eq(NETWORK_ID), (Command) any())).thenReturn(answer);
guru.reserve(nic, network, vmProfile, dest, res);
verify(agentmgr, times(0)).easySend(eq(NETWORK_ID), (Command) any());
}
Aggregations