BlueGit

timfa bluegit

Files

bluegit / internal / server / selfupdate.go

selfupdate.go

selfupdate.go 5.9 KiB Download Raw
1package server
2
3import (
4 "context"
5 "encoding/json"
6 "io"
7 "net"
8 "net/http"
9 "strings"
10 "sync"
11 "time"
12
13 "gitlab.com/Timfa/bluegit/internal/i18n"
14 "gitlab.com/Timfa/bluegit/internal/update"
15)
16
17const (
18 updateLimit = 5
19 updateWindow = time.Minute
20 updateRunning = 30 * time.Minute
21)
22
23// UpdateView is de laatste self-update op de Info- en setup-pagina.
24type UpdateView struct {
25 When, SHA, Result, ResultLabel, Error string
26 Has bool
27}
28
29// UpdateStarter start de unit. Tests zetten een stub. Nil gebruikt systemctl.
30type UpdateStarter func(ctx context.Context, ref string) error
31
32type updateLimiter struct {
33 mu sync.Mutex
34 at map[string][]time.Time
35}
36
37func (l *updateLimiter) allow(ip string, now time.Time) bool {
38 l.mu.Lock()
39 defer l.mu.Unlock()
40 if l.at == nil {
41 l.at = map[string][]time.Time{}
42 }
43 cut := now.Add(-updateWindow)
44 keep := l.at[ip][:0]
45 for _, ts := range l.at[ip] {
46 if ts.After(cut) {
47 keep = append(keep, ts)
48 }
49 }
50 if len(keep) >= updateLimit {
51 l.at[ip] = keep
52 return false
53 }
54 l.at[ip] = append(keep, now)
55 return true
56}
57
58func (s *Server) selfUpdate(w http.ResponseWriter, r *http.Request) {
59 if !update.Enabled() {
60 http.NotFound(w, r)
61 return
62 }
63 if !s.updateHits.allow(clientIP(r), time.Now()) {
64 http.Error(w, "too many requests\n", http.StatusTooManyRequests)
65 return
66 }
67 if !update.Equal(update.Token(), bearer(r)) {
68 http.Error(w, "unauthorized\n", http.StatusUnauthorized)
69 return
70 }
71 raw, _ := io.ReadAll(io.LimitReader(r.Body, 4096))
72 var flags struct {
73 Force bool `json:"force"`
74 }
75 _ = json.Unmarshal(raw, &flags)
76 r.Body = io.NopCloser(strings.NewReader(string(raw)))
77 ref, err := updateRef(r)
78 if err != nil {
79 http.Error(w, "bad request\n", http.StatusBadRequest)
80 return
81 }
82 if !update.ValidRef(ref) {
83 http.Error(w, "bad request\n", http.StatusBadRequest)
84 return
85 }
86 st, _ := update.ReadStatus(s.StateDir)
87 if pending, _ := s.UpdateGate(); pending || update.FreshRunning(st, time.Now(), updateRunning) {
88 if flags.Force {
89 _ = s.setUpdateForce(true)
90 w.Header().Set("Content-Type", "application/json; charset=utf-8")
91 w.WriteHeader(http.StatusAccepted)
92 _ = json.NewEncoder(w).Encode(map[string]string{"status": "forced", "ref": st.SHA})
93 return
94 }
95 http.Error(w, "update already running\n", http.StatusConflict)
96 return
97 }
98 force := flags.Force
99 if err := update.WriteRequest(s.StateDir, ref); err != nil {
100 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
101 return
102 }
103 _ = s.setUpdateForce(force)
104 _ = update.WriteStatus(s.StateDir, update.Status{
105 Time: time.Now().UTC().Format(time.RFC3339), SHA: ref, Result: update.ResultWaiting,
106 })
107 start := s.UpdateStarter
108 if start == nil {
109 start = func(ctx context.Context, _ string) error { return update.StartSystemd(ctx) }
110 }
111 if err := start(r.Context(), ref); err != nil {
112 _ = update.WriteStatus(s.StateDir, update.Status{
113 Time: time.Now().UTC().Format(time.RFC3339), SHA: ref, Result: "failed", Error: "start",
114 })
115 http.Error(w, "start failed\n", http.StatusBadGateway)
116 return
117 }
118 if s.Log != nil {
119 s.Log.Info("self-update gestart", "ref", ref)
120 }
121 w.Header().Set("Content-Type", "application/json; charset=utf-8")
122 w.WriteHeader(http.StatusAccepted)
123 _ = json.NewEncoder(w).Encode(map[string]string{"status": "accepted", "ref": ref})
124}
125
126func (s *Server) selfUpdateStatus(w http.ResponseWriter, r *http.Request) {
127 if !update.Enabled() {
128 http.NotFound(w, r)
129 return
130 }
131 if !update.Equal(update.Token(), bearer(r)) {
132 http.Error(w, "unauthorized\n", http.StatusUnauthorized)
133 return
134 }
135 running := 0
136 if s.Store != nil {
137 n, err := s.Store.CountRunningJobs(r.Context())
138 if err != nil {
139 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
140 return
141 }
142 running = n
143 }
144 st, err := update.ReadStatus(s.StateDir)
145 if err != nil {
146 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
147 return
148 }
149 logText, err := update.ReadLogTail(s.StateDir, update.LogTailLines)
150 if err != nil {
151 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
152 return
153 }
154 w.Header().Set("Content-Type", "application/json; charset=utf-8")
155 w.Header().Set("Cache-Control", "no-store")
156 var upd any
157 if st.Result != "" {
158 upd = st
159 }
160 body := map[string]any{
161 "running": running,
162 "status": st.Result,
163 "sha": st.SHA,
164 "started_at": st.Time,
165 "result": st.Result,
166 "log": logText,
167 "update": upd,
168 // force: de updater wacht niet langer op lopende jobs.
169 "force": s.updateForced(),
170 "waiting_pipelines": s.countHeld(r.Context()),
171 "max_wait_seconds": int(s.updateMaxWait().Seconds()),
172 }
173 if st.Error != "" {
174 body["error"] = st.Error
175 }
176 _ = json.NewEncoder(w).Encode(body)
177}
178
179func updateRef(r *http.Request) (string, error) {
180 raw, err := io.ReadAll(io.LimitReader(r.Body, 4096))
181 if err != nil {
182 return "", err
183 }
184 if strings.TrimSpace(string(raw)) == "" {
185 return "", nil
186 }
187 var body struct {
188 Ref string `json:"ref"`
189 SHA string `json:"sha"`
190 Force bool `json:"force"`
191 }
192 if err := json.Unmarshal(raw, &body); err != nil {
193 return "", err
194 }
195 ref := strings.TrimSpace(body.Ref)
196 sha := strings.TrimSpace(body.SHA)
197 if ref != "" && sha != "" && ref != sha {
198 return "", errMismatch
199 }
200 if ref == "" {
201 ref = sha
202 }
203 return ref, nil
204}
205
206var errMismatch = errString("ref")
207
208type errString string
209
210func (e errString) Error() string { return string(e) }
211
212func clientIP(r *http.Request) string {
213 host, _, err := net.SplitHostPort(r.RemoteAddr)
214 if err != nil {
215 return r.RemoteAddr
216 }
217 return host
218}
219
220func (s *Server) attachUpdate(v *View, lang i18n.Lang) {
221 if v.User == nil || !v.User.InstanceAdmin {
222 return
223 }
224 v.ShowUpdate = true
225 st, err := update.ReadStatus(s.StateDir)
226 if err != nil || st.Result == "" {
227 return
228 }
229 label := i18n.T(lang, "update.result."+st.Result)
230 if label == "update.result."+st.Result {
231 label = st.Result
232 }
233 v.Update = &UpdateView{
234 When: st.Time, SHA: st.SHA, Result: st.Result, ResultLabel: label, Error: st.Error, Has: true,
235 }
236}