denisbrodbeck / machineid

Get the unique machine id of any host (without admin privileges)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

No machine-id detected in docker containers

lox opened this issue · comments

It appears that Docker doesn't expose /var/lib/dbus/machine-id or /etc/machine-id, so no machine-id gets detected inside docker containers.

Did you try to share the file from the host to the container?

For example:

version: '3'
services:
  service:
    image: image
    ports:
    - 8080:8080
    restart: always
    network_mode: "host"
    volumes:
    - /etc/machine-id:/etc/machine-id
    - /var/lib/dbus/machine-id:/var/lib/dbus/machine-id

commented

This is a great library, thanks so much for writing it.

It would be great if docker containerisation were detected, and then a unique container ID or some information was used as the machine ID - or if it exposed a Docker ID and the machine ID, and both could be used as a third unique ID.

If neither of these paths exists, an empty string will be returned.
Instead of getting a wrong id, it's better to generate one.

// +build linux

package machineid

const (
	// 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.
	// Some systems (like Fedora 20) only know this path.
	// Sometimes it's the other way round.
	dbusPathEtc = "/etc/machine-id"

	uuid = "/proc/sys/kernel/random/uuid"
)

// machineID returns the uuid specified at `/var/lib/dbus/machine-id` or `/etc/machine-id`.
// 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)
	}
	
	if err != nil {
		id, err = readFile(uuid)
		if err == nil {
			writeFile(dbusPathEtc, id)
		}
	}

	if err != nil {
		return "", err
	}
	return trim(string(id)), nil
}

func writeFile(filename string, data []byte) error {
	return ioutil.WriteFile(filename, data, 644)
}

It works fine for my docker image

commented

Joining the party. It would be great to support docker by getting unique ids per container.

Is there any progress on this?

If neither of these paths exists, an empty string will be returned.
Instead of getting a wrong id, it's better to generate one.

Since this repository seems unmaintained, I implemented a variation of this logic in github.com/panta/machineid, where it's also possible to specify the machine-id file using the MACHINE_ID_FILE env var.
Obviously I'd be more that happy if the changes were merged upstream!