Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linux: Check historic machine-id files #44

Merged
merged 4 commits into from
Mar 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions providers/linux/machineid.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,37 @@ import (
"github.com/elastic/go-sysinfo/types"
)

var (
// Possible (current and historic) locations of the machine-id file.
// These will be searched in order.
machineIDFiles = []string{"/etc/machine-id", "/var/lib/dbus/machine-id", "/var/db/dbus/machine-id"}
)

func MachineID() (string, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about adding machine-id files to the testdata directory? Then make this unit testable by adding a machineID(rootDir string) that enables a test to point this at a specific directory in testdata. MachineID() would call machineID("/").

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We certainly could. I assume it wouldn't do much more than ioutil.ReadFile() and string(bytes.TrimSpace()) though, so I'm not sure how much testing it actually achieves.

Thanks for merging!

id, err := ioutil.ReadFile("/etc/machine-id")
var contents []byte
var err error

for _, file := range machineIDFiles {
contents, err = ioutil.ReadFile(file)
if err != nil {
if os.IsNotExist(err) {
// Try next location
continue
}

// Return with error on any other error
return "", errors.Wrapf(err, "failed to read %v", file)
}

// Found it
break
}

if os.IsNotExist(err) {
// None of the locations existed
return "", types.ErrNotImplemented
}
id = bytes.TrimSpace(id)
return string(id), errors.Wrap(err, "failed to read machine-id")

contents = bytes.TrimSpace(contents)
return string(contents), nil
}
1 change: 1 addition & 0 deletions system_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ func TestHost(t *testing.T) {

info := host.Info()
assert.NotZero(t, info)
assert.NotZero(t, info.UniqueID)

memory, err := host.Memory()
if err != nil {
Expand Down