1// Copyright 2020 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package procfs
15
16import (
17	"bufio"
18	"bytes"
19	"fmt"
20	"strconv"
21	"strings"
22
23	"github.com/prometheus/procfs/internal/util"
24)
25
26// Cgroup models one line from /proc/[pid]/cgroup. Each Cgroup struct describes the the placement of a PID inside a
27// specific control hierarchy. The kernel has two cgroup APIs, v1 and v2. v1 has one hierarchy per available resource
28// controller, while v2 has one unified hierarchy shared by all controllers. Regardless of v1 or v2, all hierarchies
29// contain all running processes, so the question answerable with a Cgroup struct is 'where is this process in
30// this hierarchy' (where==what path on the specific cgroupfs). By prefixing this path with the mount point of
31// *this specific* hierarchy, you can locate the relevant pseudo-files needed to read/set the data for this PID
32// in this hierarchy
33//
34// Also see http://man7.org/linux/man-pages/man7/cgroups.7.html
35type Cgroup struct {
36	// HierarchyID that can be matched to a named hierarchy using /proc/cgroups. Cgroups V2 only has one
37	// hierarchy, so HierarchyID is always 0. For cgroups v1 this is a unique ID number
38	HierarchyID int
39	// Controllers using this hierarchy of processes. Controllers are also known as subsystems. For
40	// Cgroups V2 this may be empty, as all active controllers use the same hierarchy
41	Controllers []string
42	// Path of this control group, relative to the mount point of the cgroupfs representing this specific
43	// hierarchy
44	Path string
45}
46
47// parseCgroupString parses each line of the /proc/[pid]/cgroup file
48// Line format is hierarchyID:[controller1,controller2]:path
49func parseCgroupString(cgroupStr string) (*Cgroup, error) {
50	var err error
51
52	fields := strings.SplitN(cgroupStr, ":", 3)
53	if len(fields) < 3 {
54		return nil, fmt.Errorf("at least 3 fields required, found %d fields in cgroup string: %s", len(fields), cgroupStr)
55	}
56
57	cgroup := &Cgroup{
58		Path:        fields[2],
59		Controllers: nil,
60	}
61	cgroup.HierarchyID, err = strconv.Atoi(fields[0])
62	if err != nil {
63		return nil, fmt.Errorf("failed to parse hierarchy ID")
64	}
65	if fields[1] != "" {
66		ssNames := strings.Split(fields[1], ",")
67		cgroup.Controllers = append(cgroup.Controllers, ssNames...)
68	}
69	return cgroup, nil
70}
71
72// parseCgroups reads each line of the /proc/[pid]/cgroup file
73func parseCgroups(data []byte) ([]Cgroup, error) {
74	var cgroups []Cgroup
75	scanner := bufio.NewScanner(bytes.NewReader(data))
76	for scanner.Scan() {
77		mountString := scanner.Text()
78		parsedMounts, err := parseCgroupString(mountString)
79		if err != nil {
80			return nil, err
81		}
82		cgroups = append(cgroups, *parsedMounts)
83	}
84
85	err := scanner.Err()
86	return cgroups, err
87}
88
89// Cgroups reads from /proc/<pid>/cgroups and returns a []*Cgroup struct locating this PID in each process
90// control hierarchy running on this system. On every system (v1 and v2), all hierarchies contain all processes,
91// so the len of the returned struct is equal to the number of active hierarchies on this system
92func (p Proc) Cgroups() ([]Cgroup, error) {
93	data, err := util.ReadFileNoStat(fmt.Sprintf("/proc/%d/cgroup", p.PID))
94	if err != nil {
95		return nil, err
96	}
97	return parseCgroups(data)
98}
99