Search in sources :

Example 86 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class ConfigurationManagerImpl method createDedicatedAffinityGroup.

private AffinityGroup createDedicatedAffinityGroup(String affinityGroupName, final Long domainId, final Long accountId) {
    if (affinityGroupName == null) {
        // default to a groupname with account/domain information
        affinityGroupName = "ZoneDedicatedGrp-domain-" + domainId + (accountId != null ? "-acct-" + accountId : "");
    }
    AffinityGroup group = null;
    String accountName = null;
    if (accountId != null) {
        final AccountVO account = _accountDao.findById(accountId);
        accountName = account.getAccountName();
        group = _affinityGroupDao.findByAccountAndName(accountId, affinityGroupName);
        if (group != null) {
            return group;
        }
    } else {
        // domain level group
        group = _affinityGroupDao.findDomainLevelGroupByName(domainId, affinityGroupName);
        if (group != null) {
            return group;
        }
    }
    group = _affinityGroupService.createAffinityGroup(accountName, null, domainId, affinityGroupName, "ExplicitDedication", "dedicated resources group");
    return group;
}
Also used : AccountVO(com.cloud.user.AccountVO) AffinityGroup(org.apache.cloudstack.affinity.AffinityGroup)

Example 87 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class ConfigurationManagerImpl method updateConfiguration.

