Search in sources :

Example 21 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method stopVmThroughJobQueue.

public Outcome<VirtualMachine> stopVmThroughJobQueue(final String vmUuid, final boolean cleanup) {
    final CallContext context = CallContext.current();
    final Account account = context.getCallingAccount();
    final User user = context.getCallingUser();
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(vm.getType(), vm.getId(), VmWorkStop.class.getName());
    VmWorkJobVO workJob = null;
    if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
        assert pendingWorkJobs.size() == 1;
        workJob = pendingWorkJobs.get(0);
    } else {
        workJob = new VmWorkJobVO(context.getContextId());
        workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
        workJob.setCmd(VmWorkStop.class.getName());
        workJob.setAccountId(account.getId());
        workJob.setUserId(user.getId());
        workJob.setStep(VmWorkJobVO.Step.Prepare);
        workJob.setVmType(VirtualMachine.Type.Instance);
        workJob.setVmInstanceId(vm.getId());
        workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
        // save work context info (there are some duplications)
        final VmWorkStop workInfo = new VmWorkStop(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, cleanup);
        workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
        _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    }
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmStateSyncOutcome(workJob, VirtualMachine.PowerState.PowerOff, vm.getId(), null);
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(com.cloud.context.CallContext) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO)

Example 22 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class VirtualMachineManagerImpl method migrateVmWithStorageThroughJobQueue.

public Outcome<VirtualMachine> migrateVmWithStorageThroughJobQueue(final String vmUuid, final long srcHostId, final long destHostId, final Map<Long, Long> volumeToPool) {
    final CallContext context = CallContext.current();
    final User user = context.getCallingUser();
    final Account account = context.getCallingAccount();
    final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
    final List<VmWorkJobVO> pendingWorkJobs = _workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vm.getId(), VmWorkMigrateWithStorage.class.getName());
    VmWorkJobVO workJob = null;
    if (pendingWorkJobs != null && pendingWorkJobs.size() > 0) {
        assert pendingWorkJobs.size() == 1;
        workJob = pendingWorkJobs.get(0);
    } else {
        workJob = new VmWorkJobVO(context.getContextId());
        workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
        workJob.setCmd(VmWorkMigrateWithStorage.class.getName());
        workJob.setAccountId(account.getId());
        workJob.setUserId(user.getId());
        workJob.setVmType(VirtualMachine.Type.Instance);
        workJob.setVmInstanceId(vm.getId());
        workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
        // save work context info (there are some duplications)
        final VmWorkMigrateWithStorage workInfo = new VmWorkMigrateWithStorage(user.getId(), account.getId(), vm.getId(), VirtualMachineManagerImpl.VM_WORK_JOB_HANDLER, srcHostId, destHostId, volumeToPool);
        workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
        _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    }
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmStateSyncOutcome(workJob, VirtualMachine.PowerState.PowerOn, vm.getId(), destHostId);
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) CallContext(com.cloud.context.CallContext) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO)

Example 23 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class ApiServer method queueCommand.

private String queueCommand(final BaseCmd cmdObj, final Map<String, String> params, final 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;
        final String objectUuid;
        if (cmdObj instanceof BaseAsyncCreateCmd) {
            final BaseAsyncCreateCmd createCmd = (BaseAsyncCreateCmd) cmdObj;
            _dispatcher.dispatchCreateCmd(createCmd, params);
            objectId = createCmd.getEntityId();
            objectUuid = createCmd.getEntityUuid();
            params.put("id", objectId.toString());
            final 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()));
        final 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
        final String injectedJobId = asyncCmd.getInjectedJobId();
        _uuidMgr.checkUuidSimple(injectedJobId, AsyncJob.class);
        final 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 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);
    }
}
Also used : UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) ListHostsCmd(com.cloud.api.command.admin.host.ListHostsCmd) ListVolumesCmdByAdmin(com.cloud.api.command.admin.volume.ListVolumesCmdByAdmin) ListZonesCmdByAdmin(com.cloud.api.command.admin.zone.ListZonesCmdByAdmin) AsyncJobVO(com.cloud.framework.jobs.impl.AsyncJobVO) ListZonesCmd(com.cloud.api.command.user.zone.ListZonesCmd) ListProjectInvitationsCmd(com.cloud.api.command.user.project.ListProjectInvitationsCmd) ListProjectAccountsCmd(com.cloud.api.command.user.account.ListProjectAccountsCmd) ListAccountsCmd(com.cloud.api.command.user.account.ListAccountsCmd) DispatchTask(com.cloud.api.dispatch.DispatchTask) ListUsersCmd(com.cloud.api.command.admin.user.ListUsersCmd) ListEventsCmd(com.cloud.api.command.user.event.ListEventsCmd) ListVolumesCmd(com.cloud.api.command.user.volume.ListVolumesCmd) ListDiskOfferingsCmd(com.cloud.api.command.user.offering.ListDiskOfferingsCmd) ListRoutersCmd(com.cloud.api.command.admin.router.ListRoutersCmd) ListProjectsCmd(com.cloud.api.command.user.project.ListProjectsCmd) ListAccountsCmdByAdmin(com.cloud.api.command.admin.account.ListAccountsCmdByAdmin) CallContext(com.cloud.context.CallContext) ListVMGroupsCmd(com.cloud.api.command.user.vmgroup.ListVMGroupsCmd) ListVMsCmd(com.cloud.api.command.user.vm.ListVMsCmd) ListVMsCmdByAdmin(com.cloud.api.command.admin.vm.ListVMsCmdByAdmin) ListStoragePoolsCmd(com.cloud.api.command.admin.storage.ListStoragePoolsCmd) ListServiceOfferingsCmd(com.cloud.api.command.user.offering.ListServiceOfferingsCmd) ListTagsCmd(com.cloud.api.command.user.tag.ListTagsCmd)

