hugetlb.go (2498B)
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 17 package cgroup1 18 19 import ( 20 "os" 21 "path/filepath" 22 "strconv" 23 "strings" 24 25 v1 "github.com/containerd/cgroups/v3/cgroup1/stats" 26 specs "github.com/opencontainers/runtime-spec/specs-go" 27 ) 28 29 func NewHugetlb(root string) (*hugetlbController, error) { 30 sizes, err := hugePageSizes() 31 if err != nil { 32 return nil, err 33 } 34 35 return &hugetlbController{ 36 root: filepath.Join(root, string(Hugetlb)), 37 sizes: sizes, 38 }, nil 39 } 40 41 type hugetlbController struct { 42 root string 43 sizes []string 44 } 45 46 func (h *hugetlbController) Name() Name { 47 return Hugetlb 48 } 49 50 func (h *hugetlbController) Path(path string) string { 51 return filepath.Join(h.root, path) 52 } 53 54 func (h *hugetlbController) Create(path string, resources *specs.LinuxResources) error { 55 if err := os.MkdirAll(h.Path(path), defaultDirPerm); err != nil { 56 return err 57 } 58 for _, limit := range resources.HugepageLimits { 59 if err := os.WriteFile( 60 filepath.Join(h.Path(path), strings.Join([]string{"hugetlb", limit.Pagesize, "limit_in_bytes"}, ".")), 61 []byte(strconv.FormatUint(limit.Limit, 10)), 62 defaultFilePerm, 63 ); err != nil { 64 return err 65 } 66 } 67 return nil 68 } 69 70 func (h *hugetlbController) Stat(path string, stats *v1.Metrics) error { 71 for _, size := range h.sizes { 72 s, err := h.readSizeStat(path, size) 73 if err != nil { 74 return err 75 } 76 stats.Hugetlb = append(stats.Hugetlb, s) 77 } 78 return nil 79 } 80 81 func (h *hugetlbController) readSizeStat(path, size string) (*v1.HugetlbStat, error) { 82 s := v1.HugetlbStat{ 83 Pagesize: size, 84 } 85 for _, t := range []struct { 86 name string 87 value *uint64 88 }{ 89 { 90 name: "usage_in_bytes", 91 value: &s.Usage, 92 }, 93 { 94 name: "max_usage_in_bytes", 95 value: &s.Max, 96 }, 97 { 98 name: "failcnt", 99 value: &s.Failcnt, 100 }, 101 } { 102 v, err := readUint(filepath.Join(h.Path(path), strings.Join([]string{"hugetlb", size, t.name}, "."))) 103 if err != nil { 104 return nil, err 105 } 106 *t.value = v 107 } 108 return &s, nil 109 }