Search in sources :

Example 21 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class TemplateManagerImpl method extract.

private String extract(Account caller, Long templateId, String url, Long zoneId, String mode, Long eventId, boolean isISO) {
    String desc = Upload.Type.TEMPLATE.toString();
    if (isISO) {
        desc = Upload.Type.ISO.toString();
    }
    if (!_accountMgr.isRootAdmin(caller.getId()) && _disableExtraction) {
        throw new PermissionDeniedException("Extraction has been disabled by admin");
    }
    VMTemplateVO template = _tmpltDao.findById(templateId);
    if (template == null || template.getRemoved() != null) {
        throw new InvalidParameterValueException("Unable to find " + desc + " with id " + templateId);
    }
    if (template.getTemplateType() == Storage.TemplateType.SYSTEM) {
        throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName() + " as it is a default System template");
    } else if (template.getTemplateType() == Storage.TemplateType.PERHOST) {
        throw new InvalidParameterValueException("Unable to extract the " + desc + " " + template.getName() + " as it resides on host and not on SSVM");
    }
    if (isISO) {
        if (template.getFormat() != ImageFormat.ISO) {
            throw new InvalidParameterValueException("Unsupported format, could not extract the ISO");
        }
    } else {
        if (template.getFormat() == ImageFormat.ISO) {
            throw new InvalidParameterValueException("Unsupported format, could not extract the template");
        }
    }
    if (zoneId != null && _dcDao.findById(zoneId) == null) {
        throw new IllegalArgumentException("Please specify a valid zone.");
    }
    if (!_accountMgr.isRootAdmin(caller.getId()) && !template.isExtractable()) {
        throw new InvalidParameterValueException("Unable to extract template id=" + templateId + " as it's not extractable");
    }
    _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
    List<DataStore> ssStores = _dataStoreMgr.getImageStoresByScope(new ZoneScope(null));
    TemplateDataStoreVO tmpltStoreRef = null;
    ImageStoreEntity tmpltStore = null;
    if (ssStores != null) {
        for (DataStore store : ssStores) {
            tmpltStoreRef = _tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
            if (tmpltStoreRef != null) {
                if (tmpltStoreRef.getDownloadState() == com.cloud.storage.VMTemplateStorageResourceAssoc.Status.DOWNLOADED) {
                    tmpltStore = (ImageStoreEntity) store;
                    break;
                }
            }
        }
    }
    if (tmpltStore == null) {
        throw new InvalidParameterValueException("The " + desc + " has not been downloaded ");
    }
    // Check if the url already exists
    if (tmpltStoreRef.getExtractUrl() != null) {
        return tmpltStoreRef.getExtractUrl();
    }
    // Handle NFS to S3 object store migration case, we trigger template sync from NFS to S3 during extract template or copy template
    _tmpltSvr.syncTemplateToRegionStore(templateId, tmpltStore);
    TemplateInfo templateObject = _tmplFactory.getTemplate(templateId, tmpltStore);
    String extractUrl = tmpltStore.createEntityExtractUrl(tmpltStoreRef.getInstallPath(), template.getFormat(), templateObject);
    tmpltStoreRef.setExtractUrl(extractUrl);
    tmpltStoreRef.setExtractUrlCreated(DateUtil.now());
    _tmplStoreDao.update(tmpltStoreRef.getId(), tmpltStoreRef);
    return extractUrl;
}
Also used : ZoneScope(org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope) TemplateInfo(org.apache.cloudstack.engine.subsystem.api.storage.TemplateInfo) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PrimaryDataStore(org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStore) DataStore(org.apache.cloudstack.engine.subsystem.api.storage.DataStore) VMTemplateVO(com.cloud.storage.VMTemplateVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ImageStoreEntity(org.apache.cloudstack.storage.image.datastore.ImageStoreEntity) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO)

Example 22 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class AccountManagerImpl method finalyzeAccountId.

