Search in sources :

Example 86 with Account

use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method uploadVolume.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_UPLOAD, eventDescription = "uploading volume for post upload", async = true)
public GetUploadParamsResponse uploadVolume(final GetUploadParamsForVolumeCmd cmd) throws ResourceAllocationException, MalformedURLException {
    final Account caller = CallContext.current().getCallingAccount();
    final long ownerId = cmd.getEntityOwnerId();
    final Account owner = _entityMgr.findById(Account.class, ownerId);
    final Long zoneId = cmd.getZoneId();
    final String volumeName = cmd.getName();
    final String format = cmd.getFormat();
    final Long diskOfferingId = cmd.getDiskOfferingId();
    final String imageStoreUuid = cmd.getImageStoreUuid();
    final DataStore store = _tmpltMgr.getImageStore(imageStoreUuid, zoneId);
    validateVolume(caller, ownerId, zoneId, volumeName, null, format, diskOfferingId);
    return Transaction.execute(new TransactionCallbackWithException<GetUploadParamsResponse, MalformedURLException>() {

        @Override
        public GetUploadParamsResponse doInTransaction(final TransactionStatus status) throws MalformedURLException {
            final VolumeVO volume = persistVolume(owner, zoneId, volumeName, null, cmd.getFormat(), diskOfferingId, Volume.State.NotUploaded);
            final VolumeInfo vol = volFactory.getVolume(volume.getId());
            final RegisterVolumePayload payload = new RegisterVolumePayload(null, cmd.getChecksum(), cmd.getFormat());
            vol.addPayload(payload);
            final Pair<EndPoint, DataObject> pair = volService.registerVolumeForPostUpload(vol, store);
            final EndPoint ep = pair.first();
            final DataObject dataObject = pair.second();
            final GetUploadParamsResponse response = new GetUploadParamsResponse();
            final String ssvmUrlDomain = _configDao.getValue(Config.SecStorageSecureCopyCert.key());
            final String url = ImageStoreUtil.generatePostUploadUrl(ssvmUrlDomain, ep.getPublicAddr(), vol.getUuid());
            response.setPostURL(new URL(url));
            // set the post url, this is used in the monitoring thread to determine the SSVM
            final VolumeDataStoreVO volumeStore = _volumeStoreDao.findByVolume(vol.getId());
            assert volumeStore != null : "sincle volume is registered, volumestore cannot be null at this stage";
            volumeStore.setExtractUrl(url);
            _volumeStoreDao.persist(volumeStore);
            response.setId(UUID.fromString(vol.getUuid()));
            final int timeout = ImageStoreUploadMonitorImpl.getUploadOperationTimeout();
            final DateTime currentDateTime = new DateTime(DateTimeZone.UTC);
            final String expires = currentDateTime.plusMinutes(timeout).toString();
            response.setTimeout(expires);
            final String key = _configDao.getValue(Config.SSVMPSK.key());
            /*
                 * encoded metadata using the post upload config key
                 */
            final TemplateOrVolumePostUploadCommand command = new TemplateOrVolumePostUploadCommand(vol.getId(), vol.getUuid(), volumeStore.getInstallPath(), cmd.getChecksum(), vol.getType().toString(), vol.getName(), vol.getFormat().toString(), dataObject.getDataStore().getUri(), dataObject.getDataStore().getRole().toString());
            command.setLocalPath(volumeStore.getLocalDownloadPath());
            // using the existing max upload size configuration
            command.setMaxUploadSize(_configDao.getValue(Config.MaxUploadVolumeSize.key()));
            command.setDefaultMaxAccountSecondaryStorage(_configDao.getValue(Config.DefaultMaxAccountSecondaryStorage.key()));
            command.setAccountId(vol.getAccountId());
            final Gson gson = new GsonBuilder().create();
            final String metadata = EncryptionUtil.encodeData(gson.toJson(command), key);
            response.setMetadata(metadata);
            /*
                 * signature calculated on the url, expiry, metadata.
                 */
            response.setSignature(EncryptionUtil.generateSignature(metadata + url + expires, key));
            return response;
        }
    });
}
Also used : Account(com.cloud.user.Account) MalformedURLException(java.net.MalformedURLException) GsonBuilder(com.google.gson.GsonBuilder) TransactionStatus(com.cloud.utils.db.TransactionStatus) Gson(com.google.gson.Gson) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) GetUploadParamsResponse(com.cloud.api.response.GetUploadParamsResponse) URL(java.net.URL) DateTime(org.joda.time.DateTime) DataObject(com.cloud.engine.subsystem.api.storage.DataObject) TemplateOrVolumePostUploadCommand(com.cloud.storage.command.TemplateOrVolumePostUploadCommand) DataStore(com.cloud.engine.subsystem.api.storage.DataStore) VolumeDataStoreVO(com.cloud.storage.datastore.db.VolumeDataStoreVO) Pair(com.cloud.utils.Pair) ActionEvent(com.cloud.event.ActionEvent)

