summaryrefslogtreecommitdiff
path: root/pkg/util/utils_linux.go
blob: 1cffab19d548b65a332282a022895cae1bfdc2a8 (plain)
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
package util

import (
	"fmt"
	"os"
	"path/filepath"
	"syscall"

	"github.com/containers/psgo"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

// GetContainerPidInformationDescriptors returns a string slice of all supported
// format descriptors of GetContainerPidInformation.
func GetContainerPidInformationDescriptors() ([]string, error) {
	return psgo.ListDescriptors(), nil
}

// FindDeviceNodes parses /dev/ into a set of major:minor -> path, where
// [major:minor] is the device's major and minor numbers formatted as, for
// example, 2:0 and path is the path to the device node.
// Symlinks to nodes are ignored.
func FindDeviceNodes() (map[string]string, error) {
	nodes := make(map[string]string)
	err := filepath.Walk("/dev", func(path string, info os.FileInfo, err error) error {
		if err != nil {
			logrus.Warnf("Error descending into path %s: %v", path, err)
			return filepath.SkipDir
		}

		// If we aren't a device node, do nothing.
		if info.Mode()&(os.ModeDevice|os.ModeCharDevice) == 0 {
			return nil
		}

		// We are a device node. Get major/minor.
		sysstat, ok := info.Sys().(*syscall.Stat_t)
		if !ok {
			return errors.Errorf("Could not convert stat output for use")
		}
		// We must typeconvert sysstat.Rdev from uint64->int to avoid constant overflow
		rdev := int(sysstat.Rdev)
		major := ((rdev >> 8) & 0xfff) | ((rdev >> 32) & ^0xfff)
		minor := (rdev & 0xff) | ((rdev >> 12) & ^0xff)

		nodes[fmt.Sprintf("%d:%d", major, minor)] = path

		return nil
	})
	if err != nil {
		return nil, err
	}

	return nodes, nil
}