Search in sources :

Example 6 with TransactionCallback

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

the class ProjectManagerImpl method updateInvitation.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_UPDATE, eventDescription = "updating project invitation", async = true)
public boolean updateInvitation(final long projectId, String accountName, String token, final boolean accept) {
    Account caller = CallContext.current().getCallingAccount();
    Long accountId = null;
    boolean result = true;
    //if accountname and token are null, default accountname to caller's account name
    if (accountName == null && token == null) {
        accountName = caller.getAccountName();
    }
    //check that the project exists
    final Project project = getProject(projectId);
    if (project == null) {
        throw new InvalidParameterValueException("Unable to find the project id=" + projectId);
    }
    if (accountName != null) {
        //check that account-to-remove exists
        Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId());
        if (account == null) {
            throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId());
        }
        //verify permissions
        _accountMgr.checkAccess(caller, null, true, account);
        accountId = account.getId();
    } else {
        accountId = caller.getId();
    }
    //check that invitation exists
    ProjectInvitationVO invite = null;
    if (token == null) {
        invite = _projectInvitationDao.findByAccountIdProjectId(accountId, projectId, ProjectInvitation.State.Pending);
    } else {
        invite = _projectInvitationDao.findPendingByTokenAndProjectId(token, projectId, ProjectInvitation.State.Pending);
    }
    if (invite != null) {
        if (!_projectInvitationDao.isActive(invite.getId(), _invitationTimeOut) && accept) {
            expireInvitation(invite);
            throw new InvalidParameterValueException("Invitation is expired for account id=" + accountName + " to the project id=" + projectId);
        } else {
            final ProjectInvitationVO inviteFinal = invite;
            final Long accountIdFinal = accountId;
            final String accountNameFinal = accountName;
            result = Transaction.execute(new TransactionCallback<Boolean>() {

                @Override
                public Boolean doInTransaction(TransactionStatus status) {
                    boolean result = true;
                    ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined;
                    //update invitation
                    s_logger.debug("Marking invitation " + inviteFinal + " with state " + newState);
                    inviteFinal.setState(newState);
                    result = _projectInvitationDao.update(inviteFinal.getId(), inviteFinal);
                    if (result && accept) {
                        //check if account already exists for the project (was added before invitation got accepted)
                        ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountIdFinal);
                        if (projectAccount != null) {
                            s_logger.debug("Account " + accountNameFinal + " already added to the project id=" + projectId);
                        } else {
                            assignAccountToProject(project, accountIdFinal, ProjectAccount.Role.Regular);
                        }
                    } else {
                        s_logger.warn("Failed to update project invitation " + inviteFinal + " with state " + newState);
                    }
                    return result;
                }
            });
        }
    } else {
        throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId);
    }
    return result;
}
Also used : Account(com.cloud.user.Account) TransactionCallback(com.cloud.utils.db.TransactionCallback) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 7 with TransactionCallback

use of com.cloud.utils.db.TransactionCallback in project cosmic by MissionCriticalCloud.

