use of com.cloud.utils.db.TransactionCallbackNoReturn in project cloudstack by apache.
the class NetscalerElement method configureNetscalerLoadBalancer.
@DB
private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(final long lbDeviceId, Long capacity, Boolean dedicatedUse, List<Long> newPodsConfig) {
final ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId);
final Map<String, String> lbDetails = _detailsDao.findDetails(lbDeviceVo.getHostId());
if ((lbDeviceVo == null) || !isNetscalerDevice(lbDeviceVo.getDeviceName())) {
throw new InvalidParameterValueException("No netscaler device found with ID: " + lbDeviceId);
}
List<Long> currentPodsConfig = new ArrayList<Long>();
List<NetScalerPodVO> currentPodVOs = _netscalerPodDao.listByNetScalerDeviceId(lbDeviceVo.getId());
if (currentPodVOs != null && currentPodVOs.size() > 0) {
for (NetScalerPodVO nsPodVo : currentPodVOs) {
currentPodsConfig.add(nsPodVo.getPodId());
}
}
final List<Long> podsToAssociate = new ArrayList<Long>();
if (newPodsConfig != null && newPodsConfig.size() > 0) {
for (Long podId : newPodsConfig) {
HostPodVO pod = _podDao.findById(podId);
if (pod == null) {
throw new InvalidParameterValueException("Can't find pod by id " + podId);
}
}
for (Long podId : newPodsConfig) {
if (!currentPodsConfig.contains(podId)) {
podsToAssociate.add(podId);
}
}
}
final List<Long> podsToDeassociate = new ArrayList<Long>();
for (Long podId : currentPodsConfig) {
if (!newPodsConfig.contains(podId)) {
podsToDeassociate.add(podId);
}
}
String deviceName = lbDeviceVo.getDeviceName();
if (dedicatedUse != null || capacity != null) {
if (NetworkDevice.NetscalerSDXLoadBalancer.getName().equalsIgnoreCase(deviceName) || NetworkDevice.NetscalerMPXLoadBalancer.getName().equalsIgnoreCase(deviceName)) {
if (dedicatedUse != null && dedicatedUse == true) {
throw new InvalidParameterValueException("Netscaler MPX and SDX device should be shared and can not be dedicated to a single account.");
}
}
// check if any networks are using this netscaler device
List<NetworkExternalLoadBalancerVO> networks = _networkLBDao.listByLoadBalancerDeviceId(lbDeviceId);
if ((networks != null) && !networks.isEmpty()) {
if (capacity != null && capacity < networks.size()) {
throw new CloudRuntimeException("There are more number of networks already using this netscaler device than configured capacity");
}
if (dedicatedUse != null && dedicatedUse == true) {
throw new CloudRuntimeException("There are networks already using this netscaler device to make device dedicated");
}
}
}
if (!NetworkDevice.NetscalerSDXLoadBalancer.getName().equalsIgnoreCase(deviceName)) {
if (capacity != null) {
lbDeviceVo.setCapacity(capacity);
}
} else {
// FIXME how to interpret configured capacity of the SDX device
}
if (dedicatedUse != null) {
lbDeviceVo.setIsDedicatedDevice(dedicatedUse);
}
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_lbDeviceDao.update(lbDeviceId, lbDeviceVo);
for (Long podId : podsToAssociate) {
NetScalerPodVO nsPodVo = new NetScalerPodVO(lbDeviceId, podId);
_netscalerPodDao.persist(nsPodVo);
}
for (Long podId : podsToDeassociate) {
NetScalerPodVO nsPodVo = _netscalerPodDao.findByPodId(podId);
_netscalerPodDao.remove(nsPodVo.getId());
}
// FIXME get the row lock to avoid race condition
_detailsDao.persist(lbDeviceVo.getHostId(), lbDetails);
}
});
HostVO host = _hostDao.findById(lbDeviceVo.getHostId());
_agentMgr.reconnect(host.getId());
return lbDeviceVo;
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cloudstack by apache.
the class DirectNetworkGuru method trash.
@Override
@DB
public boolean trash(Network network, NetworkOffering offering) {
//Have to remove all placeholder nics
try {
long id = network.getId();
final List<NicVO> nics = _nicDao.listPlaceholderNicsByNetworkId(id);
if (nics != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (Nic nic : nics) {
if (nic.getIPv4Address() != null) {
s_logger.debug("Releasing ip " + nic.getIPv4Address() + " of placeholder nic " + nic);
IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIPv4Address());
if (ip != null) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
s_logger.debug("Removing placeholder nic " + nic);
_nicDao.remove(nic.getId());
}
}
}
}
});
}
return true;
} catch (Exception e) {
s_logger.error("trash. Exception:" + e.getMessage());
throw new CloudRuntimeException("trash. Exception:" + e.getMessage(), e);
}
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method deleteLBHealthCheckPolicy.
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_HEALTHCHECKPOLICY_DELETE, eventDescription = "revoking LB HealthCheck policy ", async = true)
public boolean deleteLBHealthCheckPolicy(long healthCheckPolicyId, boolean apply) {
boolean success = true;
CallContext caller = CallContext.current();
LBHealthCheckPolicyVO healthCheckPolicy = _lb2healthcheckDao.findById(healthCheckPolicyId);
if (healthCheckPolicy == null) {
throw new InvalidParameterException("Invalid HealthCheck policy id value: " + healthCheckPolicyId);
}
LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(healthCheckPolicy.getLoadBalancerId()));
if (loadBalancer == null) {
throw new InvalidParameterException("Invalid Load balancer : " + healthCheckPolicy.getLoadBalancerId() + " for HealthCheck policy id: " + healthCheckPolicyId);
}
final long loadBalancerId = loadBalancer.getId();
FirewallRule.State backupState = loadBalancer.getState();
_accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
if (apply) {
if (loadBalancer.getState() == FirewallRule.State.Active) {
loadBalancer.setState(FirewallRule.State.Add);
_lbDao.persist(loadBalancer);
}
boolean backupStickyState = healthCheckPolicy.isRevoke();
healthCheckPolicy.setRevoke(true);
_lb2healthcheckDao.persist(healthCheckPolicy);
s_logger.debug("Set health check policy to revoke for loadbalancing rule id : " + loadBalancerId + ", healthCheckpolicyID " + healthCheckPolicyId);
// removing the state of services set by the monitor.
final List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
if (maps != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
s_logger.debug("Resetting health state policy for services in loadbalancing rule id : " + loadBalancerId);
for (LoadBalancerVMMapVO map : maps) {
map.setState(null);
_lb2VmMapDao.persist(map);
}
}
});
}
try {
if (!applyLoadBalancerConfig(loadBalancerId)) {
s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for healthCheckpolicyID " + healthCheckPolicyId);
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for healthCheckpolicyID " + healthCheckPolicyId);
}
} catch (ResourceUnavailableException e) {
if (isRollBackAllowedForProvider(loadBalancer)) {
healthCheckPolicy.setRevoke(backupStickyState);
_lb2healthcheckDao.persist(healthCheckPolicy);
loadBalancer.setState(backupState);
_lbDao.persist(loadBalancer);
s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while deleting healthcheck policy: " + healthCheckPolicyId);
}
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
success = false;
}
} else {
_lb2healthcheckDao.remove(healthCheckPolicy.getLoadBalancerId());
}
return success;
}
use of com.cloud.utils.db.TransactionCallbackNoReturn in project cloudstack by apache.
the class TaggedResourceManagerImpl method deleteTags.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TAGS_DELETE, eventDescription = "deleting resource tags")
public boolean deleteTags(List<String> resourceIds, ResourceObjectType resourceType, Map<String, String> tags) {
Account caller = CallContext.current().getCallingAccount();
SearchBuilder<ResourceTagVO> sb = _resourceTagDao.createSearchBuilder();
sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.IN);
sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.IN);
sb.cp();
sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ);
SearchCriteria<ResourceTagVO> sc = sb.create();
sc.setParameters("resourceId", resourceIds.toArray());
sc.setParameters("resourceUuid", resourceIds.toArray());
sc.setParameters("resourceType", resourceType);
List<? extends ResourceTag> resourceTags = _resourceTagDao.search(sc, null);
;
final List<ResourceTag> tagsToRemove = new ArrayList<ResourceTag>();
// Finalize which tags should be removed
for (ResourceTag resourceTag : resourceTags) {
//1) validate the permissions
Account owner = _accountMgr.getAccount(resourceTag.getAccountId());
_accountMgr.checkAccess(caller, null, false, owner);
//2) Only remove tag if it matches key value pairs
if (tags != null && !tags.isEmpty()) {
for (String key : tags.keySet()) {
boolean canBeRemoved = false;
if (resourceTag.getKey().equalsIgnoreCase(key)) {
String value = tags.get(key);
if (value != null) {
if (resourceTag.getValue().equalsIgnoreCase(value)) {
canBeRemoved = true;
}
} else {
canBeRemoved = true;
}
if (canBeRemoved) {
tagsToRemove.add(resourceTag);
break;
}
}
}
} else {
tagsToRemove.add(resourceTag);
}
}
if (tagsToRemove.isEmpty()) {
throw new InvalidParameterValueException("Unable to find tags by parameters specified");
}
//Remove the tags
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (ResourceTag tagToRemove : tagsToRemove) {
_resourceTagDao.remove(tagToRemove.getId());
s_logger.debug("Removed the tag " + tagToRemove);
}
}
});
return true;
}
use of com.cloud.utils.db.TransactionCallbackNoReturn 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;
}
Aggregations