-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_registry.go
More file actions
92 lines (77 loc) · 1.86 KB
/
debug_registry.go
File metadata and controls
92 lines (77 loc) · 1.86 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//go:build forge_debug
package forge
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
)
type debugRegistryFile struct {
Servers []DebugServerEntry `json:"servers"`
}
var debugRegistryMu sync.Mutex
func debugRegistryPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".forge", "debug-servers.json"), nil
}
func debugRegisterServer(entry DebugServerEntry) error {
debugRegistryMu.Lock()
defer debugRegistryMu.Unlock()
path, err := debugRegistryPath()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
reg := debugReadRegistry(path)
// Remove stale entries for this pid or debug address.
filtered := reg.Servers[:0]
for _, s := range reg.Servers {
if s.PID != entry.PID && s.DebugAddr != entry.DebugAddr {
filtered = append(filtered, s)
}
}
entry.PID = os.Getpid()
entry.StartedAt = time.Now().Format(time.RFC3339)
reg.Servers = append(filtered, entry)
return debugWriteRegistry(path, reg)
}
func debugUnregisterServer(debugAddr string) {
debugRegistryMu.Lock()
defer debugRegistryMu.Unlock()
path, err := debugRegistryPath()
if err != nil {
return
}
reg := debugReadRegistry(path)
pid := os.Getpid()
filtered := reg.Servers[:0]
for _, s := range reg.Servers {
if s.PID != pid && s.DebugAddr != debugAddr {
filtered = append(filtered, s)
}
}
reg.Servers = filtered
_ = debugWriteRegistry(path, reg)
}
func debugReadRegistry(path string) debugRegistryFile {
data, err := os.ReadFile(path)
if err != nil {
return debugRegistryFile{}
}
var reg debugRegistryFile
_ = json.Unmarshal(data, ®)
return reg
}
func debugWriteRegistry(path string, reg debugRegistryFile) error {
data, err := json.MarshalIndent(reg, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, data, 0o644)
}