-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
cgroup_memory_usage_linux.go
61 lines (48 loc) · 1.56 KB
/
cgroup_memory_usage_linux.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2022-present Datadog, Inc.
//go:build linux
//nolint:revive // TODO(AML) Fix revive linter
package ratelimit
import (
"errors"
"github.com/DataDog/datadog-agent/pkg/config"
"github.com/DataDog/datadog-agent/pkg/util/cgroups"
)
var _ memoryUsage = (*hostMemoryUsage)(nil)
// cgroupMemoryUsage provides a method to return the cgroup memory memory usage rate.
type cgroupMemoryUsage struct {
cgroup cgroups.Cgroup
}
func newCgroupMemoryUsage() (*cgroupMemoryUsage, error) {
selfReader, err := cgroups.NewSelfReader("/proc", config.IsContainerized())
if err != nil {
return nil, err
}
cgroup := selfReader.GetCgroup(cgroups.SelfCgroupIdentifier)
if cgroup == nil {
return nil, errors.New("cannot get cgroup")
}
cgroupMemoryUsage := &cgroupMemoryUsage{
cgroup: cgroup,
}
// Make sure cgroup is available
if _, _, err := cgroupMemoryUsage.getMemoryStats(); err != nil {
return nil, err
}
return cgroupMemoryUsage, nil
}
func (c *cgroupMemoryUsage) getMemoryStats() (float64, float64, error) {
var stats cgroups.MemoryStats
if err := c.cgroup.GetMemoryStats(&stats); err != nil {
return 0, 0, err
}
if stats.Limit == nil {
return 0, 0, errors.New("cannot get the memory `Limit`")
}
if stats.UsageTotal == nil {
return 0, 0, errors.New("cannot get the memory `UsageTotal`")
}
return float64(*stats.UsageTotal), float64(*stats.Limit), nil
}