@Override
@DB
public String updateConfiguration(final long userId, final String name, final String category, final String value, final String scope, final Long resourceId) {
    final String validationMsg = validateConfigurationValue(name, value, scope);
    if (validationMsg != null) {
        s_logger.error("Invalid configuration option, name: " + name + ", value:" + value);
        throw new InvalidParameterValueException(validationMsg);
    }
    // global parameter updation
    if (scope != null && !scope.isEmpty() && !ConfigKey.Scope.Global.toString().equalsIgnoreCase(scope)) {
        switch(ConfigKey.Scope.valueOf(scope)) {
            case Zone:
                final DataCenterVO zone = _zoneDao.findById(resourceId);
                if (zone == null) {
                    throw new InvalidParameterValueException("unable to find zone by id " + resourceId);
                }
                _dcDetailsDao.addDetail(resourceId, name, value, true);
                break;
            case Cluster:
                final ClusterVO cluster = _clusterDao.findById(resourceId);
                if (cluster == null) {
                    throw new InvalidParameterValueException("unable to find cluster by id " + resourceId);
                }
                ClusterDetailsVO clusterDetailsVO = _clusterDetailsDao.findDetail(resourceId, name);
                if (clusterDetailsVO == null) {
                    clusterDetailsVO = new ClusterDetailsVO(resourceId, name, value);
                    _clusterDetailsDao.persist(clusterDetailsVO);
                } else {
                    clusterDetailsVO.setValue(value);
                    _clusterDetailsDao.update(clusterDetailsVO.getId(), clusterDetailsVO);
                }
                break;
            case StoragePool:
                final StoragePoolVO pool = _storagePoolDao.findById(resourceId);
                if (pool == null) {
                    throw new InvalidParameterValueException("unable to find storage pool by id " + resourceId);
                }
                if (name.equals(CapacityManager.StorageOverprovisioningFactor.key())) {
                    if (!pool.getPoolType().supportsOverProvisioning()) {
                        throw new InvalidParameterValueException("Unable to update  storage pool with id " + resourceId + ". Overprovision not supported for " + pool.getPoolType());
                    }
                }
                _storagePoolDetailsDao.addDetail(resourceId, name, value, true);
                break;
            case Account:
                final AccountVO account = _accountDao.findById(resourceId);
                if (account == null) {
                    throw new InvalidParameterValueException("unable to find account by id " + resourceId);
                }
                AccountDetailVO accountDetailVO = _accountDetailsDao.findDetail(resourceId, name);
                if (accountDetailVO == null) {
                    accountDetailVO = new AccountDetailVO(resourceId, name, value);
                    _accountDetailsDao.persist(accountDetailVO);
                } else {
                    accountDetailVO.setValue(value);
                    _accountDetailsDao.update(accountDetailVO.getId(), accountDetailVO);
                }
                break;
            case ImageStore:
                final ImageStoreVO imgStore = _imageStoreDao.findById(resourceId);
                Preconditions.checkState(imgStore != null);
                _imageStoreDetailsDao.addDetail(resourceId, name, value, true);
                break;
            default:
                throw new InvalidParameterValueException("Scope provided is invalid");
        }
        return value;
    }
    // Execute all updates in a single transaction
    final TransactionLegacy txn = TransactionLegacy.currentTxn();
    txn.start();
    if (!_configDao.update(name, category, value)) {
        s_logger.error("Failed to update configuration option, name: " + name + ", value:" + value);
        throw new CloudRuntimeException("Failed to update configuration value. Please contact Cloud Support.");
    }
    PreparedStatement pstmt = null;
    if (Config.XenServerGuestNetwork.key().equalsIgnoreCase(name)) {
        final String sql = "update host_details set value=? where name=?";
        try {
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setString(1, value);
            pstmt.setString(2, "guest.network.device");
            pstmt.executeUpdate();
        } catch (final Throwable e) {
            throw new CloudRuntimeException("Failed to update guest.network.device in host_details due to exception ", e);
        }
    } else if (Config.XenServerPrivateNetwork.key().equalsIgnoreCase(name)) {
        final String sql = "update host_details set value=? where name=?";
        try {
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setString(1, value);
            pstmt.setString(2, "private.network.device");
            pstmt.executeUpdate();
        } catch (final Throwable e) {
            throw new CloudRuntimeException("Failed to update private.network.device in host_details due to exception ", e);
        }
    } else if (Config.XenServerPublicNetwork.key().equalsIgnoreCase(name)) {
        final String sql = "update host_details set value=? where name=?";
        try {
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setString(1, value);
            pstmt.setString(2, "public.network.device");
            pstmt.executeUpdate();
        } catch (final Throwable e) {
            throw new CloudRuntimeException("Failed to update public.network.device in host_details due to exception ", e);
        }
    } else if (Config.XenServerStorageNetwork1.key().equalsIgnoreCase(name)) {
        final String sql = "update host_details set value=? where name=?";
        try {
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setString(1, value);
            pstmt.setString(2, "storage.network.device1");
            pstmt.executeUpdate();
        } catch (final Throwable e) {
            throw new CloudRuntimeException("Failed to update storage.network.device1 in host_details due to exception ", e);
        }
    } else if (Config.XenServerStorageNetwork2.key().equals(name)) {
        final String sql = "update host_details set value=? where name=?";
        try {
            pstmt = txn.prepareAutoCloseStatement(sql);
            pstmt.setString(1, value);
            pstmt.setString(2, "storage.network.device2");
            pstmt.executeUpdate();
        } catch (final Throwable e) {
            throw new CloudRuntimeException("Failed to update storage.network.device2 in host_details due to exception ", e);
        }
    } else if (Config.SecStorageSecureCopyCert.key().equalsIgnoreCase(name)) {
        //FIXME - Ideally there should be a listener model to listen to global config changes and be able to take action gracefully.
        //Expire the download urls
        final String sqlTemplate = "update template_store_ref set download_url_created=?";
        final String sqlVolume = "update volume_store_ref set download_url_created=?";
        try {
            // Change for templates
            pstmt = txn.prepareAutoCloseStatement(sqlTemplate);
            // Set the time before the epoch time.
            pstmt.setDate(1, new Date(-1l));
            pstmt.executeUpdate();
            // Change for volumes
            pstmt = txn.prepareAutoCloseStatement(sqlVolume);
            // Set the time before the epoch time.
            pstmt.setDate(1, new Date(-1l));
            pstmt.executeUpdate();
            // Cleanup the download urls
            _storageManager.cleanupDownloadUrls();
        } catch (final Throwable e) {
            throw new CloudRuntimeException("Failed to clean up download URLs in template_store_ref or volume_store_ref due to exception ", e);
        }
    }
    txn.commit();
    return _configDao.getValue(name);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) ClusterVO(com.cloud.dc.ClusterVO) PreparedStatement(java.sql.PreparedStatement) AccountVO(com.cloud.user.AccountVO) Date(java.sql.Date) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) AccountDetailVO(com.cloud.user.AccountDetailVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ImageStoreVO(org.apache.cloudstack.storage.datastore.db.ImageStoreVO) ClusterDetailsVO(com.cloud.dc.ClusterDetailsVO) DB(com.cloud.utils.db.DB)

Example 88 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class DedicatedApiUnitTest method setUp.

@Before
public void setUp() {
    ComponentContext.initComponentsLifeCycle();
    AccountVO account = new AccountVO(accountName, domainId, "networkDomain", Account.ACCOUNT_TYPE_NORMAL, "uuid");
    DomainVO domain = new DomainVO("rootDomain", 5L, 5L, "networkDomain");
    UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    when(_acctMgr.finalizeOwner((Account) anyObject(), anyString(), anyLong(), anyLong())).thenReturn(account);
    when(_accountDao.findByIdIncludingRemoved(0L)).thenReturn(account);
    when(_accountDao.findById(anyLong())).thenReturn(account);
    when(_domainDao.findById(domainId)).thenReturn(domain);
}
Also used : DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) AccountVO(com.cloud.user.AccountVO) Before(org.junit.Before)