@Override
public Long finalyzeAccountId(final String accountName, final Long domainId, final Long projectId, final boolean enabledOnly) {
    if (accountName != null) {
        if (domainId == null) {
            throw new InvalidParameterValueException("Account must be specified with domainId parameter");
        }
        final Domain domain = _domainMgr.getDomain(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Unable to find domain by id");
        }
        final Account account = getActiveAccountByName(accountName, domainId);
        if (account != null && account.getType() != Account.ACCOUNT_TYPE_PROJECT) {
            if (!enabledOnly || account.getState() == Account.State.enabled) {
                return account.getId();
            } else {
                throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active");
            }
        } else {
            // idList.add(new IdentityProxy("domain", domainId, "domainId"));
            throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id");
        }
    }
    if (projectId != null) {
        final Project project = _projectMgr.getProject(projectId);
        if (project != null) {
            if (!enabledOnly || project.getState() == Project.State.Active) {
                return project.getProjectAccountId();
            } else {
                final PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() + " as it's no longer active");
                ex.addProxyObject(project.getUuid(), "projectId");
                throw ex;
            }
        } else {
            throw new InvalidParameterValueException("Unable to find project by id");
        }
    }
    return null;
}
Also used : Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) Domain(com.cloud.domain.Domain)

Example 23 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method restoreVMInternal.

