use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.
the class GlobalLoadBalancingRulesServiceImpl method listGlobalLoadBalancerRule.
@Override
public List<GlobalLoadBalancerRule> listGlobalLoadBalancerRule(ListGlobalLoadBalancerRuleCmd listGslbCmd) {
CallContext ctx = CallContext.current();
Account caller = ctx.getCallingAccount();
Integer regionId = listGslbCmd.getRegionId();
Long ruleId = listGslbCmd.getId();
List<GlobalLoadBalancerRule> response = new ArrayList<GlobalLoadBalancerRule>();
if (regionId == null && ruleId == null) {
throw new InvalidParameterValueException("Invalid arguments. At least one of region id, " + "rule id must be specified");
}
if (regionId != null && ruleId != null) {
throw new InvalidParameterValueException("Invalid arguments. Only one of region id, " + "rule id must be specified");
}
if (ruleId != null) {
GlobalLoadBalancerRule gslbRule = _gslbRuleDao.findById(ruleId);
if (gslbRule == null) {
throw new InvalidParameterValueException("Invalid gslb rule id specified");
}
_accountMgr.checkAccess(caller, org.apache.cloudstack.acl.SecurityChecker.AccessType.UseEntry, false, gslbRule);
response.add(gslbRule);
return response;
}
if (regionId != null) {
List<GlobalLoadBalancerRuleVO> gslbRules = _gslbRuleDao.listByAccount(caller.getAccountId());
if (gslbRules != null) {
response.addAll(gslbRules);
}
return response;
}
return null;
}
use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.
the class ApiServer method queueCommand.
private String queueCommand(final BaseCmd cmdObj, final Map<String, String> params, StringBuilder log) throws Exception {
final CallContext ctx = CallContext.current();
final Long callerUserId = ctx.getCallingUserId();
final Account caller = ctx.getCallingAccount();
// BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned.
if (cmdObj instanceof BaseAsyncCmd) {
Long objectId = null;
String objectUuid = null;
if (cmdObj instanceof BaseAsyncCreateCmd) {
final BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
dispatcher.dispatchCreateCmd(createCmd, params);
objectId = createCmd.getEntityId();
objectUuid = createCmd.getEntityUuid();
params.put("id", objectId.toString());
Class entityClass = EventTypes.getEntityClassForEvent(createCmd.getEventType());
if (entityClass != null)
ctx.putContextParameter(entityClass, objectUuid);
} else {
// Extract the uuid before params are processed and id reflects internal db id
objectUuid = params.get(ApiConstants.ID);
dispatchChainFactory.getStandardDispatchChain().dispatch(new DispatchTask(cmdObj, params));
}
final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj;
if (callerUserId != null) {
params.put("ctxUserId", callerUserId.toString());
}
if (caller != null) {
params.put("ctxAccountId", String.valueOf(caller.getId()));
}
if (objectUuid != null) {
params.put("uuid", objectUuid);
}
long startEventId = ctx.getStartEventId();
asyncCmd.setStartEventId(startEventId);
// save the scheduled event
final Long eventId = ActionEventUtils.onScheduledActionEvent((callerUserId == null) ? (Long) User.UID_SYSTEM : callerUserId, asyncCmd.getEntityOwnerId(), asyncCmd.getEventType(), asyncCmd.getEventDescription(), asyncCmd.isDisplay(), startEventId);
if (startEventId == 0) {
// There was no create event before, set current event id as start eventId
startEventId = eventId;
}
params.put("ctxStartEventId", String.valueOf(startEventId));
params.put("cmdEventType", asyncCmd.getEventType().toString());
params.put("ctxDetails", ApiGsonHelper.getBuilder().create().toJson(ctx.getContextParameters()));
Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId;
// users can provide the job id they want to use, so log as it is a uuid and is unique
String injectedJobId = asyncCmd.getInjectedJobId();
uuidMgr.checkUuidSimple(injectedJobId, AsyncJob.class);
AsyncJobVO job = new AsyncJobVO("", callerUserId, caller.getId(), cmdObj.getClass().getName(), ApiGsonHelper.getBuilder().create().toJson(params), instanceId, asyncCmd.getInstanceType() != null ? asyncCmd.getInstanceType().toString() : null, injectedJobId);
job.setDispatcher(asyncDispatcher.getName());
final long jobId = asyncMgr.submitAsyncJob(job);
if (jobId == 0L) {
final String errorMsg = "Unable to schedule async job for command " + job.getCmd();
s_logger.warn(errorMsg);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
}
final String response;
if (objectId != null) {
final String objUuid = (objectUuid == null) ? objectId.toString() : objectUuid;
response = getBaseAsyncCreateResponse(jobId, (BaseAsyncCreateCmd) asyncCmd, objUuid);
} else {
SerializationContext.current().setUuidTranslation(true);
response = getBaseAsyncResponse(jobId, asyncCmd);
}
// Always log response for async for now, I don't think any sensitive data will be in here.
// It might be nice to send this through scrubbing similar to how
// ApiResponseSerializer.toSerializedStringWithSecureLogs works. For now, this gets jobid's
// in the api logs.
log.append(response);
return response;
} else {
dispatcher.dispatch(cmdObj, params, false);
// For those listXXXCommand which we have already created DB views, this step is not needed since async job is joined in their db views.
if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListVMsCmdByAdmin) && !(cmdObj instanceof ListRoutersCmd) && !(cmdObj instanceof ListSecurityGroupsCmd) && !(cmdObj instanceof ListTagsCmd) && !(cmdObj instanceof ListEventsCmd) && !(cmdObj instanceof ListVMGroupsCmd) && !(cmdObj instanceof ListProjectsCmd) && !(cmdObj instanceof ListProjectAccountsCmd) && !(cmdObj instanceof ListProjectInvitationsCmd) && !(cmdObj instanceof ListHostsCmd) && !(cmdObj instanceof ListVolumesCmd) && !(cmdObj instanceof ListVolumesCmdByAdmin) && !(cmdObj instanceof ListUsersCmd) && !(cmdObj instanceof ListAccountsCmd) && !(cmdObj instanceof ListAccountsCmdByAdmin) && !(cmdObj instanceof ListStoragePoolsCmd) && !(cmdObj instanceof ListDiskOfferingsCmd) && !(cmdObj instanceof ListServiceOfferingsCmd) && !(cmdObj instanceof ListZonesCmd) && !(cmdObj instanceof ListZonesCmdByAdmin)) {
buildAsyncListResponse((BaseListCmd) cmdObj, caller);
}
SerializationContext.current().setUuidTranslation(true);
return ApiResponseSerializer.toSerializedStringWithSecureLogs((ResponseObject) cmdObj.getResponseObject(), cmdObj.getResponseType(), log);
}
}
use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method deleteLBStickinessPolicy.
@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_STICKINESSPOLICY_DELETE, eventDescription = "revoking LB Stickiness policy ", async = true)
public boolean deleteLBStickinessPolicy(long stickinessPolicyId, boolean apply) {
boolean success = true;
CallContext caller = CallContext.current();
LBStickinessPolicyVO stickinessPolicy = _lb2stickinesspoliciesDao.findById(stickinessPolicyId);
if (stickinessPolicy == null) {
throw new InvalidParameterException("Invalid Stickiness policy id value: " + stickinessPolicyId);
}
LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(stickinessPolicy.getLoadBalancerId()));
if (loadBalancer == null) {
throw new InvalidParameterException("Invalid Load balancer : " + stickinessPolicy.getLoadBalancerId() + " for Stickiness policy id: " + stickinessPolicyId);
}
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 = stickinessPolicy.isRevoke();
stickinessPolicy.setRevoke(true);
_lb2stickinesspoliciesDao.persist(stickinessPolicy);
s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", stickinesspolicyID " + stickinessPolicyId);
try {
if (!applyLoadBalancerConfig(loadBalancerId)) {
s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for stickinesspolicyID " + stickinessPolicyId);
throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for stickinesspolicyID " + stickinessPolicyId);
}
} catch (ResourceUnavailableException e) {
if (isRollBackAllowedForProvider(loadBalancer)) {
stickinessPolicy.setRevoke(backupStickyState);
_lb2stickinesspoliciesDao.persist(stickinessPolicy);
loadBalancer.setState(backupState);
_lbDao.persist(loadBalancer);
s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while deleting sticky policy: " + stickinessPolicyId);
}
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
success = false;
}
} else {
_lb2stickinesspoliciesDao.expunge(stickinessPolicyId);
}
return success;
}
use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method assignCertToLoadBalancer.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_LB_CERT_ASSIGN, eventDescription = "assigning certificate to load balancer", async = true)
public boolean assignCertToLoadBalancer(long lbRuleId, Long certId) {
CallContext caller = CallContext.current();
LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(lbRuleId));
if (loadBalancer == null) {
throw new InvalidParameterException("Invalid load balancer id: " + lbRuleId);
}
SslCertVO certVO = _entityMgr.findById(SslCertVO.class, certId);
if (certVO == null) {
throw new InvalidParameterException("Invalid certificate id: " + certId);
}
_accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
// check if LB and Cert belong to the same account
if (loadBalancer.getAccountId() != certVO.getAccountId()) {
throw new InvalidParameterValueException("Access denied for account " + certVO.getAccountId());
}
String capability = getLBCapability(loadBalancer.getNetworkId(), Capability.SslTermination.getName());
if (capability == null) {
throw new InvalidParameterValueException("Ssl termination not supported by the loadbalancer");
}
//check if the lb is already bound
LoadBalancerCertMapVO certMapRule = _lbCertMapDao.findByLbRuleId(loadBalancer.getId());
if (certMapRule != null)
throw new InvalidParameterValueException("Another certificate is already bound to the LB");
//check for correct port
if (loadBalancer.getLbProtocol() == null || !(loadBalancer.getLbProtocol().equals(NetUtils.SSL_PROTO)))
throw new InvalidParameterValueException("Bad LB protocol: Expected ssl got " + loadBalancer.getLbProtocol());
boolean success = false;
FirewallRule.State backupState = loadBalancer.getState();
try {
loadBalancer.setState(FirewallRule.State.Add);
_lbDao.persist(loadBalancer);
LoadBalancerCertMapVO certMap = new LoadBalancerCertMapVO(lbRuleId, certId, false);
_lbCertMapDao.persist(certMap);
applyLoadBalancerConfig(loadBalancer.getId());
success = true;
} catch (ResourceUnavailableException e) {
if (isRollBackAllowedForProvider(loadBalancer)) {
loadBalancer.setState(backupState);
_lbDao.persist(loadBalancer);
LoadBalancerCertMapVO certMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
_lbCertMapDao.remove(certMap.getId());
s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while adding cert");
}
s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
}
return success;
}
use of org.apache.cloudstack.context.CallContext 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;
}
Aggregations