forked from jouyouyun/hardware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hardware.go
74 lines (65 loc) · 1.46 KB
/
hardware.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
package hardware
import (
"encoding/json"
"fmt"
hdisk "github.com/jouyouyun/hardware/disk"
hdmi "github.com/jouyouyun/hardware/dmi"
"github.com/jouyouyun/hardware/utils"
)
var (
_mid string
)
// GenMachineID generate this machine's id
func GenMachineID() (string, error) {
if len(_mid) != 0 {
return _mid, nil
}
dmi, err := hdmi.GetDMI()
if err == nil && len(dmi.ProductUUID) != 0 {
mid, err := genMachineIDWithDMI(*dmi)
if err == nil {
_mid = mid
return mid, nil
}
} else if dmi == nil {
dmi = &hdmi.DMI{}
}
// if dmi product uuid null, generate machine id with root disk serial
disks, err := hdisk.GetDiskList()
if err != nil {
return "", err
}
root := disks.GetRoot()
if root == nil {
return "", fmt.Errorf("no root disk found")
}
return genMachineIDWithDisk(*dmi, root)
}
func genMachineIDWithDMI(dmi hdmi.DMI) (string, error) {
// bios info maybe changed after upgraded
dmi.BiosDate = ""
dmi.BiosVendor = ""
dmi.BiosVersion = ""
return doGenMachineID(&dmi)
}
func genMachineIDWithDisk(dmi hdmi.DMI, disk *hdisk.Disk) (string, error) {
// bios info maybe changed after upgraded
dmi.BiosDate = ""
dmi.BiosVendor = ""
dmi.BiosVersion = ""
var info = struct {
hdmi.DMI
DiskSerial string
}{
DMI: dmi,
DiskSerial: disk.Serial,
}
return doGenMachineID(&info)
}
func doGenMachineID(info interface{}) (string, error) {
data, err := json.Marshal(info)
if err != nil {
return "", err
}
return utils.SHA256Sum(data), nil
}