public UserVm restoreVMInternal(Account caller, UserVmVO vm, Long newTemplateId) throws InsufficientCapacityException, ResourceUnavailableException {
    Long userId = caller.getId();
    Account owner = _accountDao.findById(vm.getAccountId());
    _userDao.findById(userId);
    long vmId = vm.getId();
    boolean needRestart = false;
    // Input validation
    if (owner == null) {
        throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId());
    }
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId());
    }
    if (vm.getState() != VirtualMachine.State.Running && vm.getState() != VirtualMachine.State.Stopped) {
        throw new CloudRuntimeException("Vm " + vm.getUuid() + " currently in " + vm.getState() + " state, restore vm can only execute when VM in Running or Stopped");
    }
    if (vm.getState() == VirtualMachine.State.Running) {
        needRestart = true;
    }
    List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT);
    if (rootVols.isEmpty()) {
        InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vm.getUuid());
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    if (rootVols.size() > 1) {
        InvalidParameterValueException ex = new InvalidParameterValueException("There are " + rootVols.size() + " root volumes for VM " + vm.getUuid());
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    VolumeVO root = rootVols.get(0);
    if (!Volume.State.Allocated.equals(root.getState()) || newTemplateId != null) {
        Long templateId = root.getTemplateId();
        boolean isISO = false;
        if (templateId == null) {
            // Assuming that for a vm deployed using ISO, template ID is set to NULL
            isISO = true;
            templateId = vm.getIsoId();
        }
        // If target VM has associated VM snapshots then don't allow restore of VM
        List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
        if (vmSnapshots.size() > 0) {
            throw new InvalidParameterValueException("Unable to restore VM, please remove VM snapshots before restoring VM");
        }
        VMTemplateVO template = null;
        //newTemplateId can be either template or ISO id. In the following snippet based on the vm deployment (from template or ISO) it is handled accordingly
        if (newTemplateId != null) {
            template = _templateDao.findById(newTemplateId);
            _accountMgr.checkAccess(caller, null, true, template);
            if (isISO) {
                if (!template.getFormat().equals(ImageFormat.ISO)) {
                    throw new InvalidParameterValueException("Invalid ISO id provided to restore the VM ");
                }
            } else {
                if (template.getFormat().equals(ImageFormat.ISO)) {
                    throw new InvalidParameterValueException("Invalid template id provided to restore the VM ");
                }
            }
        } else {
            if (isISO && templateId == null) {
                throw new CloudRuntimeException("Cannot restore the VM since there is no ISO attached to VM");
            }
            template = _templateDao.findById(templateId);
            if (template == null) {
                InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template/ISO for specified volumeid and vmId");
                ex.addProxyObject(vm.getUuid(), "vmId");
                ex.addProxyObject(root.getUuid(), "volumeId");
                throw ex;
            }
        }
        TemplateDataStoreVO tmplStore = _templateStoreDao.findByTemplateZoneReady(template.getId(), vm.getDataCenterId());
        if (tmplStore == null) {
            throw new InvalidParameterValueException("Cannot restore the vm as the template " + template.getUuid() + " isn't available in the zone");
        }
        if (needRestart) {
            try {
                _itMgr.stop(vm.getUuid());
            } catch (ResourceUnavailableException e) {
                s_logger.debug("Stop vm " + vm.getUuid() + " failed", e);
                CloudRuntimeException ex = new CloudRuntimeException("Stop vm failed for specified vmId");
                ex.addProxyObject(vm.getUuid(), "vmId");
                throw ex;
            }
        }
        /* If new template/ISO is provided allocate a new volume from new template/ISO otherwise allocate new volume from original template/ISO */
        Volume newVol = null;
        if (newTemplateId != null) {
            if (isISO) {
                newVol = volumeMgr.allocateDuplicateVolume(root, null);
                vm.setIsoId(newTemplateId);
                vm.setGuestOSId(template.getGuestOSId());
                vm.setTemplateId(newTemplateId);
                _vmDao.update(vmId, vm);
            } else {
                newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
                vm.setGuestOSId(template.getGuestOSId());
                vm.setTemplateId(newTemplateId);
                _vmDao.update(vmId, vm);
            }
        } else {
            newVol = volumeMgr.allocateDuplicateVolume(root, null);
        }
        // 1. Save usage event and update resource count for user vm volumes
        _resourceLimitMgr.incrementResourceCount(newVol.getAccountId(), ResourceType.volume, newVol.isDisplay());
        _resourceLimitMgr.incrementResourceCount(newVol.getAccountId(), ResourceType.primary_storage, newVol.isDisplay(), new Long(newVol.getSize()));
        // 2. Create Usage event for the newly created volume
        UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, newVol.getAccountId(), newVol.getDataCenterId(), newVol.getId(), newVol.getName(), newVol.getDiskOfferingId(), template.getId(), newVol.getSize());
        _usageEventDao.persist(usageEvent);
        handleManagedStorage(vm, root);
        _volsDao.attachVolume(newVol.getId(), vmId, newVol.getDeviceId());
        // Detach, destroy and create the usage event for the old root volume.
        _volsDao.detachVolume(root.getId());
        volumeMgr.destroyVolume(root);
        // For VMware hypervisor since the old root volume is replaced by the new root volume, force expunge old root volume if it has been created in storage
        if (vm.getHypervisorType() == HypervisorType.VMware) {
            VolumeInfo volumeInStorage = volFactory.getVolume(root.getId());
            if (volumeInStorage != null) {
                s_logger.info("Expunging volume " + root.getId() + " from primary data store");
                AsyncCallFuture<VolumeApiResult> future = _volService.expungeVolumeAsync(volFactory.getVolume(root.getId()));
                try {
                    future.get();
                } catch (Exception e) {
                    s_logger.debug("Failed to expunge volume:" + root.getId(), e);
                }
            }
        }
        Map<VirtualMachineProfile.Param, Object> params = null;
        String password = null;
        if (template.getEnablePassword()) {
            password = _mgr.generateRandomPassword();
            boolean result = resetVMPasswordInternal(vmId, password);
            if (result) {
                vm.setPassword(password);
                _vmDao.loadDetails(vm);
                // update the password in vm_details table too
                // Check if an SSH key pair was selected for the instance and if so
                // use it to encrypt & save the vm password
                encryptAndStorePassword(vm, password);
            } else {
                throw new CloudRuntimeException("VM reset is completed but failed to reset password for the virtual machine ");
            }
        }
        if (needRestart) {
            try {
                if (vm.getDetail("password") != null) {
                    params = new HashMap<VirtualMachineProfile.Param, Object>();
                    params.put(VirtualMachineProfile.Param.VmPassword, password);
                }
                _itMgr.start(vm.getUuid(), params);
                vm = _vmDao.findById(vmId);
                if (template.getEnablePassword()) {
                    // this value is not being sent to the backend; need only for api
                    // display purposes
                    vm.setPassword(password);
                    if (vm.isUpdateParameters()) {
                        vm.setUpdateParameters(false);
                        _vmDao.loadDetails(vm);
                        if (vm.getDetail("password") != null) {
                            _vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
                        }
                        _vmDao.update(vm.getId(), vm);
                    }
                }
            } catch (Exception e) {
                s_logger.debug("Unable to start VM " + vm.getUuid(), e);
                CloudRuntimeException ex = new CloudRuntimeException("Unable to start VM with specified id" + e.getMessage());
                ex.addProxyObject(vm.getUuid(), "vmId");
                throw ex;
            }
        }
    }
    s_logger.debug("Restore VM " + vmId + " done successfully");
    return vm;
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) UsageEventVO(com.cloud.event.UsageEventVO) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) VolumeApiResult(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) Volume(com.cloud.storage.Volume) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 24 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UsageServiceImpl method getUsageRecords.

