Search in sources :

Example 51 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class SystemVmLoadScanner method getCapacityScanTask.

private Runnable getCapacityScanTask() {
    return new ManagedContextRunnable() {

        @Override
        protected void runInContext() {
            try {
                CallContext callContext = CallContext.current();
                assert (callContext != null);
                AsyncJobExecutionContext.registerPseudoExecutionContext(callContext.getCallingAccountId(), callContext.getCallingUserId());
                reallyRun();
                AsyncJobExecutionContext.unregister();
            } catch (Throwable e) {
                s_logger.warn("Unexpected exception " + e.getMessage(), e);
            }
        }

        private void reallyRun() {
            loadScan();
        }
    };
}
Also used : ManagedContextRunnable(org.apache.cloudstack.managed.context.ManagedContextRunnable) CallContext(org.apache.cloudstack.context.CallContext)

Example 52 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class ApiAsyncJobDispatcher method runJob.

@Override
public void runJob(final AsyncJob job) {
    BaseAsyncCmd cmdObj = null;
    try {
        Class<?> cmdClass = Class.forName(job.getCmd());
        cmdObj = (BaseAsyncCmd) cmdClass.newInstance();
        cmdObj = ComponentContext.inject(cmdObj);
        cmdObj.configure();
        cmdObj.setJob(job);
        Type mapType = new TypeToken<Map<String, String>>() {
        }.getType();
        Gson gson = ApiGsonHelper.getBuilder().create();
        Map<String, String> params = gson.fromJson(job.getCmdInfo(), mapType);
        // whenever we deserialize, the UserContext needs to be updated
        String userIdStr = params.get("ctxUserId");
        String acctIdStr = params.get("ctxAccountId");
        String contextDetails = params.get("ctxDetails");
        Long userId = null;
        Account accountObject = null;
        if (cmdObj instanceof BaseAsyncCreateCmd) {
            BaseAsyncCreateCmd create = (BaseAsyncCreateCmd) cmdObj;
            create.setEntityId(Long.parseLong(params.get("id")));
            create.setEntityUuid(params.get("uuid"));
        }
        User user = null;
        if (userIdStr != null) {
            userId = Long.parseLong(userIdStr);
            user = _entityMgr.findById(User.class, userId);
        }
        if (acctIdStr != null) {
            accountObject = _entityMgr.findById(Account.class, Long.parseLong(acctIdStr));
        }
        CallContext ctx = CallContext.register(user, accountObject);
        if (contextDetails != null) {
            Type objectMapType = new TypeToken<Map<Object, Object>>() {
            }.getType();
            ctx.putContextParameters((Map<Object, Object>) gson.fromJson(contextDetails, objectMapType));
        }
        try {
            // dispatch could ultimately queue the job
            _dispatcher.dispatch(cmdObj, params, true);
            // serialize this to the async job table
            _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, ApiSerializerHelper.toSerializedString(cmdObj.getResponseObject()));
        } catch (InvalidParameterValueException ipve) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage());
        } finally {
            CallContext.unregister();
        }
    } catch (Throwable e) {
        String errorMsg = null;
        int errorCode = ApiErrorCode.INTERNAL_ERROR.getHttpCode();
        if (!(e instanceof ServerApiException)) {
            s_logger.error("Unexpected exception while executing " + job.getCmd(), e);
            errorMsg = e.getMessage();
        } else {
            ServerApiException sApiEx = (ServerApiException) e;
            errorMsg = sApiEx.getDescription();
            errorCode = sApiEx.getErrorCode().getHttpCode();
        }
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode(errorCode);
        response.setErrorText(errorMsg);
        response.setResponseName((cmdObj == null) ? "unknowncommandresponse" : cmdObj.getCommandName());
        // FIXME:  setting resultCode to ApiErrorCode.INTERNAL_ERROR is not right, usually executors have their exception handling
        //         and we need to preserve that as much as possible here
        _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), ApiSerializerHelper.toSerializedString(response));
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) ExceptionResponse(org.apache.cloudstack.api.response.ExceptionResponse) BaseAsyncCreateCmd(org.apache.cloudstack.api.BaseAsyncCreateCmd) Gson(com.google.gson.Gson) CallContext(org.apache.cloudstack.context.CallContext) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) Type(java.lang.reflect.Type) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Map(java.util.Map)

Example 53 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class ApiDispatcher method dispatch.

