use of com.cloud.vm.UserVmVO in project cloudstack by apache.
the class QueryManagerImpl method searchForSecurityGroupsInternal.
private Pair<List<SecurityGroupJoinVO>, Integer> searchForSecurityGroupsInternal(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException {
Account caller = CallContext.current().getCallingAccount();
Long instanceId = cmd.getVirtualMachineId();
String securityGroup = cmd.getSecurityGroupName();
Long id = cmd.getId();
Object keyword = cmd.getKeyword();
List<Long> permittedAccounts = new ArrayList<Long>();
Map<String, String> tags = cmd.getTags();
if (instanceId != null) {
UserVmVO userVM = _userVmDao.findById(instanceId);
if (userVM == null) {
throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found.");
}
_accountMgr.checkAccess(caller, null, true, userVM);
return listSecurityGroupRulesByVM(instanceId.longValue(), cmd.getStartIndex(), cmd.getPageSizeVal());
}
Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
_accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
Long domainId = domainIdRecursiveListProject.first();
Boolean isRecursive = domainIdRecursiveListProject.second();
ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
Filter searchFilter = new Filter(SecurityGroupJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
SearchBuilder<SecurityGroupJoinVO> sb = _securityGroupJoinDao.createSearchBuilder();
// select distinct
sb.select(null, Func.DISTINCT, sb.entity().getId());
// ids
_accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
SearchCriteria<SecurityGroupJoinVO> sc = sb.create();
_accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
if (id != null) {
sc.setParameters("id", id);
}
if (tags != null && !tags.isEmpty()) {
SearchCriteria<SecurityGroupJoinVO> tagSc = _securityGroupJoinDao.createSearchCriteria();
for (String key : tags.keySet()) {
SearchCriteria<SecurityGroupJoinVO> tsc = _securityGroupJoinDao.createSearchCriteria();
tsc.addAnd("tagKey", SearchCriteria.Op.EQ, key);
tsc.addAnd("tagValue", SearchCriteria.Op.EQ, tags.get(key));
tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
}
sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
}
if (securityGroup != null) {
sc.setParameters("name", securityGroup);
}
if (keyword != null) {
SearchCriteria<SecurityGroupJoinVO> ssc = _securityGroupJoinDao.createSearchCriteria();
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
// search security group together with rules
Pair<List<SecurityGroupJoinVO>, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter);
Integer count = uniqueSgPair.second();
if (count.intValue() == 0) {
// handle empty result cases
return uniqueSgPair;
}
List<SecurityGroupJoinVO> uniqueSgs = uniqueSgPair.first();
Long[] sgIds = new Long[uniqueSgs.size()];
int i = 0;
for (SecurityGroupJoinVO v : uniqueSgs) {
sgIds[i++] = v.getId();
}
List<SecurityGroupJoinVO> sgs = _securityGroupJoinDao.searchByIds(sgIds);
return new Pair<List<SecurityGroupJoinVO>, Integer>(sgs, count);
}
use of com.cloud.vm.UserVmVO in project cloudstack by apache.
the class QueryManagerImpl method searchForServiceOfferingsInternal.
private Pair<List<ServiceOfferingJoinVO>, Integer> searchForServiceOfferingsInternal(ListServiceOfferingsCmd cmd) {
// Note
// The filteredOfferings method for offerings is being modified in accordance with
// discussion with Will/Kevin
// For now, we will be listing the following based on the usertype
// 1. For root, we will filteredOfferings all offerings
// 2. For domainAdmin and regular users, we will filteredOfferings everything in
// their domains+parent domains ... all the way
// till
// root
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = (isAscending == null ? true : isAscending);
Filter searchFilter = new Filter(ServiceOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
Account caller = CallContext.current().getCallingAccount();
Object name = cmd.getServiceOfferingName();
Object id = cmd.getId();
Object keyword = cmd.getKeyword();
Long vmId = cmd.getVirtualMachineId();
Long domainId = cmd.getDomainId();
Boolean isSystem = cmd.getIsSystem();
String vmTypeStr = cmd.getSystemVmType();
ServiceOfferingVO currentVmOffering = null;
Boolean isRecursive = cmd.isRecursive();
SearchCriteria<ServiceOfferingJoinVO> sc = _srvOfferingJoinDao.createSearchCriteria();
if (!_accountMgr.isRootAdmin(caller.getId()) && isSystem) {
throw new InvalidParameterValueException("Only ROOT admins can access system's offering");
}
// domain
if (domainId != null && !_accountMgr.isRootAdmin(caller.getId())) {
// child of so's domain
if (!isPermissible(caller.getDomainId(), domainId)) {
throw new PermissionDeniedException("The account:" + caller.getAccountName() + " does not fall in the same domain hierarchy as the service offering");
}
}
if (vmId != null) {
VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if ((vmInstance == null) || (vmInstance.getRemoved() != null)) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find a virtual machine with specified id");
ex.addProxyObject(vmId.toString(), "vmId");
throw ex;
}
_accountMgr.checkAccess(caller, null, true, vmInstance);
currentVmOffering = _srvOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
sc.addAnd("id", SearchCriteria.Op.NEQ, currentVmOffering.getId());
// 1. Only return offerings with the same storage type
sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, currentVmOffering.getUseLocalStorage());
// 2.In case vm is running return only offerings greater than equal to current offering compute.
if (vmInstance.getState() == VirtualMachine.State.Running) {
sc.addAnd("cpu", Op.GTEQ, currentVmOffering.getCpu());
sc.addAnd("speed", Op.GTEQ, currentVmOffering.getSpeed());
sc.addAnd("ramSize", Op.GTEQ, currentVmOffering.getRamSize());
}
}
// boolean includePublicOfferings = false;
if ((_accountMgr.isNormalUser(caller.getId()) || _accountMgr.isDomainAdmin(caller.getId())) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// For non-root users.
if (isSystem) {
throw new InvalidParameterValueException("Only root admins can access system's offering");
}
if (isRecursive) {
// domain + all sub-domains
if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL)
throw new InvalidParameterValueException("Only ROOT admins and Domain admins can list service offerings with isrecursive=true");
DomainVO domainRecord = _domainDao.findById(caller.getDomainId());
sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domainRecord.getPath() + "%");
} else {
// domain + all ancestors
// find all domain Id up to root domain for this account
List<Long> domainIds = new ArrayList<Long>();
DomainVO domainRecord;
if (vmId != null) {
UserVmVO vmInstance = _userVmDao.findById(vmId);
domainRecord = _domainDao.findById(vmInstance.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for vmId:" + vmId);
throw new CloudAuthenticationException("Could not find the domainId for vmId:" + vmId);
}
} else {
domainRecord = _domainDao.findById(caller.getDomainId());
if (domainRecord == null) {
s_logger.error("Could not find the domainId for account:" + caller.getAccountName());
throw new CloudAuthenticationException("Could not find the domainId for account:" + caller.getAccountName());
}
}
domainIds.add(domainRecord.getId());
while (domainRecord.getParent() != null) {
domainRecord = _domainDao.findById(domainRecord.getParent());
domainIds.add(domainRecord.getId());
}
SearchCriteria<ServiceOfferingJoinVO> spc = _srvOfferingJoinDao.createSearchCriteria();
spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
// include public offering as well
spc.addOr("domainId", SearchCriteria.Op.NULL);
sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
}
} else {
// for root users
if (caller.getDomainId() != 1 && isSystem) {
// NON ROOT admin
throw new InvalidParameterValueException("Non ROOT admins cannot access system's offering");
}
if (domainId != null) {
sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
}
}
if (keyword != null) {
SearchCriteria<ServiceOfferingJoinVO> ssc = _srvOfferingJoinDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (isSystem != null) {
// note that for non-root users, isSystem is always false when
// control comes to here
sc.addAnd("systemUse", SearchCriteria.Op.EQ, isSystem);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (vmTypeStr != null) {
sc.addAnd("vmType", SearchCriteria.Op.EQ, vmTypeStr);
}
Pair<List<ServiceOfferingJoinVO>, Integer> result = _srvOfferingJoinDao.searchAndCount(sc, searchFilter);
//Couldn't figure out a smart way to filter offerings based on tags in sql so doing it in Java.
List<ServiceOfferingJoinVO> filteredOfferings = filterOfferingsOnCurrentTags(result.first(), currentVmOffering);
return new Pair<>(filteredOfferings, result.second());
}
use of com.cloud.vm.UserVmVO in project cloudstack by apache.
the class AffinityGroupServiceImpl method updateVMAffinityGroups.
@Override
public UserVm updateVMAffinityGroups(Long vmId, List<Long> affinityGroupIds) {
// Verify input parameters
UserVmVO vmInstance = _userVmDao.findById(vmId);
if (vmInstance == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
// Check that the VM is stopped
if (!vmInstance.getState().equals(State.Stopped)) {
s_logger.warn("Unable to update affinity groups of the virtual machine " + vmInstance.toString() + " in state " + vmInstance.getState());
throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before updating.");
}
Account caller = CallContext.current().getCallingAccount();
Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
// check that the affinity groups exist
for (Long affinityGroupId : affinityGroupIds) {
AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
if (ag == null) {
throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
} else {
// verify permissions
_accountMgr.checkAccess(caller, null, true, owner, ag);
// owner of these entities is same
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
if (ag.getAccountId() != owner.getAccountId()) {
throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's account");
}
}
}
}
_affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
}
// APIResponseHelper will pull out the updated affinitygroups.
return vmInstance;
}
use of com.cloud.vm.UserVmVO in project cloudstack by apache.
the class VMSnapshotManagerImpl method orchestrateRevertToVMSnapshot.
private UserVm orchestrateRevertToVMSnapshot(Long vmSnapshotId) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException {
// check if VM snapshot exists in DB
final VMSnapshotVO vmSnapshotVo = _vmSnapshotDao.findById(vmSnapshotId);
if (vmSnapshotVo == null) {
throw new InvalidParameterValueException("unable to find the vm snapshot with id " + vmSnapshotId);
}
Long vmId = vmSnapshotVo.getVmId();
final UserVmVO userVm = _userVMDao.findById(vmId);
// check if VM exists
if (userVm == null) {
throw new InvalidParameterValueException("Revert vm to snapshot: " + vmSnapshotId + " failed due to vm: " + vmId + " is not found");
}
// check if there are other active VM snapshot tasks
if (hasActiveVMSnapshotTasks(vmId)) {
throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later");
}
Account caller = getCaller();
_accountMgr.checkAccess(caller, null, true, vmSnapshotVo);
// VM should be in running or stopped states
if (userVm.getState() != VirtualMachine.State.Running && userVm.getState() != VirtualMachine.State.Stopped) {
throw new InvalidParameterValueException("VM Snapshot reverting failed due to vm is not in the state of Running or Stopped.");
}
// if snapshot is not created, error out
if (vmSnapshotVo.getState() != VMSnapshot.State.Ready) {
throw new InvalidParameterValueException("VM Snapshot reverting failed due to vm snapshot is not in the state of Created.");
}
UserVmVO vm = null;
Long hostId = null;
// start or stop VM first, if revert from stopped state to running state, or from running to stopped
if (userVm.getState() == VirtualMachine.State.Stopped && vmSnapshotVo.getType() == VMSnapshot.Type.DiskAndMemory) {
try {
_itMgr.advanceStart(userVm.getUuid(), new HashMap<VirtualMachineProfile.Param, Object>(), null);
vm = _userVMDao.findById(userVm.getId());
hostId = vm.getHostId();
} catch (Exception e) {
s_logger.error("Start VM " + userVm.getInstanceName() + " before reverting failed due to " + e.getMessage());
throw new CloudRuntimeException(e.getMessage());
}
} else {
if (userVm.getState() == VirtualMachine.State.Running && vmSnapshotVo.getType() == VMSnapshot.Type.Disk) {
try {
_itMgr.advanceStop(userVm.getUuid(), true);
} catch (Exception e) {
s_logger.error("Stop VM " + userVm.getInstanceName() + " before reverting failed due to " + e.getMessage());
throw new CloudRuntimeException(e.getMessage());
}
}
}
// check if there are other active VM snapshot tasks
if (hasActiveVMSnapshotTasks(userVm.getId())) {
throw new InvalidParameterValueException("There is other active vm snapshot tasks on the instance, please try again later");
}
try {
VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshotVo);
strategy.revertVMSnapshot(vmSnapshotVo);
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<CloudRuntimeException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws CloudRuntimeException {
revertUserVmDetailsFromVmSnapshot(userVm, vmSnapshotVo);
updateUserVmServiceOffering(userVm, vmSnapshotVo);
}
});
return userVm;
} catch (Exception e) {
s_logger.debug("Failed to revert vmsnapshot: " + vmSnapshotId, e);
throw new CloudRuntimeException(e.getMessage());
}
}
use of com.cloud.vm.UserVmVO in project cloudstack by apache.
the class VMSnapshotManagerImpl method orchestrateCreateVMSnapshot.
private VMSnapshot orchestrateCreateVMSnapshot(Long vmId, Long vmSnapshotId, Boolean quiescevm) {
UserVmVO userVm = _userVMDao.findById(vmId);
if (userVm == null) {
throw new InvalidParameterValueException("Create vm to snapshot failed due to vm: " + vmId + " is not found");
}
List<VolumeVO> volumeVos = _volumeDao.findByInstanceAndType(vmId, Type.ROOT);
if (volumeVos == null || volumeVos.isEmpty()) {
throw new CloudRuntimeException("Create vm to snapshot failed due to no root disk found");
}
VolumeVO rootVolume = volumeVos.get(0);
if (!rootVolume.getState().equals(Volume.State.Ready)) {
throw new CloudRuntimeException("Create vm to snapshot failed due to vm: " + vmId + " has root disk in " + rootVolume.getState() + " state");
}
VMSnapshotVO vmSnapshot = _vmSnapshotDao.findById(vmSnapshotId);
if (vmSnapshot == null) {
throw new CloudRuntimeException("VM snapshot id: " + vmSnapshotId + " can not be found");
}
VMSnapshotOptions options = new VMSnapshotOptions(quiescevm);
vmSnapshot.setOptions(options);
try {
VMSnapshotStrategy strategy = findVMSnapshotStrategy(vmSnapshot);
VMSnapshot snapshot = strategy.takeVMSnapshot(vmSnapshot);
return snapshot;
} catch (Exception e) {
s_logger.debug("Failed to create vm snapshot: " + vmSnapshotId, e);
return null;
}
}
Aggregations