Example 87 with Account

use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.

the class VolumeApiServiceImpl method detachVolumeFromVmThroughJobQueue.

public Outcome<Volume> detachVolumeFromVmThroughJobQueue(final Long vmId, final Long volumeId) {
    final CallContext context = CallContext.current();
    final User callingUser = context.getCallingUser();
    final Account callingAccount = context.getCallingAccount();
    final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
    final VmWorkJobVO workJob = new VmWorkJobVO(context.getContextId());
    workJob.setDispatcher(VmWorkConstants.VM_WORK_JOB_DISPATCHER);
    workJob.setCmd(VmWorkDetachVolume.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)
    final VmWorkDetachVolume workInfo = new VmWorkDetachVolume(callingUser.getId(), callingAccount.getId(), vm.getId(), VolumeApiServiceImpl.VM_WORK_JOB_HANDLER, volumeId);
    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) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) CallContext(com.cloud.context.CallContext) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO)

Example 88 with Account

use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.

the class ConfigurationManagerTest method setup.

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    configurationMgr._accountMgr = _accountMgr;
    configurationMgr._projectMgr = _projectMgr;
    configurationMgr._resourceLimitMgr = _resourceLimitMgr;
    configurationMgr._networkMgr = _networkMgr;
    configurationMgr._accountDao = _accountDao;
    configurationMgr._vlanDao = _vlanDao;
    configurationMgr._accountVlanMapDao = _accountVlanMapDao;
    configurationMgr._domainVlanMapDao = _domainVlanMapDao;
    configurationMgr._publicIpAddressDao = _publicIpAddressDao;
    configurationMgr._zoneDao = _zoneDao;
    configurationMgr._firewallDao = _firewallDao;
    configurationMgr._ipAddrMgr = _ipAddrMgr;
    configurationMgr._networkModel = _networkModel;
    configurationMgr._privateIpAddressDao = _privateIpAddressDao;
    configurationMgr._volumeDao = _volumeDao;
    configurationMgr._hostDao = _hostDao;
    configurationMgr._vmInstanceDao = _vmInstanceDao;
    configurationMgr._clusterDao = _clusterDao;
    configurationMgr._podDao = _podDao;
    configurationMgr._physicalNetworkDao = _physicalNetworkDao;
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(configurationMgr._accountMgr.getAccount(anyLong())).thenReturn(account);
    when(configurationMgr._accountDao.findActiveAccount(anyString(), anyLong())).thenReturn(account);
    when(configurationMgr._accountMgr.getActiveAccountById(anyLong())).thenReturn(account);
    final UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    when(configurationMgr._publicIpAddressDao.countIPs(anyLong(), anyLong(), anyBoolean())).thenReturn(1);
    doNothing().when(configurationMgr._resourceLimitMgr).checkResourceLimit(any(Account.class), any(ResourceType.class), anyLong());
    when(configurationMgr._accountVlanMapDao.persist(any(AccountVlanMapVO.class))).thenReturn(new AccountVlanMapVO());
    when(configurationMgr._vlanDao.acquireInLockTable(anyLong(), anyInt())).thenReturn(vlan);
    final Field dedicateIdField = _dedicatePublicIpRangeClass.getDeclaredField("id");
    dedicateIdField.setAccessible(true);
    dedicateIdField.set(dedicatePublicIpRangesCmd, 1L);
    final Field accountNameField = _dedicatePublicIpRangeClass.getDeclaredField("accountName");
    accountNameField.setAccessible(true);
    accountNameField.set(dedicatePublicIpRangesCmd, "accountname");
    final Field projectIdField = _dedicatePublicIpRangeClass.getDeclaredField("projectId");
    projectIdField.setAccessible(true);
    projectIdField.set(dedicatePublicIpRangesCmd, null);
    final Field domainIdField = _dedicatePublicIpRangeClass.getDeclaredField("domainId");
    domainIdField.setAccessible(true);
    domainIdField.set(dedicatePublicIpRangesCmd, 1L);
    final Field releaseIdField = _releasePublicIpRangeClass.getDeclaredField("id");
    releaseIdField.setAccessible(true);
    releaseIdField.set(releasePublicIpRangesCmd, 1L);
}
Also used : Account(com.cloud.user.Account) Field(java.lang.reflect.Field) UserVO(com.cloud.user.UserVO) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) ResourceType(com.cloud.configuration.Resource.ResourceType) AccountVO(com.cloud.user.AccountVO) Before(org.junit.Before)

