github.com/pdmccormick/importable-docker-buildx@v0.0.0-20240426161518-e47091289030/util/confutil/node.go (about)

     1  package confutil
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding/hex"
     6  	"os"
     7  	"path/filepath"
     8  	"sync"
     9  )
    10  
    11  var nodeIdentifierMu sync.Mutex
    12  
    13  func TryNodeIdentifier(configDir string) (out string) {
    14  	nodeIdentifierMu.Lock()
    15  	defer nodeIdentifierMu.Unlock()
    16  	sessionFile := filepath.Join(configDir, ".buildNodeID")
    17  	if _, err := os.Lstat(sessionFile); err != nil {
    18  		if os.IsNotExist(err) { // create a new file with stored randomness
    19  			b := make([]byte, 8)
    20  			if _, err := rand.Read(b); err != nil {
    21  				return out
    22  			}
    23  			if err := os.WriteFile(sessionFile, []byte(hex.EncodeToString(b)), 0600); err != nil {
    24  				return out
    25  			}
    26  		}
    27  	}
    28  
    29  	dt, err := os.ReadFile(sessionFile)
    30  	if err == nil {
    31  		return string(dt)
    32  	}
    33  	return
    34  }