Search in sources :

Example 26 with CallContext

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

the class DomainManagerImpl method cleanupDomain.

protected boolean cleanupDomain(Long domainId, Long ownerId) throws ConcurrentOperationException, ResourceUnavailableException {
    s_logger.debug("Cleaning up domain id=" + domainId);
    boolean success = true;
    DomainVO domainHandle = _domainDao.findById(domainId);
    {
        domainHandle.setState(Domain.State.Inactive);
        _domainDao.update(domainId, domainHandle);
        SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
        sc.addAnd("parent", SearchCriteria.Op.EQ, domainId);
        List<DomainVO> domains = _domainDao.search(sc, null);
        SearchCriteria<DomainVO> sc1 = _domainDao.createSearchCriteria();
        sc1.addAnd("path", SearchCriteria.Op.LIKE, "%" + "replace(" + domainHandle.getPath() + ", '%', '[%]')" + "%");
        List<DomainVO> domainsToBeInactivated = _domainDao.search(sc1, null);
        // update all subdomains to inactive so no accounts/users can be created
        for (DomainVO domain : domainsToBeInactivated) {
            domain.setState(Domain.State.Inactive);
            _domainDao.update(domain.getId(), domain);
        }
        // cleanup sub-domains first
        for (DomainVO domain : domains) {
            success = (success && cleanupDomain(domain.getId(), domain.getAccountId()));
            if (!success) {
                s_logger.warn("Failed to cleanup domain id=" + domain.getId());
            }
        }
    }
    // delete users which will also delete accounts and release resources for those accounts
    SearchCriteria<AccountVO> sc = _accountDao.createSearchCriteria();
    sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
    List<AccountVO> accounts = _accountDao.search(sc, null);
    for (AccountVO account : accounts) {
        if (account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            s_logger.debug("Deleting account " + account + " as a part of domain id=" + domainId + " cleanup");
            boolean deleteAccount = _accountMgr.deleteAccount(account, CallContext.current().getCallingUserId(), getCaller());
            if (!deleteAccount) {
                s_logger.warn("Failed to cleanup account id=" + account.getId() + " as a part of domain cleanup");
            }
            success = (success && deleteAccount);
        } else {
            ProjectVO project = _projectDao.findByProjectAccountId(account.getId());
            s_logger.debug("Deleting project " + project + " as a part of domain id=" + domainId + " cleanup");
            boolean deleteProject = _projectMgr.deleteProject(getCaller(), CallContext.current().getCallingUserId(), project);
            if (!deleteProject) {
                s_logger.warn("Failed to cleanup project " + project + " as a part of domain cleanup");
            }
            success = (success && deleteProject);
        }
    }
    //delete the domain shared networks
    boolean networksDeleted = true;
    s_logger.debug("Deleting networks for domain id=" + domainId);
    List<Long> networkIds = _networkDomainDao.listNetworkIdsByDomain(domainId);
    CallContext ctx = CallContext.current();
    ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallingUserId()), ctx.getCallingAccount());
    for (Long networkId : networkIds) {
        s_logger.debug("Deleting network id=" + networkId + " as a part of domain id=" + domainId + " cleanup");
        if (!_networkMgr.destroyNetwork(networkId, context, false)) {
            s_logger.warn("Unable to destroy network id=" + networkId + " as a part of domain id=" + domainId + " cleanup.");
            networksDeleted = false;
        } else {
            s_logger.debug("Network " + networkId + " successfully deleted as a part of domain id=" + domainId + " cleanup.");
        }
    }
    //don't proceed if networks failed to cleanup. The cleanup will be performed for inactive domain once again
    if (!networksDeleted) {
        s_logger.debug("Failed to delete the shared networks as a part of domain id=" + domainId + " clenaup");
        return false;
    }
    // don't remove the domain if there are accounts required cleanup
    boolean deleteDomainSuccess = true;
    List<AccountVO> accountsForCleanup = _accountDao.findCleanupsForRemovedAccounts(domainId);
    if (accountsForCleanup.isEmpty()) {
        //release dedication if any, before deleting the domain
        List<DedicatedResourceVO> dedicatedResources = _dedicatedDao.listByDomainId(domainId);
        if (dedicatedResources != null && !dedicatedResources.isEmpty()) {
            s_logger.debug("Releasing dedicated resources for domain" + domainId);
            for (DedicatedResourceVO dr : dedicatedResources) {
                if (!_dedicatedDao.remove(dr.getId())) {
                    s_logger.warn("Fail to release dedicated resources for domain " + domainId);
                    return false;
                }
            }
        }
        //delete domain
        _messageBus.publish(_name, MESSAGE_PRE_REMOVE_DOMAIN_EVENT, PublishScope.LOCAL, domainHandle);
        deleteDomainSuccess = _domainDao.remove(domainId);
        _messageBus.publish(_name, MESSAGE_REMOVE_DOMAIN_EVENT, PublishScope.LOCAL, domainHandle);
        // Delete resource count and resource limits entries set for this domain (if there are any).
        _resourceCountDao.removeEntriesByOwner(domainId, ResourceOwnerType.Domain);
        _resourceLimitDao.removeEntriesByOwner(domainId, ResourceOwnerType.Domain);
    } else {
        s_logger.debug("Can't delete the domain yet because it has " + accountsForCleanup.size() + "accounts that need a cleanup");
        return false;
    }
    return success && deleteDomainSuccess;
}
Also used : CallContext(org.apache.cloudstack.context.CallContext) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) SearchCriteria(com.cloud.utils.db.SearchCriteria) ProjectVO(com.cloud.projects.ProjectVO) ReservationContext(com.cloud.vm.ReservationContext) DomainVO(com.cloud.domain.DomainVO) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO)