Example 89 with Account

use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.

the class CertServiceTest method runUploadSslCertBadChain.

@Test
public void runUploadSslCertBadChain() throws IOException, IllegalAccessException, NoSuchFieldException {
    Assume.assumeTrue(isOpenJdk() || isJCEInstalled());
    final String certFile = URLDecoder.decode(getClass().getResource("/certs/rsa_ca_signed.crt").getFile(), Charset.defaultCharset().name());
    final String keyFile = URLDecoder.decode(getClass().getResource("/certs/rsa_ca_signed.key").getFile(), Charset.defaultCharset().name());
    final String chainFile = URLDecoder.decode(getClass().getResource("/certs/rsa_self_signed.crt").getFile(), Charset.defaultCharset().name());
    final String cert = readFileToString(new File(certFile));
    final String key = readFileToString(new File(keyFile));
    final String chain = readFileToString(new File(chainFile));
    final CertServiceImpl certService = new CertServiceImpl();
    // setting mock objects
    certService._accountMgr = Mockito.mock(AccountManager.class);
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(certService._accountMgr.getAccount(anyLong())).thenReturn(account);
    certService._domainDao = Mockito.mock(DomainDao.class);
    final DomainVO domain = new DomainVO("networkdomain", 1L, 1L, "networkdomain");
    when(certService._domainDao.findByIdIncludingRemoved(anyLong())).thenReturn(domain);
    certService._sslCertDao = Mockito.mock(SslCertDao.class);
    when(certService._sslCertDao.persist(any(SslCertVO.class))).thenReturn(new SslCertVO());
    // creating the command
    final UploadSslCertCmd uploadCmd = new UploadSslCertCmdExtn();
    final Class<?> _class = uploadCmd.getClass().getSuperclass();
    final Field certField = _class.getDeclaredField("cert");
    certField.setAccessible(true);
    certField.set(uploadCmd, cert);
    final Field keyField = _class.getDeclaredField("key");
    keyField.setAccessible(true);
    keyField.set(uploadCmd, key);
    final Field chainField = _class.getDeclaredField("chain");
    chainField.setAccessible(true);
    chainField.set(uploadCmd, chain);
    try {
        certService.uploadSslCert(uploadCmd);
        fail("The chain given is not the correct chain for the certificate");
    } catch (final Exception e) {
        assertTrue(e.getMessage().contains("Invalid certificate chain"));
    }
}
Also used : Account(com.cloud.user.Account) SslCertDao(com.cloud.network.dao.SslCertDao) FileUtils.readFileToString(org.apache.commons.io.FileUtils.readFileToString) AccountVO(com.cloud.user.AccountVO) IOException(java.io.IOException) DomainVO(com.cloud.domain.DomainVO) Field(java.lang.reflect.Field) SslCertVO(com.cloud.network.dao.SslCertVO) DomainDao(com.cloud.domain.dao.DomainDao) AccountManager(com.cloud.user.AccountManager) UploadSslCertCmd(com.cloud.api.command.user.loadbalancer.UploadSslCertCmd) File(java.io.File) Test(org.junit.Test)

