Search in sources :

Example 1 with TransactionCallback

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

the class CiscoNexusVSMElement method validateAndAddVsm.

@Override
@DB
public Pair<Boolean, Long> validateAndAddVsm(final String vsmIp, final String vsmUser, final String vsmPassword, final long clusterId, String clusterName) throws ResourceInUseException {
    CiscoNexusVSMDeviceVO vsm = null;
    boolean vsmAdded = false;
    Long vsmId = 0L;
    if (vsmIp != null && vsmUser != null && vsmPassword != null) {
        NetconfHelper netconfClient;
        try {
            netconfClient = new NetconfHelper(vsmIp, vsmUser, vsmPassword);
            netconfClient.disconnect();
        } catch (CloudRuntimeException e) {
            String msg = "Invalid credentials supplied for user " + vsmUser + " for Cisco Nexus 1000v VSM at " + vsmIp;
            s_logger.error(msg);
            _clusterDao.remove(clusterId);
            throw new CloudRuntimeException(msg);
        }
        // If VSM already exists and is mapped to a cluster, fail this operation.
        vsm = _vsmDao.getVSMbyIpaddress(vsmIp);
        if (vsm != null) {
            List<ClusterVSMMapVO> clusterList = _clusterVSMDao.listByVSMId(vsm.getId());
            if (clusterList != null && !clusterList.isEmpty()) {
                s_logger.error("Failed to add cluster: specified Nexus VSM is already associated with another cluster");
                ResourceInUseException ex = new ResourceInUseException("Failed to add cluster: specified Nexus VSM is already associated with another cluster with specified Id");
                // get clusterUuid to report error
                ClusterVO cluster = _clusterDao.findById(clusterList.get(0).getClusterId());
                ex.addProxyObject(cluster.getUuid());
                _clusterDao.remove(clusterId);
                throw ex;
            }
        }
        // persist credentials to database if the VSM entry is not already in the db.
        vsm = Transaction.execute(new TransactionCallback<CiscoNexusVSMDeviceVO>() {

            @Override
            public CiscoNexusVSMDeviceVO doInTransaction(TransactionStatus status) {
                CiscoNexusVSMDeviceVO vsm = null;
                if (_vsmDao.getVSMbyIpaddress(vsmIp) == null) {
                    vsm = new CiscoNexusVSMDeviceVO(vsmIp, vsmUser, vsmPassword);
                    _vsmDao.persist(vsm);
                }
                // Create a mapping between the cluster and the vsm.
                vsm = _vsmDao.getVSMbyIpaddress(vsmIp);
                if (vsm != null) {
                    ClusterVSMMapVO connectorObj = new ClusterVSMMapVO(clusterId, vsm.getId());
                    _clusterVSMDao.persist(connectorObj);
                }
                return vsm;
            }
        });
    } else {
        String msg;
        msg = "The global parameter " + Config.VmwareUseNexusVSwitch.toString() + " is set to \"true\". Following mandatory parameters are not specified. ";
        if (vsmIp == null) {
            msg += "vsmipaddress: Management IP address of Cisco Nexus 1000v dvSwitch. ";
        }
        if (vsmUser == null) {
            msg += "vsmusername: Name of a user account with admin privileges over Cisco Nexus 1000v dvSwitch. ";
        }
        if (vsmPassword == null) {
            if (vsmUser != null) {
                msg += "vsmpassword: Password of user account " + vsmUser + ". ";
            } else {
                msg += "vsmpassword: Password of user account with admin privileges over Cisco Nexus 1000v dvSwitch. ";
            }
        }
        s_logger.error(msg);
        // Cleaning up the cluster record as addCluster operation failed because of invalid credentials of Nexus dvSwitch.
        _clusterDao.remove(clusterId);
        throw new CloudRuntimeException(msg);
    }
    if (vsm != null) {
        vsmAdded = true;
        vsmId = vsm.getId();
    }
    return new Pair<Boolean, Long>(vsmAdded, vsmId);
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) CiscoNexusVSMDeviceVO(com.cloud.network.CiscoNexusVSMDeviceVO) ClusterVSMMapVO(com.cloud.dc.ClusterVSMMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallback(com.cloud.utils.db.TransactionCallback) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceInUseException(com.cloud.exception.ResourceInUseException) NetconfHelper(com.cloud.utils.cisco.n1kv.vsm.NetconfHelper) Pair(com.cloud.utils.Pair) DB(com.cloud.utils.db.DB)

Example 2 with TransactionCallback

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

the class NetworkServiceImpl method migrateVpcNetwork.

@Override
public Vpc migrateVpcNetwork(long vpcId, long vpcOfferingId, Map<String, String> networkToOffering, Account account, User callerUser, boolean resume) {
    // Check if a previous migration run failed and try to resume if resume = true
    ResourceTag relatedVpc = _resourceTagDao.findByKey(vpcId, ResourceObjectType.Vpc, NetworkMigrationManager.MIGRATION);
    long vpcCopyId = 0;
    /*
         * In the vpc migration process the newly created Vpc will be used as the new VPC (opposed to network tier migration).
         * In case the copy of the vpc was already created. The uuid where already swapped and the id we receive here is the id of the Copy!
         * The id stored in the resource tag table under the key "migration" is the id of the ORIGINAL vpc!
         */
    if (relatedVpc != null) {
        if (resume) {
            vpcCopyId = vpcId;
            vpcId = Long.parseLong(relatedVpc.getValue());
            // let's check if the user did not change the vpcoffering opposed to the last failed run.
            verifyAlreadyMigratedTiers(vpcCopyId, vpcOfferingId, networkToOffering);
        } else {
            s_logger.warn("This vpc has a migration row in the resource details table. You might want to re-run migration with resume = true command.");
            throw new CloudRuntimeException("Failed to migrate VPC as previous migration left this VPC in transient condition. Specify resume as true.");
        }
    }
    Vpc vpc = _vpcDao.findById(vpcId);
    _accountMgr.checkAccess(account, null, true, vpc);
    _accountMgr.checkAccess(account, _vpcOfferingDao.findById(vpcOfferingId), _dcDao.findById(vpc.getZoneId()));
    if (vpc.getVpcOfferingId() == vpcOfferingId) {
        return vpc;
    }
    // Try to fail fast, check networks in the VPC and if we can migrate them before proceeding.
    List<NetworkVO> tiersInVpc = _networksDao.listByVpc(vpcId);
    vpcTiersCanBeMigrated(tiersInVpc, account, networkToOffering, resume);
    // In case this is the first time we try to migrate this vpc
    if (relatedVpc == null) {
        final long vpcIdFinal = vpcId;
        vpcCopyId = Transaction.execute((TransactionCallback<Long>) (status) -> _networkMigrationManager.makeCopyOfVpc(vpcIdFinal, vpcOfferingId));
    }
    Vpc copyOfVpc = _vpcDao.findById(vpcCopyId);
    _networkMigrationManager.startVpc(copyOfVpc);
    for (Network tier : tiersInVpc) {
        String networkOfferingUuid = networkToOffering.get(tier.getUuid());
        // UUID may be swapped already with a new uuid due to previous migration failure.
        // So we check the related network also in case we don't find the network offering
        Long networkId = null;
        if (resume && networkOfferingUuid == null) {
            tier = _networksDao.findById(tier.getRelated());
            networkOfferingUuid = networkToOffering.get(tier.getUuid());
            // In this case the tier already exists so we need to get the id of the tier so we can validate correctly
            networkId = tier.getId();
        }
        NetworkOfferingVO newNtwkOff = _networkOfferingDao.findByUuid(networkOfferingUuid);
        Account networkAccount = _accountService.getActiveAccountById(tier.getAccountId());
        try {
            _vpcMgr.validateNtwkOffForNtwkInVpc(networkId, newNtwkOff.getId(), tier.getCidr(), tier.getNetworkDomain(), copyOfVpc, tier.getGateway(), networkAccount, tier.getNetworkACLId());
        } catch (InvalidParameterValueException e) {
            s_logger.error("Specified network offering can not be used in combination with specified vpc offering. Aborting migration. You can re-run with resume = true and the correct uuid.");
            throw e;
        }
        long newPhysicalNetworkId = findPhysicalNetworkId(tier.getDataCenterId(), newNtwkOff.getTags(), newNtwkOff.getTrafficType());
        final long oldNetworkOfferingId = tier.getNetworkOfferingId();
        NetworkOffering oldNtwkOff = _networkOfferingDao.findByIdIncludingRemoved(oldNetworkOfferingId);
        if (networkNeedsMigration(tier, newPhysicalNetworkId, oldNtwkOff, newNtwkOff) || (resume && tier.getRelated() != tier.getId())) {
            migrateNetworkToPhysicalNetwork(tier, oldNtwkOff, newNtwkOff, vpcId, vpcCopyId, newPhysicalNetworkId, account, callerUser);
        }
    }
    _networkMigrationManager.deleteCopyOfVpc(vpcId, vpcCopyId);
    return _vpcDao.findById(vpcCopyId);
}
Also used : Account(com.cloud.user.Account) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) Vpc(com.cloud.network.vpc.Vpc) TransactionCallback(com.cloud.utils.db.TransactionCallback) ResourceTag(com.cloud.server.ResourceTag) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO)