public void dispatch(final BaseCmd cmd, final Map<String, String> params, final boolean execute) throws Exception {
    // Let the chain of responsibility dispatch gradually
    standardDispatchChain.dispatch(new DispatchTask(cmd, params));
    final CallContext ctx = CallContext.current();
    ctx.setEventDisplayEnabled(cmd.isDisplay());
    if (params.get(ApiConstants.PROJECT_ID) != null) {
        Project project = _entityMgr.findByUuidIncludingRemoved(Project.class, params.get(ApiConstants.PROJECT_ID));
        ctx.setProject(project);
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCmd) {
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
        final String startEventId = params.get(ApiConstants.CTX_START_EVENT_ID);
        ctx.setStartEventId(Long.parseLong(startEventId));
        // Synchronise job on the object if needed
        if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
            Long queueSizeLimit = null;
            if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
                queueSizeLimit = _createSnapshotQueueSizeLimit;
            } else {
                queueSizeLimit = 1L;
            }
            if (queueSizeLimit != null) {
                if (!execute) {
                    // if we are not within async-execution context, enqueue the command
                    _asyncMgr.syncAsyncJobExecution((AsyncJob) asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
                    return;
                }
            } else {
                s_logger.trace("The queue size is unlimited, skipping the synchronizing");
            }
        }
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCustomIdCmd) {
        ((BaseAsyncCustomIdCmd) cmd).checkUuid();
    } else if (cmd instanceof BaseCustomIdCmd) {
        ((BaseCustomIdCmd) cmd).checkUuid();
    }
    cmd.execute();
}
Also used : Project(com.cloud.projects.Project) BaseCustomIdCmd(org.apache.cloudstack.api.BaseCustomIdCmd) CallContext(org.apache.cloudstack.context.CallContext) DispatchTask(com.cloud.api.dispatch.DispatchTask) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) BaseAsyncCustomIdCmd(org.apache.cloudstack.api.BaseAsyncCustomIdCmd)

Example 54 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class GlobalLoadBalancingRulesServiceImpl method updateGlobalLoadBalancerRule.

@Override
public GlobalLoadBalancerRule updateGlobalLoadBalancerRule(UpdateGlobalLoadBalancerRuleCmd updateGslbCmd) {
    String algorithm = updateGslbCmd.getAlgorithm();
    String stickyMethod = updateGslbCmd.getStickyMethod();
    String description = updateGslbCmd.getDescription();
    long gslbRuleId = updateGslbCmd.getId();
    GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
    if (gslbRule == null) {
        throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
    }
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule);
    if (algorithm != null && !GlobalLoadBalancerRule.Algorithm.isValidAlgorithm(algorithm)) {
        throw new InvalidParameterValueException("Invalid Algorithm: " + algorithm);
    }
    if (stickyMethod != null && !GlobalLoadBalancerRule.Persistence.isValidPersistence(stickyMethod)) {
        throw new InvalidParameterValueException("Invalid persistence: " + stickyMethod);
    }
    if (algorithm != null) {
        gslbRule.setAlgorithm(algorithm);
    }
    if (stickyMethod != null) {
        gslbRule.setPersistence(stickyMethod);
    }
    if (description != null) {
        gslbRule.setDescription(description);
    }
    gslbRule.setState(GlobalLoadBalancerRule.State.Add);
    _gslbRuleDao.update(gslbRule.getId(), gslbRule);
    try {
        s_logger.debug("Updating global load balancer with id " + gslbRule.getUuid());
        // apply the gslb rule on to the back end gslb service providers on zones participating in gslb
        applyGlobalLoadBalancerRuleConfig(gslbRuleId, false);
        // on success set state to Active
        gslbRule.setState(GlobalLoadBalancerRule.State.Active);
        _gslbRuleDao.update(gslbRule.getId(), gslbRule);
        return gslbRule;
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Failed to configure gslb config due to " + e.getMessage());
    }
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CallContext(org.apache.cloudstack.context.CallContext)

Example 55 with CallContext

use of org.apache.cloudstack.context.CallContext in project cloudstack by apache.