Example 24 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class CertServiceImpl method uploadSslCert.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_CERT_UPLOAD, eventDescription = "Uploading a certificate to cloudstack", async = false)
public SslCertResponse uploadSslCert(final UploadSslCertCmd certCmd) {
    try {
        final String cert = certCmd.getCert();
        final String key = certCmd.getKey();
        final String password = certCmd.getPassword();
        final String chain = certCmd.getChain();
        validate(cert, key, password, chain);
        s_logger.debug("Certificate Validation succeeded");
        final String fingerPrint = generateFingerPrint(parseCertificate(cert));
        final CallContext ctx = CallContext.current();
        final Account caller = ctx.getCallingAccount();
        Account owner = null;
        if ((certCmd.getAccountName() != null && certCmd.getDomainId() != null) || certCmd.getProjectId() != null) {
            owner = _accountMgr.finalizeOwner(caller, certCmd.getAccountName(), certCmd.getDomainId(), certCmd.getProjectId());
        } else {
            owner = caller;
        }
        final Long accountId = owner.getId();
        final Long domainId = owner.getDomainId();
        final SslCertVO certVO = new SslCertVO(cert, key, password, chain, accountId, domainId, fingerPrint);
        _sslCertDao.persist(certVO);
        return createCertResponse(certVO, null);
    } catch (final Exception e) {
        throw new CloudRuntimeException("Error parsing certificate data " + e.getMessage());
    }
}
Also used : Account(com.cloud.user.Account) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SslCertVO(com.cloud.network.dao.SslCertVO) CallContext(com.cloud.context.CallContext) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CertPathBuilderException(java.security.cert.CertPathBuilderException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 25 with CallContext

use of com.cloud.context.CallContext in project cosmic by MissionCriticalCloud.

the class CertServiceImpl method deleteSslCert.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_CERT_DELETE, eventDescription = "Deleting a certificate to cloudstack", async = false)
public void deleteSslCert(final DeleteSslCertCmd deleteSslCertCmd) {
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    final Long certId = deleteSslCertCmd.getId();
    final SslCertVO certVO = _sslCertDao.findById(certId);
    if (certVO == null) {
        throw new InvalidParameterValueException("Invalid certificate id: " + certId);
    }
    _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, certVO);
    final List<LoadBalancerCertMapVO> lbCertRule = _lbCertDao.listByCertId(certId);
    if ((lbCertRule != null) && (!lbCertRule.isEmpty())) {
        String lbUuids = "";
        for (final LoadBalancerCertMapVO rule : lbCertRule) {
            final LoadBalancerVO lb = _entityMgr.findById(LoadBalancerVO.class, rule.getLbId());
            lbUuids += " " + lb.getUuid();
        }
        throw new CloudRuntimeException("Certificate in use by a loadbalancer(s)" + lbUuids);
    }
    _sslCertDao.remove(certId);
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SslCertVO(com.cloud.network.dao.SslCertVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) CallContext(com.cloud.context.CallContext) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

CallContext (com.cloud.context.CallContext)72 Account (com.cloud.user.Account)41 User (com.cloud.user.User)26 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)26 VmWorkJobVO (com.cloud.framework.jobs.impl.VmWorkJobVO)22 ActionEvent (com.cloud.event.ActionEvent)20 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)19 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)19 DB (com.cloud.utils.db.DB)12 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)10 VMInstanceVO (com.cloud.vm.VMInstanceVO)10 NetworkRuleConflictException (com.cloud.exception.NetworkRuleConflictException)9 ServerApiException (com.cloud.api.ServerApiException)8 FirewallRule (com.cloud.network.rules.FirewallRule)8 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)6 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)6 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)6 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)6 Network (com.cloud.network.Network)6 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)5