This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
system.go
110 lines (91 loc) · 2.26 KB
/
system.go
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//go:generate stringer -type=Packages
package dep
import (
"bytes"
"fmt"
"os/exec"
"strings"
"github.com/pkg/errors"
)
type Packages int
const (
UnknownPkg Packages = iota
DebianBased
REMBased
)
type OperatingSystem struct {
Packages Packages
}
func (o OperatingSystem) String() string {
var os string
switch o {
case Ubuntu:
os = "Ubuntu"
case CentOS:
os = "CentOS"
}
return os
}
var (
UnknownOS OperatingSystem = OperatingSystem{}
Ubuntu OperatingSystem = OperatingSystem{DebianBased}
CentOS OperatingSystem = OperatingSystem{REMBased}
)
type OperatingSystemMajor struct {
OperatingSystem OperatingSystem
Version string
}
func (o OperatingSystemMajor) String() string {
var versionName string
switch o {
case Bionic:
versionName = "18.04 LTS Bionic Beaver"
case CentOS7:
versionName = "7"
}
return fmt.Sprintf("%s %s", o.OperatingSystem, versionName)
}
var (
Unknown OperatingSystemMajor = OperatingSystemMajor{UnknownOS, ""}
Bionic OperatingSystemMajor = OperatingSystemMajor{Ubuntu, "bionic"}
CentOS7 OperatingSystemMajor = OperatingSystemMajor{CentOS, "7"}
// Debian OperatingSystem = OperatingSystem{DebianBased}
)
func GetOperatingSystem() (OperatingSystemMajor, error) {
buf := new(bytes.Buffer)
defer buf.Reset()
hostnamectl := exec.Command("hostnamectl")
hostnamectl.Stdout = buf
if err := hostnamectl.Run(); err != nil {
return Unknown, errors.Wrap(err, "running hostnamectl in order to get operating system information failed")
}
var (
osLine string
err error
)
for err == nil {
osLine, err = buf.ReadString('\n')
if strings.Contains(osLine, "Operating System") {
break
}
}
if err != nil {
return Unknown, errors.Wrap(err, "finding line containing \"Operating System\" in hostnamectl output failed")
}
os := strings.Fields(osLine)[2]
switch os {
case "Ubuntu":
version := strings.Fields(osLine)[3]
if strings.HasPrefix(version, "18.04") {
return Bionic, nil
}
return Unknown, errors.Errorf("Unsupported ubuntu version %s", version)
case "CentOS":
version := strings.Fields(osLine)[4]
if version == "7" {
return CentOS7, nil
}
return Unknown, errors.Errorf("Unsupported centOS version %s", version)
}
return Unknown, errors.Errorf("Unknown operating system %s", os)
}