Ejemplo n.º 1
0
func getCPUStats(domain *libvirtgo.VirDomain) (types.CpuStats, error) {
	stats := types.CpuStats{
		Usage: types.CpuUsage{
			PerCpu: make([]uint64, 0, 1),
		},
	}

	// Get the number of cpus available to query from the host perspective,
	ncpus, err := domain.GetCPUStats(nil, 0, 0, 0, 0)
	if err != nil {
		return stats, err
	}

	// Get how many statistics are available for the given @start_cpu.
	nparams, err := domain.GetCPUStats(nil, 0, 0, 1, 0)
	if err != nil {
		return stats, err
	}

	// Query per-cpu stats
	var perCPUStats libvirtgo.VirTypedParameters
	_, err = domain.GetCPUStats(&perCPUStats, nparams, 0, uint32(ncpus), 0)
	if err != nil {
		return stats, err
	}
	if len(perCPUStats) == 0 {
		return stats, fmt.Errorf("Can't get per-cpu stats")
	}
	for _, stat := range perCPUStats {
		stats.Usage.PerCpu = append(stats.Usage.PerCpu, stat.Value.(uint64))
	}
	glog.V(4).Infof("Get per-cpu stats: %v", perCPUStats)

	// Query total stats
	var cpuStats libvirtgo.VirTypedParameters
	nparams, err = domain.GetCPUStats(nil, 0, -1, 1, 0)
	if err != nil {
		return stats, err
	}
	_, err = domain.GetCPUStats(&cpuStats, nparams, -1, 1, 0)
	if err != nil {
		return stats, err
	}
	for _, stat := range cpuStats {
		switch stat.Name {
		case VIR_DOMAIN_CPU_STATS_CPUTIME:
			stats.Usage.Total = stat.Value.(uint64)
		case VIR_DOMAIN_CPU_STATS_USERTIME:
			stats.Usage.User = stat.Value.(uint64)
		case VIR_DOMAIN_CPU_STATS_SYSTEMTIME:
			stats.Usage.System = stat.Value.(uint64)
		}
	}
	glog.V(4).Infof("Get total cpu stats: %v", cpuStats)

	return stats, nil
}