summaryrefslogtreecommitdiff
path: root/internal/control/state.go
blob: 7fc7827956274f05f619c70f86c8c53aa3cbf7b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package control

import (
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
	"sort"
	"time"
)

type NodeState struct {
	NodeID            string          `json:"node_id"`
	BootstrapStatus   string          `json:"bootstrap_status"`
	LastBootstrapAt   *time.Time      `json:"last_bootstrap_at,omitempty"`
	LastHealthCheckAt *time.Time      `json:"last_health_check_at,omitempty"`
	LastDNSSyncAt     *time.Time      `json:"last_dns_sync_at,omitempty"`
	PublicHost        string          `json:"public_host,omitempty"`
	Services          []ServiceStatus `json:"services,omitempty"`
	Metadata          map[string]any  `json:"metadata,omitempty"`
}

type ServiceStatus struct {
	Type   string `json:"type"`
	Status string `json:"status"`
	Port   int    `json:"port"`
}

func LoadNodeState(dir, nodeID string) (*NodeState, error) {
	data, err := os.ReadFile(filepath.Join(dir, nodeID+".json"))
	if err != nil {
		return nil, err
	}

	var state NodeState
	if err := json.Unmarshal(data, &state); err != nil {
		return nil, err
	}
	return &state, nil
}

func SaveNodeState(dir string, state NodeState) error {
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return err
	}

	sort.Slice(state.Services, func(i, j int) bool {
		return state.Services[i].Type < state.Services[j].Type
	})

	data, err := json.MarshalIndent(state, "", "  ")
	if err != nil {
		return err
	}
	data = append(data, '\n')

	tmpPath := filepath.Join(dir, state.NodeID+".json.tmp")
	finalPath := filepath.Join(dir, state.NodeID+".json")
	if err := os.WriteFile(tmpPath, data, 0o600); err != nil {
		return err
	}
	return os.Rename(tmpPath, finalPath)
}

func DeleteNodeState(dir, nodeID string) error {
	err := os.Remove(filepath.Join(dir, nodeID+".json"))
	if errors.Is(err, os.ErrNotExist) {
		return nil
	}
	return err
}