Example 90 with Account

use of com.cloud.user.Account in project cosmic by MissionCriticalCloud.

the class CertServiceTest method runUploadSslCertNotX509.

@Test
public void runUploadSslCertNotX509() throws IOException, IllegalAccessException, NoSuchFieldException {
    // Reading appropritate files
    final String certFile = URLDecoder.decode(getClass().getResource("/certs/non_x509_pem.crt").getFile(), Charset.defaultCharset().name());
    final String keyFile = URLDecoder.decode(getClass().getResource("/certs/rsa_self_signed.key").getFile(), Charset.defaultCharset().name());
    final String cert = readFileToString(new File(certFile));
    final String key = readFileToString(new File(keyFile));
    final CertServiceImpl certService = new CertServiceImpl();
    // setting mock objects
    certService._accountMgr = Mockito.mock(AccountManager.class);
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(certService._accountMgr.getAccount(anyLong())).thenReturn(account);
    certService._domainDao = Mockito.mock(DomainDao.class);
    final DomainVO domain = new DomainVO("networkdomain", 1L, 1L, "networkdomain");
    when(certService._domainDao.findByIdIncludingRemoved(anyLong())).thenReturn(domain);
    certService._sslCertDao = Mockito.mock(SslCertDao.class);
    when(certService._sslCertDao.persist(any(SslCertVO.class))).thenReturn(new SslCertVO());
    // creating the command
    final UploadSslCertCmd uploadCmd = new UploadSslCertCmdExtn();
    final Class<?> _class = uploadCmd.getClass().getSuperclass();
    final Field certField = _class.getDeclaredField("cert");
    certField.setAccessible(true);
    certField.set(uploadCmd, cert);
    final Field keyField = _class.getDeclaredField("key");
    keyField.setAccessible(true);
    keyField.set(uploadCmd, key);
    try {
        certService.uploadSslCert(uploadCmd);
        fail("Given a Certificate which is not X509, upload should fail");
    } catch (final Exception e) {
        assertTrue(e.getMessage().contains("Expected X509 certificate"));
    }
}
Also used : Account(com.cloud.user.Account) SslCertDao(com.cloud.network.dao.SslCertDao) FileUtils.readFileToString(org.apache.commons.io.FileUtils.readFileToString) AccountVO(com.cloud.user.AccountVO) IOException(java.io.IOException) DomainVO(com.cloud.domain.DomainVO) Field(java.lang.reflect.Field) SslCertVO(com.cloud.network.dao.SslCertVO) DomainDao(com.cloud.domain.dao.DomainDao) AccountManager(com.cloud.user.AccountManager) UploadSslCertCmd(com.cloud.api.command.user.loadbalancer.UploadSslCertCmd) File(java.io.File) Test(org.junit.Test)

Aggregations

Account (com.cloud.user.Account)1088 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)308 ArrayList (java.util.ArrayList)293 ActionEvent (com.cloud.event.ActionEvent)243 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)216 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)207 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)170 User (com.cloud.user.User)149 List (java.util.List)147 DB (com.cloud.utils.db.DB)130 Test (org.junit.Test)123 Pair (com.cloud.utils.Pair)115 AccountVO (com.cloud.user.AccountVO)113 Network (com.cloud.network.Network)104 Filter (com.cloud.utils.db.Filter)103 TransactionStatus (com.cloud.utils.db.TransactionStatus)95 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)94 DomainVO (com.cloud.domain.DomainVO)91 Domain (com.cloud.domain.Domain)87 UserVO (com.cloud.user.UserVO)86