From 865ab5f7b9b713aa604e3f4cb4461a4d98dfcecf Mon Sep 17 00:00:00 2001 From: Marco Pantaleoni Date: Wed, 30 Dec 2020 11:26:59 +0100 Subject: [PATCH] Add support for MACHINE_ID_FILE environment variable (on linux). --- helper.go | 15 +++++++++++++++ id_linux.go | 14 +++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/helper.go b/helper.go index a16056d..a071dd7 100644 --- a/helper.go +++ b/helper.go @@ -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")) } diff --git a/id_linux.go b/id_linux.go index e68eb45..35c8462 100644 --- a/id_linux.go +++ b/id_linux.go @@ -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. @@ -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 }