Search in sources :

Example 16 with TransactionStatus

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

the class DedicatedResourceManagerImpl method dedicateZone.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_DEDICATE_RESOURCE, eventDescription = "dedicating a Zone")
public List<DedicatedResourceVO> dedicateZone(final Long zoneId, final Long domainId, final String accountName) {
    Long accountId = null;
    List<HostVO> hosts = null;
    if (accountName != null) {
        Account caller = CallContext.current().getCallingAccount();
        Account owner = _accountMgr.finalizeOwner(caller, accountName, domainId, null);
        accountId = owner.getId();
    }
    List<Long> childDomainIds = getDomainChildIds(domainId);
    childDomainIds.add(domainId);
    checkAccountAndDomain(accountId, domainId);
    final DataCenterVO dc = _zoneDao.findById(zoneId);
    if (dc == null) {
        throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
    } else {
        DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zoneId);
        // check if zone is dedicated
        if (dedicatedZone != null) {
            s_logger.error("Zone " + dc.getName() + " is already dedicated");
            throw new CloudRuntimeException("Zone  " + dc.getName() + " is already dedicated");
        }
        // check if any resource under this zone is dedicated to different account or sub-domain
        List<HostPodVO> pods = _podDao.listByDataCenterId(dc.getId());
        List<DedicatedResourceVO> podsToRelease = new ArrayList<DedicatedResourceVO>();
        List<DedicatedResourceVO> clustersToRelease = new ArrayList<DedicatedResourceVO>();
        List<DedicatedResourceVO> hostsToRelease = new ArrayList<DedicatedResourceVO>();
        for (HostPodVO pod : pods) {
            DedicatedResourceVO dPod = _dedicatedDao.findByPodId(pod.getId());
            if (dPod != null) {
                if (!(childDomainIds.contains(dPod.getDomainId()))) {
                    throw new CloudRuntimeException("Pod " + pod.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                }
                if (accountId != null) {
                    if (dPod.getAccountId().equals(accountId)) {
                        podsToRelease.add(dPod);
                    } else {
                        s_logger.error("Pod " + pod.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                        throw new CloudRuntimeException("Pod " + pod.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                    }
                } else {
                    if (dPod.getAccountId() == null && dPod.getDomainId().equals(domainId)) {
                        podsToRelease.add(dPod);
                    }
                }
            }
        }
        for (DedicatedResourceVO dr : podsToRelease) {
            releaseDedicatedResource(null, dr.getPodId(), null, null);
        }
        List<ClusterVO> clusters = _clusterDao.listClustersByDcId(dc.getId());
        for (ClusterVO cluster : clusters) {
            DedicatedResourceVO dCluster = _dedicatedDao.findByClusterId(cluster.getId());
            if (dCluster != null) {
                if (!(childDomainIds.contains(dCluster.getDomainId()))) {
                    throw new CloudRuntimeException("Cluster " + cluster.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                }
                if (accountId != null) {
                    if (dCluster.getAccountId().equals(accountId)) {
                        clustersToRelease.add(dCluster);
                    } else {
                        s_logger.error("Cluster " + cluster.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                        throw new CloudRuntimeException("Cluster " + cluster.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                    }
                } else {
                    if (dCluster.getAccountId() == null && dCluster.getDomainId().equals(domainId)) {
                        clustersToRelease.add(dCluster);
                    }
                }
            }
        }
        for (DedicatedResourceVO dr : clustersToRelease) {
            releaseDedicatedResource(null, null, dr.getClusterId(), null);
        }
        hosts = _hostDao.listByDataCenterId(dc.getId());
        for (HostVO host : hosts) {
            DedicatedResourceVO dHost = _dedicatedDao.findByHostId(host.getId());
            if (dHost != null) {
                if (!(childDomainIds.contains(dHost.getDomainId()))) {
                    throw new CloudRuntimeException("Host " + host.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                }
                if (accountId != null) {
                    if (dHost.getAccountId().equals(accountId)) {
                        hostsToRelease.add(dHost);
                    } else {
                        s_logger.error("Host " + host.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                        throw new CloudRuntimeException("Host " + host.getName() + " under this Zone " + dc.getName() + " is dedicated to different account/domain");
                    }
                } else {
                    if (dHost.getAccountId() == null && dHost.getDomainId().equals(domainId)) {
                        hostsToRelease.add(dHost);
                    }
                }
            }
        }
        for (DedicatedResourceVO dr : hostsToRelease) {
            releaseDedicatedResource(null, null, null, dr.getHostId());
        }
    }
    checkHostsSuitabilityForExplicitDedication(accountId, childDomainIds, hosts);
    final Long accountIdFinal = accountId;
    return Transaction.execute(new TransactionCallback<List<DedicatedResourceVO>>() {

        @Override
        public List<DedicatedResourceVO> doInTransaction(TransactionStatus status) {
            // find or create the affinity group by name under this account/domain
            AffinityGroup group = findOrCreateDedicatedAffinityGroup(domainId, accountIdFinal);
            if (group == null) {
                s_logger.error("Unable to dedicate zone due to, failed to create dedication affinity group");
                throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
            }
            DedicatedResourceVO dedicatedResource = new DedicatedResourceVO(zoneId, null, null, null, null, null, group.getId());
            try {
                dedicatedResource.setDomainId(domainId);
                if (accountIdFinal != null) {
                    dedicatedResource.setAccountId(accountIdFinal);
                }
                dedicatedResource = _dedicatedDao.persist(dedicatedResource);
                // save the domainId in the zone
                dc.setDomainId(domainId);
                if (!_zoneDao.update(zoneId, dc)) {
                    throw new CloudRuntimeException("Failed to dedicate zone, could not set domainId. Please contact Cloud Support.");
                }
            } catch (Exception e) {
                s_logger.error("Unable to dedicate zone due to " + e.getMessage(), e);
                throw new CloudRuntimeException("Failed to dedicate zone. Please contact Cloud Support.");
            }
            List<DedicatedResourceVO> result = new ArrayList<DedicatedResourceVO>();
            result.add(dedicatedResource);
            return result;
        }
    });
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) ClusterVO(com.cloud.dc.ClusterVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) HostPodVO(com.cloud.dc.HostPodVO) HostVO(com.cloud.host.HostVO) AffinityGroup(org.apache.cloudstack.affinity.AffinityGroup) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) List(java.util.List) ArrayList(java.util.ArrayList) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 17 with TransactionStatus

use of com.cloud.utils.db.TransactionStatus 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 18 with TransactionStatus

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

the class LoadBalancingRulesManagerImpl method assignToLoadBalancer.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true)
public boolean assignToLoadBalancer(long loadBalancerId, List<Long> instanceIds, Map<Long, List<String>> vmIdIpMap) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
        throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found.");
    }
    if (instanceIds == null && vmIdIpMap.isEmpty()) {
        throw new InvalidParameterValueException("Both instanceids and vmidipmap  can't be null");
    }
    // instanceIds and vmIdipmap is passed
    if (instanceIds != null && !vmIdIpMap.isEmpty()) {
        for (long instanceId : instanceIds) {
            if (!vmIdIpMap.containsKey(instanceId)) {
                vmIdIpMap.put(instanceId, null);
            }
        }
    }
    // only instanceids list passed
    if (instanceIds != null && vmIdIpMap.isEmpty()) {
        vmIdIpMap = new HashMap<Long, List<String>>();
        for (long instanceId : instanceIds) {
            vmIdIpMap.put(instanceId, null);
        }
    }
    List<LoadBalancerVMMapVO> mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
    Set<Long> mappedInstanceIds = new HashSet<Long>();
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
    }
    Map<Long, List<String>> existingVmIdIps = new HashMap<Long, List<String>>();
    // now get the ips of vm and add it to map
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        List<String> ipsList = null;
        if (existingVmIdIps.containsKey(mappedInstance.getInstanceId())) {
            ipsList = existingVmIdIps.get(mappedInstance.getInstanceId());
        } else {
            ipsList = new ArrayList<String>();
        }
        ipsList.add(mappedInstance.getInstanceIp());
        existingVmIdIps.put(mappedInstance.getInstanceId(), ipsList);
    }
    final List<UserVm> vmsToAdd = new ArrayList<UserVm>();
    // check for conflict
    Set<Long> passedInstanceIds = vmIdIpMap.keySet();
    for (Long instanceId : passedInstanceIds) {
        UserVm vm = _vmDao.findById(instanceId);
        if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Invalid instance id specified");
            if (vm == null) {
                ex.addProxyObject(instanceId.toString(), "instanceId");
            } else {
                ex.addProxyObject(vm.getUuid(), "instanceId");
            }
            throw ex;
        }
        _rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller);
        if (vm.getAccountId() != loadBalancer.getAccountId()) {
            throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner.");
        }
        // Let's check to make sure the vm has a nic in the same network as
        // the load balancing rule.
        List<? extends Nic> nics = _networkModel.getNics(vm.getId());
        Nic nicInSameNetwork = null;
        for (Nic nic : nics) {
            if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
                nicInSameNetwork = nic;
                break;
            }
        }
        if (nicInSameNetwork == null) {
            InvalidParameterValueException ex = new InvalidParameterValueException("VM with id specified cannot be added because it doesn't belong in the same network.");
            ex.addProxyObject(vm.getUuid(), "instanceId");
            throw ex;
        }
        String priIp = nicInSameNetwork.getIPv4Address();
        if (existingVmIdIps.containsKey(instanceId)) {
            // now check for ip address
            List<String> mappedIps = existingVmIdIps.get(instanceId);
            List<String> newIps = vmIdIpMap.get(instanceId);
            if (newIps == null) {
                newIps = new ArrayList<String>();
                newIps.add(priIp);
            }
            for (String newIp : newIps) {
                if (mappedIps.contains(newIp)) {
                    throw new InvalidParameterValueException("VM " + instanceId + " with " + newIp + " is already mapped to load balancer.");
                }
            }
        }
        List<String> vmIpsList = vmIdIpMap.get(instanceId);
        String vmLbIp = null;
        if (vmIpsList != null) {
            // check if the ips belongs to nic secondary ip
            for (String ip : vmIpsList) {
                // skip the primary ip from vm secondary ip comparisions
                if (ip.equals(priIp)) {
                    continue;
                }
                if (_nicSecondaryIpDao.findByIp4AddressAndNicId(ip, nicInSameNetwork.getId()) == null) {
                    throw new InvalidParameterValueException("VM ip " + ip + " specified does not belong to " + "nic in network " + nicInSameNetwork.getNetworkId());
                }
            }
        } else {
            vmIpsList = new ArrayList<String>();
            vmIpsList.add(priIp);
        }
        // assign for primary ip and ip passed in vmidipmap
        if (instanceIds != null) {
            if (instanceIds.contains(instanceId)) {
                vmIpsList.add(priIp);
            }
        }
        vmIdIpMap.put(instanceId, vmIpsList);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding " + vm + " to the load balancer pool");
        }
        vmsToAdd.add(vm);
    }
    final Set<Long> vmIds = vmIdIpMap.keySet();
    final Map<Long, List<String>> newMap = vmIdIpMap;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            for (Long vmId : vmIds) {
                final Set<String> lbVmIps = new HashSet<String>(newMap.get(vmId));
                for (String vmIp : lbVmIps) {
                    LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vmId, vmIp, false);
                    map = _lb2VmMapDao.persist(map);
                }
            }
        }
    });
    if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) {
        // We can consider the job done.
        return true;
    }
    boolean success = false;
    FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        applyLoadBalancerConfig(loadBalancerId);
        success = true;
    } catch (ResourceUnavailableException e) {
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
        success = false;
    } finally {
        if (!success) {
            final List<Long> vmInstanceIds = new ArrayList<Long>();
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    for (Long vmId : vmIds) {
                        vmInstanceIds.add(vmId);
                    }
                }
            });
            if (!vmInstanceIds.isEmpty()) {
                _lb2VmMapDao.remove(loadBalancer.getId(), vmInstanceIds, null);
                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while attaching VM: " + vmInstanceIds);
            }
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to add specified loadbalancerruleid for vms " + vmInstanceIds);
            ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
            // right VO object or table name.
            throw ex;
        }
    }
    return success;
}
Also used : Account(com.cloud.user.Account) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule) HashSet(java.util.HashSet) Nic(com.cloud.vm.Nic) CallContext(org.apache.cloudstack.context.CallContext) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 19 with TransactionStatus

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

