Skip to content

Commit

Permalink
Add support for MACHINE_ID_FILE environment variable (on linux).
Browse files Browse the repository at this point in the history
  • Loading branch information
panta committed Dec 30, 2020
1 parent ac4d261 commit 865ab5f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
15 changes: 15 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ func readFile(filename string) ([]byte, error) {
return ioutil.ReadFile(filename)
}

// readFirstFile tries all the pathnames listed and returns the contents of the first readable file.
func readFirstFile(pathnames []string) ([]byte, error) {
contents := []byte{}
var err error
for _, pathname := range pathnames {
if pathname != "" {
contents, err = readFile(pathname)
if err == nil {
return contents, nil
}
}
}
return contents, err
}

func trim(s string) string {
return strings.TrimSpace(strings.Trim(s, "\n"))
}
14 changes: 9 additions & 5 deletions id_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

package machineid

import "os"

const (
// the environment variable name pointing to the machine id pathname
ENV_VARNAME = "MACHINE_ID_FILE"

// dbusPath is the default path for dbus machine id.
dbusPath = "/var/lib/dbus/machine-id"
// dbusPathEtc is the default path for dbus machine id located in /etc.
Expand All @@ -15,11 +20,10 @@ const (
// If there is an error reading the files an empty string is returned.
// See https://unix.stackexchange.com/questions/144812/generate-consistent-machine-unique-id
func machineID() (string, error) {
id, err := readFile(dbusPath)
if err != nil {
// try fallback path
id, err = readFile(dbusPathEtc)
}
env_pathname := os.Getenv(ENV_VARNAME)
id, err := readFirstFile([]string{
env_pathname, dbusPath, dbusPathEtc,
})
if err != nil {
return "", err
}
Expand Down

0 comments on commit 865ab5f

Please sign in to comment.