Adding more db operations to the API utils class and removing them from ManagementServer. These methods delegate directly to the DAO and are cluttering ManagementServer with cover methods specifically for the API. Now that these methods are being moved to the API Utils class, ManagementServer has a smaller, cleaner API than before.

This commit is contained in:
Kris McQueen 2010-09-15 12:16:00 -07:00
parent dc6e07ad75
commit 8bdb8f3581
6 changed files with 76 additions and 193 deletions

View File

@ -2,6 +2,7 @@ package com.cloud.api;
import java.util.List;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.domain.DomainVO;
@ -15,27 +16,39 @@ import com.cloud.offering.ServiceOffering;
import com.cloud.server.Criteria;
import com.cloud.server.ManagementServer;
import com.cloud.service.dao.ServiceOfferingDao;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.StoragePoolVO;
import com.cloud.storage.VMTemplateVO;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.dao.DiskOfferingDao;
import com.cloud.storage.dao.StoragePoolDao;
import com.cloud.storage.dao.VMTemplateDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserStatisticsVO;
import com.cloud.user.dao.AccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.vm.UserVmVO;
public class ApiDBUtils {
private static ManagementServer _ms;
private static AccountManager _accountMgr;
private static NetworkGroupManager _networkGroupMgr;
private static AccountDao _accountDao;
private static DiskOfferingDao _diskOfferingDao;
private static DomainDao _domainDao;
private static HostDao _hostDao;
private static IPAddressDao _ipAddressDao;
private static ServiceOfferingDao _serviceOfferingDao;
private static StoragePoolDao _storagePoolDao;
private static VMTemplateDao _templateDao;
private static UserDao _userDao;
private static UserStatisticsDao _userStatsDao;
private static VolumeDao _volumeDao;
private static DataCenterDao _zoneDao;
@ -43,14 +56,18 @@ public class ApiDBUtils {
_ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name);
ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name);
_accountMgr = locator.getManager(AccountManager.class);
_networkGroupMgr = locator.getManager(NetworkGroupManager.class);
_accountDao = locator.getDao(AccountDao.class);
_diskOfferingDao = locator.getDao(DiskOfferingDao.class);
_domainDao = locator.getDao(DomainDao.class);
_hostDao = locator.getDao(HostDao.class);
_ipAddressDao = locator.getDao(IPAddressDao.class);
_serviceOfferingDao = locator.getDao(ServiceOfferingDao.class);
_storagePoolDao = locator.getDao(StoragePoolDao.class);
_templateDao = locator.getDao(VMTemplateDao.class);
_userDao = locator.getDao(UserDao.class);
_userStatsDao = locator.getDao(UserStatisticsDao.class);
_volumeDao = locator.getDao(VolumeDao.class);
_zoneDao = locator.getDao(DataCenterDao.class);
}
@ -67,6 +84,26 @@ public class ApiDBUtils {
// Manager methods //
/////////////////////////////////////////////////////////////
public static long findCorrectResourceLimit(ResourceType type, long accountId) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
return -1;
}
return _accountMgr.findCorrectResourceLimit(account, type);
}
public static long getResourceCount(ResourceType type, long accountId) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
return -1;
}
return _accountMgr.getResourceCount(account, type);
}
public static String getNetworkGroupsNamesForVm(long vmId) {
return _networkGroupMgr.getNetworkGroupsNamesForVm(vmId);
}
@ -79,6 +116,10 @@ public class ApiDBUtils {
return _accountDao.findById(accountId);
}
public static DiskOfferingVO findDiskOfferingById(Long diskOfferingId) {
return _diskOfferingDao.findById(diskOfferingId);
}
public static DomainVO findDomainById(Long domainId) {
return _domainDao.findById(domainId);
}
@ -95,6 +136,10 @@ public class ApiDBUtils {
return _serviceOfferingDao.findById(serviceOfferingId);
}
public static StoragePoolVO findStoragePoolById(Long storagePoolId) {
return _storagePoolDao.findById(storagePoolId);
}
public static VMTemplateVO findTemplateById(Long templateId) {
return _templateDao.findById(templateId);
}
@ -110,4 +155,8 @@ public class ApiDBUtils {
public static DataCenterVO findZoneById(Long zoneId) {
return _zoneDao.findById(zoneId);
}
public static List<UserStatisticsVO> listUserStatsBy(Long accountId) {
return _userStatsDao.listBy(accountId);
}
}

View File

