group.go 1.31 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
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
66
67
68
69
70
71
72
73
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package info

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

// Get groups to add to container
func GetAdditionalGroups() ([]string, error) {
	groups := []string{"video"}

	subGrps, err := GetSubsystemGroups("kfd")
	if err != nil {
		return nil, err
	}

	groups = append(groups, subGrps...)

	return groups, nil
}

func GetSubsystemGroups(subsystem string) ([]string, error) {
	ruleFiles, err := filepath.Glob("/lib/udev/rules.d/*.rules")
	if err != nil {
		return nil, err
	}

	var groups []string

	for _, f := range ruleFiles {
		g, err := parseRuleFile(f, subsystem)
		if err != nil {
			return nil, err
		}
		if g != "" {
			groups = append(groups, g)
		}
	}

	return groups, nil
}

func parseRuleFile(path string, subsystem string) (string, error) {
	infoFile, err := os.Open(path)
	if err != nil {
		return "", fmt.Errorf("failed to open %v: %v", path, err)
	}
	defer infoFile.Close()

	key := fmt.Sprintf(`SUBSYSTEM=="%s"`, subsystem)
	reg := regexp.MustCompile(`GROUP="(\w+)"`)

	scanner := bufio.NewScanner(infoFile)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, key) {
			found := reg.FindStringSubmatch(line)
			if len(found) < 2 {
				continue
			}
			return found[1], nil
		}
	}
	return "", nil
}