@Override
public Pair<List<? extends Usage>, Integer> getUsageRecords(GetUsageRecordsCmd cmd) {
    Long accountId = cmd.getAccountId();
    Long domainId = cmd.getDomainId();
    String accountName = cmd.getAccountName();
    Account userAccount = null;
    Account caller = CallContext.current().getCallingAccount();
    Long usageType = cmd.getUsageType();
    Long projectId = cmd.getProjectId();
    String usageId = cmd.getUsageId();
    if (projectId != null) {
        if (accountId != null) {
            throw new InvalidParameterValueException("Projectid and accountId can't be specified together");
        }
        Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            throw new InvalidParameterValueException("Unable to find project by id " + projectId);
        }
        accountId = project.getProjectAccountId();
    }
    //if accountId is not specified, use accountName and domainId
    if ((accountId == null) && (accountName != null) && (domainId != null)) {
        if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
            Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
            List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
            if (accounts.size() > 0) {
                userAccount = accounts.get(0);
            }
            if (userAccount != null) {
                accountId = userAccount.getId();
            } else {
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
            }
        } else {
            throw new PermissionDeniedException("Invalid Domain Id or Account");
        }
    }
    boolean isAdmin = false;
    boolean isDomainAdmin = false;
    //If accountId couldn't be found using accountName and domainId, get it from userContext
    if (accountId == null) {
        accountId = caller.getId();
        //If account_id or account_name is explicitly mentioned, list records for the specified account only even if the caller is of type admin
        if (_accountService.isRootAdmin(caller.getId())) {
            isAdmin = true;
        } else if (_accountService.isDomainAdmin(caller.getId())) {
            isDomainAdmin = true;
        }
        s_logger.debug("Account details not available. Using userContext accountId: " + accountId);
    }
    Date startDate = cmd.getStartDate();
    Date endDate = cmd.getEndDate();
    if (startDate.after(endDate)) {
        throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
    }
    TimeZone usageTZ = getUsageTimezone();
    Date adjustedStartDate = computeAdjustedTime(startDate, usageTZ);
    Date adjustedEndDate = computeAdjustedTime(endDate, usageTZ);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("getting usage records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate + ", using pageSize: " + cmd.getPageSizeVal() + " and startIndex: " + cmd.getStartIndex());
    }
    Filter usageFilter = new Filter(UsageVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchCriteria<UsageVO> sc = _usageDao.createSearchCriteria();
    if (accountId != -1 && accountId != Account.ACCOUNT_ID_SYSTEM && !isAdmin && !isDomainAdmin) {
        sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId);
    }
    if (isDomainAdmin) {
        SearchCriteria<DomainVO> sdc = _domainDao.createSearchCriteria();
        sdc.addOr("path", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
        List<DomainVO> domains = _domainDao.search(sdc, null);
        List<Long> domainIds = new ArrayList<Long>();
        for (DomainVO domain : domains) domainIds.add(domain.getId());
        sc.addAnd("domainId", SearchCriteria.Op.IN, domainIds.toArray());
    }
    if (domainId != null) {
        sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
    }
    if (usageType != null) {
        sc.addAnd("usageType", SearchCriteria.Op.EQ, usageType);
    }
    if (usageId != null) {
        if (usageType == null) {
            throw new InvalidParameterValueException("Usageid must be specified together with usageType");
        }
        Long usageDbId = null;
        switch(usageType.intValue()) {
            case UsageTypes.NETWORK_BYTES_RECEIVED:
            case UsageTypes.NETWORK_BYTES_SENT:
            case UsageTypes.RUNNING_VM:
            case UsageTypes.ALLOCATED_VM:
            case UsageTypes.VM_SNAPSHOT:
                VMInstanceVO vm = _vmDao.findByUuidIncludingRemoved(usageId);
                if (vm != null) {
                    usageDbId = vm.getId();
                }
                if (vm == null && (usageType == UsageTypes.NETWORK_BYTES_RECEIVED || usageType == UsageTypes.NETWORK_BYTES_SENT)) {
                    HostVO host = _hostDao.findByUuidIncludingRemoved(usageId);
                    if (host != null) {
                        usageDbId = host.getId();
                    }
                }
                break;
            case UsageTypes.SNAPSHOT:
                SnapshotVO snap = _snapshotDao.findByUuidIncludingRemoved(usageId);
                if (snap != null) {
                    usageDbId = snap.getId();
                }
                break;
            case UsageTypes.TEMPLATE:
            case UsageTypes.ISO:
                VMTemplateVO tmpl = _vmTemplateDao.findByUuidIncludingRemoved(usageId);
                if (tmpl != null) {
                    usageDbId = tmpl.getId();
                }
                break;
            case UsageTypes.LOAD_BALANCER_POLICY:
                LoadBalancerVO lb = _lbDao.findByUuidIncludingRemoved(usageId);
                if (lb != null) {
                    usageDbId = lb.getId();
                }
                break;
            case UsageTypes.PORT_FORWARDING_RULE:
                PortForwardingRuleVO pf = _pfDao.findByUuidIncludingRemoved(usageId);
                if (pf != null) {
                    usageDbId = pf.getId();
                }
                break;
            case UsageTypes.VOLUME:
            case UsageTypes.VM_DISK_IO_READ:
            case UsageTypes.VM_DISK_IO_WRITE:
            case UsageTypes.VM_DISK_BYTES_READ:
            case UsageTypes.VM_DISK_BYTES_WRITE:
                VolumeVO volume = _volumeDao.findByUuidIncludingRemoved(usageId);
                if (volume != null) {
                    usageDbId = volume.getId();
                }
                break;
            case UsageTypes.VPN_USERS:
                VpnUserVO vpnUser = _vpnUserDao.findByUuidIncludingRemoved(usageId);
                if (vpnUser != null) {
                    usageDbId = vpnUser.getId();
                }
                break;
            case UsageTypes.SECURITY_GROUP:
                SecurityGroupVO sg = _sgDao.findByUuidIncludingRemoved(usageId);
                if (sg != null) {
                    usageDbId = sg.getId();
                }
                break;
            case UsageTypes.IP_ADDRESS:
                IPAddressVO ip = _ipDao.findByUuidIncludingRemoved(usageId);
                if (ip != null) {
                    usageDbId = ip.getId();
                }
                break;
            default:
                break;
        }
        if (usageDbId != null) {
            sc.addAnd("usageId", SearchCriteria.Op.EQ, usageDbId);
        } else {
            // return an empty list if usageId was not found
            return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
        }
    }
    if ((adjustedStartDate != null) && (adjustedEndDate != null) && adjustedStartDate.before(adjustedEndDate)) {
        sc.addAnd("startDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
        sc.addAnd("endDate", SearchCriteria.Op.BETWEEN, adjustedStartDate, adjustedEndDate);
    } else {
        // return an empty list if we fail to validate the dates
        return new Pair<List<? extends Usage>, Integer>(new ArrayList<Usage>(), new Integer(0));
    }
    Pair<List<UsageVO>, Integer> usageRecords = null;
    TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.USAGE_DB);
    try {
        usageRecords = _usageDao.searchAndCountAllRecords(sc, usageFilter);
    } finally {
        txn.close();
        // switch back to VMOPS_DB
        TransactionLegacy swap = TransactionLegacy.open(TransactionLegacy.CLOUD_DB);
        swap.close();
    }
    return new Pair<List<? extends Usage>, Integer>(usageRecords.first(), usageRecords.second());
}
Also used : Account(com.cloud.user.Account) VpnUserVO(com.cloud.network.VpnUserVO) ArrayList(java.util.ArrayList) VMTemplateVO(com.cloud.storage.VMTemplateVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) AccountVO(com.cloud.user.AccountVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair) PortForwardingRuleVO(com.cloud.network.rules.PortForwardingRuleVO) Usage(org.apache.cloudstack.usage.Usage) SecurityGroupVO(com.cloud.network.security.SecurityGroupVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) Project(com.cloud.projects.Project) DomainVO(com.cloud.domain.DomainVO) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) TimeZone(java.util.TimeZone) SnapshotVO(com.cloud.storage.SnapshotVO) Filter(com.cloud.utils.db.Filter) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 25 with PermissionDeniedException