the class ProjectManagerImpl method updateInvitation.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_UPDATE, eventDescription = "updating project invitation", async = true)
public boolean updateInvitation(final long projectId, String accountName, final String token, final boolean accept) {
    final Account caller = CallContext.current().getCallingAccount();
    final Long accountId;
    final boolean result;
    // if accountname and token are null, default accountname to caller's account name
    if (accountName == null && token == null) {
        accountName = caller.getAccountName();
    }
    // check that the project exists
    final Project project = getProject(projectId);
    if (project == null) {
        throw new InvalidParameterValueException("Unable to find the project id=" + projectId);
    }
    if (accountName != null) {
        // check that account-to-remove exists
        final Account account = _accountMgr.getActiveAccountByName(accountName, project.getDomainId());
        if (account == null) {
            throw new InvalidParameterValueException("Unable to find account name=" + accountName + " in domain id=" + project.getDomainId());
        }
        // verify permissions
        _accountMgr.checkAccess(caller, null, true, account);
        accountId = account.getId();
    } else {
        accountId = caller.getId();
    }
    // check that invitation exists
    final ProjectInvitationVO invite;
    if (token == null) {
        invite = _projectInvitationDao.findByAccountIdProjectId(accountId, projectId, ProjectInvitation.State.Pending);
    } else {
        invite = _projectInvitationDao.findPendingByTokenAndProjectId(token, projectId, ProjectInvitation.State.Pending);
    }
    if (invite != null) {
        if (!_projectInvitationDao.isActive(invite.getId(), _invitationTimeOut) && accept) {
            expireInvitation(invite);
            throw new InvalidParameterValueException("Invitation is expired for account id=" + accountName + " to the project id=" + projectId);
        } else {
            final ProjectInvitationVO inviteFinal = invite;
            final Long accountIdFinal = accountId;
            final String accountNameFinal = accountName;
            result = Transaction.execute(new TransactionCallback<Boolean>() {

                @Override
                public Boolean doInTransaction(final TransactionStatus status) {
                    final boolean result;
                    final ProjectInvitation.State newState = accept ? ProjectInvitation.State.Completed : ProjectInvitation.State.Declined;
                    // update invitation
                    s_logger.debug("Marking invitation " + inviteFinal + " with state " + newState);
                    inviteFinal.setState(newState);
                    result = _projectInvitationDao.update(inviteFinal.getId(), inviteFinal);
                    if (result && accept) {
                        // check if account already exists for the project (was added before invitation got accepted)
                        final ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(projectId, accountIdFinal);
                        if (projectAccount != null) {
                            s_logger.debug("Account " + accountNameFinal + " already added to the project id=" + projectId);
                        } else {
                            assignAccountToProject(project, accountIdFinal, ProjectAccount.Role.Regular);
                        }
                    } else {
                        s_logger.warn("Failed to update project invitation " + inviteFinal + " with state " + newState);
                    }
                    return result;
                }
            });
        }
    } else {
        throw new InvalidParameterValueException("Unable to find invitation for account name=" + accountName + " to the project id=" + projectId);
    }
    return result;
}
Also used : Account(com.cloud.user.Account) TransactionCallback(com.cloud.utils.db.TransactionCallback) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 8 with TransactionCallback

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

the class ProjectManagerImpl method cleanupProject.

@DB
private boolean cleanupProject(final Project project, AccountVO caller, Long callerUserId) {
    boolean result = true;
    // Delete project's account
    AccountVO account = _accountDao.findById(project.getProjectAccountId());
    s_logger.debug("Deleting projects " + project + " internal account id=" + account.getId() + " as a part of project cleanup...");
    result = result && _accountMgr.deleteAccount(account, callerUserId, caller);
    if (result) {
        // Unassign all users from the project
        result = Transaction.execute(new TransactionCallback<Boolean>() {

            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                boolean result = true;
                s_logger.debug("Unassigning all accounts from project " + project + " as a part of project cleanup...");
                List<? extends ProjectAccount> projectAccounts = _projectAccountDao.listByProjectId(project.getId());
                for (ProjectAccount projectAccount : projectAccounts) {
                    result = result && unassignAccountFromProject(projectAccount.getProjectId(), projectAccount.getAccountId());
                }
                s_logger.debug("Removing all invitations for the project " + project + " as a part of project cleanup...");
                _projectInvitationDao.cleanupInvitations(project.getId());
                return result;
            }
        });
        if (result) {
            s_logger.debug("Accounts are unassign successfully from project " + project + " as a part of project cleanup...");
        }
    } else {
        s_logger.warn("Failed to cleanup project's internal account");
    }
    return result;
}
Also used : TransactionCallback(com.cloud.utils.db.TransactionCallback) TransactionStatus(com.cloud.utils.db.TransactionStatus) AccountVO(com.cloud.user.AccountVO) DB(com.cloud.utils.db.DB)

Example 9 with TransactionCallback

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

the class NetworkMigrationManagerImpl method assignNicsToNewPhysicalNetwork.