@ -27,10 +27,6 @@ import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.serializer.SerializerHelper;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
@ -365,6 +361,7 @@ public abstract class BaseCmd {
}
}
@SuppressWarnings("rawtypes")
private void writeObjectArray(String responseType, StringBuffer sb, int propertyCount, String tagName, Object[] subObjects) {
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
String separator = ((propertyCount > 0) ? ", " : "");
@ -383,6 +380,7 @@ public abstract class BaseCmd {
}
}
@SuppressWarnings("rawtypes")
private void writeSubObject(StringBuffer sb, String tagName, List tagList, String responseType, int objectCount) {
if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
sb.append(((objectCount == 0) ? "\"" + tagName + "\" : [ { " : ", { "));
@ -447,65 +445,6 @@ public abstract class BaseCmd {
return str.replace("\"", "\\\"");
}
protected long waitInstanceCreation(long jobId) {
ManagementServer mgr = getManagementServer();
long instanceId = 0;
AsyncJobVO job = null;
boolean interruped = false;
// as job may be executed in other management server, we need to do a database polling here
try {
boolean quit = false;
while(!quit) {
job = mgr.findAsyncJobById(jobId);
if(job == null) {
s_logger.error("Async command " + this.getClass().getName() + " waitInstanceCreation error: job-" + jobId + " no longer exists");
break;
}
switch(job.getStatus()) {
case AsyncJobResult.STATUS_IN_PROGRESS :
if(job.getProcessStatus() == BaseCmd.PROGRESS_INSTANCE_CREATED) {
Long id = (Long)SerializerHelper.fromSerializedString(job.getResult());
if(id != null) {
instanceId = id.longValue();
if(s_logger.isDebugEnabled())
s_logger.debug("Async command " + this.getClass().getName() + " succeeded in waiting for new instance to be created, instance Id: " + instanceId);
} else {
s_logger.warn("Async command " + this.getClass().getName() + " has new instance created, but value as null?");
}
quit = true;
}
break;
case AsyncJobResult.STATUS_SUCCEEDED :
instanceId = getInstanceIdFromJobSuccessResult(job.getResult());
quit = true;
break;
case AsyncJobResult.STATUS_FAILED :
s_logger.error("Async command " + this.getClass().getName() + " executing job-" + jobId + " failed, result: " + job.getResult());
quit = true;
break;
}
if(quit)
break;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
interruped = true;
}
}
} finally {
if(interruped)
Thread.currentThread().interrupt();
}
return instanceId;
}
protected long getInstanceIdFromJobSuccessResult(String result) {
s_logger.debug("getInstanceIdFromJobSuccessResult not overridden in subclass " + this.getClass().getName());
return 0;
@ -516,62 +455,4 @@ public abstract class BaseCmd {
(accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) ||
(accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN));
}
private Account getAccount(Map<String, Object> params) throws ServerApiException {
// FIXME: This should go into the context!
Long domainId = (Long) params.get("domainid");
Account account = (Account)params.get("accountobj");
String accountName = (String) params.get("account");
Long accountId = null;
Account finalAccount = null;
ManagementServer managementServer = getManagementServer();
if ((account == null) || isAdmin(account.getType())) {
if (domainId != null) {
if ((account != null) && !managementServer.isChildDomain(account.getDomainId(), domainId)) {
throw new ServerApiException(PARAM_ERROR, "Invalid domain id (" + domainId + ") ");
}
if (accountName != null) {
Account userAccount = managementServer.findActiveAccount(accountName, domainId);
if (userAccount == null) {
throw new ServerApiException(PARAM_ERROR, "Unable to find account " + accountName + " in domain " + domainId);
}
accountId = userAccount.getId();
}
} else {
accountId = ((account != null) ? account.getId() : null);
}
} else {
accountId = account.getId();
}
if (accountId != null) {
finalAccount = managementServer.findAccountById(accountId);
}
return finalAccount;
}
protected Long checkAccountPermissions(Map<String, Object> params,
long targetAccountId,
long targetDomainId,
String targetDesc,
long targetId)
throws ServerApiException
{
Long accountId = null;
Account account = getAccount(params);
if (account != null) {
if (!isAdmin(account.getType())) {
if (account.getId().longValue() != targetAccountId) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to find a " + targetDesc + " with id " + targetId + " for this account");
}
} else if (!getManagementServer().isChildDomain(account.getDomainId(), targetDomainId)) {
throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to perform operation for " + targetDesc + " with id " + targetId + ", permission denied.");
}
accountId = account.getId();
}
return accountId;
}
}

View File

