forked from DataDog/datadog-agent
-
Notifications
You must be signed in to change notification settings - Fork 2
/
reader_detector.go
80 lines (65 loc) · 1.8 KB
/
reader_detector.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
70
71
72
73
74
75
76
77
78
79
80
// 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 2016-present Datadog, Inc.
//go:build linux
// +build linux
package cgroups
import (
"bufio"
"os"
"path"
"path/filepath"
"strings"
)
const (
cgroupV2Key = "cgroupv2"
)
func discoverCgroupMountPoints(hostPrefix, procFsPath string) (map[string]string, error) {
f, err := os.Open(filepath.Join(procFsPath, "/mounts"))
if err != nil {
return nil, err
}
defer f.Close()
mountPointsv1 := make(map[string]string)
var mountPointsv2 string
s := bufio.NewScanner(f)
for s.Scan() {
line := s.Text()
if !strings.HasPrefix(line, "cgroup") {
continue
}
tokens := strings.Fields(line)
// Check if the filesystem type is 'cgroup' or 'cgroup2'
if len(tokens) >= 3 {
fsType := tokens[2]
cgroupPath := tokens[1]
// Mounts are duplicated when /sys/fs is mounted inside a container (like /host/sys/fs)
if !strings.HasPrefix(cgroupPath, hostPrefix) {
continue
}
if fsType == "cgroup" {
// Target can be comma-separate values like cpu,cpuacct
tsp := strings.Split(path.Base(cgroupPath), ",")
for _, target := range tsp {
mountPointsv1[target] = cgroupPath
}
} else if tokens[2] == "cgroup2" {
mountPointsv2 = cgroupPath
}
}
}
if len(mountPointsv1) == 0 && mountPointsv2 != "" {
return map[string]string{cgroupV2Key: mountPointsv2}, nil
}
return mountPointsv1, nil
}
func isCgroup1(cgroupMountPoints map[string]string) bool {
return len(cgroupMountPoints) > 1
}
func isCgroup2(cgroupMountPoints map[string]string) bool {
if _, found := cgroupMountPoints[cgroupV2Key]; found && len(cgroupMountPoints) == 1 {
return true
}
return false
}