use of com.cloud.utils.db.TransactionStatus in project cosmic by MissionCriticalCloud.
the class DomainManagerImpl method createDomain.
@Override
@DB
public Domain createDomain(final String name, final Long parentId, final Long ownerId, final String networkDomain, String domainUUID, final String email) {
// Verify network domain
if (networkDomain != null) {
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 SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, name);
sc.addAnd("parent", SearchCriteria.Op.EQ, parentId);
final List<DomainVO> domains = _domainDao.search(sc, null);
if (!domains.isEmpty()) {
throw new InvalidParameterValueException("Domain with name " + name + " already exists for the parent id=" + parentId);
}
if (domainUUID == null) {
domainUUID = UUID.randomUUID().toString();
}
final EmailValidator validator = EmailValidator.getInstance();
if (!StringUtils.isEmpty(email) && !validator.isValid(email)) {
throw new InvalidParameterValueException("Email address is not formatted correctly");
}
final String domainUUIDFinal = domainUUID;
final DomainVO domain = Transaction.execute(new TransactionCallback<DomainVO>() {
@Override
public DomainVO doInTransaction(final TransactionStatus status) {
final DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, domainUUIDFinal, email));
_resourceCountDao.createResourceCounts(domain.getId(), ResourceLimit.ResourceOwnerType.Domain);
return domain;
}
});
CallContext.current().putContextParameter(Domain.class, domain.getUuid());
_messageBus.publish(_name, MESSAGE_ADD_DOMAIN_EVENT, PublishScope.LOCAL, domain.getId());
return domain;
}
use of com.cloud.utils.db.TransactionStatus in project cosmic by MissionCriticalCloud.
the class DomainManagerImpl method updateDomain.
@Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
@DB
public DomainVO updateDomain(final UpdateDomainCmd cmd) {
final Long domainId = cmd.getId();
final String domainName = cmd.getDomainName();
final String networkDomain = cmd.getNetworkDomain();
final String email = cmd.getEmail();
// check if domain exists in the system
final DomainVO domain = _domainDao.findById(domainId);
if (domain == null) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
ex.addProxyObject(domainId.toString(), "domainId");
throw ex;
} else if (domain.getParent() == null && domainName != null) {
// check if domain is ROOT domain - and deny to edit it with the new name
throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
}
// check permissions
final Account caller = CallContext.current().getCallingAccount();
_accountMgr.checkAccess(caller, domain);
// domain name is unique in the cloud
if (domainName != null) {
final SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
final List<DomainVO> domains = _domainDao.search(sc, null);
final boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
if (!domains.isEmpty() && !sameDomain) {
final InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
ex.addProxyObject(domain.getUuid(), "domainId");
throw ex;
}
}
// validate network domain
if (networkDomain != null && !networkDomain.isEmpty()) {
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 EmailValidator validator = EmailValidator.getInstance();
if (!StringUtils.isEmpty(email) && !validator.isValid(email)) {
throw new InvalidParameterValueException("Email address is not formatted correctly");
}
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
if (domainName != null) {
final String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
updateDomainChildren(domain, updatedDomainPath);
domain.setName(domainName);
domain.setPath(updatedDomainPath);
}
if (networkDomain != null) {
if (networkDomain.isEmpty()) {
domain.setNetworkDomain(null);
} else {
domain.setNetworkDomain(networkDomain);
}
}
if (email != null) {
if (email.isEmpty()) {
domain.setEmail(null);
} else {
domain.setEmail(email);
}
}
_domainDao.update(domainId, domain);
CallContext.current().putContextParameter(Domain.class, domain.getUuid());
}
});
return _domainDao.findById(domainId);
}
use of com.cloud.utils.db.TransactionStatus in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method recoverVirtualMachine.
@Override
@DB
public UserVm recoverVirtualMachine(final RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
final Long vmId = cmd.getId();
final 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(final TransactionStatus status) throws ResourceAllocationException {
final 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
final 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 (final NoTransitionException e) {
throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
}
// Recover the VM's disks
final List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
for (final VolumeVO volume : volumes) {
if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
// Create an event
final Long templateId = volume.getTemplateId();
final Long diskOfferingId = volume.getDiskOfferingId();
Long offeringId = null;
if (diskOfferingId != null) {
final DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
if (offering != null && offering.getType() == DiskOfferingVO.Type.Disk) {
offeringId = offering.getId();
}
}
}
}
// Update Resource Count for the given account
resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
}
});
return _vmDao.findById(vmId);
}
use of com.cloud.utils.db.TransactionStatus in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method updateNicIpForVirtualMachine.
@Override
public UserVm updateNicIpForVirtualMachine(final UpdateVmNicIpCmd cmd) {
final Long nicId = cmd.getNicId();
String ipaddr = cmd.getIpaddress();
final Account caller = CallContext.current().getCallingAccount();
// check whether the nic belongs to user vm.
final NicVO nicVO = _nicDao.findById(nicId);
if (nicVO == null) {
throw new InvalidParameterValueException("There is no nic for the " + nicId);
}
if (nicVO.getVmType() != VirtualMachine.Type.User) {
throw new InvalidParameterValueException("The nic is not belongs to user vm");
}
final UserVm vm = _vmDao.findById(nicVO.getInstanceId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the nic");
}
final Network network = _networkDao.findById(nicVO.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("There is no network with the nic");
}
// Don't allow to update vm nic ip if network is not in Implemented/Setup/Allocated state
if (!(network.getState() == Network.State.Allocated || network.getState() == Network.State.Implemented || network.getState() == Network.State.Setup)) {
throw new InvalidParameterValueException("Network is not in the right state to update vm nic ip. Correct states are: " + Network.State.Allocated + ", " + Network.State.Implemented + ", " + Network.State.Setup);
}
final NetworkOfferingVO offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering == null) {
throw new InvalidParameterValueException("There is no network offering with the network");
}
if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && vm.getState() != State.Stopped) {
final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Stopped, unable to update the vm nic having the specified id");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
final Account ipOwner = _accountDao.findByIdIncludingRemoved(vm.getAccountId());
// verify ip address
s_logger.debug("Calling the ip allocation ...");
final Zone zone = zoneRepository.findOne(network.getDataCenterId());
if (zone == null) {
throw new InvalidParameterValueException("There is no dc with the nic");
}
if (zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
try {
ipaddr = _ipAddrMgr.allocateGuestIP(network, ipaddr);
} catch (final InsufficientAddressCapacityException e) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
}
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
}
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
if (oldIP != null) {
oldIP.setVmIp(ipaddr);
_ipAddressDao.persist(oldIP);
}
}
// implementing the network elements and resources as a part of vm nic ip update if network has services and it is in Implemented state
if (!_networkModel.listNetworkOfferingServices(offering.getId()).isEmpty() && network.getState() == Network.State.Implemented) {
final User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
final ReservationContext context = new ReservationContextImpl(null, null, callerUser, caller);
final DeployDestination dest = new DeployDestination(zoneRepository.findOne(network.getDataCenterId()), null, null, null);
s_logger.debug("Implementing the network " + network + " elements and resources as a part of vm nic ip update");
try {
// implement the network elements and rules again
_networkMgr.implementNetworkElementsAndResources(dest, context, network, offering);
} catch (final Exception ex) {
s_logger.warn("Failed to implement network " + network + " elements and resources as a part of vm nic ip update due to ", ex);
final CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of vm nic ip " + "update");
e.addProxyObject(network.getUuid(), "networkId");
// restore to old ip address
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.StaticNat)) {
final IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
if (oldIP != null) {
oldIP.setVmIp(nicVO.getIPv4Address());
_ipAddressDao.persist(oldIP);
}
}
throw e;
}
}
} else if (zone.getNetworkType() == NetworkType.Basic || network.getGuestType() == Network.GuestType.Shared) {
// handle the basic networks here
// for basic zone, need to provide the podId to ensure proper ip alloation
Long podId = null;
if (zone.getNetworkType() == NetworkType.Basic) {
podId = vm.getPodIdToDeployIn();
if (podId == null) {
throw new InvalidParameterValueException("vm pod id is null in Basic zone; can't decide the range for ip allocation");
}
}
try {
ipaddr = _ipAddrMgr.allocatePublicIpForGuestNic(network, podId, ipOwner, ipaddr);
if (ipaddr == null) {
throw new InvalidParameterValueException("Allocating ip to guest nic " + nicVO.getUuid() + " failed, please choose another ip");
}
final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nicVO.getNetworkId(), nicVO.getIPv4Address());
if (ip != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
}
});
}
} catch (final InsufficientAddressCapacityException e) {
s_logger.error("Allocating ip to guest nic " + nicVO.getUuid() + " failed, for insufficient address capacity");
return null;
}
} else {
s_logger.error("UpdateVmNicIpCmd is not supported in this network...");
return null;
}
// update nic ipaddress
nicVO.setIPv4Address(ipaddr);
_nicDao.persist(nicVO);
return vm;
}
use of com.cloud.utils.db.TransactionStatus 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;
}
});
}
Aggregations