github.com/toplink-cn/moby@v0.0.0-20240305205811-460b4aebdf81/daemon/id.go (about)

     1  package daemon // import "github.com/docker/docker/daemon"
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  
     7  	"github.com/docker/docker/pkg/ioutils"
     8  	"github.com/google/uuid"
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  const idFilename = "engine-id"
    13  
    14  // LoadOrCreateID loads the engine's ID from the given root, or generates a new ID
    15  // if it doesn't exist. It returns the ID, and any error that occurred when
    16  // saving the file.
    17  //
    18  // Note that this function expects the daemon's root directory to already have
    19  // been created with the right permissions and ownership (usually this would
    20  // be done by daemon.CreateDaemonRoot().
    21  func LoadOrCreateID(root string) (string, error) {
    22  	var id string
    23  	idPath := filepath.Join(root, idFilename)
    24  	idb, err := os.ReadFile(idPath)
    25  	if os.IsNotExist(err) {
    26  		id = uuid.New().String()
    27  		if err := ioutils.AtomicWriteFile(idPath, []byte(id), os.FileMode(0o600)); err != nil {
    28  			return "", errors.Wrap(err, "error saving ID file")
    29  		}
    30  	} else if err != nil {
    31  		return "", errors.Wrapf(err, "error loading ID file %s", idPath)
    32  	} else {
    33  		id = string(idb)
    34  	}
    35  	return id, nil
    36  }