bug 9458: do searchIncludingRemoved when decrement resource count as corresponding domain might be removed already

status 9458: resolved fixed

Conflicts:

	server/src/com/cloud/user/AccountManagerImpl.java
This commit is contained in:
alena 2011-04-14 15:39:51 -07:00
parent 86f32e4735
commit 52fe53f497
3 changed files with 604 additions and 569 deletions

View File

@ -115,47 +115,74 @@ import com.cloud.vm.dao.InstanceGroupDao;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
@Local(value={AccountManager.class, AccountService.class})
@Local(value = { AccountManager.class, AccountService.class })
public class AccountManagerImpl implements AccountManager, AccountService, Manager {
public static final Logger s_logger = Logger.getLogger(AccountManagerImpl.class);
private String _name;
@Inject private AccountDao _accountDao;
@Inject ConfigurationDao _configDao;
@Inject private DomainDao _domainDao;
@Inject private ResourceLimitDao _resourceLimitDao;
@Inject private ResourceCountDao _resourceCountDao;
@Inject private UserDao _userDao;
@Inject private InstanceGroupDao _vmGroupDao;
@Inject private UserAccountDao _userAccountDao;
@Inject private VolumeDao _volumeDao;
@Inject private UserVmDao _userVmDao;
@Inject private VMTemplateDao _templateDao;
@Inject private NetworkDao _networkDao;
@Inject private SecurityGroupDao _securityGroupDao;
@Inject private VMInstanceDao _vmDao;
@Inject
private AccountDao _accountDao;
@Inject
ConfigurationDao _configDao;
@Inject
private DomainDao _domainDao;
@Inject
private ResourceLimitDao _resourceLimitDao;
@Inject
private ResourceCountDao _resourceCountDao;
@Inject
private UserDao _userDao;
@Inject
private InstanceGroupDao _vmGroupDao;
@Inject
private UserAccountDao _userAccountDao;
@Inject
private VolumeDao _volumeDao;
@Inject
private UserVmDao _userVmDao;
@Inject
private VMTemplateDao _templateDao;
@Inject
private NetworkDao _networkDao;
@Inject
private SecurityGroupDao _securityGroupDao;
@Inject
private VMInstanceDao _vmDao;
@Inject
private SecurityGroupManager _networkGroupMgr;
@Inject
private NetworkManager _networkMgr;
@Inject
private SnapshotManager _snapMgr;
@Inject
private UserVmManager _vmMgr;
@Inject
private StorageManager _storageMgr;
@Inject
private TemplateManager _tmpltMgr;
@Inject
private ConfigurationManager _configMgr;
@Inject
private VirtualMachineManager _itMgr;
@Inject
private UsageEventDao _usageEventDao;
@Inject
private RemoteAccessVpnDao _remoteAccessVpnDao;
@Inject
private RemoteAccessVpnService _remoteAccessVpnMgr;
@Inject
private VpnUserDao _vpnUser;
@Inject
private DataCenterDao _dcDao;
@Inject private SecurityGroupManager _networkGroupMgr;
@Inject private NetworkManager _networkMgr;
@Inject private SnapshotManager _snapMgr;
@Inject private UserVmManager _vmMgr;
@Inject private StorageManager _storageMgr;
@Inject private TemplateManager _tmpltMgr;
@Inject private ConfigurationManager _configMgr;
@Inject private VirtualMachineManager _itMgr;
@Inject private UsageEventDao _usageEventDao;
@Inject private RemoteAccessVpnDao _remoteAccessVpnDao;
@Inject private RemoteAccessVpnService _remoteAccessVpnMgr;
@Inject private VpnUserDao _vpnUser;
@Inject private DataCenterDao _dcDao;
private final ScheduledExecutorService _executor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("AccountChecker"));
private final GlobalLock m_resourceCountLock = GlobalLock.getInternLock("resource.count");
UserVO _systemUser;
AccountVO _systemAccount;
@Inject(adapter=SecurityChecker.class)
@Inject(adapter = SecurityChecker.class)
Adapters<SecurityChecker> _securityCheckers;
int _cleanupInterval;
@ -205,7 +232,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public void incrementResourceCount(long accountId, ResourceType type, Long...delta) {
public void incrementResourceCount(long accountId, ResourceType type, Long... delta) {
long numToIncrement = (delta.length == 0) ? 1 : delta[0].longValue();
if (m_resourceCountLock.lock(120)) { // 2 minutes
@ -228,7 +255,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public void decrementResourceCount(long accountId, ResourceType type, Long...delta) {
public void decrementResourceCount(long accountId, ResourceType type, Long... delta) {
long numToDecrement = (delta.length == 0) ? 1 : delta[0].longValue();
if (m_resourceCountLock.lock(120)) { // 2 minutes
@ -238,12 +265,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
// on a per-domain basis, decrement the count
// FIXME: can this decrement be done on the database side in a custom update statement?
Account account = _accountDao.findByIdIncludingRemoved(accountId); // find all accounts, even removed accounts if this happens to be for an account that's being deleted
Account account = _accountDao.findByIdIncludingRemoved(accountId); // find all accounts, even removed accounts
// if this happens to be for an account
// that's being deleted
Long domainId = account.getDomainId();
while (domainId != null) {
assert ((_resourceCountDao.getDomainCount(domainId, type) - numToDecrement) >= 0) : "Resource counts can not be negative. Check where we skipped increment.";
_resourceCountDao.updateDomainCount(domainId, type, false, numToDecrement);
DomainVO domain = _domainDao.findById(domainId);
DomainVO domain = _domainDao.findByIdIncludingRemoved(domainId);
domainId = domain.getParent();
}
} finally {
@ -316,7 +345,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public boolean resourceLimitExceeded(Account account, ResourceType type, long...count) {
public boolean resourceLimitExceeded(Account account, ResourceType type, long... count) {
long numResources = ((count.length == 0) ? 1 : count[0]);
// Don't place any limits on system or admin accounts
@ -374,8 +403,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
if ((accountId != null) && (domainId != null)) {
//if domainId==ROOT_DOMAIN and account belongs to admin
//return all records for resource limits (bug 3778)
// if domainId==ROOT_DOMAIN and account belongs to admin
// return all records for resource limits (bug 3778)
if (domainId == DomainVO.ROOT_DOMAIN) {
AccountVO account = _accountDao.findById(accountId);
@ -410,12 +439,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
// Listing all limits for an account
if (type == null) {
//List<ResourceLimitVO> userLimits = _resourceLimitDao.search(sc, searchFilter);
// List<ResourceLimitVO> userLimits = _resourceLimitDao.search(sc, searchFilter);
List<ResourceLimitVO> userLimits = _resourceLimitDao.listByAccountId(accountId);
List<ResourceLimitVO> rootLimits = _resourceLimitDao.listByDomainId(DomainVO.ROOT_DOMAIN);
ResourceType resourceTypes[] = ResourceType.values();
for (ResourceType resourceType: resourceTypes) {
for (ResourceType resourceType : resourceTypes) {
boolean found = false;
for (ResourceLimitVO userLimit : userLimits) {
if (userLimit.getType() == resourceType) {
@ -446,7 +475,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (type == null) {
ResourceType resourceTypes[] = ResourceType.values();
List<ResourceLimitVO> domainLimits = _resourceLimitDao.listByDomainId(domainId);
for (ResourceType resourceType: resourceTypes) {
for (ResourceType resourceType : resourceTypes) {
boolean found = false;
for (ResourceLimitVO domainLimit : domainLimits) {
if (domainLimit.getType() == resourceType) {
@ -485,7 +514,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (userAccount == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
} else if (account != null && (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN || account.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)) {
} else if (account != null
&& (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN || account.getType() == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)) {
// If this is a non-root admin, make sure that the admin and the user account belong in the same domain or
// that the user account's domain is a child domain of the parent
if (account.getDomainId() != userAccount.getDomainId() && !_domainDao.isChildDomain(account.getDomainId(), userAccount.getDomainId())) {
@ -539,7 +569,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
Long max = cmd.getMax();
Integer type = cmd.getResourceType();
//Validate input
// Validate input
Long accountId = null;
if (max == null) {
@ -556,7 +586,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
throw new InvalidParameterValueException("Please specify a valid resource type.");
}
// Either a domainId or an accountId must be passed in, but not both.
if ((domainId == null) && (accountName == null)) {
throw new InvalidParameterValueException("Either a domainId or domainId/account must be passed in.");
@ -565,7 +594,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (account != null) {
if (domainId != null) {
if (!_domainDao.isChildDomain(account.getDomainId(), domainId)) {
throw new PermissionDeniedException("Unable to update resource limit for " + ((account.getAccountName() == null) ? "" : "account " + account.getAccountName() + " in ") + "domain " + domainId + ", permission denied");
throw new PermissionDeniedException("Unable to update resource limit for " + ((account.getAccountName() == null) ? "" : "account " + account.getAccountName() + " in ") + "domain "
+ domainId + ", permission denied");
}
} else if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) {
domainId = DomainVO.ROOT_DOMAIN; // for root admin, default to root domain if domain is not specified
@ -592,7 +622,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
if (accountName != null) {
if (domainId == null) {
throw new InvalidParameterValueException("domainId parameter is required if account is specified");
@ -608,8 +637,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
domainId = null;
}
// Check if the domain or account exists and is valid
if (accountId != null) {
AccountVO accountHandle = _accountDao.findById(accountId);
@ -624,8 +651,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
DomainVO domain = _domainDao.findById(accountHandle.getDomainId());
long parentMaximum = findCorrectResourceLimit(domain, resourceType);
if ((parentMaximum >= 0) && ((max.longValue() == -1) || (max.longValue() > parentMaximum))) {
throw new InvalidParameterValueException("Account " + account.getAccountName() + "(id: " + accountId + ") has maximum allowed resource limit " + parentMaximum +
" for " + type + ", please specify a value less that or equal to " + parentMaximum);
throw new InvalidParameterValueException("Account " + account.getAccountName() + "(id: " + accountId + ") has maximum allowed resource limit " + parentMaximum + " for " + type
+ ", please specify a value less that or equal to " + parentMaximum);
}
} else if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
@ -640,8 +667,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
DomainVO parentDomain = _domainDao.findById(parentDomainId);
long parentMaximum = findCorrectResourceLimit(parentDomain, resourceType);
if ((parentMaximum >= 0) && (max.longValue() > parentMaximum)) {
throw new InvalidParameterValueException("Domain " + domain.getName() + "(id: " + domainId + ") has maximum allowed resource limit " + parentMaximum +
" for " + type + ", please specify a value less that or equal to " + parentMaximum);
throw new InvalidParameterValueException("Domain " + domain.getName() + "(id: " + domainId + ") has maximum allowed resource limit " + parentMaximum + " for " + type
+ ", please specify a value less that or equal to " + parentMaximum);
}
}
}
@ -670,9 +697,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
List<ResourceLimitVO> limits = _resourceLimitDao.search(sc, searchFilter);
if (limits.size() == 1) {
ResourceLimitVO limit = limits.get(0);
//if limit is set to -1, remove the record
// if limit is set to -1, remove the record
if (max != null && max.longValue() == -1L) {
//this parameter is needed by API as it expects the object to be returned and updates the UI with the object's new "max" parameter
// this parameter is needed by API as it expects the object to be returned and updates the UI with the object's
// new "max" parameter
ResourceLimitVO limitToReturn = limit;
limitToReturn.setMax(-1L);
_resourceLimitDao.remove(limit.getId());
@ -698,10 +726,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
@Override
public boolean isAdmin(short accountType) {
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
@Override
@ -709,7 +734,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return (accountType == Account.ACCOUNT_TYPE_ADMIN);
}
public boolean isResourceDomainAdmin(short accountType){
public boolean isResourceDomainAdmin(short accountType) {
return (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN);
}
@ -775,13 +800,13 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId){
//We just care for resource domain admin for now. He should be permitted to see only his zone.
if (isResourceDomainAdmin(caller.getType())){
public Long checkAccessAndSpecifyAuthority(Account caller, Long zoneId) {
// We just care for resource domain admin for now. He should be permitted to see only his zone.
if (isResourceDomainAdmin(caller.getType())) {
if (zoneId == null)
return getZoneIdForAccount(caller);
else if (getZoneIdForAccount(caller) != zoneId)
throw new PermissionDeniedException("Caller " +caller+ "is not allowed to access the zone " +zoneId);
throw new PermissionDeniedException("Caller " + caller + "is not allowed to access the zone " + zoneId);
else
return zoneId;
}
@ -792,9 +817,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
private Long getZoneIdForAccount(Account account) {
//Currently just for resource domain admin
// Currently just for resource domain admin
List<DataCenterVO> dcList = _dcDao.findZonesByDomainId(account.getDomainId());
if(dcList != null && dcList.size()!=0)
if (dcList != null && dcList.size() != 0)
return dcList.get(0).getId();
else
throw new CloudRuntimeException("Failed to find any private zone for Resource domain admin.");
@ -847,7 +872,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
List<UserVO> users = _userDao.listByAccount(accountId);
for(UserVO user : users){
for (UserVO user : users) {
_userDao.remove(user.getId());
}
@ -860,12 +885,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller){
public boolean cleanupAccount(AccountVO account, long callerUserId, Account caller) {
long accountId = account.getId();
boolean accountCleanupNeeded = false;
try {
//delete all vm groups belonging to accont
// delete all vm groups belonging to accont
List<InstanceGroupVO> groups = _vmGroupDao.listByAccountId(accountId);
for (InstanceGroupVO group : groups) {
if (!_vmMgr.deleteVmGroup(group.getId())) {
@ -908,39 +933,38 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
s_logger.error("Unable to destroy vm: " + vm.getId());
accountCleanupNeeded = true;
}
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(),
vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString());
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getName(), vm.getServiceOfferingId(),
vm.getTemplateId(), vm.getHypervisorType().toString());
_usageEventDao.persist(usageEvent);
}
// Mark the account's volumes as destroyed
List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(accountId);
for (VolumeVO volume : volumes) {
if(!volume.getState().equals(Volume.State.Destroy)) {
if (!volume.getState().equals(Volume.State.Destroy)) {
try {
_storageMgr.destroyVolume(volume);
if(volume.getPoolId() != null){
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(),
volume.getName());
if (volume.getPoolId() != null) {
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName());
_usageEventDao.persist(usageEvent);
}
}catch (ConcurrentOperationException ex) {
} catch (ConcurrentOperationException 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
// delete remote access vpns and associated users
List<RemoteAccessVpnVO> remoteAccessVpns = _remoteAccessVpnDao.findByAccount(accountId);
List<VpnUserVO> vpnUsers = _vpnUser.listByAccount(accountId);
for(VpnUserVO vpnUser : vpnUsers) {
for (VpnUserVO vpnUser : vpnUsers) {
_remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername());
}
try {
for(RemoteAccessVpnVO vpn : remoteAccessVpns) {
for (RemoteAccessVpnVO vpn : remoteAccessVpns) {
_remoteAccessVpnMgr.destroyRemoteAccessVpn(vpn.getServerAddressId());
}
} catch (ResourceUnavailableException ex) {
@ -948,12 +972,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
accountCleanupNeeded = true;
}
//Cleanup security groups
// Cleanup security groups
int numRemoved = _securityGroupDao.removeByAccountId(accountId);
s_logger.info("deleteAccount: Deleted " + numRemoved + " network groups for account " + accountId);
//Delete all the networks
// Delete all the networks
boolean networksDeleted = true;
s_logger.debug("Deleting networks for account " + account.getId());
List<NetworkVO> networks = _networkDao.listByOwner(accountId);
@ -963,7 +986,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), account);
if (!_networkMgr.destroyNetwork(network.getId(), context)) {
s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId +" cleanup.");
s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup.");
accountCleanupNeeded = true;
networksDeleted = false;
} else {
@ -972,9 +995,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
//delete account specific Virtual vlans (belong to system Public Network) - only when networks are cleaned up successfully
// delete account specific Virtual vlans (belong to system Public Network) - only when networks are cleaned up
// successfully
if (networksDeleted) {
if (!_configMgr.deleteAccountSpecificVirtualRanges(accountId)){
if (!_configMgr.deleteAccountSpecificVirtualRanges(accountId)) {
accountCleanupNeeded = true;
} else {
s_logger.debug("Account specific Virtual IP ranges " + " are successfully deleted as a part of account id=" + accountId + " cleanup.");
@ -991,7 +1015,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public boolean disableAccount(long accountId) throws ConcurrentOperationException, ResourceUnavailableException{
public boolean disableAccount(long accountId) throws ConcurrentOperationException, ResourceUnavailableException {
boolean success = false;
if (accountId <= 2) {
if (s_logger.isInfoEnabled()) {
@ -1013,7 +1037,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return success;
}
private boolean doDisableAccount(long accountId) throws ConcurrentOperationException, ResourceUnavailableException{
private boolean doDisableAccount(long accountId) throws ConcurrentOperationException, ResourceUnavailableException {
List<VMInstanceVO> vms = _vmDao.listByAccountId(accountId);
boolean success = true;
for (VMInstanceVO vm : vms) {
@ -1021,11 +1045,11 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
try {
success = (success && _itMgr.advanceStop(vm, true, getSystemUser(), getSystemAccount()));
} catch (OperationTimedoutException ote) {
s_logger.warn("Operation for stopping vm timed out, unable to stop vm " + vm.getName(),ote);
s_logger.warn("Operation for stopping vm timed out, unable to stop vm " + vm.getName(), ote);
success = false;
}
} catch (AgentUnavailableException aue) {
s_logger.warn("Agent running on host " + vm.getHostId() + " is unavailable, unable to stop vm " + vm.getName(),aue);
s_logger.warn("Agent running on host " + vm.getHostId() + " is unavailable, unable to stop vm " + vm.getName(), aue);
success = false;
}
}
@ -1033,12 +1057,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return success;
}
/////////////////////////////////////////////////////
//////////////// API commands /////////////////////
/////////////////////////////////////////////////////
// ///////////////////////////////////////////////////
// ////////////// API commands /////////////////////
// ///////////////////////////////////////////////////
@Override @ActionEvent (eventType=EventTypes.EVENT_ACCOUNT_CREATE, eventDescription="creating Account")
@Override
@ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account")
public UserAccount createAccount(CreateAccountCmd cmd) {
Long accountId = null;
String username = cmd.getUsername();
@ -1052,7 +1076,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
short userType = cmd.getAccountType().shortValue();
DomainVO domain = _domainDao.findById(domainId);
checkAccess(UserContext.current().getCaller(), domain);
try {
if (accountName == null) {
accountName = username;
@ -1063,14 +1086,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
Account account = _accountDao.findActiveAccount(accountName, domainId);
if (account != null) {
throw new CloudRuntimeException("The specified account: "+account.getAccountName()+" already exists");
throw new CloudRuntimeException("The specified account: " + account.getAccountName() + " already exists");
}
if(domain == null) {
throw new CloudRuntimeException("The domain "+domainId+" does not exist; unable to create account");
if (domain == null) {
throw new CloudRuntimeException("The domain " + domainId + " does not exist; unable to create account");
} else {
if(domain.getState().equals(Domain.State.Inactive)) {
throw new CloudRuntimeException("The account cannot be created as domain "+domain.getName()+" is being deleted");
if (domain.getState().equals(Domain.State.Inactive)) {
throw new CloudRuntimeException("The account cannot be created as domain " + domain.getName() + " is being deleted");
}
}
@ -1102,10 +1125,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
accountId = newAccount.getId();
}
if(userType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN){
if (userType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
List<DataCenterVO> dc = _dcDao.findZonesByDomainId(domainId);
if (dc == null || dc.size() == 0 ){
throw new CloudRuntimeException("The account cannot be created as domain "+domain.getName()+" is not associated with any private Zone");
if (dc == null || dc.size() == 0) {
throw new CloudRuntimeException("The account cannot be created as domain " + domain.getName() + " is not associated with any private Zone");
}
}
if (accountId == null) {
@ -1122,7 +1145,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
user.setEmail(email);
user.setTimezone(timezone);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating user: " + username + ", account: " + accountName + " (id:" + accountId + "), domain: " + domainId + " timezone:"+ timezone);
s_logger.debug("Creating user: " + username + ", account: " + accountName + " (id:" + accountId + "), domain: " + domainId + " timezone:" + timezone);
}
UserVO dbUser = _userDao.persist(user);
@ -1144,8 +1167,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
@Override @ActionEvent (eventType=EventTypes.EVENT_USER_CREATE, eventDescription="creating User")
public UserVO createUser(CreateUserCmd cmd){
@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User")
public UserVO createUser(CreateUserCmd cmd) {
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
String userName = cmd.getUsername();
@ -1156,7 +1180,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
String timeZone = cmd.getTimezone();
Long accountId = null;
//default domain to ROOT if not specified
// default domain to ROOT if not specified
if (domainId == null) {
domainId = Domain.ROOT_DOMAIN;
}
@ -1164,17 +1188,17 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
checkAccess(UserContext.current().getCaller(), domain);
Account account = _accountDao.findActiveAccount(accountName, domainId);
if(account == null){
if (account == null) {
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user");
}else{
} else {
accountId = account.getAccountId();
}
if(domain == null) {
throw new CloudRuntimeException("The domain "+domainId+" does not exist; unable to create user");
if (domain == null) {
throw new CloudRuntimeException("The domain " + domainId + " does not exist; unable to create user");
} else {
if(domain.getState().equals(Domain.State.Inactive)) {
throw new CloudRuntimeException("The user cannot be created as domain "+domain.getName()+" is being deleted");
if (domain.getState().equals(Domain.State.Inactive)) {
throw new CloudRuntimeException("The user cannot be created as domain " + domain.getName() + " is being deleted");
}
}
@ -1192,7 +1216,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
user.setEmail(email);
user.setTimezone(timeZone);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Creating user: " + userName + ", account: " + accountName + " (id:" + accountId + "), domain: " + domainId + " timezone:"+ timeZone);
s_logger.debug("Creating user: " + userName + ", account: " + accountName + " (id:" + accountId + "), domain: " + domainId + " timezone:" + timeZone);
}
UserVO dbUser = _userDao.persist(user);
@ -1204,7 +1228,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return dbUser;
}
@Override @ActionEvent (eventType=EventTypes.EVENT_USER_UPDATE, eventDescription="updating User")
@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_UPDATE, eventDescription = "updating User")
public UserAccount updateUser(UpdateUserCmd cmd) throws InvalidParameterValueException {
Long id = cmd.getId();
String apiKey = cmd.getApiKey();
@ -1216,15 +1241,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
String timeZone = cmd.getTimezone();
String userName = cmd.getUsername();
//Input validation
// Input validation
UserVO user = _userDao.getUser(id);
if (user == null) {
throw new InvalidParameterValueException("unable to find user by id");
}
if((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null)) {
if ((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null)) {
throw new InvalidParameterValueException("Please provide an api key/secret key pair");
}
@ -1234,6 +1258,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (account != null && (account.getId() == Account.ACCOUNT_ID_SYSTEM)) {
throw new PermissionDeniedException("user id : " + id + " is system account, update is not allowed");
}
checkAccess(UserContext.current().getCaller(), account);
if (firstName == null) {
@ -1267,16 +1292,16 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
s_logger.debug("updating user with id: " + id);
}
try {
//check if the apiKey and secretKey are globally unique
// check if the apiKey and secretKey are globally unique
if (apiKey != null && secretKey != null) {
Pair<User, Account> apiKeyOwner = _accountDao.findUserAccountByApiKey(apiKey);
if(apiKeyOwner != null) {
if (apiKeyOwner != null) {
User usr = apiKeyOwner.first();
if (usr.getId() != id) {
throw new InvalidParameterValueException("The api key:"+apiKey+" exists in the system for user id:"+id+" ,please provide a unique key");
throw new InvalidParameterValueException("The api key:" + apiKey + " exists in the system for user id:" + id + " ,please provide a unique key");
} else {
//allow the updation to take place
// allow the updation to take place
}
}
}
@ -1289,12 +1314,13 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
return _userAccountDao.findById(id);
}
@Override @ActionEvent (eventType=EventTypes.EVENT_USER_DISABLE, eventDescription="disabling User", async=true)
public UserAccount disableUser(DisableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_DISABLE, eventDescription = "disabling User", async = true)
public UserAccount disableUser(DisableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
Long userId = cmd.getId();
Account adminAccount = UserContext.current().getCaller();
//Check if user exists in the system
// Check if user exists in the system
User user = _userDao.findById(userId);
if ((user == null) || (user.getRemoved() != null)) {
throw new InvalidParameterValueException("Unable to find active user by id " + userId);
@ -1312,20 +1338,21 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
boolean success = doSetUserStatus(userId, State.disabled);
if (success) {
//user successfully disabled
// user successfully disabled
return _userAccountDao.findById(userId);
} else {
throw new CloudRuntimeException("Unable to disable user " + userId);
}
}
@Override @ActionEvent (eventType=EventTypes.EVENT_USER_ENABLE, eventDescription="enabling User")
public UserAccount enableUser(EnableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_ENABLE, eventDescription = "enabling User")
public UserAccount enableUser(EnableUserCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
Long userId = cmd.getId();
Account adminAccount = UserContext.current().getCaller();
boolean success = false;
//Check if user exists in the system
// Check if user exists in the system
User user = _userDao.findById(userId);
if ((user == null) || (user.getRemoved() != null)) {
throw new InvalidParameterValueException("Unable to find active user by id " + userId);
@ -1411,8 +1438,9 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
@Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DELETE, eventDescription = "deleting account", async=true)
//This method deletes the account
@Override
@ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DELETE, eventDescription = "deleting account", async = true)
// This method deletes the account
public boolean deleteUserAccount(DeleteAccountCmd cmd) {
UserContext ctx = UserContext.current();
@ -1428,39 +1456,37 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
throw new PermissionDeniedException("Account id : " + accountId + " is a system account, delete is not allowed");
}
if(account == null){
if (account == null) {
throw new InvalidParameterValueException("The specified account does not exist in the system");
}
if(account.getRemoved() != null){
s_logger.info("The account:"+account.getAccountName()+" is already removed");
if (account.getRemoved() != null) {
s_logger.info("The account:" + account.getAccountName() + " is already removed");
return true;
}
return deleteAccount(account, callerUserId, caller);
}
@Override
public AccountVO enableAccount(EnableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
public AccountVO enableAccount(EnableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
boolean success = false;
Account account = _accountDao.findActiveAccount(accountName, domainId);
//Check if account exists
// Check if account exists
if (account == null) {
s_logger.error("Unable to find account " + accountName + " in domain " + domainId);
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
}
//Don't allow to modify system account
// Don't allow to modify system account
if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException ("Can not modify system account");
throw new InvalidParameterValueException("Can not modify system account");
}
//Check if user performing the action is allowed to modify this account
// Check if user performing the action is allowed to modify this account
Account adminAccount = UserContext.current().getCaller();
if ((adminAccount != null) && !_domainDao.isChildDomain(adminAccount.getDomainId(), account.getDomainId())) {
throw new PermissionDeniedException("Invalid account " + accountName + " in domain " + domainId + " given, permission denied");
@ -1474,7 +1500,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
@Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "locking account", async=true)
@Override
@ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "locking account", async = true)
public AccountVO lockAccount(DisableAccountCmd cmd) {
Account adminAccount = UserContext.current().getCaller();
Long domainId = cmd.getDomainId();
@ -1501,7 +1528,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
@Override @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "disabling account", async=true)
@Override
@ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_DISABLE, eventDescription = "disabling account", async = true)
public AccountVO disableAccount(DisableAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException, ConcurrentOperationException, ResourceUnavailableException {
String accountName = cmd.getAccountName();
Long domainId = cmd.getDomainId();
@ -1523,7 +1551,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
@Override
public AccountVO updateAccount(UpdateAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException{
public AccountVO updateAccount(UpdateAccountCmd cmd) throws InvalidParameterValueException, PermissionDeniedException {
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
String newAccountName = cmd.getNewName();
@ -1531,27 +1559,33 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
boolean success = false;
Account account = _accountDao.findAccount(accountName, domainId);
//Check if account exists
// Check if account exists
if (account == null) {
s_logger.error("Unable to find account " + accountName + " in domain " + domainId);
throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
}
//Don't allow to modify system account
// Don't allow to modify system account
if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
throw new InvalidParameterValueException ("Can not modify system account");
throw new InvalidParameterValueException("Can not modify system account");
}
//Check if user performing the action is allowed to modify this account
// Check if user performing the action is allowed to modify this account
Account adminAccount = UserContext.current().getCaller();
if ((adminAccount != null) && (adminAccount.getType() != Account.ACCOUNT_TYPE_ADMIN) && _domainDao.isChildDomain(adminAccount.getDomainId(), account.getDomainId())) {
throw new PermissionDeniedException("Invalid account " + accountName + " in domain " + domainId + " given, permission denied");
}
//check if the given account name is unique in this domain for updating
// check if the given account name is unique in this domain for updating
Account duplicateAcccount = _accountDao.findAccount(newAccountName, domainId);
if(duplicateAcccount != null && duplicateAcccount.getRemoved() == null && duplicateAcccount.getId() != account.getId()){//allow same account to update itself
throw new PermissionDeniedException("There already exists an account with the name:"+newAccountName+" in the domain:"+domainId+" with existing account id:"+duplicateAcccount.getId());
if (duplicateAcccount != null && duplicateAcccount.getRemoved() == null && duplicateAcccount.getId() != account.getId()) {// allow
// same
// account
// to
// update
// itself
throw new PermissionDeniedException("There already exists an account with the name:" + newAccountName + " in the domain:" + domainId + " with existing account id:"
+ duplicateAcccount.getId());
}
if (account.getAccountName().equals(newAccountName)) {
@ -1568,13 +1602,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
@Override @ActionEvent (eventType=EventTypes.EVENT_USER_DELETE, eventDescription="deleting User")
@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_DELETE, eventDescription = "deleting User")
public boolean deleteUser(DeleteUserCmd deleteUserCmd) {
long id = deleteUserCmd.getId();
UserVO user = _userDao.findById(id);
if(user == null) {
if (user == null) {
throw new InvalidParameterValueException("The specified user doesn't exist in the system");
}
@ -1617,7 +1652,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
} catch (Exception e) {
s_logger.error("Exception ", e);
} finally {
if(txn != null) {
if (txn != null) {
txn.close();
}
@ -1631,7 +1666,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
@Override
public Account finalizeOwner(Account caller, String accountName, Long domainId) {
//don't default the owner to the system account
// don't default the owner to the system account
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM && (accountName == null || domainId == null)) {
throw new InvalidParameterValueException("Account and domainId are needed for resource creation");
}
@ -1659,7 +1694,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if ((accountName == null && domainId != null) || (accountName != null && domainId == null)) {
throw new InvalidParameterValueException("AccountName and domainId must be specified together");
}
//regular user can't create/list resources for other people
// regular user can't create/list resources for other people
return caller;
}
}
@ -1673,7 +1708,6 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
}
}
@Override
public Account getActiveAccount(Long accountId) {
if (accountId == null) {
@ -1707,7 +1741,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag
if (isAdmin(caller.getType())) {
if (domainId == null && accountName != null) {
throw new InvalidParameterValueException("accountName and domainId might be specified together");
} else if (domainId != null){
} else if (domainId != null) {
Domain domain = getDomain(domainId);
if (domain == null) {
throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId);

View File

@ -959,7 +959,7 @@ CREATE TABLE `cloud`.`domain` (
`parent` bigint unsigned,
`name` varchar(255),
`owner` bigint unsigned NOT NULL,
`path` varchar(255) UNIQUE NOT NULL,
`path` varchar(255) NOT NULL,
`level` int(10) NOT NULL DEFAULT 0,
`child_count` int(10) NOT NULL DEFAULT 0,
`next_child_seq` bigint unsigned NOT NULL DEFAULT 1,

View File

@ -60,6 +60,7 @@ ALTER TABLE `cloud`.`host_pod_ref` ADD INDEX `i_host_pod_ref__allocation_state`(
ALTER TABLE `cloud`.`host` ADD COLUMN `allocation_state` varchar(32) NOT NULL DEFAULT 'Enabled';
ALTER TABLE `cloud`.`host` ADD INDEX `i_host__allocation_state`(`allocation_state`);
ALTER TABLE `cloud`.`domain` DROP index `path`;
ALTER TABLE `cloud`.`domain` ADD INDEX `i_domain__path`(`path`);
CREATE TABLE `cloud`.`data_center_details` (