the class VirtualNetworkApplianceManagerImpl method removeDhcpSupportForSubnet.

@Override
public boolean removeDhcpSupportForSubnet(final Network network, final List<DomainRouterVO> routers) throws ResourceUnavailableException {
    if (routers == null || routers.isEmpty()) {
        s_logger.warn("Failed to add/remove VPN users: no router found for account and zone");
        throw new ResourceUnavailableException("Unable to assign ip addresses, domR doesn't exist for network " + network.getId(), DataCenter.class, network.getDataCenterId());
    }
    for (final DomainRouterVO router : routers) {
        if (router.getState() != VirtualMachine.State.Running) {
            s_logger.warn("Failed to add/remove VPN users: router not in running state");
            throw new ResourceUnavailableException("Unable to assign ip addresses, domR is not in right state " + router.getState(), DataCenter.class, network.getDataCenterId());
        }
        final Commands cmds = new Commands(Command.OnError.Continue);
        final List<NicIpAliasVO> revokedIpAliasVOs = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.State.revoked);
        s_logger.debug("Found" + revokedIpAliasVOs.size() + "ip Aliases to revoke on the router as a part of dhcp configuration");
        final List<IpAliasTO> revokedIpAliasTOs = new ArrayList<IpAliasTO>();
        for (final NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
            revokedIpAliasTOs.add(new IpAliasTO(revokedAliasVO.getIp4Address(), revokedAliasVO.getNetmask(), revokedAliasVO.getAliasCount().toString()));
        }
        final List<NicIpAliasVO> aliasVOs = _nicIpAliasDao.listByNetworkIdAndState(network.getId(), NicIpAlias.State.active);
        s_logger.debug("Found" + aliasVOs.size() + "ip Aliases to apply on the router as a part of dhcp configuration");
        final List<IpAliasTO> activeIpAliasTOs = new ArrayList<IpAliasTO>();
        for (final NicIpAliasVO aliasVO : aliasVOs) {
            activeIpAliasTOs.add(new IpAliasTO(aliasVO.getIp4Address(), aliasVO.getNetmask(), aliasVO.getAliasCount().toString()));
        }
        _commandSetupHelper.createDeleteIpAliasCommand(router, revokedIpAliasTOs, activeIpAliasTOs, network.getId(), cmds);
        _commandSetupHelper.configDnsMasq(router, network, cmds);
        final boolean result = _nwHelper.sendCommandsToRouter(router, cmds);
        if (result) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    for (final NicIpAliasVO revokedAliasVO : revokedIpAliasVOs) {
                        _nicIpAliasDao.expunge(revokedAliasVO.getId());
                    }
                }
            });
            return true;
        }
    }
    return false;
}
Also used : ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) Commands(com.cloud.agent.manager.Commands) ArrayList(java.util.ArrayList) IpAliasTO(com.cloud.agent.api.routing.IpAliasTO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NicIpAliasVO(com.cloud.vm.dao.NicIpAliasVO) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 20 with TransactionStatus

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

the class VirtualNetworkApplianceManagerImpl method collectNetworkStatistics.

@Override
public <T extends VirtualRouter> void collectNetworkStatistics(final T router, final Nic nic) {
    if (router == null) {
        return;
    }
    final String privateIP = router.getPrivateIpAddress();
    if (privateIP != null) {
        final boolean forVpc = router.getVpcId() != null;
        List<Nic> routerNics = new ArrayList<Nic>();
        if (nic != null) {
            routerNics.add(nic);
        } else {
            routerNics.addAll(_nicDao.listByVmId(router.getId()));
        }
        for (final Nic routerNic : routerNics) {
            final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
            // [TODO] Avoiding the NPE now, but I have to find out what is going on with the network. - Wilder Rodrigues
            if (network == null) {
                s_logger.error("Could not find a network with ID => " + routerNic.getNetworkId() + ". It might be a problem!");
                continue;
            }
            if (forVpc && network.getTrafficType() == TrafficType.Public || !forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated) {
                final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(), forVpc, routerNic.getIPv4Address());
                final String routerType = router.getType().toString();
                final UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(), router.getDataCenterId(), network.getId(), forVpc ? routerNic.getIPv4Address() : null, router.getId(), routerType);
                NetworkUsageAnswer answer = null;
                try {
                    answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd);
                } catch (final Exception e) {
                    s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId(), e);
                    continue;
                }
                if (answer != null) {
                    if (!answer.getResult()) {
                        s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails());
                        continue;
                    }
                    try {
                        if (answer.getBytesReceived() == 0 && answer.getBytesSent() == 0) {
                            s_logger.debug("Recieved and Sent bytes are both 0. Not updating user_statistics");
                            continue;
                        }
                        final NetworkUsageAnswer answerFinal = answer;
                        Transaction.execute(new TransactionCallbackNoReturn() {

                            @Override
                            public void doInTransactionWithoutResult(final TransactionStatus status) {
                                final UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(), router.getDataCenterId(), network.getId(), forVpc ? routerNic.getIPv4Address() : null, router.getId(), routerType);
                                if (stats == null) {
                                    s_logger.warn("unable to find stats for account: " + router.getAccountId());
                                    return;
                                }
                                if (previousStats != null && (previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived() || previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent())) {
                                    s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " + "Ignoring current answer. Router: " + answerFinal.getRouterName() + " Rcvd: " + answerFinal.getBytesReceived() + "Sent: " + answerFinal.getBytesSent());
                                    return;
                                }
                                if (stats.getCurrentBytesReceived() > answerFinal.getBytesReceived()) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("Received # of bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Router: " + answerFinal.getRouterName() + " Reported: " + toHumanReadableSize(answerFinal.getBytesReceived()) + " Stored: " + toHumanReadableSize(stats.getCurrentBytesReceived()));
                                    }
                                    stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
                                }
                                stats.setCurrentBytesReceived(answerFinal.getBytesReceived());
                                if (stats.getCurrentBytesSent() > answerFinal.getBytesSent()) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("Received # of bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Router: " + answerFinal.getRouterName() + " Reported: " + toHumanReadableSize(answerFinal.getBytesSent()) + " Stored: " + toHumanReadableSize(stats.getCurrentBytesSent()));
                                    }
                                    stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
                                }
                                stats.setCurrentBytesSent(answerFinal.getBytesSent());
                                if (!_dailyOrHourly) {
                                    // update agg bytes
                                    stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
                                    stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
                                }
                                _userStatsDao.update(stats.getId(), stats);
                            }
                        });
                    } catch (final Exception e) {
                        s_logger.warn("Unable to update user statistics for account: " + router.getAccountId() + " Rx: " + toHumanReadableSize(answer.getBytesReceived()) + "; Tx: " + toHumanReadableSize(answer.getBytesSent()));
                    }
                }
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Nic(com.cloud.vm.Nic) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) NetworkUsageCommand(com.cloud.agent.api.NetworkUsageCommand) ConnectionException(com.cloud.exception.ConnectionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) JsonSyntaxException(com.google.gson.JsonSyntaxException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ParseException(java.text.ParseException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) Network(com.cloud.network.Network) NetworkUsageAnswer(com.cloud.agent.api.NetworkUsageAnswer) UserStatisticsVO(com.cloud.user.UserStatisticsVO)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)323 DB (com.cloud.utils.db.DB)257 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)150 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)117 ArrayList (java.util.ArrayList)104 Account (com.cloud.user.Account)93 List (java.util.List)89 ActionEvent (com.cloud.event.ActionEvent)88 ConfigurationException (javax.naming.ConfigurationException)71 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)64 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)64 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)50 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)49 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)47 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)45 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)45 IPAddressVO (com.cloud.network.dao.IPAddressVO)43 HashMap (java.util.HashMap)38 Network (com.cloud.network.Network)37