This repository has been archived by the owner on Sep 2, 2023. It is now read-only.
generated from hashicorp/nomad-skeleton-driver-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
69 lines (58 loc) · 2.41 KB
/
stats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package ch
import (
"runtime"
"time"
"github.com/docker/docker/api/types"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/helper/stats"
"github.com/hashicorp/nomad/plugins/drivers"
)
var (
DockerMeasuredCPUStats = []string{"Throttled Periods", "Throttled Time", "Percent"}
// cgroup-v2 only exposes a subset of memory stats
DockerCgroupV1MeasuredMemStats = []string{"RSS", "Cache", "Swap", "Usage", "Max Usage"}
)
func (h *taskHandle) DockerStatsToTaskResourceUsage(s *types.StatsJSON) *drivers.TaskResourceUsage {
if err := stats.Init(); err != nil {
h.logger.Info("stats error", "error", hclog.Fmt("%+v", err))
}
measuredMems := DockerCgroupV1MeasuredMemStats
ms := &drivers.MemoryStats{
RSS: s.MemoryStats.Stats["rss"],
Cache: s.MemoryStats.Stats["cache"],
Swap: s.MemoryStats.Stats["swap"],
Usage: s.MemoryStats.Usage,
MaxUsage: s.MemoryStats.MaxUsage,
Measured: measuredMems,
}
cs := &drivers.CpuStats{
ThrottledPeriods: s.CPUStats.ThrottlingData.ThrottledPeriods,
ThrottledTime: s.CPUStats.ThrottlingData.ThrottledTime,
Measured: DockerMeasuredCPUStats,
}
// Calculate percentage
cs.Percent = h.totalCpuStats.Percent(float64(s.CPUStats.CPUUsage.TotalUsage))
cs.SystemMode = CalculateCPUPercent(
s.CPUStats.CPUUsage.UsageInKernelmode, s.PreCPUStats.CPUUsage.UsageInKernelmode,
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage, runtime.NumCPU())
cs.UserMode = CalculateCPUPercent(
s.CPUStats.CPUUsage.UsageInUsermode, s.PreCPUStats.CPUUsage.UsageInUsermode,
s.CPUStats.CPUUsage.TotalUsage, s.PreCPUStats.CPUUsage.TotalUsage, runtime.NumCPU())
cs.TotalTicks = (cs.Percent / 100) * stats.TotalTicksAvailable() / float64(runtime.NumCPU())
h.logger.Info("stats calculator", "model_name", stats.CPUModelName(), "total_cpu", stats.CPUNumCores(), "mhz_per_core", stats.CPUMHzPerCore(), "total_ticks", hclog.Fmt("%+v", cs.TotalTicks), "total_ticks_available", hclog.Fmt("%f", stats.TotalTicksAvailable()))
return &drivers.TaskResourceUsage{
ResourceUsage: &drivers.ResourceUsage{
MemoryStats: ms,
CpuStats: cs,
},
Timestamp: time.Now().UTC().UnixNano(),
}
}
func CalculateCPUPercent(newSample, oldSample, newTotal, oldTotal uint64, cores int) float64 {
numerator := newSample - oldSample
denom := newTotal - oldTotal
if numerator <= 0 || denom <= 0 {
return 0.0
}
return (float64(numerator) / float64(denom)) * float64(cores) * 100.0
}