podman

Форк
0
/
stats_linux.go 
134 строки · 4.4 Кб
1
//go:build !remote
2

3
package libpod
4

5
import (
6
	"fmt"
7
	"strings"
8
	"syscall"
9
	"time"
10

11
	runccgroup "github.com/opencontainers/runc/libcontainer/cgroups"
12

13
	"github.com/containers/common/pkg/cgroups"
14
	"github.com/containers/podman/v5/libpod/define"
15
	"golang.org/x/sys/unix"
16
)
17

18
// getPlatformContainerStats gets the platform-specific running stats
19
// for a given container.  The previousStats is used to correctly
20
// calculate cpu percentages. You should pass nil if there is no
21
// previous stat for this container.
22
func (c *Container) getPlatformContainerStats(stats *define.ContainerStats, previousStats *define.ContainerStats) error {
23
	if c.config.NoCgroups {
24
		return fmt.Errorf("cannot run top on container %s as it did not create a cgroup: %w", c.ID(), define.ErrNoCgroups)
25
	}
26

27
	cgroupPath, err := c.cGroupPath()
28
	if err != nil {
29
		return err
30
	}
31
	cgroup, err := cgroups.Load(cgroupPath)
32
	if err != nil {
33
		return fmt.Errorf("unable to load cgroup at %s: %w", cgroupPath, err)
34
	}
35

36
	// Ubuntu does not have swap memory in cgroups because swap is often not enabled.
37
	cgroupStats, err := cgroup.Stat()
38
	if err != nil {
39
		return fmt.Errorf("unable to obtain cgroup stats: %w", err)
40
	}
41
	conState := c.state.State
42

43
	// If the current total usage in the cgroup is less than what was previously
44
	// recorded then it means the container was restarted and runs in a new cgroup
45
	if previousStats.Duration > cgroupStats.CpuStats.CpuUsage.TotalUsage {
46
		previousStats = &define.ContainerStats{}
47
	}
48

49
	previousCPU := previousStats.CPUNano
50
	now := uint64(time.Now().UnixNano())
51
	stats.Duration = cgroupStats.CpuStats.CpuUsage.TotalUsage
52
	stats.UpTime = time.Duration(stats.Duration)
53
	stats.CPU = calculateCPUPercent(cgroupStats, previousCPU, now, previousStats.SystemNano)
54
	// calc the average cpu usage for the time the container is running
55
	stats.AvgCPU = calculateCPUPercent(cgroupStats, 0, now, uint64(c.state.StartedTime.UnixNano()))
56
	stats.MemUsage = cgroupStats.MemoryStats.Usage.Usage
57
	stats.MemLimit = c.getMemLimit(cgroupStats.MemoryStats.Usage.Limit)
58
	stats.MemPerc = (float64(stats.MemUsage) / float64(stats.MemLimit)) * 100
59
	stats.PIDs = 0
60
	if conState == define.ContainerStateRunning || conState == define.ContainerStatePaused {
61
		stats.PIDs = cgroupStats.PidsStats.Current
62
	}
63
	stats.BlockInput, stats.BlockOutput = calculateBlockIO(cgroupStats)
64
	stats.CPUNano = cgroupStats.CpuStats.CpuUsage.TotalUsage
65
	stats.CPUSystemNano = cgroupStats.CpuStats.CpuUsage.UsageInKernelmode
66
	stats.SystemNano = now
67
	stats.PerCPU = cgroupStats.CpuStats.CpuUsage.PercpuUsage
68

69
	return nil
70
}
71

72
// getMemLimit returns the memory limit for a container
73
func (c *Container) getMemLimit(memLimit uint64) uint64 {
74
	si := &syscall.Sysinfo_t{}
75
	err := syscall.Sysinfo(si)
76
	if err != nil {
77
		return memLimit
78
	}
79

80
	//nolint:unconvert
81
	physicalLimit := uint64(si.Totalram)
82

83
	if memLimit <= 0 || memLimit > physicalLimit {
84
		return physicalLimit
85
	}
86

87
	return memLimit
88
}
89

90
// calculateCPUPercent calculates the cpu usage using the latest measurement in stats.
91
// previousCPU is the last value of stats.CPU.Usage.Total measured at the time previousSystem.
92
//
93
//	(now - previousSystem) is the time delta in nanoseconds, between the measurement in previousCPU
94
//
95
// and the updated value in stats.
96
func calculateCPUPercent(stats *runccgroup.Stats, previousCPU, now, previousSystem uint64) float64 {
97
	var (
98
		cpuPercent  = 0.0
99
		cpuDelta    = float64(stats.CpuStats.CpuUsage.TotalUsage - previousCPU)
100
		systemDelta = float64(now - previousSystem)
101
	)
102
	if systemDelta > 0.0 && cpuDelta > 0.0 {
103
		// gets a ratio of container cpu usage total, and multiplies that by 100 to get a percentage
104
		cpuPercent = (cpuDelta / systemDelta) * 100
105
	}
106
	return cpuPercent
107
}
108

109
func calculateBlockIO(stats *runccgroup.Stats) (read uint64, write uint64) {
110
	for _, blkIOEntry := range stats.BlkioStats.IoServiceBytesRecursive {
111
		switch strings.ToLower(blkIOEntry.Op) {
112
		case "read":
113
			read += blkIOEntry.Value
114
		case "write":
115
			write += blkIOEntry.Value
116
		}
117
	}
118
	return
119
}
120

121
func getOnlineCPUs(container *Container) (int, error) {
122
	ctrPID, err := container.PID()
123
	if err != nil {
124
		return -1, fmt.Errorf("failed to obtain Container %s PID: %w", container.Name(), err)
125
	}
126
	if ctrPID == 0 {
127
		return ctrPID, define.ErrCtrStopped
128
	}
129
	var cpuSet unix.CPUSet
130
	if err := unix.SchedGetaffinity(ctrPID, &cpuSet); err != nil {
131
		return -1, fmt.Errorf("failed to obtain Container %s online cpus: %w", container.Name(), err)
132
	}
133
	return cpuSet.Count(), nil
134
}
135

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.