@Override
public void assignNicsToNewPhysicalNetwork(Network srcNetwork, Network networkInNewPhysicalNet) {
    List<NicVO> nics = _nicDao.listByNetworkId(srcNetwork.getId());
    final CallContext cctx = CallContext.current();
    final ReservationContext context = new ReservationContextImpl(null, null, cctx.getCallingUser(), cctx.getCallingAccount());
    final DataCenter dc = _entityMgr.findById(DataCenter.class, networkInNewPhysicalNet.getDataCenterId());
    // For each nic in the old network check if the nic belongs to a guest vm and migrate it to the new network.
    for (NicVO originalNic : nics) {
        if (originalNic.getVmType() != VirtualMachine.Type.User) {
            continue;
        }
        Transaction.execute((TransactionCallback<Boolean>) (status) -> migrateNicsInDB(originalNic, networkInNewPhysicalNet, dc, context));
    }
    // Now that nics are migrated we can migrate the static nats on those nics
    reapplyPublicIps(srcNetwork, networkInNewPhysicalNet);
}
Also used : NicSecondaryIpDao(com.cloud.vm.dao.NicSecondaryIpDao) HostDao(com.cloud.host.dao.HostDao) VMNetworkMapDao(org.apache.cloudstack.engine.cloud.entity.api.db.dao.VMNetworkMapDao) VpcVO(com.cloud.network.vpc.VpcVO) Transaction(com.cloud.utils.db.Transaction) NicDetailsDao(com.cloud.vm.dao.NicDetailsDao) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Logger(org.apache.log4j.Logger) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ReservationContext(com.cloud.vm.ReservationContext) FirewallRulesCidrsDao(com.cloud.network.dao.FirewallRulesCidrsDao) FirewallRulesCidrsVO(com.cloud.network.dao.FirewallRulesCidrsVO) ResourceLimitService(com.cloud.user.ResourceLimitService) NetworkOrchestrationService(org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService) VirtualRouter(com.cloud.network.router.VirtualRouter) CallContext(org.apache.cloudstack.context.CallContext) NetworkGuru(com.cloud.network.guru.NetworkGuru) TransactionCallback(com.cloud.utils.db.TransactionCallback) DeployDestination(com.cloud.deploy.DeployDestination) VpcGatewayDao(com.cloud.network.vpc.dao.VpcGatewayDao) Account(com.cloud.user.Account) NicVO(com.cloud.vm.NicVO) VMNetworkMapVO(org.apache.cloudstack.engine.cloud.entity.api.db.VMNetworkMapVO) RouterNetworkVO(com.cloud.network.dao.RouterNetworkVO) VirtualMachineProfileImpl(com.cloud.vm.VirtualMachineProfileImpl) VpcManager(com.cloud.network.vpc.VpcManager) List(java.util.List) ResourceTagVO(com.cloud.tags.ResourceTagVO) DataCenterDao(com.cloud.dc.dao.DataCenterDao) NetworkDomainVO(com.cloud.network.dao.NetworkDomainVO) VpcDetailsDao(org.apache.cloudstack.resourcedetail.dao.VpcDetailsDao) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) VpcGatewayVO(com.cloud.network.vpc.VpcGatewayVO) VirtualMachineManager(com.cloud.vm.VirtualMachineManager) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) AccountDao(com.cloud.user.dao.AccountDao) FirewallRuleDetailVO(org.apache.cloudstack.resourcedetail.FirewallRuleDetailVO) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) NetworkDomainDao(com.cloud.network.dao.NetworkDomainDao) VirtualMachine(com.cloud.vm.VirtualMachine) VirtualMachineProfile(com.cloud.vm.VirtualMachineProfile) EntityManager(com.cloud.utils.db.EntityManager) FirewallRule(com.cloud.network.rules.FirewallRule) DataCenterDeployment(com.cloud.deploy.DataCenterDeployment) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) NetworkDetailsDao(com.cloud.network.dao.NetworkDetailsDao) NetworkDao(com.cloud.network.dao.NetworkDao) VpcService(com.cloud.network.vpc.VpcService) NetworkOfferingServiceMapDao(com.cloud.offerings.dao.NetworkOfferingServiceMapDao) VpcDetailVO(org.apache.cloudstack.resourcedetail.VpcDetailVO) Nic(com.cloud.vm.Nic) RouterNetworkDao(com.cloud.network.dao.RouterNetworkDao) NicProfile(com.cloud.vm.NicProfile) Inject(javax.inject.Inject) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) DomainRouterVO(com.cloud.vm.DomainRouterVO) NicIpAliasDao(com.cloud.vm.dao.NicIpAliasDao) NetworkVO(com.cloud.network.dao.NetworkVO) IPAddressDao(com.cloud.network.dao.IPAddressDao) ResourceTag(com.cloud.server.ResourceTag) DomainRouterDao(com.cloud.vm.dao.DomainRouterDao) FirewallRulesDao(com.cloud.network.dao.FirewallRulesDao) DataCenter(com.cloud.dc.DataCenter) NicDetailVO(com.cloud.vm.NicDetailVO) FirewallRuleDetailsDao(org.apache.cloudstack.resourcedetail.dao.FirewallRuleDetailsDao) Resource(com.cloud.configuration.Resource) Vpc(com.cloud.network.vpc.Vpc) AccountVO(com.cloud.user.AccountVO) UserVmDao(com.cloud.vm.dao.UserVmDao) NicDao(com.cloud.vm.dao.NicDao) DB(com.cloud.utils.db.DB) ResourceTagDao(com.cloud.tags.dao.ResourceTagDao) NetworkOffering(com.cloud.offering.NetworkOffering) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) Host(com.cloud.host.Host) UserVmVO(com.cloud.vm.UserVmVO) VpcDao(com.cloud.network.vpc.dao.VpcDao) NetworkOfferingDao(com.cloud.offerings.dao.NetworkOfferingDao) NetworkDetailVO(com.cloud.network.dao.NetworkDetailVO) NetworkACLVO(com.cloud.network.vpc.NetworkACLVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) NetworkACLDao(com.cloud.network.vpc.dao.NetworkACLDao) RulesManager(com.cloud.network.rules.RulesManager) DataCenter(com.cloud.dc.DataCenter) NicVO(com.cloud.vm.NicVO) CallContext(org.apache.cloudstack.context.CallContext) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) ReservationContext(com.cloud.vm.ReservationContext)