@ -22,10 +22,12 @@ import org.apache.log4j.Logger;
import com.cloud.api.BaseAsyncCreateCmd;
import com.cloud.api.BaseCmd.Manager;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.Implementation;
import com.cloud.api.Parameter;
import com.cloud.api.response.VolumeResponse;
import com.cloud.serializer.SerializerHelper;
import com.cloud.storage.DiskOfferingVO;
import com.cloud.storage.VolumeVO;
@Implementation(createMethod="createVolumeDB", method="createVolume", manager=Manager.StorageManager)
@ -116,20 +118,22 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd {
response.setSize(volume.getSize());
response.setCreated(volume.getCreated());
response.setState(volume.getStatus().toString());
response.setAccountName(ggetManagementServer().findAccountById(volume.getAccountId()).getAccountName());
response.setAccountName(ApiDBUtils.findAccountById(volume.getAccountId()).getAccountName());
response.setDomainId(volume.getDomainId());
response.setDiskOfferingId(volume.getDiskOfferingId());
if (volume.getDiskOfferingId() != null) {
response.setDiskOfferingName(getManagementServer().findDiskOfferingById(volume.getDiskOfferingId()).getName());
response.setDiskOfferingDisplayText(getManagementServer().findDiskOfferingById(volume.getDiskOfferingId()).getDisplayText());
DiskOfferingVO diskOffering = ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId());
response.setDiskOfferingName(diskOffering.getName());
response.setDiskOfferingDisplayText(diskOffering.getDisplayText());
}
response.setDomain(getManagementServer().findDomainIdById(volume.getDomainId()).getName());
response.setDomainName(ApiDBUtils.findDomainById(volume.getDomainId()).getName());
response.setStorageType("shared"); // NOTE: You can never create a local disk volume but if that changes, we need to change this
if (volume.getPoolId() != null)
response.setStorage(getManagementServer().findPoolById(volume.getPoolId()).getName());
if (volume.getPoolId() != null) {
response.setStoragePoolName(ApiDBUtils.findStoragePoolById(volume.getPoolId()).getName());
}
response.setZoneId(volume.getDataCenterId());
response.setZoneName(getManagementServer().getDataCenterBy(volume.getDataCenterId()).getName());
response.setZoneName(ApiDBUtils.findZoneById(volume.getDataCenterId()).getName());
return SerializerHelper.toSerializedString(response);
}

View File

