Debian Codegraph @

internal/memorylimiter/cgroups/cgroup.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Keep the original Uber license.
5
6 // Copyright (c) 2017 Uber Technologies, Inc.
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the "Software"), to deal
10 // in the Software without restriction, including without limitation the rights
11 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 // copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
14 //
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
17 //
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 // THE SOFTWARE.
25
26 //go:build linux
27
28 package cgroups // import "go.opentelemetry.io/collector/internal/memorylimiter/cgroups"
29
30 import (
31 "bufio"
32 "io"
33 "os"
34 "path/filepath"
35 "strconv"
36 )
37
38 // CGroup represents the data structure for a Linux control group.
39 type CGroup struct {
40 path string
41 }
42
43 // NewCGroup returns a new *CGroup from a given path.
44 func NewCGroup(path string) *CGroup {
45 return &CGroup{path: path}
46 }
47
48 // Path returns the path of the CGroup*.
49 func (cg *CGroup) Path() string {
50 return cg.path
51 }
52
53 // ParamPath returns the path of the given cgroup param under itself.
54 func (cg *CGroup) ParamPath(param string) string {
55 return filepath.Join(cg.path, param)
56 }
57
58 // readFirstLine reads the first line from a cgroup param file.
59 func (cg *CGroup) readFirstLine(param string) (string, error) {
60 paramFile, err := os.Open(cg.ParamPath(param))
61 if err != nil {
62 return "", err
63 }
64 defer paramFile.Close()
65
66 scanner := bufio.NewScanner(paramFile)
67 if scanner.Scan() {
68 return scanner.Text(), nil
69 }
70 if err := scanner.Err(); err != nil {
71 return "", err
72 }
73 return "", io.ErrUnexpectedEOF
74 }
75
76 // readInt parses the first line from a cgroup param file as int.
77 func (cg *CGroup) readInt(param string) (int64, error) {
78 text, err := cg.readFirstLine(param)
79 if err != nil {
80 return 0, err
81 }
82 return strconv.ParseInt(text, 10, 64)
83 }