gunk-dev/the-valley

sources.go

source78684ec35c8emain's published tip history
13.2 KiB
1package main
2
3import (
4 "bufio"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "slices"
12 "strconv"
13 "strings"
14 "syscall"
15 "time"
16
17 "the-valley/telemetry"
18)
19
20// unitProperties are the properties read of every unit, and no others: an
21// unrestricted show would print the unit's environment, which can carry a
22// credential.
23var unitProperties = []string{
24 "Id", "LoadState", "ActiveState", "SubState", "Result", "UnitFileState",
25 "ExecMainStatus", "ExecMainCode", "ExecMainStartTimestamp", "ExecMainExitTimestamp",
26 "StateChangeTimestamp", "NRestarts", "MemoryCurrent", "MemoryPeak", "CPUUsageNSec",
27 "InvocationID", "LastTriggerUSec", "NextElapseUSecRealtime",
28}
29
30type unitState map[string]string
31
32const commandDeadline = 5 * time.Second
33
34func systemctlShow(units []string) ([]unitState, error) {
35 if len(units) == 0 {
36 return nil, nil
37 }
38 ctx, cancel := context.WithTimeout(context.Background(), commandDeadline)
39 defer cancel()
40 args := append([]string{"show", "--property=" + strings.Join(unitProperties, ","), "--"}, units...)
41 out, err := exec.CommandContext(ctx, "systemctl", args...).Output()
42 if err != nil {
43 return nil, fmt.Errorf("systemctl show: %v", err)
44 }
45 var states []unitState
46 for _, block := range strings.Split(strings.TrimSpace(string(out)), "\n\n") {
47 s := unitState{}
48 for _, line := range strings.Split(block, "\n") {
49 if k, v, ok := strings.Cut(line, "="); ok {
50 s[k] = v
51 }
52 }
53 states = append(states, s)
54 }
55 if len(states) != len(units) {
56 return nil, fmt.Errorf("systemctl show answered for %d of %d units", len(states), len(units))
57 }
58 return states, nil
59}
60
61// journalEntry is one journal entry of a source's units. An entry systemd
62// itself wrote (PID 1) is lifecycle: a start, an exit and its status, a
63// kill. Every other entry is what the unit's own processes printed, which
64// is untrusted text.
65type journalEntry struct {
66 Time string `json:"time"`
67 Unit string `json:"unit"`
68 Lifecycle bool `json:"-"`
69 Message string `json:"message"`
70 Cursor string `json:"-"`
71}
72
73func journalArgs(units []string) []string {
74 var args []string
75 for _, u := range units {
76 args = append(args, "--unit="+u)
77 }
78 return args
79}
80
81func journalRead(units []string, n int, logs bool) ([]journalEntry, error) {
82 ctx, cancel := context.WithTimeout(context.Background(), commandDeadline)
83 defer cancel()
84 args := append([]string{"--no-pager", "--quiet", "--output=json", "--lines=" + strconv.Itoa(n),
85 "--output-fields=MESSAGE,_PID,UNIT,_SYSTEMD_UNIT"}, journalArgs(units)...)
86 if !logs {
87 args = append(args, "_PID=1")
88 }
89 out, err := exec.CommandContext(ctx, "journalctl", args...).Output()
90 if err != nil {
91 return nil, fmt.Errorf("journalctl: %v", err)
92 }
93 var entries []journalEntry
94 sc := bufio.NewScanner(strings.NewReader(string(out)))
95 sc.Buffer(make([]byte, 64<<10), 1<<20)
96 for sc.Scan() {
97 var raw map[string]any
98 if json.Unmarshal(sc.Bytes(), &raw) != nil {
99 continue
100 }
101 e := journalEntry{Lifecycle: raw["_PID"] == "1", Message: journalText(raw["MESSAGE"])}
102 e.Unit, _ = raw["UNIT"].(string)
103 if e.Unit == "" {
104 e.Unit, _ = raw["_SYSTEMD_UNIT"].(string)
105 }
106 if us, ok := raw["__REALTIME_TIMESTAMP"].(string); ok {
107 if n, err := strconv.ParseInt(us, 10, 64); err == nil {
108 e.Time = telemetry.Stamp(time.UnixMicro(n))
109 }
110 }
111 e.Cursor, _ = raw["__CURSOR"].(string)
112 entries = append(entries, e)
113 }
114 return entries, nil
115}
116
117// journalText is a journal field's text: a string, or the bytes journalctl
118// writes as an array when the field is not UTF-8. It is cut to 2 KiB and
119// made safe to show.
120func journalText(v any) string {
121 var s string
122 switch v := v.(type) {
123 case string:
124 s = v
125 case []any:
126 b := make([]byte, 0, len(v))
127 for _, x := range v {
128 if f, ok := x.(float64); ok {
129 b = append(b, byte(f))
130 }
131 }
132 s = string(b)
133 }
134 if len(s) > 2048 {
135 s = s[:2048] + "…"
136 }
137 return telemetry.Sanitize(s)
138}
139
140// journalHorizon is the time of the oldest journal entry the host still
141// holds for the units: how far back their lifecycle and logs reach. The
142// host's journal settings decide it, not the collector.
143func journalHorizon(units []string) string {
144 ctx, cancel := context.WithTimeout(context.Background(), commandDeadline)
145 defer cancel()
146 cmd := exec.CommandContext(ctx, "journalctl", append([]string{"--no-pager", "--quiet", "--output=json", "--output-fields=_PID"}, journalArgs(units)...)...)
147 out, err := cmd.StdoutPipe()
148 if err != nil || cmd.Start() != nil {
149 return ""
150 }
151 defer func() { cancel(); cmd.Wait() }()
152 line, err := bufio.NewReader(out).ReadBytes('\n')
153 if err != nil {
154 return ""
155 }
156 var raw map[string]any
157 if json.Unmarshal(line, &raw) != nil {
158 return ""
159 }
160 us, _ := raw["__REALTIME_TIMESTAMP"].(string)
161 n, err := strconv.ParseInt(us, 10, 64)
162 if err != nil {
163 return ""
164 }
165 return telemetry.Stamp(time.UnixMicro(n))
166}
167
168// streams are every stream the collector reads, by name: each source's
169// exported stream, and each reporter's reports.
170func (c *collector) streams() map[string]*telemetry.Stream {
171 out := map[string]*telemetry.Stream{}
172 for _, s := range c.manifest.Sources {
173 if s.Stream != "" && s.Enabled {
174 out[s.Name] = &telemetry.Stream{Dir: s.Stream}
175 }
176 }
177 for _, p := range c.manifest.Reporters {
178 if telemetry.ValidPrincipal(p) {
179 out["report."+p] = c.reportStream(p)
180 }
181 }
182 return out
183}
184
185func (c *collector) reportStream(principal string) *telemetry.Stream {
186 return &telemetry.Stream{Dir: c.state + "/reports/" + principal, SegmentBytes: 512 << 10, Segments: 8}
187}
188
189// streamOf is the stream a source reads from: its own, or for a remote
190// source, its reporter's reports.
191func (c *collector) streamOf(s source) string {
192 if s.Stream != "" {
193 return s.Name
194 }
195 if s.Reporter != "" {
196 return "report." + s.Reporter
197 }
198 return ""
199}
200
201// runSummary is one run, as a stream's recent records tell it.
202type runSummary struct {
203 Run string `json:"run"`
204 Producer string `json:"producer,omitempty"`
205 First string `json:"first"`
206 Last string `json:"last"`
207 LastType string `json:"last_type"`
208 Open bool `json:"open"`
209 Project string `json:"project,omitempty"`
210 Change string `json:"change,omitempty"`
211 Version int `json:"version,omitempty"`
212 Head string `json:"head,omitempty"`
213 Tree string `json:"tree,omitempty"`
214 Checks map[string]string `json:"checks,omitempty"`
215 Received string `json:"received,omitempty"`
216}
217
218// ends are the record types that end a run.
219var ends = map[string]bool{"pass.end": true, "run.end": true, "approve.end": true, "decision": true}
220
221// runs summarises the runs among a stream's newest records, newest first.
222func runs(recs []telemetry.Record) []*runSummary {
223 byRun := map[string]*runSummary{}
224 var order []*runSummary
225 for _, r := range recs {
226 if r.Run == "" {
227 continue
228 }
229 s := byRun[r.Run]
230 if s == nil {
231 s = &runSummary{Run: r.Run, First: r.Time, Open: true, Checks: map[string]string{}}
232 if r.Producer != nil {
233 s.Producer = r.Producer.Name
234 }
235 byRun[r.Run] = s
236 order = append(order, s)
237 }
238 s.Last, s.LastType, s.Received = r.Time, r.Type, r.Received
239 for _, f := range []struct {
240 to *string
241 from string
242 }{{&s.Project, r.Project}, {&s.Change, r.Change}, {&s.Head, r.Head}, {&s.Tree, r.Tree}} {
243 if f.from != "" {
244 *f.to = f.from
245 }
246 }
247 if r.Version != 0 {
248 s.Version = r.Version
249 }
250 if r.Check != "" {
251 switch r.Type {
252 case "check.queued":
253 s.Checks[r.Check] = "queued"
254 case "check.build-start", "check.start":
255 s.Checks[r.Check] = "running"
256 case "check.build-end":
257 s.Checks[r.Check] = "built"
258 case "check.result":
259 res, _ := r.Data["result"].(string)
260 s.Checks[r.Check] = res
261 }
262 }
263 if ends[r.Type] {
264 s.Open = false
265 }
266 }
267 slices.Reverse(order)
268 return order
269}
270
271// sources writes one line per source: its units' states, its stream's
272// range and latest runs, and how far its journal reaches. With snapshot,
273// each source's exported state and open runs come with it.
274func (c *collector) sources(snapshot bool) {
275 streams := c.streams()
276 for _, s := range c.manifest.Sources {
277 line := map[string]any{"kind": "source", "name": s.Name, "description": s.Description,
278 "enabled": s.Enabled, "location": s.Location}
279 for k, v := range map[string]any{"units": s.Units, "configured": s.Configured, "instruments": s.Instruments, "not_instrumented": s.Missing, "reporter": s.Reporter} {
280 if v != nil && v != "" {
281 line[k] = v
282 }
283 }
284 state, detail := c.sourceState(s, streams, line, snapshot)
285 line["state"], line["detail"] = state, detail
286 if !c.out.send(line) {
287 return
288 }
289 }
290 for _, p := range c.manifest.Reporters {
291 name := "report." + p
292 line := map[string]any{"kind": "source", "name": name, "description": "reports from " + p,
293 "enabled": true, "location": "client", "reporter": p}
294 state, detail := c.streamState(name, streams[name], nil, line, snapshot, 0)
295 line["state"], line["detail"] = state, detail
296 if !c.out.send(line) {
297 return
298 }
299 }
300}
301
302// sourceState decides a source's state: disabled, unavailable, failed,
303// stale, active or idle, and says why.
304func (c *collector) sourceState(s source, streams map[string]*telemetry.Stream, line map[string]any, snapshot bool) (string, string) {
305 if !s.Enabled {
306 return "disabled", "not enabled in this host's configuration"
307 }
308 var units []unitState
309 var unitErr error
310 if len(s.Units) > 0 {
311 units, unitErr = c.systemctl(s.Units)
312 line["unit_states"] = units
313 if h := c.horizon(s.Units); h != "" {
314 line["journal_since"] = h
315 }
316 }
317 if s.StateFile != "" && snapshot {
318 if data, err := readBounded(s.StateFile, 256<<10); err != nil {
319 line["exported_state_error"] = err.Error()
320 } else if json.Valid(data) {
321 line["exported_state"] = json.RawMessage(data)
322 }
323 }
324 running := false
325 for _, u := range units {
326 if strings.HasSuffix(u["Id"], ".service") && (u["ActiveState"] == "active" || u["ActiveState"] == "activating" || u["ActiveState"] == "deactivating" || u["ActiveState"] == "reloading") {
327 running = true
328 }
329 }
330 name := c.streamOf(s)
331 state, detail := "idle", "nothing is running"
332 if name != "" {
333 state, detail = c.streamState(name, streams[name], &running, line, snapshot, s.StaleAfter)
334 }
335 switch {
336 case unitErr != nil:
337 return "unavailable", unitErr.Error()
338 case s.Reporter != "" && line["stream"] == nil:
339 return "unavailable", fmt.Sprintf("%s has reported nothing: this host has no observation of the source", s.Reporter)
340 case state == "unavailable" || state == "stale":
341 return state, detail
342 }
343 for _, u := range units {
344 if u["LoadState"] != "loaded" {
345 return "unavailable", fmt.Sprintf("%s is %s", u["Id"], u["LoadState"])
346 }
347 if u["ActiveState"] == "failed" || (u["Result"] != "" && u["Result"] != "success") {
348 return "failed", fmt.Sprintf("%s: %s, result %s, status %s", u["Id"], u["ActiveState"], u["Result"], u["ExecMainStatus"])
349 }
350 }
351 if running {
352 return "active", "a unit is running"
353 }
354 return state, detail
355}
356
357// streamState reads a stream's range and recent runs into line. running,
358// when the source has units, says whether one of its services is running:
359// a run the stream holds open while none is was interrupted, since a
360// killed process records no end of its own.
361func (c *collector) streamState(name string, st *telemetry.Stream, running *bool, line map[string]any, snapshot bool, staleAfter int) (string, string) {
362 if st == nil {
363 return "unavailable", "the stream is not configured"
364 }
365 rng, err := st.Range()
366 if os.IsNotExist(err) {
367 return "idle", "no record has been stored yet"
368 }
369 if err != nil {
370 return "unavailable", err.Error()
371 }
372 recs, _, err := st.Read(max(rng.Last-2000, 0), 2000, 2<<20)
373 if err != nil {
374 return "unavailable", err.Error()
375 }
376 info := map[string]any{"name": name, "epoch": rng.Epoch, "first": rng.First, "last": rng.Last}
377 if len(recs) > 0 {
378 last := recs[len(recs)-1]
379 info["last_time"], info["last_type"] = last.Time, last.Type
380 if last.Received != "" {
381 info["last_received"] = last.Received
382 }
383 }
384 line["stream"] = info
385 rs := runs(recs)
386 var open []*runSummary
387 for _, r := range rs {
388 if r.Open {
389 open = append(open, r)
390 }
391 }
392 if snapshot {
393 line["open_runs"] = open
394 if len(rs) > 0 {
395 line["latest_runs"] = rs[:min(len(rs), 5)]
396 }
397 }
398 if staleAfter > 0 && len(recs) > 0 {
399 last := recs[len(recs)-1]
400 at := last.Received
401 if at == "" {
402 at = last.Time
403 }
404 if t, err := time.Parse(time.RFC3339, at); err == nil && c.now().Sub(t) > time.Duration(staleAfter)*time.Second {
405 return "stale", fmt.Sprintf("nothing received since %s", at)
406 }
407 }
408 if len(open) > 0 {
409 if running != nil && !*running {
410 // Only a run the unit's own producer holds open says the
411 // unit was interrupted: the newest open run.
412 return "stale", fmt.Sprintf("run %s recorded no end and no unit of the source is running: it was interrupted", open[0].Run)
413 }
414 return "active", fmt.Sprintf("%d open runs", len(open))
415 }
416 return "idle", "no open run"
417}
418
419func readBounded(path string, max int64) ([]byte, error) {
420 f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
421 if err != nil {
422 return nil, err
423 }
424 defer f.Close()
425 buf, err := io.ReadAll(io.LimitReader(f, max+1))
426 if err != nil {
427 return nil, err
428 }
429 if int64(len(buf)) > max {
430 return nil, fmt.Errorf("%s is larger than %d bytes", path, max)
431 }
432 return buf, nil
433}