use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class StorageManagerImpl method deleteSecondaryStagingStore.
@Override
public boolean deleteSecondaryStagingStore(DeleteSecondaryStagingStoreCmd cmd) {
final long storeId = cmd.getId();
// Verify that cache store exists
ImageStoreVO store = _imageStoreDao.findById(storeId);
if (store == null) {
throw new InvalidParameterValueException("Cache store with id " + storeId + " doesn't exist");
}
_accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), store.getDataCenterId());
// Verify that there are no live snapshot, template, volume on the cache
// store that is currently referenced
List<SnapshotDataStoreVO> snapshots = _snapshotStoreDao.listActiveOnCache(storeId);
if (snapshots != null && snapshots.size() > 0) {
throw new InvalidParameterValueException("Cannot delete cache store with staging snapshots currently in use!");
}
List<VolumeDataStoreVO> volumes = _volumeStoreDao.listActiveOnCache(storeId);
if (volumes != null && volumes.size() > 0) {
throw new InvalidParameterValueException("Cannot delete cache store with staging volumes currently in use!");
}
List<TemplateDataStoreVO> templates = _templateStoreDao.listActiveOnCache(storeId);
if (templates != null && templates.size() > 0) {
throw new InvalidParameterValueException("Cannot delete cache store with staging templates currently in use!");
}
// ready to delete
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
// first delete from image_store_details table, we need to do that since
// we are not actually deleting record from main
// image_data_store table, so delete cascade will not work
_imageStoreDetailsDao.deleteDetails(storeId);
_snapshotStoreDao.deletePrimaryRecordsForStore(storeId, DataStoreRole.ImageCache);
_volumeStoreDao.deletePrimaryRecordsForStore(storeId);
_templateStoreDao.deletePrimaryRecordsForStore(storeId);
_imageStoreDao.remove(storeId);
}
});
return true;
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class TemplateManagerImpl method createPrivateTemplate.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", async = true)
public VirtualMachineTemplate createPrivateTemplate(CreateTemplateCmd command) throws CloudRuntimeException {
final long templateId = command.getEntityId();
Long volumeId = command.getVolumeId();
Long snapshotId = command.getSnapshotId();
VMTemplateVO privateTemplate = null;
final Long accountId = CallContext.current().getCallingAccountId();
SnapshotVO snapshot = null;
VolumeVO volume = null;
try {
TemplateInfo tmplInfo = _tmplFactory.getTemplate(templateId, DataStoreRole.Image);
long zoneId = 0;
if (snapshotId != null) {
snapshot = _snapshotDao.findById(snapshotId);
zoneId = snapshot.getDataCenterId();
} else if (volumeId != null) {
volume = _volumeDao.findById(volumeId);
zoneId = volume.getDataCenterId();
}
DataStore store = _dataStoreMgr.getImageStore(zoneId);
if (store == null) {
throw new CloudRuntimeException("cannot find an image store for zone " + zoneId);
}
AsyncCallFuture<TemplateApiResult> future = null;
if (snapshotId != null) {
DataStoreRole dataStoreRole = ApiResponseHelper.getDataStoreRole(snapshot, _snapshotStoreDao, _dataStoreMgr);
SnapshotInfo snapInfo = _snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
if (dataStoreRole == DataStoreRole.Image) {
if (snapInfo == null) {
snapInfo = _snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
if (snapInfo == null) {
throw new CloudRuntimeException("Cannot find snapshot " + snapshotId);
}
// We need to copy the snapshot onto secondary.
SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.BACKUP);
snapshotStrategy.backupSnapshot(snapInfo);
// Attempt to grab it again.
snapInfo = _snapshotFactory.getSnapshot(snapshotId, dataStoreRole);
if (snapInfo == null) {
throw new CloudRuntimeException("Cannot find snapshot " + snapshotId + " on secondary and could not create backup");
}
}
DataStore snapStore = snapInfo.getDataStore();
if (snapStore != null) {
// pick snapshot image store to create template
store = snapStore;
}
}
future = _tmpltSvr.createTemplateFromSnapshotAsync(snapInfo, tmplInfo, store);
} else if (volumeId != null) {
VolumeInfo volInfo = _volFactory.getVolume(volumeId);
future = _tmpltSvr.createTemplateFromVolumeAsync(volInfo, tmplInfo, store);
} else {
throw new CloudRuntimeException("Creating private Template need to specify snapshotId or volumeId");
}
CommandResult result = null;
try {
result = future.get();
if (result.isFailed()) {
privateTemplate = null;
s_logger.debug("Failed to create template" + result.getResult());
throw new CloudRuntimeException("Failed to create template" + result.getResult());
}
// create entries in template_zone_ref table
if (_dataStoreMgr.isRegionStore(store)) {
// template created on region store
_tmpltSvr.associateTemplateToZone(templateId, null);
} else {
VMTemplateZoneVO templateZone = new VMTemplateZoneVO(zoneId, templateId, new Date());
_tmpltZoneDao.persist(templateZone);
}
privateTemplate = _tmpltDao.findById(templateId);
TemplateDataStoreVO srcTmpltStore = _tmplStoreDao.findByStoreTemplate(store.getId(), templateId);
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_TEMPLATE_CREATE, privateTemplate.getAccountId(), zoneId, privateTemplate.getId(), privateTemplate.getName(), null, privateTemplate.getSourceTemplateId(), srcTmpltStore.getPhysicalSize(), privateTemplate.getSize());
_usageEventDao.persist(usageEvent);
} catch (InterruptedException e) {
s_logger.debug("Failed to create template", e);
throw new CloudRuntimeException("Failed to create template", e);
} catch (ExecutionException e) {
s_logger.debug("Failed to create template", e);
throw new CloudRuntimeException("Failed to create template", e);
}
} finally {
if (privateTemplate == null) {
final VolumeVO volumeFinal = volume;
final SnapshotVO snapshotFinal = snapshot;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
// template_store_ref entries should have been removed using our
// DataObject.processEvent command in case of failure, but clean
// it up here to avoid
// some leftovers which will cause removing template from
// vm_template table fail.
_tmplStoreDao.deletePrimaryRecordsForTemplate(templateId);
// Remove the template_zone_ref record
_tmpltZoneDao.deletePrimaryRecordsForTemplate(templateId);
// Remove the template record
_tmpltDao.expunge(templateId);
// decrement resource count
if (accountId != null) {
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
_resourceLimitMgr.decrementResourceCount(accountId, ResourceType.secondary_storage, new Long(volumeFinal != null ? volumeFinal.getSize() : snapshotFinal.getSize()));
}
}
});
}
}
if (privateTemplate != null) {
return privateTemplate;
} else {
throw new CloudRuntimeException("Failed to create a template");
}
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class DatabaseConfig method doConfig.
@DB
protected void doConfig() {
try {
final File configFile = new File(_configFileName);
SAXParserFactory spfactory = SAXParserFactory.newInstance();
final SAXParser saxParser = spfactory.newSAXParser();
final DbConfigXMLHandler handler = new DbConfigXMLHandler();
handler.setParent(this);
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<Exception>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws Exception {
// Save user configured values for all fields
saxParser.parse(configFile, handler);
// Save default values for configuration fields
saveVMTemplate();
saveRootDomain();
saveDefaultConfiguations();
}
});
// Check pod CIDRs against each other, and against the guest ip network/netmask
pzc.checkAllPodCidrSubnets();
} catch (Exception ex) {
System.out.print("ERROR IS" + ex);
s_logger.error("error", ex);
}
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class AccountManagerImpl method createUserAccount.
// ///////////////////////////////////////////////////
// ////////////// API commands /////////////////////
// ///////////////////////////////////////////////////
@Override
@DB
@ActionEvents({ @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account"), @ActionEvent(eventType = EventTypes.EVENT_USER_CREATE, eventDescription = "creating User") })
public UserAccount createUserAccount(final String userName, final String password, final String firstName, final String lastName, final String email, final String timezone, String accountName, final short accountType, final Long roleId, Long domainId, final String networkDomain, final Map<String, String> details, String accountUUID, final String userUUID, final User.Source source) {
if (accountName == null) {
accountName = userName;
}
if (domainId == null) {
domainId = Domain.ROOT_DOMAIN;
}
if (StringUtils.isEmpty(userName)) {
throw new InvalidParameterValueException("Username is empty");
}
if (StringUtils.isEmpty(firstName)) {
throw new InvalidParameterValueException("Firstname is empty");
}
if (StringUtils.isEmpty(lastName)) {
throw new InvalidParameterValueException("Lastname is empty");
}
// Validate domain
Domain domain = _domainMgr.getDomain(domainId);
if (domain == null) {
throw new InvalidParameterValueException("The domain " + domainId + " does not exist; unable to create account");
}
// Check permissions
checkAccess(CallContext.current().getCallingAccount(), domain);
if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) {
throw new InvalidParameterValueException("The user " + userName + " already exists in domain " + domainId);
}
if (networkDomain != null && networkDomain.length() > 0) {
if (!NetUtils.verifyDomainName(networkDomain)) {
throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
}
}
final String accountNameFinal = accountName;
final Long domainIdFinal = domainId;
final String accountUUIDFinal = accountUUID;
Pair<Long, Account> pair = Transaction.execute(new TransactionCallback<Pair<Long, Account>>() {
@Override
public Pair<Long, Account> doInTransaction(TransactionStatus status) {
// create account
String accountUUID = accountUUIDFinal;
if (accountUUID == null) {
accountUUID = UUID.randomUUID().toString();
}
AccountVO account = createAccount(accountNameFinal, accountType, roleId, domainIdFinal, networkDomain, details, accountUUID);
long accountId = account.getId();
// create the first user for the account
UserVO user = createUser(accountId, userName, password, firstName, lastName, email, timezone, userUUID, source);
if (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
// set registration token
byte[] bytes = (domainIdFinal + accountNameFinal + userName + System.currentTimeMillis()).getBytes();
String registrationToken = UUID.nameUUIDFromBytes(bytes).toString();
user.setRegistrationToken(registrationToken);
}
return new Pair<Long, Account>(user.getId(), account);
}
});
long userId = pair.first();
Account account = pair.second();
// create correct account and group association based on accountType
if (accountType != Account.ACCOUNT_TYPE_PROJECT) {
Map<Long, Long> accountGroupMap = new HashMap<Long, Long>();
accountGroupMap.put(account.getId(), new Long(accountType + 1));
_messageBus.publish(_name, MESSAGE_ADD_ACCOUNT_EVENT, PublishScope.LOCAL, accountGroupMap);
}
CallContext.current().putContextParameter(Account.class, account.getUuid());
// check success
return _userAccountDao.findById(userId);
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class AccountManagerImpl method createApiKeyAndSecretKey.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REGISTER_FOR_SECRET_API_KEY, eventDescription = "register for the developer API keys")
public String[] createApiKeyAndSecretKey(final long userId) {
User user = getUserIncludingRemoved(userId);
if (user == null) {
throw new InvalidParameterValueException("Unable to find user by id");
}
final String[] keys = new String[2];
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
keys[0] = AccountManagerImpl.this.createUserApiKey(userId);
keys[1] = AccountManagerImpl.this.createUserSecretKey(userId);
}
});
return keys;
}
Aggregations