Example 89 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class SnapshotManagerImpl method createPolicy.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_POLICY_CREATE, eventDescription = "creating snapshot policy")
public SnapshotPolicyVO createPolicy(CreateSnapshotPolicyCmd cmd, Account policyOwner) {
    Long volumeId = cmd.getVolumeId();
    boolean display = cmd.isDisplay();
    VolumeVO volume = _volsDao.findById(cmd.getVolumeId());
    if (volume == null) {
        throw new InvalidParameterValueException("Failed to create snapshot policy, unable to find a volume with id " + volumeId);
    }
    _accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
    // If display is false we don't actually schedule snapshots.
    if (volume.getState() != Volume.State.Ready && display) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
    }
    if (volume.getTemplateId() != null) {
        VMTemplateVO template = _templateDao.findById(volume.getTemplateId());
        if (template != null && template.getTemplateType() == Storage.TemplateType.SYSTEM) {
            throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
        }
    }
    AccountVO owner = _accountDao.findById(volume.getAccountId());
    Long instanceId = volume.getInstanceId();
    if (instanceId != null) {
        // It is not detached, but attached to a VM
        if (_vmDao.findById(instanceId) == null) {
            // It is not a UserVM but a SystemVM or DomR
            throw new InvalidParameterValueException("Failed to create snapshot policy, snapshots of volumes attached to System or router VM are not allowed");
        }
    }
    IntervalType intvType = DateUtil.IntervalType.getIntervalType(cmd.getIntervalType());
    if (intvType == null) {
        throw new InvalidParameterValueException("Unsupported interval type " + cmd.getIntervalType());
    }
    Type type = getSnapshotType(intvType);
    TimeZone timeZone = TimeZone.getTimeZone(cmd.getTimezone());
    String timezoneId = timeZone.getID();
    if (!timezoneId.equals(cmd.getTimezone())) {
        s_logger.warn("Using timezone: " + timezoneId + " for running this snapshot policy as an equivalent of " + cmd.getTimezone());
    }
    try {
        DateUtil.getNextRunTime(intvType, cmd.getSchedule(), timezoneId, null);
    } catch (Exception e) {
        throw new InvalidParameterValueException("Invalid schedule: " + cmd.getSchedule() + " for interval type: " + cmd.getIntervalType());
    }
    if (cmd.getMaxSnaps() <= 0) {
        throw new InvalidParameterValueException("maxSnaps should be greater than 0");
    }
    int intervalMaxSnaps = type.getMax();
    if (cmd.getMaxSnaps() > intervalMaxSnaps) {
        throw new InvalidParameterValueException("maxSnaps exceeds limit: " + intervalMaxSnaps + " for interval type: " + cmd.getIntervalType());
    }
    // Verify that max doesn't exceed domain and account snapshot limits in case display is on
    if (display) {
        long accountLimit = _resourceLimitMgr.findCorrectResourceLimitForAccount(owner, ResourceType.snapshot);
        long domainLimit = _resourceLimitMgr.findCorrectResourceLimitForDomain(_domainMgr.getDomain(owner.getDomainId()), ResourceType.snapshot);
        int max = cmd.getMaxSnaps().intValue();
        if (!_accountMgr.isRootAdmin(owner.getId()) && ((accountLimit != -1 && max > accountLimit) || (domainLimit != -1 && max > domainLimit))) {
            String message = "domain/account";
            if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) {
                message = "domain/project";
            }
            throw new InvalidParameterValueException("Max number of snapshots shouldn't exceed the " + message + " level snapshot limit");
        }
    }
    SnapshotPolicyVO policy = _snapshotPolicyDao.findOneByVolumeInterval(volumeId, intvType);
    if (policy == null) {
        policy = new SnapshotPolicyVO(volumeId, cmd.getSchedule(), timezoneId, intvType, cmd.getMaxSnaps(), display);
        policy = _snapshotPolicyDao.persist(policy);
        _snapSchedMgr.scheduleNextSnapshotJob(policy);
    } else {
        try {
            boolean previousDisplay = policy.isDisplay();
            policy = _snapshotPolicyDao.acquireInLockTable(policy.getId());
            policy.setSchedule(cmd.getSchedule());
            policy.setTimezone(timezoneId);
            policy.setInterval((short) intvType.ordinal());
            policy.setMaxSnaps(cmd.getMaxSnaps());
            policy.setActive(true);
            policy.setDisplay(display);
            _snapshotPolicyDao.update(policy.getId(), policy);
            _snapSchedMgr.scheduleOrCancelNextSnapshotJobOnDisplayChange(policy, previousDisplay);
        } finally {
            if (policy != null) {
                _snapshotPolicyDao.releaseFromLockTable(policy.getId());
            }
        }
    }
    // TODO - Make createSnapshotPolicy - BaseAsyncCreate and remove this.
    CallContext.current().putContextParameter(SnapshotPolicy.class, policy.getUuid());
    return policy;
}
Also used : IntervalType(com.cloud.utils.DateUtil.IntervalType) VMTemplateVO(com.cloud.storage.VMTemplateVO) AccountVO(com.cloud.user.AccountVO) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) ScopeType(com.cloud.storage.ScopeType) Type(com.cloud.storage.Snapshot.Type) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ResourceType(com.cloud.configuration.Resource.ResourceType) IntervalType(com.cloud.utils.DateUtil.IntervalType) ResourceObjectType(com.cloud.server.ResourceTag.ResourceObjectType) TimeZone(java.util.TimeZone) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) SnapshotPolicyVO(com.cloud.storage.SnapshotPolicyVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 90 with AccountVO

use of com.cloud.user.AccountVO in project cloudstack by apache.

the class SnapshotManagerTest method setup.

@Before
public void setup() throws ResourceAllocationException {
    MockitoAnnotations.initMocks(this);
    _snapshotMgr._snapshotDao = _snapshotDao;
    _snapshotMgr._volsDao = _volumeDao;
    _snapshotMgr._vmDao = _vmDao;
    _snapshotMgr.volFactory = volumeFactory;
    _snapshotMgr.snapshotFactory = snapshotFactory;
    _snapshotMgr._storageStrategyFactory = _storageStrategyFactory;
    _snapshotMgr._accountMgr = _accountMgr;
    _snapshotMgr._resourceLimitMgr = _resourceLimitMgr;
    _snapshotMgr._storagePoolDao = _storagePoolDao;
    _snapshotMgr._resourceMgr = _resourceMgr;
    _snapshotMgr._vmSnapshotDao = _vmSnapshotDao;
    _snapshotMgr._snapshotStoreDao = _snapshotStoreDao;
    when(_snapshotDao.findById(anyLong())).thenReturn(snapshotMock);
    when(snapshotMock.getVolumeId()).thenReturn(TEST_VOLUME_ID);
    when(snapshotMock.isRecursive()).thenReturn(false);
    when(_volumeDao.findById(anyLong())).thenReturn(volumeMock);
    when(volumeMock.getState()).thenReturn(Volume.State.Ready);
    when(volumeFactory.getVolume(anyLong())).thenReturn(volumeInfoMock);
    when(volumeInfoMock.getDataStore()).thenReturn(storeMock);
    when(volumeInfoMock.getState()).thenReturn(Volume.State.Ready);
    when(storeMock.getId()).thenReturn(TEST_STORAGE_POOL_ID);
    when(snapshotFactory.getSnapshot(anyLong(), Mockito.any(DataStoreRole.class))).thenReturn(snapshotInfoMock);
    when(_storageStrategyFactory.getSnapshotStrategy(Mockito.any(SnapshotVO.class), Mockito.eq(SnapshotOperation.BACKUP))).thenReturn(snapshotStrategy);
    when(_storageStrategyFactory.getSnapshotStrategy(Mockito.any(SnapshotVO.class), Mockito.eq(SnapshotOperation.REVERT))).thenReturn(snapshotStrategy);
    when(_storageStrategyFactory.getSnapshotStrategy(Mockito.any(SnapshotVO.class), Mockito.eq(SnapshotOperation.DELETE))).thenReturn(snapshotStrategy);
    doNothing().when(_accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class));
    doNothing().when(_snapshotMgr._resourceLimitMgr).checkResourceLimit(any(Account.class), any(ResourceType.class));
    doNothing().when(_snapshotMgr._resourceLimitMgr).checkResourceLimit(any(Account.class), any(ResourceType.class), anyLong());
    doNothing().when(_snapshotMgr._resourceLimitMgr).decrementResourceCount(anyLong(), any(ResourceType.class), anyLong());
    doNothing().when(_snapshotMgr._resourceLimitMgr).incrementResourceCount(anyLong(), any(ResourceType.class));
    doNothing().when(_snapshotMgr._resourceLimitMgr).incrementResourceCount(anyLong(), any(ResourceType.class), anyLong());
    Account account = new AccountVO("testaccount", 1L, "networkdomain", (short) 0, "uuid");
    UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    when(_accountMgr.getAccount(anyLong())).thenReturn(account);
    when(_storagePoolDao.findById(anyLong())).thenReturn(poolMock);
    when(poolMock.getScope()).thenReturn(ScopeType.ZONE);
    when(poolMock.getHypervisor()).thenReturn(HypervisorType.KVM);
    when(_resourceMgr.listAllUpAndEnabledHostsInOneZoneByHypervisor(any(HypervisorType.class), anyLong())).thenReturn(null);
}
Also used : HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) DataStoreRole(com.cloud.storage.DataStoreRole) Account(com.cloud.user.Account) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) UserVO(com.cloud.user.UserVO) ControlledEntity(org.apache.cloudstack.acl.ControlledEntity) ResourceType(com.cloud.configuration.Resource.ResourceType) AccountVO(com.cloud.user.AccountVO) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) Before(org.junit.Before)

Aggregations

AccountVO (com.cloud.user.AccountVO)139 Account (com.cloud.user.Account)65 Test (org.junit.Test)52 UserVO (com.cloud.user.UserVO)44 Field (java.lang.reflect.Field)41 ArrayList (java.util.ArrayList)40 DomainVO (com.cloud.domain.DomainVO)32 AccountManager (com.cloud.user.AccountManager)27 Before (org.junit.Before)22 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)21 TransactionLegacy (com.cloud.utils.db.TransactionLegacy)21 Date (java.util.Date)16 QuotaAccountVO (org.apache.cloudstack.quota.vo.QuotaAccountVO)16 DomainDao (com.cloud.domain.dao.DomainDao)14 SslCertDao (com.cloud.network.dao.SslCertDao)14 AgentManager (com.cloud.agent.AgentManager)13 IPAddressDao (com.cloud.network.dao.IPAddressDao)13 LoadBalancerDao (com.cloud.network.dao.LoadBalancerDao)13 NetworkDao (com.cloud.network.dao.NetworkDao)13 NetworkVO (com.cloud.network.dao.NetworkVO)13