File: cgroupid.go

package info (click to toggle)
golang-github-intel-goresctrl 0.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,064 kB
  • sloc: makefile: 19; sh: 15
file content (65 lines) | stat: -rw-r--r-- 1,121 bytes parent folder | download
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
package cgroups

import (
	"fmt"
	"os"
	"path/filepath"
	"sync"
)

// CgroupID implements mapping kernel cgroup IDs to cgroupfs paths with transparent caching.
type CgroupID struct {
	root  string
	cache map[uint64]string
	sync.Mutex
}

// NewCgroupID creates a new CgroupID map/cache.
func NewCgroupID(root string) *CgroupID {
	return &CgroupID{
		root:  root,
		cache: make(map[uint64]string),
	}
}

// Find finds the path for the given cgroup id.
func (cgid *CgroupID) Find(id uint64) (string, error) {
	found := false
	var p string

	cgid.Lock()
	defer cgid.Unlock()

	if path, ok := cgid.cache[id]; ok {
		return path, nil
	}

	err := fsi.Walk(cgid.root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			if os.IsNotExist(err) {
				return nil
			}
			return err
		}

		if found {
			return filepath.SkipDir
		}

		if info.IsDir() && id == getID(path) {
			found = true
			p = path
			return filepath.SkipDir
		}
		return nil
	})

	if err != nil {
		return "", err
	} else if !found {
		return "", fmt.Errorf("cgroupid %v not found", id)
	} else {
		cgid.cache[id] = p
		return p, nil
	}
}