gunk-dev/the-valley

main.go

source68d12192bbd3main's published tip history
10.7 KiB
1// valley-telemetry serve is the collector: it answers one telemetry
2// request on its standard input, which is a connection to the collector's
3// socket that systemd accepted for it (Accept=yes), and exits.
4//
5// The only peer it serves is the git user, whose shell (valleyhook shell)
6// has derived the principal from the key sshd authenticated and passed
7// one request line for a command it parsed. The collector checks that
8// line again, and the principal's grant, and then reads only what the
9// manifest the host module generated declares: the units of each source,
10// the streams producers export, and the reports it keeps itself. Nothing
11// in a request names a file, a unit or a pattern.
12//
13// Anything running as the git user can connect to the socket and name any
14// principal; the collector cannot tell such a process from the shell. The
15// shared git account is its own trust boundary, and this is not a second
16// one inside it.
17package main
18
19import (
20 "bufio"
21 "encoding/json"
22 "errors"
23 "flag"
24 "fmt"
25 "io"
26 "net"
27 "os"
28 "os/user"
29 "path/filepath"
30 "strconv"
31 "strings"
32 "syscall"
33 "time"
34
35 "the-valley/telemetry"
36)
37
38const usage = `usage: valley-telemetry serve --manifest FILE --grants FILE --state DIR --peer-user NAME
39
40Answers one telemetry request on standard input, a connection systemd
41accepted on the collector's socket, and exits.`
42
43func main() {
44 if len(os.Args) < 2 || os.Args[1] != "serve" {
45 fmt.Fprintln(os.Stderr, usage)
46 os.Exit(2)
47 }
48 os.Exit(serve(os.Args[2:]))
49}
50
51type collector struct {
52 manifest manifest
53 grants map[string]map[string]bool
54 state string
55 out *output
56 now func() time.Time
57 systemctl func(units []string) ([]unitState, error)
58 journal func(units []string, n int, logs bool) ([]journalEntry, error)
59 horizon func(units []string) string
60}
61
62func serve(args []string) int {
63 fs := flag.NewFlagSet("serve", flag.ContinueOnError)
64 manifestPath := fs.String("manifest", "", "the source manifest")
65 grantsPath := fs.String("grants", "", "the telemetry grants")
66 state := fs.String("state", "", "the collector's own state directory")
67 peer := fs.String("peer-user", "", "the one user that may connect")
68 if err := fs.Parse(args); err != nil || *manifestPath == "" || *grantsPath == "" || *state == "" || *peer == "" {
69 fmt.Fprintln(os.Stderr, usage)
70 return 2
71 }
72 conn, err := net.FileConn(os.Stdin)
73 if err != nil {
74 fmt.Fprintf(os.Stderr, "valley-telemetry: standard input is not a connection: %v\n", err)
75 return 1
76 }
77 defer conn.Close()
78 if err := checkPeer(conn, *peer); err != nil {
79 fmt.Fprintf(os.Stderr, "valley-telemetry: %v\n", err)
80 return 1
81 }
82 c := &collector{state: *state, now: time.Now, systemctl: systemctlShow, journal: journalRead, horizon: journalHorizon}
83 c.out = newOutput(conn)
84 if c.manifest, err = readManifest(*manifestPath); err == nil {
85 c.grants, err = readGrants(*grantsPath)
86 }
87 if err != nil {
88 c.out.fail("the collector's configuration does not read: %v", err)
89 return 1
90 }
91 conn.SetReadDeadline(time.Now().Add(10 * time.Second))
92 in := bufio.NewReaderSize(conn, 8<<10)
93 return c.handle(in, conn)
94}
95
96// handle answers one request: the line the shell sent, and for a report
97// the records after it.
98func (c *collector) handle(in *bufio.Reader, conn net.Conn) int {
99 line, err := readLine(in, telemetry.MaxCommandBytes*2)
100 if err != nil {
101 c.out.fail("no request: %v", err)
102 return 1
103 }
104 req, err := telemetry.DecodeRequest(line)
105 if err == nil {
106 err = req.Check()
107 }
108 if err != nil {
109 c.out.fail("%v", err)
110 return 1
111 }
112 if !c.grants[req.Principal][req.Grant()] {
113 c.out.fail("%s does not hold the %s grant", req.Principal, req.Grant())
114 return 1
115 }
116 release, err := c.slot(req)
117 if err != nil {
118 c.out.fail("%v", err)
119 return 1
120 }
121 defer release()
122
123 c.out.send(map[string]any{
124 "kind": "header", "format": telemetry.Format, "op": req.Op, "host": c.manifest.Host,
125 "server_time": telemetry.Stamp(c.now()), "collector": telemetry.Self("valley-telemetry", ""),
126 "limits": map[string]any{"response_bytes": telemetry.MaxResponseBytes, "read_limit": req.Limit, "follow_seconds": req.Seconds},
127 })
128 switch req.Op {
129 case telemetry.OpSources:
130 c.sources(false)
131 c.out.end(nil)
132 case telemetry.OpSnapshot:
133 c.sources(true)
134 c.out.end(nil)
135 case telemetry.OpRead:
136 cur, err := c.read(req)
137 if err != nil {
138 c.out.fail("%v", err)
139 return 1
140 }
141 c.out.end(cur)
142 case telemetry.OpFollow:
143 if conn != nil {
144 conn.SetReadDeadline(time.Time{})
145 }
146 c.out.end(c.follow(req))
147 case telemetry.OpReport:
148 if conn != nil {
149 conn.SetReadDeadline(time.Now().Add(30 * time.Second))
150 }
151 if err := c.report(req.Principal, in); err != nil {
152 c.out.fail("%v", err)
153 return 1
154 }
155 }
156 if c.out.err != nil {
157 return 1
158 }
159 return 0
160}
161
162// slot takes one of the principal's slots for the request's kind, or
163// says that all are taken: telemetry.FollowSlots for a follow,
164// telemetry.ReportSlots for a report, and telemetry.BoundedSlots for any
165// other request. The pools bound each principal; the socket's
166// MaxConnections (16, nix/telemetry.nix) bounds every principal's
167// requests together, so one principal at every bound holds 9 connections
168// and leaves 7 to all others. A slot is a lock file named for the
169// principal and the kind; the lock is the open file's, so a collector
170// that dies releases it.
171func (c *collector) slot(req telemetry.Request) (func(), error) {
172 n, kind := telemetry.BoundedSlots, "bounded"
173 switch req.Op {
174 case telemetry.OpFollow:
175 n, kind = telemetry.FollowSlots, "follow"
176 case telemetry.OpReport:
177 n, kind = telemetry.ReportSlots, "report"
178 }
179 dir := filepath.Join(c.state, "slots")
180 if err := os.MkdirAll(dir, 0o700); err != nil {
181 return nil, err
182 }
183 for i := 0; i < n; i++ {
184 f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("%s.%s.%d", req.Principal, kind, i)), os.O_CREATE|os.O_RDWR, 0o600)
185 if err != nil {
186 return nil, err
187 }
188 if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil {
189 return func() { f.Close() }, nil
190 }
191 f.Close()
192 }
193 return nil, errors.New(telemetry.SlotRefusal(req.Principal, n, kind))
194}
195
196func readLine(in *bufio.Reader, max int) ([]byte, error) {
197 var line []byte
198 for {
199 chunk, more, err := in.ReadLine()
200 if err != nil {
201 return nil, err
202 }
203 line = append(line, chunk...)
204 if len(line) > max {
205 return nil, errors.New("line too long")
206 }
207 if !more {
208 return line, nil
209 }
210 }
211}
212
213// checkPeer holds the connection to the one user allowed to make it.
214func checkPeer(conn net.Conn, name string) error {
215 u, err := user.Lookup(name)
216 if err != nil {
217 return fmt.Errorf("the peer user %s: %v", name, err)
218 }
219 uc, ok := conn.(*net.UnixConn)
220 if !ok {
221 return errors.New("the connection is not a unix socket")
222 }
223 raw, err := uc.SyscallConn()
224 if err != nil {
225 return err
226 }
227 var cred *syscall.Ucred
228 var credErr error
229 if err := raw.Control(func(fd uintptr) {
230 cred, credErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
231 }); err != nil {
232 return err
233 }
234 if credErr != nil {
235 return credErr
236 }
237 if strconv.Itoa(int(cred.Uid)) != u.Uid {
238 return fmt.Errorf("uid %d may not ask the collector anything", cred.Uid)
239 }
240 return nil
241}
242
243// manifest is what the host module declares: every source the host has,
244// enabled or not.
245type manifest struct {
246 V int `json:"v"`
247 Host string `json:"host"`
248 Reporters []string `json:"reporters"`
249 Sources []source `json:"sources"`
250}
251
252type source struct {
253 Name string `json:"name"`
254 Description string `json:"description"`
255 Enabled bool `json:"enabled"`
256 Location string `json:"location"` // local or remote
257 Units []string `json:"units,omitempty"`
258 Stream string `json:"stream,omitempty"` // a stream a producer exports
259 StateFile string `json:"state,omitempty"` // the state a producer exports
260 Reporter string `json:"reporter,omitempty"` // a remote source's reporting principal
261 StaleAfter int `json:"stale_after_s,omitempty"`
262 Configured map[string]string `json:"configured,omitempty"`
263 Instruments []string `json:"instruments,omitempty"`
264 Missing []string `json:"not_instrumented,omitempty"`
265}
266
267func readManifest(path string) (manifest, error) {
268 var m manifest
269 data, err := os.ReadFile(path)
270 if err != nil {
271 return m, err
272 }
273 d := json.NewDecoder(strings.NewReader(string(data)))
274 d.DisallowUnknownFields()
275 if err := d.Decode(&m); err != nil {
276 return m, err
277 }
278 if m.V != 1 {
279 return m, fmt.Errorf("manifest version %d is not 1", m.V)
280 }
281 for _, s := range m.Sources {
282 if !telemetry.ValidSource(s.Name) || strings.HasPrefix(s.Name, "report.") {
283 return m, fmt.Errorf("%q is not a source name", s.Name)
284 }
285 }
286 return m, nil
287}
288
289// readGrants reads the telemetry grants: lines of a grant and a
290// principal, as the push grants are written.
291func readGrants(path string) (map[string]map[string]bool, error) {
292 data, err := os.ReadFile(path)
293 if err != nil {
294 return nil, err
295 }
296 g := map[string]map[string]bool{}
297 for n, line := range strings.Split(string(data), "\n") {
298 line = strings.TrimSpace(line)
299 if line == "" || strings.HasPrefix(line, "#") {
300 continue
301 }
302 f := strings.Fields(line)
303 if len(f) != 2 {
304 return nil, fmt.Errorf("%s:%d is not a grant and a principal", path, n+1)
305 }
306 if g[f[1]] == nil {
307 g[f[1]] = map[string]bool{}
308 }
309 g[f[1]][f[0]] = true
310 }
311 return g, nil
312}
313
314// output writes response lines, and stops at MaxResponseBytes or at the
315// first write that fails or takes more than writeDeadline.
316type output struct {
317 w io.Writer
318 conn net.Conn
319 bytes int
320 truncated bool
321 err error
322}
323
324const writeDeadline = 10 * time.Second
325
326func newOutput(conn net.Conn) *output { return &output{w: conn, conn: conn} }
327
328// send writes one line, and reports whether the response has room for
329// more.
330func (o *output) send(v any) bool {
331 if o.err != nil || o.truncated {
332 return false
333 }
334 line, err := json.Marshal(v)
335 if err != nil {
336 o.err = err
337 return false
338 }
339 if o.bytes+len(line) > telemetry.MaxResponseBytes-1024 {
340 o.truncated = true
341 return false
342 }
343 if o.conn != nil {
344 o.conn.SetWriteDeadline(time.Now().Add(writeDeadline))
345 }
346 n, err := o.w.Write(append(line, '\n'))
347 o.bytes += n
348 if err != nil {
349 o.err = err
350 return false
351 }
352 return true
353}
354
355func (o *output) fail(format string, args ...any) {
356 o.truncated = false
357 o.send(map[string]any{"kind": "error", "error": fmt.Sprintf(format, args...)})
358}
359
360// end is the last line of a response that ended as it should: where a
361// reader resumes from, and whether the response was cut short.
362func (o *output) end(cur telemetry.Cursor) {
363 t := o.truncated
364 o.truncated = false
365 line := map[string]any{"kind": "end", "truncated": t, "bytes": o.bytes}
366 if cur != nil {
367 line["cursor"] = cur.String()
368 }
369 o.send(line)
370}