File: hardware.go

package info (click to toggle)
golang-github-jouyouyun-hardware 0.1.6-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 580 kB
  • sloc: ansic: 43; makefile: 4
file content (75 lines) | stat: -rw-r--r-- 1,579 bytes parent folder | download
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
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
	IncludeDiskInfo bool
)

// GenMachineID generate this machine's id
func GenMachineID() (string, error) {
	if len(_mid) != 0 {
		return _mid, nil
	}

	dmi, err := hdmi.GetDMI()
	if !IncludeDiskInfo && 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 or IncludeDiskInfo is true, 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
}