1/*
2   Copyright The containerd Authors.
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17package cgroups
18
19import (
20	"io/ioutil"
21	"os"
22	"path/filepath"
23	"strconv"
24	"strings"
25
26	v1 "github.com/containerd/cgroups/stats/v1"
27	specs "github.com/opencontainers/runtime-spec/specs-go"
28)
29
30func NewPids(root string) *pidsController {
31	return &pidsController{
32		root: filepath.Join(root, string(Pids)),
33	}
34}
35
36type pidsController struct {
37	root string
38}
39
40func (p *pidsController) Name() Name {
41	return Pids
42}
43
44func (p *pidsController) Path(path string) string {
45	return filepath.Join(p.root, path)
46}
47
48func (p *pidsController) Create(path string, resources *specs.LinuxResources) error {
49	if err := os.MkdirAll(p.Path(path), defaultDirPerm); err != nil {
50		return err
51	}
52	if resources.Pids != nil && resources.Pids.Limit > 0 {
53		return ioutil.WriteFile(
54			filepath.Join(p.Path(path), "pids.max"),
55			[]byte(strconv.FormatInt(resources.Pids.Limit, 10)),
56			defaultFilePerm,
57		)
58	}
59	return nil
60}
61
62func (p *pidsController) Update(path string, resources *specs.LinuxResources) error {
63	return p.Create(path, resources)
64}
65
66func (p *pidsController) Stat(path string, stats *v1.Metrics) error {
67	current, err := readUint(filepath.Join(p.Path(path), "pids.current"))
68	if err != nil {
69		return err
70	}
71	var max uint64
72	maxData, err := ioutil.ReadFile(filepath.Join(p.Path(path), "pids.max"))
73	if err != nil {
74		return err
75	}
76	if maxS := strings.TrimSpace(string(maxData)); maxS != "max" {
77		if max, err = parseUint(maxS, 10, 64); err != nil {
78			return err
79		}
80	}
81	stats.Pids = &v1.PidsStat{
82		Current: current,
83		Limit:   max,
84	}
85	return nil
86}
87