the class GlobalLoadBalancingRulesServiceImpl method removeFromGlobalLoadBalancerRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOVE_FROM_GLOBAL_LOAD_BALANCER_RULE, eventDescription = "Removing a load balancer rule to be part of global load balancer rule")
public boolean removeFromGlobalLoadBalancerRule(RemoveFromGlobalLoadBalancerRuleCmd removeFromGslbCmd) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    final long gslbRuleId = removeFromGslbCmd.getGlobalLoadBalancerRuleId();
    final GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
    if (gslbRule == null) {
        throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
    }
    _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule);
    if (gslbRule.getState() == GlobalLoadBalancerRule.State.Revoke) {
        throw new InvalidParameterValueException("global load balancer rule id: " + gslbRuleId + " is already in revoked state");
    }
    final List<Long> lbRuleIdsToremove = removeFromGslbCmd.getLoadBalancerRulesIds();
    if (lbRuleIdsToremove == null || lbRuleIdsToremove.isEmpty()) {
        throw new InvalidParameterValueException("empty list of load balancer rule Ids specified to be un-assigned" + " to global load balancer rule");
    }
    // get the active list of LB rule id's that are assigned currently to GSLB rule and corresponding zone id's
    List<Long> oldLbRuleIds = new ArrayList<Long>();
    List<Long> oldZones = new ArrayList<Long>();
    List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
    if (gslbLbMapVos == null) {
        throw new InvalidParameterValueException(" There are no load balancer rules that are assigned to global " + " load balancer rule id: " + gslbRule.getUuid() + " that are available for deletion");
    }
    for (Long lbRuleId : lbRuleIdsToremove) {
        LoadBalancerVO loadBalancer = _lbDao.findById(lbRuleId);
        if (loadBalancer == null) {
            throw new InvalidParameterValueException("Specified load balancer rule ID does not exist.");
        }
        _accountMgr.checkAccess(caller, null, true, loadBalancer);
    }
    for (GlobalLoadBalancerLbRuleMapVO gslbLbMapVo : gslbLbMapVos) {
        LoadBalancerVO loadBalancer = _lbDao.findById(gslbLbMapVo.getLoadBalancerId());
        Network network = _networkDao.findById(loadBalancer.getNetworkId());
        oldLbRuleIds.add(gslbLbMapVo.getLoadBalancerId());
        oldZones.add(network.getDataCenterId());
    }
    for (Long lbRuleId : lbRuleIdsToremove) {
        LoadBalancerVO loadBalancer = _lbDao.findById(lbRuleId);
        if (oldLbRuleIds != null && !oldLbRuleIds.contains(loadBalancer.getId())) {
            throw new InvalidParameterValueException("Load balancer ID " + loadBalancer.getUuid() + " is not assigned" + " to global load balancer rule: " + gslbRule.getUuid());
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // update the mapping of gslb rule to Lb rule, to revoke state
            for (Long lbRuleId : lbRuleIdsToremove) {
                GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
                removeGslbLbMap.setRevoke(true);
                _gslbLbMapDao.update(removeGslbLbMap.getId(), removeGslbLbMap);
            }
            // mark the gslb rule state as add
            if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged) {
                gslbRule.setState(GlobalLoadBalancerRule.State.Add);
                _gslbRuleDao.update(gslbRule.getId(), gslbRule);
            }
        }
    });
    boolean success = false;
    try {
        s_logger.debug("Attempting to configure global load balancer rule configuration on the gslb service providers ");
        // apply the gslb rule on to the back end gslb service providers
        if (!applyGlobalLoadBalancerRuleConfig(gslbRuleId, false)) {
            s_logger.warn("Failed to remove load balancer rules " + lbRuleIdsToremove + " from global load balancer rule id " + gslbRuleId);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to remove load balancer rule ids from GSLB rule ");
            throw ex;
        }
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                // remove the mappings of gslb rule to Lb rule that are in revoked state
                for (Long lbRuleId : lbRuleIdsToremove) {
                    GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
                    _gslbLbMapDao.remove(removeGslbLbMap.getId());
                }
                // on success set state back to Active
                gslbRule.setState(GlobalLoadBalancerRule.State.Active);
                _gslbRuleDao.update(gslbRule.getId(), gslbRule);
            }
        });
        success = true;
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Failed to update removed load balancer details from gloabal load balancer");
    }
    return success;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

CallContext (org.apache.cloudstack.context.CallContext)76 Account (com.cloud.user.Account)45 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)29 User (com.cloud.user.User)26 ActionEvent (com.cloud.event.ActionEvent)22 VmWorkJobVO (org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)22 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)21 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)21 DB (com.cloud.utils.db.DB)13 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)12 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 FirewallRule (com.cloud.network.rules.FirewallRule)8 ArrayList (java.util.ArrayList)8 ServerApiException (org.apache.cloudstack.api.ServerApiException)8 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)7 Network (com.cloud.network.Network)7 TransactionStatus (com.cloud.utils.db.TransactionStatus)6 DeployDestination (com.cloud.deploy.DeployDestination)5 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)5 IPAddressVO (com.cloud.network.dao.IPAddressVO)5