use of com.cloud.projects.Project in project cloudstack by apache.
the class ApiResponseHelper method populateAccount.
private void populateAccount(ControlledEntityResponse response, long accountId) {
Account account = ApiDBUtils.findAccountById(accountId);
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
// find the project
Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
response.setProjectId(project.getUuid());
response.setProjectName(project.getName());
response.setAccountName(account.getAccountName());
} else {
response.setAccountName(account.getAccountName());
}
}
use of com.cloud.projects.Project in project cloudstack by apache.
the class ApiResponseHelper method populateOwner.
// TODO: we may need to refactor once ControlledEntityResponse and
// ControlledEntity id to uuid conversion are all done.
// currently code is scattered in
private void populateOwner(ControlledEntityResponse response, ControlledEntity object) {
Account account = ApiDBUtils.findAccountById(object.getAccountId());
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
// find the project
Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
response.setProjectId(project.getUuid());
response.setProjectName(project.getName());
} else {
response.setAccountName(account.getAccountName());
}
Domain domain = ApiDBUtils.findDomainById(object.getDomainId());
response.setDomainId(domain.getUuid());
response.setDomainName(domain.getName());
}
use of com.cloud.projects.Project in project cloudstack by apache.
the class TemplateManagerImpl method updateTemplateOrIsoPermissions.
@DB
@Override
public boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd) {
// Input validation
final Long id = cmd.getId();
final Account caller = CallContext.current().getCallingAccount();
List<String> accountNames = cmd.getAccountNames();
List<Long> projectIds = cmd.getProjectIds();
Boolean isFeatured = cmd.isFeatured();
Boolean isPublic = cmd.isPublic();
Boolean isExtractable = cmd.isExtractable();
String operation = cmd.getOperation();
String mediaType = "";
VMTemplateVO template = _tmpltDao.findById(id);
if (template == null) {
throw new InvalidParameterValueException("unable to find " + mediaType + " with id " + id);
}
if (cmd instanceof UpdateTemplatePermissionsCmd) {
mediaType = "template";
if (template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Please provide a valid template");
}
}
if (cmd instanceof UpdateIsoPermissionsCmd) {
mediaType = "iso";
if (!template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Please provide a valid iso");
}
}
// convert projectIds to accountNames
if (projectIds != null) {
// CS-17842, initialize accountNames list
if (accountNames == null) {
accountNames = new ArrayList<String>();
}
for (Long projectId : projectIds) {
Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by id " + projectId);
}
if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
throw new InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId);
}
accountNames.add(_accountMgr.getAccount(project.getProjectAccountId()).getAccountName());
}
}
//_accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
//TODO: should we replace all ModifyEntry as OperateEntry?
_accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
// If the template is removed throw an error.
if (template.getRemoved() != null) {
s_logger.error("unable to update permissions for " + mediaType + " with id " + id + " as it is removed ");
throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id + " as it is removed ");
}
if (id.equals(Long.valueOf(1))) {
throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id);
}
boolean isAdmin = _accountMgr.isAdmin(caller.getId());
// check configuration parameter(allow.public.user.templates) value for
// the template owner
boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(template.getAccountId());
if (!isAdmin && !allowPublicUserTemplates && isPublic != null && isPublic) {
throw new InvalidParameterValueException("Only private " + mediaType + "s can be created.");
}
if (accountNames != null) {
if ((operation == null) || (!operation.equalsIgnoreCase("add") && !operation.equalsIgnoreCase("remove") && !operation.equalsIgnoreCase("reset"))) {
throw new InvalidParameterValueException("Invalid operation on accounts, the operation must be either 'add' or 'remove' in order to modify launch permissions." + " Given operation is: '" + operation + "'");
}
}
Long ownerId = template.getAccountId();
if (ownerId == null) {
// publishing to individual users is irrelevant
throw new InvalidParameterValueException("Update template permissions is an invalid operation on template " + template.getName());
}
//Only admin or owner of the template should be able to change its permissions
if (caller.getId() != ownerId && !isAdmin) {
throw new InvalidParameterValueException("Unable to grant permission to account " + caller.getAccountName() + " as it is neither admin nor owner or the template");
}
VMTemplateVO updatedTemplate = _tmpltDao.createForUpdate();
if (isPublic != null) {
updatedTemplate.setPublicTemplate(isPublic.booleanValue());
}
if (isFeatured != null) {
updatedTemplate.setFeatured(isFeatured.booleanValue());
}
if (isExtractable != null) {
// Only Root admins allowed to change it for templates
if (!template.getFormat().equals(ImageFormat.ISO) && !_accountMgr.isRootAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only ROOT admins are allowed to modify isExtractable attribute.");
} else {
// For Isos normal user can change it, as their are no derivatives.
updatedTemplate.setExtractable(isExtractable.booleanValue());
}
}
_tmpltDao.update(template.getId(), updatedTemplate);
//when operation is add/remove, accountNames can not be null
if (("add".equalsIgnoreCase(operation) || "remove".equalsIgnoreCase(operation)) && accountNames == null) {
throw new InvalidParameterValueException("Operation " + operation + " requires accounts or projectIds to be passed in");
}
//Derive the domain id from the template owner as updateTemplatePermissions is not cross domain operation
Account owner = _accountMgr.getAccount(ownerId);
final Domain domain = _domainDao.findById(owner.getDomainId());
if ("add".equalsIgnoreCase(operation)) {
final List<String> accountNamesFinal = accountNames;
final List<Long> accountIds = new ArrayList<Long>();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (String accountName : accountNamesFinal) {
Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
if (permittedAccount != null) {
if (permittedAccount.getId() == caller.getId()) {
// don't grant permission to the template
continue;
// owner, they implicitly have permission
}
accountIds.add(permittedAccount.getId());
LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
if (existingPermission == null) {
LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
_launchPermissionDao.persist(launchPermission);
}
} else {
throw new InvalidParameterValueException("Unable to grant a launch permission to account " + accountName + " in domain id=" + domain.getUuid() + ", account not found. " + "No permissions updated, please verify the account names and retry.");
}
}
}
});
// add ACL permission in IAM
Map<String, Object> permit = new HashMap<String, Object>();
permit.put(ApiConstants.ENTITY_TYPE, VirtualMachineTemplate.class);
permit.put(ApiConstants.ENTITY_ID, id);
permit.put(ApiConstants.ACCESS_TYPE, AccessType.UseEntry);
permit.put(ApiConstants.IAM_ACTION, "listTemplates");
permit.put(ApiConstants.ACCOUNTS, accountIds);
_messageBus.publish(_name, EntityManager.MESSAGE_GRANT_ENTITY_EVENT, PublishScope.LOCAL, permit);
} else if ("remove".equalsIgnoreCase(operation)) {
List<Long> accountIds = new ArrayList<Long>();
for (String accountName : accountNames) {
Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
if (permittedAccount != null) {
accountIds.add(permittedAccount.getId());
}
}
_launchPermissionDao.removePermissions(id, accountIds);
// remove ACL permission in IAM
Map<String, Object> permit = new HashMap<String, Object>();
permit.put(ApiConstants.ENTITY_TYPE, VirtualMachineTemplate.class);
permit.put(ApiConstants.ENTITY_ID, id);
permit.put(ApiConstants.ACCESS_TYPE, AccessType.UseEntry);
permit.put(ApiConstants.IAM_ACTION, "listTemplates");
permit.put(ApiConstants.ACCOUNTS, accountIds);
_messageBus.publish(_name, EntityManager.MESSAGE_REVOKE_ENTITY_EVENT, PublishScope.LOCAL, permit);
} else if ("reset".equalsIgnoreCase(operation)) {
// do we care whether the owning account is an admin? if the
// owner is an admin, will we still set public to false?
updatedTemplate = _tmpltDao.createForUpdate();
updatedTemplate.setPublicTemplate(false);
updatedTemplate.setFeatured(false);
_tmpltDao.update(template.getId(), updatedTemplate);
_launchPermissionDao.removeAllPermissions(id);
_messageBus.publish(_name, TemplateManager.MESSAGE_RESET_TEMPLATE_PERMISSION_EVENT, PublishScope.LOCAL, template.getId());
}
return true;
}
use of com.cloud.projects.Project in project cloudstack by apache.
the class NetworkServiceImpl method searchForNetworks.
@Override
public Pair<List<? extends Network>, Integer> searchForNetworks(ListNetworksCmd cmd) {
Long id = cmd.getId();
String keyword = cmd.getKeyword();
Long zoneId = cmd.getZoneId();
Account caller = CallContext.current().getCallingAccount();
Long domainId = cmd.getDomainId();
String accountName = cmd.getAccountName();
String guestIpType = cmd.getGuestIpType();
String trafficType = cmd.getTrafficType();
Boolean isSystem = cmd.getIsSystem();
String aclType = cmd.getAclType();
Long projectId = cmd.getProjectId();
List<Long> permittedAccounts = new ArrayList<Long>();
String path = null;
Long physicalNetworkId = cmd.getPhysicalNetworkId();
List<String> supportedServicesStr = cmd.getSupportedServices();
Boolean restartRequired = cmd.getRestartRequired();
boolean listAll = cmd.listAll();
boolean isRecursive = cmd.isRecursive();
Boolean specifyIpRanges = cmd.getSpecifyIpRanges();
Long vpcId = cmd.getVpcId();
Boolean canUseForDeploy = cmd.canUseForDeploy();
Map<String, String> tags = cmd.getTags();
Boolean forVpc = cmd.getForVpc();
Boolean display = cmd.getDisplay();
// 2) reset parameter to false if it's specified by the regular user
if ((isSystem == null || _accountMgr.isNormalUser(caller.getId())) && id == null) {
isSystem = false;
}
// Account/domainId parameters and isSystem are mutually exclusive
if (isSystem != null && isSystem && (accountName != null || domainId != null)) {
throw new InvalidParameterValueException("System network belongs to system, account and domainId parameters can't be specified");
}
if (domainId != null) {
DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
// see DomainVO.java
throw new InvalidParameterValueException("Specified domain id doesn't exist in the system");
}
_accountMgr.checkAccess(caller, domain);
if (accountName != null) {
Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
if (owner == null) {
// see DomainVO.java
throw new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain");
}
_accountMgr.checkAccess(caller, null, true, owner);
permittedAccounts.add(owner.getId());
}
}
if (!_accountMgr.isAdmin(caller.getId()) || (projectId != null && projectId.longValue() != -1 && domainId == null)) {
permittedAccounts.add(caller.getId());
domainId = caller.getDomainId();
}
// set project information
boolean skipProjectNetworks = true;
if (projectId != null) {
if (projectId.longValue() == -1) {
if (!_accountMgr.isAdmin(caller.getId())) {
permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId()));
}
} else {
permittedAccounts.clear();
Project project = _projectMgr.getProject(projectId);
if (project == null) {
throw new InvalidParameterValueException("Unable to find project by specified id");
}
if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
// getProject() returns type ProjectVO.
InvalidParameterValueException ex = new InvalidParameterValueException("Account " + caller + " cannot access specified project id");
ex.addProxyObject(project.getUuid(), "projectId");
throw ex;
}
//add project account
permittedAccounts.add(project.getProjectAccountId());
//add caller account (if admin)
if (_accountMgr.isAdmin(caller.getId())) {
permittedAccounts.add(caller.getId());
}
}
skipProjectNetworks = false;
}
if (domainId != null) {
path = _domainDao.findById(domainId).getPath();
} else {
path = _domainDao.findById(caller.getDomainId()).getPath();
}
if (listAll && domainId == null) {
isRecursive = true;
}
Filter searchFilter = new Filter(NetworkVO.class, "id", false, null, null);
SearchBuilder<NetworkVO> sb = _networksDao.createSearchBuilder();
if (forVpc != null) {
if (forVpc) {
sb.and("vpc", sb.entity().getVpcId(), Op.NNULL);
} else {
sb.and("vpc", sb.entity().getVpcId(), Op.NULL);
}
}
// Don't display networks created of system network offerings
SearchBuilder<NetworkOfferingVO> networkOfferingSearch = _networkOfferingDao.createSearchBuilder();
networkOfferingSearch.and("systemOnly", networkOfferingSearch.entity().isSystemOnly(), SearchCriteria.Op.EQ);
if (isSystem != null && isSystem) {
networkOfferingSearch.and("trafficType", networkOfferingSearch.entity().getTrafficType(), SearchCriteria.Op.EQ);
}
sb.join("networkOfferingSearch", networkOfferingSearch, sb.entity().getNetworkOfferingId(), networkOfferingSearch.entity().getId(), JoinBuilder.JoinType.INNER);
SearchBuilder<DataCenterVO> zoneSearch = _dcDao.createSearchBuilder();
zoneSearch.and("networkType", zoneSearch.entity().getNetworkType(), SearchCriteria.Op.EQ);
sb.join("zoneSearch", zoneSearch, sb.entity().getDataCenterId(), zoneSearch.entity().getId(), JoinBuilder.JoinType.INNER);
sb.and("removed", sb.entity().getRemoved(), Op.NULL);
if (tags != null && !tags.isEmpty()) {
SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
if (permittedAccounts.isEmpty()) {
SearchBuilder<DomainVO> domainSearch = _domainDao.createSearchBuilder();
domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE);
sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
SearchBuilder<AccountVO> accountSearch = _accountDao.createSearchBuilder();
accountSearch.and("typeNEQ", accountSearch.entity().getType(), SearchCriteria.Op.NEQ);
accountSearch.and("typeEQ", accountSearch.entity().getType(), SearchCriteria.Op.EQ);
sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER);
List<NetworkVO> networksToReturn = new ArrayList<NetworkVO>();
if (isSystem == null || !isSystem) {
if (!permittedAccounts.isEmpty()) {
//get account level networks
networksToReturn.addAll(listAccountSpecificNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, permittedAccounts));
//get domain level networks
if (domainId != null) {
networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, domainId, false));
}
} else {
//add account specific networks
networksToReturn.addAll(listAccountSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
//add domain specific networks of domain + parent domains
networksToReturn.addAll(listDomainSpecificNetworksByDomainPath(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, path, isRecursive));
//add networks of subdomains
if (domainId == null) {
networksToReturn.addAll(listDomainLevelNetworks(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, aclType, true, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter, caller.getDomainId(), true));
}
}
} else {
networksToReturn = _networksDao.search(buildNetworkSearchCriteria(sb, keyword, id, isSystem, zoneId, guestIpType, trafficType, physicalNetworkId, null, skipProjectNetworks, restartRequired, specifyIpRanges, vpcId, tags, display), searchFilter);
}
if (supportedServicesStr != null && !supportedServicesStr.isEmpty() && !networksToReturn.isEmpty()) {
List<NetworkVO> supportedNetworks = new ArrayList<NetworkVO>();
Service[] suppportedServices = new Service[supportedServicesStr.size()];
int i = 0;
for (String supportedServiceStr : supportedServicesStr) {
Service service = Service.getService(supportedServiceStr);
if (service == null) {
throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
} else {
suppportedServices[i] = service;
}
i++;
}
for (NetworkVO network : networksToReturn) {
if (areServicesSupportedInNetwork(network.getId(), suppportedServices)) {
supportedNetworks.add(network);
}
}
networksToReturn = supportedNetworks;
}
if (canUseForDeploy != null) {
List<NetworkVO> networksForDeploy = new ArrayList<NetworkVO>();
for (NetworkVO network : networksToReturn) {
if (_networkModel.canUseForDeploy(network) == canUseForDeploy) {
networksForDeploy.add(network);
}
}
networksToReturn = networksForDeploy;
}
//Now apply pagination
List<? extends Network> wPagination = StringUtils.applyPagination(networksToReturn, cmd.getStartIndex(), cmd.getPageSizeVal());
if (wPagination != null) {
Pair<List<? extends Network>, Integer> listWPagination = new Pair<List<? extends Network>, Integer>(wPagination, networksToReturn.size());
return listWPagination;
}
return new Pair<List<? extends Network>, Integer>(networksToReturn, networksToReturn.size());
}
use of com.cloud.projects.Project in project cloudstack by apache.
the class ActivateProjectCmd method execute.
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() {
CallContext.current().setEventDetails("Project id: " + getId());
Project project = _projectService.activateProject(getId());
if (project != null) {
ProjectResponse response = _responseGenerator.createProjectResponse(project);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to activate a project");
}
}
Aggregations