Implement Monlet MVP stack and UI updates
This commit is contained in:
@@ -2,38 +2,24 @@ 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) {
|
||||
func ResolveAgentID(configured, hostname 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))
|
||||
id := strings.TrimSpace(configured)
|
||||
if err := config.ValidateID("agent_id", id); err != nil {
|
||||
return "", fmt.Errorf("persisted agent_id invalid: %w", err)
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
if !os.IsNotExist(err) {
|
||||
return "", err
|
||||
id := strings.TrimSpace(hostname)
|
||||
if id == "" {
|
||||
return "", fmt.Errorf("hostname is empty")
|
||||
}
|
||||
id := uuid.NewString()
|
||||
if err := os.WriteFile(path, []byte(id+"\n"), 0o600); err != nil {
|
||||
if err := config.ValidateID("hostname as agent_id", id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id, nil
|
||||
|
||||
@@ -1,33 +1,17 @@
|
||||
package ids
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
import "testing"
|
||||
|
||||
func TestConfiguredWins(t *testing.T) {
|
||||
id, err := LoadOrCreateAgentID(t.TempDir(), "fixed")
|
||||
id, err := ResolveAgentID("fixed", "host")
|
||||
if err != nil || id != "fixed" {
|
||||
t.Fatalf("got %q %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateAndReuse(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
id1, err := LoadOrCreateAgentID(dir, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id2, err := LoadOrCreateAgentID(dir, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id1 != id2 {
|
||||
t.Fatalf("not stable: %q vs %q", id1, id2)
|
||||
}
|
||||
b, _ := os.ReadFile(filepath.Join(dir, "agent_id"))
|
||||
if len(b) == 0 {
|
||||
t.Fatal("agent_id not persisted")
|
||||
func TestHostnameFallback(t *testing.T) {
|
||||
id, err := ResolveAgentID("", "host-1")
|
||||
if err != nil || id != "host-1" {
|
||||
t.Fatalf("got %q %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user