use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.

the class UserVmManagerImpl method recoverVirtualMachine.

@Override
@DB
public UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
    final Long vmId = cmd.getId();
    Account caller = CallContext.current().getCallingAccount();
    final Long userId = caller.getAccountId();
    // Verify input parameters
    final UserVmVO vm = _vmDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
    }
    // When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
    if (!_accountMgr.isAdmin(userId) && !AllowUserExpungeRecoverVm.valueIn(userId)) {
        throw new PermissionDeniedException("Recovering a vm can only be done by an Admin. Or when the allow.user.expunge.recover.vm key is set.");
    }
    if (vm.getRemoved() != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unable to find vm or vm is removed: " + vmId);
        }
        throw new InvalidParameterValueException("Unable to find vm by id " + vmId);
    }
    if (vm.getState() != State.Destroyed) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("vm is not in the right state: " + vmId);
        }
        throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Recovering vm " + vmId);
    }
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
            Account account = _accountDao.lockRow(vm.getAccountId(), true);
            // if the account is deleted, throw error
            if (account.getRemoved() != null) {
                throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
            }
            // Get serviceOffering for Virtual Machine
            ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
            // First check that the maximum number of UserVMs, CPU and Memory limit for the given
            // accountId will not be exceeded
            resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
            _haMgr.cancelDestroy(vm, vm.getHostId());
            try {
                if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) {
                    s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId);
                    throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
                }
            } catch (NoTransitionException e) {
                throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
            }
            // Recover the VM's disks
            List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
            for (VolumeVO volume : volumes) {
                if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
                    // Create an event
                    Long templateId = volume.getTemplateId();
                    Long diskOfferingId = volume.getDiskOfferingId();
                    Long offeringId = null;
                    if (diskOfferingId != null) {
                        DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
                        if (offering != null && (offering.getType() == DiskOfferingVO.Type.Disk)) {
                            offeringId = offering.getId();
                        }
                    }
                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
                }
            }
            //Update Resource Count for the given account
            resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
        }
    });
    return _vmDao.findById(vmId);
}
Also used : Account(com.cloud.user.Account) TransactionStatus(com.cloud.utils.db.TransactionStatus) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) DB(com.cloud.utils.db.DB)

Aggregations

PermissionDeniedException (com.cloud.exception.PermissionDeniedException)82 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)70 Account (com.cloud.user.Account)69 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)26 ActionEvent (com.cloud.event.ActionEvent)23 ArrayList (java.util.ArrayList)22 Project (com.cloud.projects.Project)16 DB (com.cloud.utils.db.DB)15 HashMap (java.util.HashMap)15 DataCenterVO (com.cloud.dc.DataCenterVO)13 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)13 ConfigurationException (javax.naming.ConfigurationException)13 DomainVO (com.cloud.domain.DomainVO)11 Pair (com.cloud.utils.Pair)11 List (java.util.List)11 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)10 VolumeVO (com.cloud.storage.VolumeVO)10 TransactionStatus (com.cloud.utils.db.TransactionStatus)10 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)8