BlueGit

timfa bluegit

Files

bluegit / internal / backup / client.go

client.go

client.go 7.9 KiB Download Raw
1package backup
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "sync"
11 "time"
12)
13
14// Archive is één archief zoals de backup server het meldt.
15type Archive struct {
16 Name string `json:"name"`
17 CreatedAt time.Time `json:"created_at"`
18 Size int64 `json:"size"`
19}
20
21// RemoteStatus is wat de backup server over zichzelf zegt.
22type RemoteStatus struct {
23 Version string `json:"version"`
24 ServerID string `json:"server_id"`
25 LastSync time.Time `json:"last_sync"`
26 SyncError string `json:"sync_error,omitempty"`
27 Syncs int `json:"syncs"`
28 Notifies int `json:"notifies"`
29 MirrorBytes int64 `json:"mirror_bytes"`
30 LastStats struct {
31 Files int `json:"files"`
32 Downloaded int `json:"downloaded"`
33 Bytes int64 `json:"bytes"`
34 Deleted int `json:"deleted"`
35 } `json:"last_stats"`
36 Archives int `json:"archives"`
37 LastArchive time.Time `json:"last_archive"`
38 ArchiveError string `json:"archive_error,omitempty"`
39 Rollback struct {
40 State string `json:"state"`
41 Archive string `json:"archive,omitempty"`
42 Error string `json:"error,omitempty"`
43 At time.Time `json:"at,omitempty"`
44 } `json:"rollback"`
45 Interval string `json:"archive_interval"`
46 RetentionDays int `json:"retention_days"`
47 RateLimitKiB int64 `json:"rate_limit_kib"`
48 // Sync is de voortgang van de kopie (optioneel; oudere backup servers
49 // sturen het niet, Known is dan false).
50 Sync Progress `json:"sync"`
51}
52
53// Progress is het deel van deze BlueGit dat een backup server al bij heeft.
54type Progress struct {
55 Known bool `json:"known"`
56 Percent int `json:"percent"`
57 Syncing bool `json:"syncing,omitempty"`
58 DoneBytes int64 `json:"done_bytes"`
59 TotalBytes int64 `json:"total_bytes"`
60 DoneFiles int `json:"done_files"`
61 TotalFiles int `json:"total_files"`
62 UpdatedAt time.Time `json:"updated_at,omitempty"`
63}
64
65// Client praat ondertekend met de backup servers.
66type Client struct {
67 Manager *Manager
68 HTTP *http.Client
69 Now func() time.Time
70}
71
72// RemoteError is een foutantwoord van de backup server.
73type RemoteError struct {
74 Status int
75 Msg string
76}
77
78func (e *RemoteError) Error() string { return "backup server: " + e.Msg }
79
80// Call stuurt een ondertekend verzoek naar backup server conn en geeft het
81// ruwe antwoord terug. in is nil of wordt JSON.
82func (c *Client) Call(ctx context.Context, conn Conn, method, p string, in any) (int, []byte, error) {
83 if !conn.Connected() {
84 return 0, nil, fmt.Errorf("backup server %s is niet gekoppeld", conn.Name)
85 }
86 inst, err := c.Manager.InstanceID()
87 if err != nil {
88 return 0, nil, err
89 }
90 var body []byte
91 if in != nil {
92 if body, err = json.Marshal(in); err != nil {
93 return 0, nil, err
94 }
95 }
96 req, err := http.NewRequestWithContext(ctx, method, conn.ServerURL+p, bytes.NewReader(body))
97 if err != nil {
98 return 0, nil, err
99 }
100 if in != nil {
101 req.Header.Set("Content-Type", "application/json")
102 }
103 now := time.Now
104 if c.Now != nil {
105 now = c.Now
106 }
107 Sign(req, conn.SignSecret, inst, body, now())
108 SetOwnHeaders(req.Header)
109 hc := c.HTTP
110 if hc == nil {
111 hc = &http.Client{Timeout: 15 * time.Second}
112 }
113 resp, err := hc.Do(req)
114 if err != nil {
115 return 0, nil, err
116 }
117 defer resp.Body.Close()
118 // Alleen een antwoord met protocolkop zegt iets over de backup server
119 // (een proxy-fout heeft er geen).
120 if p, ok := PeerFromHeader(resp.Header); ok {
121 c.Manager.SetPeer(conn.ID, p)
122 }
123 raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
124 return resp.StatusCode, raw, nil
125}
126
127func (c *Client) do(ctx context.Context, conn Conn, method, p string, in, out any) error {
128 code, raw, err := c.Call(ctx, conn, method, p, in)
129 if err != nil {
130 return err
131 }
132 if code >= 300 {
133 var e struct {
134 Error string `json:"error"`
135 }
136 _ = json.Unmarshal(raw, &e)
137 if e.Error == "" {
138 e.Error = http.StatusText(code)
139 }
140 return &RemoteError{Status: code, Msg: e.Error}
141 }
142 if out != nil {
143 return json.Unmarshal(raw, out)
144 }
145 return nil
146}
147
148// Archives vraagt de lijst met archieven op, nieuwste eerst.
149func (c *Client) Archives(ctx context.Context, conn Conn) ([]Archive, error) {
150 var out struct {
151 Archives []Archive `json:"archives"`
152 }
153 err := c.do(ctx, conn, http.MethodGet, "/api/v1/archives", nil, &out)
154 return out.Archives, err
155}
156
157// Status vraagt de toestand van de backup server op.
158func (c *Client) Status(ctx context.Context, conn Conn) (RemoteStatus, error) {
159 var out RemoteStatus
160 err := c.do(ctx, conn, http.MethodGet, "/api/v1/status", nil, &out)
161 return out, err
162}
163
164// RemoteField is één instelling van de backup server.
165type RemoteField struct {
166 Key string `json:"key"`
167 Label string `json:"label"`
168 Help string `json:"help"`
169 Kind string `json:"kind"`
170 Restart bool `json:"restart"`
171 Readonly bool `json:"readonly"`
172 Placeholder string `json:"placeholder"`
173 Value string `json:"value"`
174}
175
176// RemoteConfig is GET /api/v1/admin/config van de backup server.
177type RemoteConfig struct {
178 Fields []RemoteField `json:"fields"`
179 DataDir string `json:"data_dir"`
180 Restart bool `json:"restart_pending"`
181 Listening string `json:"listening,omitempty"`
182 ListenNotice string `json:"listen_notice,omitempty"`
183}
184
185// Config vraagt de instellingen van de backup server op.
186func (c *Client) Config(ctx context.Context, conn Conn) (RemoteConfig, error) {
187 var out RemoteConfig
188 err := c.do(ctx, conn, http.MethodGet, "/api/v1/admin/config", nil, &out)
189 return out, err
190}
191
192// RemoteAction is één beheeractie die de backup server aanbiedt.
193type RemoteAction struct {
194 Name string `json:"name"`
195 Method string `json:"method"`
196 Path string `json:"path"`
197 Title string `json:"title"`
198 Signed bool `json:"bluegit"`
199 Params []string `json:"params"`
200 Fields []string `json:"fields"`
201}
202
203// Actions vraagt op wat de backup server aanbiedt.
204func (c *Client) Actions(ctx context.Context, conn Conn) ([]RemoteAction, error) {
205 var out struct {
206 Actions []RemoteAction `json:"actions"`
207 }
208 err := c.do(ctx, conn, http.MethodGet, "/api/v1/admin/actions", nil, &out)
209 return out.Actions, err
210}
211
212// Rollback vraagt de backup server om archive terug te zetten. De server
213// antwoordt meteen; het terugsturen naar BlueGit gebeurt daarna.
214func (c *Client) Rollback(ctx context.Context, conn Conn, archive string) error {
215 return c.do(ctx, conn, http.MethodPost, "/api/v1/rollback", map[string]string{"archive": archive}, nil)
216}
217
218// Notify meldt dat er iets veranderd is.
219func (c *Client) Notify(ctx context.Context, conn Conn) error {
220 return c.do(ctx, conn, http.MethodPost, "/api/v1/notify", map[string]any{"at": time.Now().UTC()}, nil)
221}
222
223// Notifier bundelt wijzigingen: hoogstens één melding per Delay, aan elke
224// gekoppelde backup server, met een paar nieuwe pogingen bij een fout. De
225// backup servers halen daarnaast periodiek alles op, dus een gemiste
226// melding kost alleen vertraging.
227type Notifier struct {
228 Client *Client
229 Delay time.Duration
230 once sync.Once
231 kick chan struct{}
232}
233
234// Changed zegt dat er iets veranderd is. Blokkeert nooit.
235func (n *Notifier) Changed() {
236 if n == nil {
237 return
238 }
239 n.once.Do(func() {
240 n.kick = make(chan struct{}, 1)
241 go n.loop()
242 })
243 select {
244 case n.kick <- struct{}{}:
245 default:
246 }
247}
248
249func (n *Notifier) loop() {
250 delay := n.Delay
251 if delay <= 0 {
252 delay = 2 * time.Second
253 }
254 for range n.kick {
255 time.Sleep(delay)
256 // Wat in de tussentijd binnenkwam, zit in deze melding.
257 select {
258 case <-n.kick:
259 default:
260 }
261 list, err := n.Client.Manager.List()
262 if err != nil {
263 continue
264 }
265 var wg sync.WaitGroup
266 for _, conn := range list {
267 if !conn.Connected() {
268 continue
269 }
270 wg.Add(1)
271 go func(conn Conn) {
272 defer wg.Done()
273 for try := 0; try < 4; try++ {
274 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
275 err := n.Client.Notify(ctx, conn)
276 cancel()
277 if err == nil {
278 return
279 }
280 time.Sleep(time.Duration(1<<try) * 2 * time.Second)
281 }
282 }(conn)
283 }
284 wg.Wait()
285 }
286}