miaopanel
1package system
2
3import (
4 "bufio"
5 "os"
6 "runtime"
7 "strings"
8)
9
10// Distro describes the host operating system family.
11type Distro struct {
12 ID string `json:"id"` // ubuntu, debian, rocky, centos...
13 Version string `json:"version"`
14 PrettyName string `json:"pretty_name"`
15 Kernel string `json:"kernel"`
16 Arch string `json:"arch"`
17 Family string `json:"family"` // debian | rhel | unknown
18 Supported bool `json:"supported"`
19 Systemd bool `json:"systemd"`
20 PanelOS string `json:"panel_os"`
21}
22
23// Detect reads /etc/os-release and reports the package manager family.
24func Detect() Distro {
25 d := Distro{Arch: runtime.GOARCH, PanelOS: runtime.GOOS}
26 d.Kernel = readTrim("/proc/sys/kernel/osrelease")
27 if d.Kernel == "" {
28 d.Kernel = runtime.GOOS
29 }
30 f, err := os.Open("/etc/os-release")
31 if err != nil {
32 d.ID = runtime.GOOS
33 d.PrettyName = runtime.GOOS
34 return d
35 }
36 defer f.Close()
37 sc := bufio.NewScanner(f)
38 for sc.Scan() {
39 line := strings.TrimSpace(sc.Text())
40 key, val, ok := strings.Cut(line, "=")
41 if !ok {
42 continue
43 }
44 val = strings.Trim(val, `"'`)
45 switch key {
46 case "ID":
47 d.ID = val
48 case "VERSION_ID":
49 d.Version = val
50 case "PRETTY_NAME":
51 d.PrettyName = val
52 }
53 }
54 if err := sc.Err(); err != nil && d.ID == "" {
55 // A truncated os-release should still yield a usable identifier.
56 d.ID = runtime.GOOS
57 d.PrettyName = runtime.GOOS
58 }
59 switch d.ID {
60 case "ubuntu", "debian", "linuxmint", "raspbian":
61 d.Family = "debian"
62 case "centos", "rhel", "rocky", "almalinux", "fedora", "openeuler", "anolis":
63 d.Family = "rhel"
64 default:
65 d.Family = "unknown"
66 }
67 d.Supported = d.Family == "debian" || d.Family == "rhel"
68 if st, err := os.Stat("/run/systemd/system"); err == nil && st.IsDir() {
69 d.Systemd = true
70 }
71 return d
72}
73
74// PackageManager returns apt-get / dnf / yum for the detected family.
75func (d Distro) PackageManager() string {
76 switch d.Family {
77 case "debian":
78 return "apt-get"
79 case "rhel":
80 if Lookup("dnf") {
81 return "dnf"
82 }
83 return "yum"
84 }
85 return ""
86}
87
88// ServiceManager returns "systemd" or "" when unsupported.
89func (d Distro) ServiceManager() string {
90 if d.Systemd {
91 return "systemd"
92 }
93 return ""
94}
95
96func readTrim(path string) string {
97 b, err := os.ReadFile(path)
98 if err != nil {
99 return ""
100 }
101 return strings.TrimSpace(string(b))
102}