@ -24,6 +24,7 @@ import java.util.List;
import org.apache.log4j.Logger;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.BaseCmd;
import com.cloud.api.BaseListCmd;
import com.cloud.api.Implementation;
@ -125,10 +126,10 @@ public class ListAccountsCmd extends BaseListCmd {
acctResponse.setName(account.getAccountName());
acctResponse.setAccountType(account.getType());
acctResponse.setDomainId(account.getDomainId());
acctResponse.setDomainName(getManagementServer().findDomainIdById(account.getDomainId()).getName());
acctResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName());
//get network stat
List<UserStatisticsVO> stats = getManagementServer().listUserStatsBy(account.getId());
List<UserStatisticsVO> stats = ApiDBUtils.listUserStatsBy(account.getId());
if (stats == null) {
throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats");
}
@ -146,41 +147,41 @@ public class ListAccountsCmd extends BaseListCmd {
// Get resource limits and counts
long vmLimit = getManagementServer().findCorrectResourceLimit(ResourceType.user_vm, account.getId());
long vmLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.user_vm, account.getId());
String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit);
long vmTotal = getManagementServer().getResourceCount(ResourceType.user_vm, account.getId());
long vmTotal = ApiDBUtils.getResourceCount(ResourceType.user_vm, account.getId());
String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal);
acctResponse.setVmLimit(vmLimitDisplay);
acctResponse.setVmTotal(vmTotal);
acctResponse.setVmAvailable(vmAvail);
long ipLimit = getManagementServer().findCorrectResourceLimit(ResourceType.public_ip, account.getId());
long ipLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.public_ip, account.getId());
String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit);
long ipTotal = getManagementServer().getResourceCount(ResourceType.public_ip, account.getId());
long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId());
String ipAvail = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit - ipTotal);
acctResponse.setIpLimit(ipLimitDisplay);
acctResponse.setIpTotal(ipTotal);
acctResponse.setIpAvailable(ipAvail);
long volumeLimit = getManagementServer().findCorrectResourceLimit(ResourceType.volume, account.getId());
long volumeLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.volume, account.getId());
String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit);
long volumeTotal = getManagementServer().getResourceCount(ResourceType.volume, account.getId());
long volumeTotal = ApiDBUtils.getResourceCount(ResourceType.volume, account.getId());
String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal);
acctResponse.setVolumeLimit(volumeLimitDisplay);
acctResponse.setVolumeTotal(volumeTotal);
acctResponse.setVolumeAvailable(volumeAvail);
long snapshotLimit = getManagementServer().findCorrectResourceLimit(ResourceType.snapshot, account.getId());
long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.snapshot, account.getId());
String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit);
long snapshotTotal = getManagementServer().getResourceCount(ResourceType.snapshot, account.getId());
long snapshotTotal = ApiDBUtils.getResourceCount(ResourceType.snapshot, account.getId());
String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal);
acctResponse.setSnapshotLimit(snapshotLimitDisplay);
acctResponse.setSnapshotTotal(snapshotTotal);
acctResponse.setSnapshotAvailable(snapshotAvail);
long templateLimit = getManagementServer().findCorrectResourceLimit(ResourceType.template, account.getId());
long templateLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.template, account.getId());
String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit);
long templateTotal = getManagementServer().getResourceCount(ResourceType.template, account.getId());
long templateTotal = ApiDBUtils.getResourceCount(ResourceType.template, account.getId());
String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal);
acctResponse.setTemplateLimit(templateLimitDisplay);
acctResponse.setTemplateTotal(templateTotal);
@ -195,7 +196,7 @@ public class ListAccountsCmd extends BaseListCmd {
Criteria c1 = new Criteria();
c1.addCriteria(Criteria.ACCOUNTID, accountIds);
List<? extends UserVm> virtualMachines = getManagementServer().searchForUserVMs(c1);
List<? extends UserVm> virtualMachines = ApiDBUtils.searchForUserVMs(c1);
//get Running/Stopped VMs
for (Iterator<? extends UserVm> iter = virtualMachines.iterator(); iter.hasNext();) {

View File

@ -90,7 +90,6 @@ import com.cloud.async.AsyncJobResult;
import com.cloud.async.AsyncJobVO;
import com.cloud.capacity.CapacityVO;
import com.cloud.configuration.ConfigurationVO;
import com.cloud.configuration.ResourceCount.ResourceType;
import com.cloud.configuration.ResourceLimitVO;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.DataCenterIpAddressVO;
@ -137,7 +136,6 @@ import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserAccount;
import com.cloud.user.UserAccountVO;
import com.cloud.user.UserStatisticsVO;
import com.cloud.uservm.UserVm;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.ExecutionException;
@ -634,13 +632,6 @@ public interface ManagementServer {
*/
User getUser(long userId, boolean active);
/**
* Obtains a list of user statistics for the specified user ID.
* @param userId
* @return List of UserStatistics
*/
List<UserStatisticsVO> listUserStatsBy(Long userId);
/**
* Obtains a list of virtual machines that are similar to the VM with the specified name.
* @param vmInstanceName
@ -1069,21 +1060,6 @@ public interface ManagementServer {
*/
ResourceLimitVO findLimitById(long limitId);
/**
* Finds the correct limit for an account. I.e. if an account's limit is not present, it will check the account's domain, and as a last resort use the global limit.
* @param type
* @param accountId
*/
long findCorrectResourceLimit(ResourceType type, long accountId);
/**
* Gets the count of resources for a resource type and account
* @param Type
* @param accountId
* @return count of resources
*/
long getResourceCount(ResourceType type, long accountId);
/**
* Lists ISOs that are available for the specified account ID.
* @param accountId

View File

@ -3376,29 +3376,6 @@ public class ManagementServerImpl implements ManagementServer {
return _resourceLimitDao.findById(limitId);
}
@Override
public long findCorrectResourceLimit(ResourceType type, long accountId) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
return -1;
}
return _accountMgr.findCorrectResourceLimit(account, type);
}
@Override
public long getResourceCount(ResourceType type, long accountId) {
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
return -1;
}
return _accountMgr.getResourceCount(account, type);
}
@Override
public List<VMTemplateVO> listIsos(Criteria c) {
Filter searchFilter = new Filter(VMTemplateVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit());
@ -3432,11 +3409,6 @@ public class ManagementServerImpl implements ManagementServer {
return _templateDao.search(sc, searchFilter);
}
@Override
public List<UserStatisticsVO> listUserStatsBy(Long accountId) {
return _userStatsDao.listBy(accountId);
}
@Override
public List<VMInstanceVO> findVMInstancesLike(String vmInstanceName) {
return _vmInstanceDao.findVMInstancesLike(vmInstanceName);