Example 27 with CallContext

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

the class VolumeApiServiceImpl method migrateVolumeThroughJobQueue.

public Outcome<Volume> migrateVolumeThroughJobQueue(final Long vmId, final long volumeId, final long destPoolId, final boolean liveMigrate) {
    final CallContext context = CallContext.current();
    final User callingUser = context.getCallingUser();
    final Account callingAccount = context.getCallingAccount();
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
    workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
    workJob.setCmd(VmWorkMigrateVolume.class.getName());
    workJob.setAccountId(callingAccount.getId());
    workJob.setUserId(callingUser.getId());
    workJob.setStep(VmWorkJobVO.Step.Starting);
    workJob.setVmType(VirtualMachine.Type.Instance);
    workJob.setVmInstanceId(vm.getId());
    workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
    // save work context info (there are some duplications)
    VmWorkMigrateVolume workInfo = new VmWorkMigrateVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId, destPoolId, liveMigrate);
    workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
    _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVolumeOutcome(workJob, volumeId);
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) VMInstanceVO(com.cloud.vm.VMInstanceVO) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Example 28 with CallContext

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

the class VMSnapshotManagerImpl method deleteAllVMSnapshotsThroughJobQueue.

public Outcome<VirtualMachine> deleteAllVMSnapshotsThroughJobQueue(final Long vmId, final VMSnapshot.Type type) {
    final CallContext context = CallContext.current();
    final User callingUser = context.getCallingUser();
    final Account callingAccount = context.getCallingAccount();
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
    workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
    workJob.setCmd(VmWorkDeleteAllVMSnapshots.class.getName());
    workJob.setAccountId(callingAccount.getId());
    workJob.setUserId(callingUser.getId());
    workJob.setStep(VmWorkJobVO.Step.Starting);
    workJob.setVmType(VirtualMachine.Type.Instance);
    workJob.setVmInstanceId(vm.getId());
    workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
    // save work context info (there are some duplications)
    VmWorkDeleteAllVMSnapshots workInfo = new VmWorkDeleteAllVMSnapshots(callingUser.getId(), callingAccount.getId(), vm.getId(), VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, type);
    workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
    _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVirtualMachineOutcome(workJob, vmId);
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) VMInstanceVO(com.cloud.vm.VMInstanceVO) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Example 29 with CallContext

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

the class VMSnapshotManagerImpl method createVMSnapshotThroughJobQueue.

public Outcome<VMSnapshot> createVMSnapshotThroughJobQueue(final Long vmId, final Long vmSnapshotId, final boolean quiesceVm) {
    final CallContext context = CallContext.current();
    final User callingUser = context.getCallingUser();
    final Account callingAccount = context.getCallingAccount();
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
    workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
    workJob.setCmd(VmWorkCreateVMSnapshot.class.getName());
    workJob.setAccountId(callingAccount.getId());
    workJob.setUserId(callingUser.getId());
    workJob.setStep(VmWorkJobVO.Step.Starting);
    workJob.setVmType(VirtualMachine.Type.Instance);
    workJob.setVmInstanceId(vm.getId());
    workJob.setRelated(AsyncJobExecutionContext.getOriginJobId());
    // save work context info (there are some duplications)
    VmWorkCreateVMSnapshot workInfo = new VmWorkCreateVMSnapshot(callingUser.getId(), callingAccount.getId(), vm.getId(), VMSnapshotManagerImpl.VM_WORK_JOB_HANDLER, vmSnapshotId, quiesceVm);
    workJob.setCmdInfo(VmWorkSerializer.serialize(workInfo));
    _jobMgr.submitAsyncJob(workJob, VmWorkConstants.VM_WORK_QUEUE, vm.getId());
    AsyncJobExecutionContext.getCurrentExecutionContext().joinJob(workJob.getId());
    return new VmJobVMSnapshotOutcome(workJob, vmSnapshotId);
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) VMInstanceVO(com.cloud.vm.VMInstanceVO) CallContext(org.apache.cloudstack.context.CallContext) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO)

Example 30 with CallContext

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

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) {
    Preconditions.checkNotNull(certCmd);
    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 = CertificateHelper.generateFingerPrint(parseCertificate(cert));
    final CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    Account owner = null;
    if (!Strings.isNullOrEmpty(certCmd.getAccountName()) && 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);
}
Also used : Account(com.cloud.user.Account) SslCertVO(com.cloud.network.dao.SslCertVO) CallContext(org.apache.cloudstack.context.CallContext) 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