init monlet repo with stage 0-2 (docs, contract, agent MVP)
This commit is contained in:
40
agent/internal/ids/ids.go
Normal file
40
agent/internal/ids/ids.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package ids
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/monlet/agent/internal/config"
|
||||
)
|
||||
|
||||
// LoadOrCreateAgentID returns configured ID if non-empty, otherwise loads
|
||||
// state_dir/agent_id, generating and persisting it on first run.
|
||||
func LoadOrCreateAgentID(stateDir, configured string) (string, error) {
|
||||
if configured != "" {
|
||||
return configured, nil
|
||||
}
|
||||
if err := os.MkdirAll(stateDir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("create state dir: %w", err)
|
||||
}
|
||||
path := filepath.Join(stateDir, "agent_id")
|
||||
b, err := os.ReadFile(path)
|
||||
if err == nil {
|
||||
id := strings.TrimSpace(string(b))
|
||||
if err := config.ValidateID("agent_id", id); err != nil {
|
||||
return "", fmt.Errorf("persisted agent_id invalid: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
if !os.IsNotExist(err) {
|
||||
return "", err
|
||||
}
|
||||
id := uuid.NewString()
|
||||
if err := os.WriteFile(path, []byte(id+"\n"), 0o600); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
Reference in New Issue
Block a user