Example 3 with TransactionCallback

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

the class NetworkServiceImpl method migrateNetworkToPhysicalNetwork.

private Network migrateNetworkToPhysicalNetwork(Network network, NetworkOffering oldNtwkOff, NetworkOffering newNtwkOff, Long oldVpcId, Long newVpcId, long newPhysicalNetworkId, Account callerAccount, User callerUser) {
    boolean resume = network.getRelated() != network.getId();
    NetworkCopy networkCopy;
    // Resume is only true when there is already a copy of the network created
    if (resume) {
        Network networkInNewPhysicalNet = network;
        networkCopy = new NetworkCopy(network.getRelated(), networkInNewPhysicalNet);
        // the old network offering uuid should be the one of the already created copy
        if (networkInNewPhysicalNet.getNetworkOfferingId() != newNtwkOff.getId()) {
            throw new InvalidParameterValueException("Failed to resume migrating network as network offering does not match previously specified network offering (" + newNtwkOff.getUuid() + ")");
        }
    } else {
        networkCopy = Transaction.execute((TransactionCallback<NetworkCopy>) (status) -> migrateNetworkInDb(network, oldNtwkOff, newNtwkOff, oldVpcId, newVpcId, newPhysicalNetworkId));
    }
    Long networkIdInOldPhysicalNet = networkCopy.getNetworkIdInOldPhysicalNet();
    Network networkInNewPhysicalNet = networkCopy.getNetworkInNewPhysicalNet();
    ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount);
    DataCenter zone = _dcDao.findById(network.getDataCenterId());
    NetworkVO networkInOldPhysNet = _networksDao.findById(networkIdInOldPhysicalNet);
    boolean shouldImplement = (newNtwkOff.isPersistent() || networkInOldPhysNet.getState() == Network.State.Implemented) && networkInNewPhysicalNet.getState() != Network.State.Implemented;
    if (shouldImplement) {
        DeployDestination dest = new DeployDestination(zone, null, null, null);
        s_logger.debug("Implementing the network " + network + " elements and resources as a part of network update");
        try {
            networkInNewPhysicalNet = _networkMgr.implementNetwork(networkInNewPhysicalNet.getId(), dest, context).second();
        } catch (Exception ex) {
            s_logger.warn("Failed to implement network " + network + " elements and resources as a part of network update due to ", ex);
            CloudRuntimeException e = new CloudRuntimeException("Failed to implement network (with specified id) elements and resources as a part of network update");
            e.addProxyObject(network.getUuid(), "networkId");
            throw e;
        }
    }
    _networkMigrationManager.assignNicsToNewPhysicalNetwork(networkInOldPhysNet, networkInNewPhysicalNet);
    // clean up the old copy of the network
    _networkMigrationManager.deleteCopyOfNetwork(networkIdInOldPhysicalNet, networkInNewPhysicalNet.getId());
    return getNetwork(network.getId());
}
Also used : PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) ReservationContextImpl(com.cloud.vm.ReservationContextImpl) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) UnknownHostException(java.net.UnknownHostException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ReservationContext(com.cloud.vm.ReservationContext) TransactionCallback(com.cloud.utils.db.TransactionCallback) DataCenter(com.cloud.dc.DataCenter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DeployDestination(com.cloud.deploy.DeployDestination) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 4 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, Long userId, String token, final boolean accept) {
    Account caller = CallContext.current().getCallingAccount();
    Long accountId = null;
    User user = null;
    boolean result = true;
    // check that the project exists
    final Project project = getProject(projectId);
    if (project == null) {
        throw new InvalidParameterValueException("Unable to find the project id=" + projectId);
    }
    CallContext.current().setProject(project);
    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 if (userId != null) {
        user = userDao.findById(userId);
        if (user == null) {
            throw new InvalidParameterValueException("Invalid user ID provided. Please provide a valid user ID or " + "account name whose invitation is to be updated");
        }
        Account userAccount = _accountDao.findById(user.getAccountId());
        if (userAccount.getDomainId() != project.getDomainId()) {
            throw new InvalidParameterValueException("Unable to find user =" + userId + " in domain id=" + project.getDomainId());
        }
    } else {
        accountId = caller.getId();
        user = CallContext.current().getCallingUser();
    }
    // check that invitation exists
    ProjectInvitationVO invite = null;
    if (token == null) {
        if (accountName != null) {
            invite = _projectInvitationDao.findByAccountIdProjectId(accountId, projectId, ProjectInvitation.State.Pending);
        } else {
            invite = _projectInvitationDao.findByUserIdProjectId(user.getId(), user.getAccountId(), 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;
            final User finalUser = user;
            ProjectInvitationVO finalInvite = invite;
            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)
                        if (finalInvite.getForUserId() == -1) {
                            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, finalInvite.getAccountRole(), null, finalInvite.getProjectRoleId());
                            }
                        } else {
                            ProjectAccount projectAccount = _projectAccountDao.findByProjectIdUserId(projectId, finalUser.getAccountId(), finalUser.getId());
                            if (projectAccount != null) {
                                s_logger.debug("User " + finalUser.getId() + "has already been added to the project id=" + projectId);
                            } else {
                                assignUserToProject(project, finalInvite.getForUserId(), finalUser.getAccountId(), finalInvite.getAccountRole(), finalInvite.getProjectRoleId());
                            }
                        }
                    } 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) User(com.cloud.user.User) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallback(com.cloud.utils.db.TransactionCallback) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 5 with TransactionCallback

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

the class ProjectManagerImpl method cleanupProject.

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

            @Override
            public Boolean doInTransaction(final TransactionStatus status) {
                boolean result = true;
                s_logger.debug("Unassigning all accounts from project " + project + " as a part of project cleanup...");
                final List<? extends ProjectAccount> projectAccounts = _projectAccountDao.listByProjectId(project.getId());
                for (final 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)

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