Search in sources :

Example 71 with TransactionStatus

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(RegisterCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    final Long userId = cmd.getId();
    User user = getUserIncludingRemoved(userId);
    if (user == null) {
        throw new InvalidParameterValueException("unable to find user by id");
    }
    Account account = _accountDao.findById(user.getAccountId());
    checkAccess(caller, null, true, account);
    // don't allow updating system user
    if (user.getId() == User.UID_SYSTEM) {
        throw new PermissionDeniedException("user id : " + user.getId() + " is system account, update is not allowed");
    }
    // don't allow baremetal system user
    if (BaremetalUtils.BAREMETAL_SYSTEM_ACCOUNT_NAME.equals(user.getUsername())) {
        throw new PermissionDeniedException("user id : " + user.getId() + " is system account, update is not allowed");
    }
    // generate both an api key and a secret key, update the user table with the keys, return the keys to the user
    final String[] keys = new String[2];
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            keys[0] = createUserApiKey(userId);
            keys[1] = createUserSecretKey(userId);
        }
    });
    return keys;
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 72 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class UserVmManagerImpl method addInstanceToGroup.

@Override
@DB
public boolean addInstanceToGroup(final long userVmId, String groupName) {
    UserVmVO vm = _vmDao.findById(userVmId);
    InstanceGroupVO group = _vmGroupDao.findByAccountAndName(vm.getAccountId(), groupName);
    // Create vm group if the group doesn't exist for this account
    if (group == null) {
        group = createVmGroup(groupName, vm.getAccountId());
    }
    if (group != null) {
        UserVm userVm = _vmDao.acquireInLockTable(userVmId);
        if (userVm == null) {
            s_logger.warn("Failed to acquire lock on user vm id=" + userVmId);
        }
        try {
            final InstanceGroupVO groupFinal = group;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    // don't let the group be deleted when we are assigning vm to
                    // it.
                    InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(groupFinal.getId(), false);
                    if (ngrpLock == null) {
                        s_logger.warn("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
                        throw new CloudRuntimeException("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
                    }
                    // Currently don't allow to assign a vm to more than one group
                    if (_groupVMMapDao.listByInstanceId(userVmId) != null) {
                        // Delete all mappings from group_vm_map table
                        List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId);
                        for (InstanceGroupVMMapVO groupMap : groupVmMaps) {
                            SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria();
                            sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId());
                            _groupVMMapDao.expunge(sc);
                        }
                    }
                    InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(groupFinal.getId(), userVmId);
                    _groupVMMapDao.persist(groupVmMapVO);
                }
            });
            return true;
        } finally {
            if (userVm != null) {
                _vmDao.releaseFromLockTable(userVmId);
            }
        }
    }
    return false;
}
Also used : UserVm(com.cloud.uservm.UserVm) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) SearchCriteria(com.cloud.utils.db.SearchCriteria) DB(com.cloud.utils.db.DB)

Example 73 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class UserVmManagerImpl method updateNicIpForVirtualMachine.

@Override
public UserVm updateNicIpForVirtualMachine(UpdateVmNicIpCmd cmd) {
    Long nicId = cmd.getNicId();
    String ipaddr = cmd.getIpaddress();
    Account caller = CallContext.current().getCallingAccount();
    //check whether the nic belongs to user vm.
    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");
    }
    UserVm vm = _vmDao.findById(nicVO.getInstanceId());
    if (vm == null) {
        throw new InvalidParameterValueException("There is no vm with the nic");
    }
    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);
    }
    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) {
        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);
    Account ipOwner = _accountDao.findByIdIncludingRemoved(vm.getAccountId());
    // verify ip address
    s_logger.debug("Calling the ip allocation ...");
    DataCenter dc = _dcDao.findById(network.getDataCenterId());
    if (dc == null) {
        throw new InvalidParameterValueException("There is no dc with the nic");
    }
    if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
        try {
            ipaddr = _ipAddrMgr.allocateGuestIP(network, ipaddr);
        } catch (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)) {
            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) {
            User callerUser = _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
            ReservationContext context = new ReservationContextImpl(null, null, callerUser, caller);
            DeployDestination dest = new DeployDestination(_dcDao.findById(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 (Exception ex) {
                s_logger.warn("Failed to implement network " + network + " elements and resources as a part of vm nic ip update due to ", ex);
                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)) {
                    IPAddressVO oldIP = _ipAddressDao.findByAssociatedVmId(vm.getId());
                    if (oldIP != null) {
                        oldIP.setVmIp(nicVO.getIPv4Address());
                        _ipAddressDao.persist(oldIP);
                    }
                }
                throw e;
            }
        }
    } else if (dc.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 (dc.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(TransactionStatus status) {
                        _ipAddrMgr.markIpAsUnavailable(ip.getId());
                        _ipAddressDao.unassignIpAddress(ip.getId());
                    }
                });
            }
        } catch (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;
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) 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) UserVm(com.cloud.uservm.UserVm) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 74 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class DomainManagerImpl method createDomain.

@Override
@DB
public Domain createDomain(final String name, final Long parentId, final Long ownerId, final String networkDomain, String domainUUID) {
    // 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 \"-\"");
        }
    }
    SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
    sc.addAnd("name", SearchCriteria.Op.EQ, name);
    sc.addAnd("parent", SearchCriteria.Op.EQ, parentId);
    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 String domainUUIDFinal = domainUUID;
    DomainVO domain = Transaction.execute(new TransactionCallback<DomainVO>() {

        @Override
        public DomainVO doInTransaction(TransactionStatus status) {
            DomainVO domain = _domainDao.create(new DomainVO(name, ownerId, parentId, networkDomain, domainUUIDFinal));
            _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;
}
Also used : DomainVO(com.cloud.domain.DomainVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) DB(com.cloud.utils.db.DB)

Example 75 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.

the class DomainManagerImpl method updateDomain.

@Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
@DB
public DomainVO updateDomain(UpdateDomainCmd cmd) {
    final Long domainId = cmd.getId();
    final String domainName = cmd.getDomainName();
    final String networkDomain = cmd.getNetworkDomain();
    // check if domain exists in the system
    final DomainVO domain = _domainDao.findById(domainId);
    if (domain == null) {
        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
    Account caller = getCaller();
    _accountMgr.checkAccess(caller, domain);
    // domain name is unique in the cloud
    if (domainName != null) {
        SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
        sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
        List<DomainVO> domains = _domainDao.search(sc, null);
        boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
        if (!domains.isEmpty() && !sameDomain) {
            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 \"-\"");
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            if (domainName != null) {
                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);
                }
            }
            _domainDao.update(domainId, domain);
            CallContext.current().putContextParameter(Domain.class, domain.getUuid());
        }
    });
    return _domainDao.findById(domainId);
}
Also used : DomainVO(com.cloud.domain.DomainVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) Domain(com.cloud.domain.Domain) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)171 DB (com.cloud.utils.db.DB)139 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)100 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)93 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)77 ArrayList (java.util.ArrayList)54 Account (com.cloud.user.Account)44 List (java.util.List)44 ActionEvent (com.cloud.event.ActionEvent)40 ConfigurationException (javax.naming.ConfigurationException)40 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)35 IPAddressVO (com.cloud.network.dao.IPAddressVO)26 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)26 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)23 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)23 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)22 HashMap (java.util.HashMap)22 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)21 Network (com.cloud.network.Network)20 DataCenterVO (com.cloud.dc.DataCenterVO)17