Example 10 with TransactionCallback

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

the class BigSwitchBcfElement method addBigSwitchBcfDevice.

@Override
@DB
public BigSwitchBcfDeviceVO addBigSwitchBcfDevice(AddBigSwitchBcfDeviceCmd cmd) {
    BigSwitchBcfDeviceVO newBcfDevice;
    bcfUtilsInit();
    ServerResource resource = new BigSwitchBcfResource();
    final String deviceName = BcfConstants.BIG_SWITCH_BCF.getName();
    NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    final String hostname = cmd.getHost();
    final String username = cmd.getUsername();
    final String password = cmd.getPassword();
    final Boolean nat = cmd.getNat();
    PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
    }
    long zoneId = physicalNetwork.getDataCenterId();
    final PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
    if (ntwkSvcProvider == null) {
        throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
    } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
        throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
    }
    ntwkSvcProvider.setFirewallServiceProvided(true);
    ntwkSvcProvider.setGatewayServiceProvided(true);
    ntwkSvcProvider.setNetworkAclServiceProvided(true);
    ntwkSvcProvider.setSourcenatServiceProvided(true);
    ntwkSvcProvider.setStaticnatServiceProvided(true);
    if (_bigswitchBcfDao.listByPhysicalNetwork(physicalNetworkId).size() > 1) {
        throw new CloudRuntimeException("At most two BCF controllers can be configured");
    }
    DataCenterVO zone = _zoneDao.findById(physicalNetwork.getDataCenterId());
    String zoneName;
    if (zone != null) {
        zoneName = zone.getName();
    } else {
        zoneName = String.valueOf(zoneId);
    }
    Boolean natNow = _bcfUtils.isNatEnabled();
    if (!nat && natNow) {
        throw new CloudRuntimeException("NAT is enabled in existing controller. Enable NAT for new controller or remove existing controller first.");
    } else if (nat && !natNow) {
        throw new CloudRuntimeException("NAT is disabled in existing controller. Disable NAT for new controller or remove existing controller first.");
    }
    Map<String, String> params = new HashMap<String, String>();
    params.put("guid", UUID.randomUUID().toString());
    params.put("zoneId", zoneName);
    params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
    params.put("name", "BigSwitch Controller - " + cmd.getHost());
    params.put("hostname", cmd.getHost());
    params.put("username", username);
    params.put("password", password);
    params.put("nat", nat.toString());
    // FIXME What to do with multiple isolation types
    params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase());
    Map<String, Object> hostdetails = new HashMap<String, Object>();
    hostdetails.putAll(params);
    try {
        resource.configure(cmd.getHost(), hostdetails);
        // store current topology in bcf resource
        TopologyData topo = _bcfUtils.getTopology(physicalNetwork.getId());
        ((BigSwitchBcfResource) resource).setTopology(topo);
        final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
        if (host != null) {
            newBcfDevice = Transaction.execute(new TransactionCallback<BigSwitchBcfDeviceVO>() {

                @Override
                public BigSwitchBcfDeviceVO doInTransaction(TransactionStatus status) {
                    BigSwitchBcfDeviceVO bigswitchBcfDevice = new BigSwitchBcfDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName, hostname, username, password, nat, BigSwitchBcfApi.HASH_IGNORE);
                    _bigswitchBcfDao.persist(bigswitchBcfDevice);
                    DetailVO detail = new DetailVO(host.getId(), "bigswitchbcfdeviceid", String.valueOf(bigswitchBcfDevice.getId()));
                    _hostDetailsDao.persist(detail);
                    return bigswitchBcfDevice;
                }
            });
        } else {
            throw new CloudRuntimeException("Failed to add BigSwitch BCF Controller Device due to internal error.");
        }
    } catch (ConfigurationException e) {
        throw new CloudRuntimeException(e.getMessage());
    }
    // initial topology sync to newly added BCF controller
    HostVO bigswitchBcfHost = _hostDao.findById(newBcfDevice.getHostId());
    _bcfUtils.syncTopologyToBcfHost(bigswitchBcfHost, nat);
    return newBcfDevice;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) HashMap(java.util.HashMap) NetworkDevice(org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice) ServerResource(com.cloud.resource.ServerResource) TransactionStatus(com.cloud.utils.db.TransactionStatus) Host(com.cloud.host.Host) HostVO(com.cloud.host.HostVO) TransactionCallback(com.cloud.utils.db.TransactionCallback) BigSwitchBcfResource(com.cloud.network.resource.BigSwitchBcfResource) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DetailVO(com.cloud.host.DetailVO) ConfigurationException(javax.naming.ConfigurationException) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) TopologyData(com.cloud.network.bigswitch.TopologyData) BigSwitchBcfDeviceVO(com.cloud.network.BigSwitchBcfDeviceVO) DB(com.cloud.utils.db.DB)

Aggregations

TransactionCallback (com.cloud.utils.db.TransactionCallback)10 DB (com.cloud.utils.db.DB)8 TransactionStatus (com.cloud.utils.db.TransactionStatus)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)6 Account (com.cloud.user.Account)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 ActionEvent (com.cloud.event.ActionEvent)3 NetworkVO (com.cloud.network.dao.NetworkVO)3 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)3 AccountVO (com.cloud.user.AccountVO)3 DataCenter (com.cloud.dc.DataCenter)2 DeployDestination (com.cloud.deploy.DeployDestination)2 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)2 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)2 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)2 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)2 Host (com.cloud.host.Host)2 Resource (com.cloud.configuration.Resource)1 ClusterVO (com.cloud.dc.ClusterVO)1 ClusterVSMMapVO (com.cloud.dc.ClusterVSMMapVO)1