gunk-dev/the-valley

main.go

sourceebf24df4d772main's published tip history
10.4 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// slots: how many requests of one kind one principal may have open at
163// once. The socket's own MaxConnections bounds them all together.
164const (
165 observeSlots = 4
166 reportSlots = 1
167)
168
169// slot takes one of the principal's slots for the request's kind, or
170// says that all are taken. A slot is a lock file; the lock is the open
171// file's, so a collector that dies releases it.
172func (c *collector) slot(req telemetry.Request) (func(), error) {
173 n, kind := observeSlots, "observe"
174 if req.Op == telemetry.OpReport {
175 n, kind = reportSlots, "report"
176 }
177 dir := filepath.Join(c.state, "slots")
178 if err := os.MkdirAll(dir, 0o700); err != nil {
179 return nil, err
180 }
181 for i := 0; i < n; i++ {
182 f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("%s.%s.%d", req.Principal, kind, i)), os.O_CREATE|os.O_RDWR, 0o600)
183 if err != nil {
184 return nil, err
185 }
186 if syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil {
187 return func() { f.Close() }, nil
188 }
189 f.Close()
190 }
191 return nil, fmt.Errorf("%s already has %d %s requests open; try again when one ends", req.Principal, n, kind)
192}
193
194func readLine(in *bufio.Reader, max int) ([]byte, error) {
195 var line []byte
196 for {
197 chunk, more, err := in.ReadLine()
198 if err != nil {
199 return nil, err
200 }
201 line = append(line, chunk...)
202 if len(line) > max {
203 return nil, errors.New("line too long")
204 }
205 if !more {
206 return line, nil
207 }
208 }
209}
210
211// checkPeer holds the connection to the one user allowed to make it.
212func checkPeer(conn net.Conn, name string) error {
213 u, err := user.Lookup(name)
214 if err != nil {
215 return fmt.Errorf("the peer user %s: %v", name, err)
216 }
217 uc, ok := conn.(*net.UnixConn)
218 if !ok {
219 return errors.New("the connection is not a unix socket")
220 }
221 raw, err := uc.SyscallConn()
222 if err != nil {
223 return err
224 }
225 var cred *syscall.Ucred
226 var credErr error
227 if err := raw.Control(func(fd uintptr) {
228 cred, credErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
229 }); err != nil {
230 return err
231 }
232 if credErr != nil {
233 return credErr
234 }
235 if strconv.Itoa(int(cred.Uid)) != u.Uid {
236 return fmt.Errorf("uid %d may not ask the collector anything", cred.Uid)
237 }
238 return nil
239}
240
241// manifest is what the host module declares: every source the host has,
242// enabled or not.
243type manifest struct {
244 V int `json:"v"`
245 Host string `json:"host"`
246 Reporters []string `json:"reporters"`
247 Sources []source `json:"sources"`
248}
249
250type source struct {
251 Name string `json:"name"`
252 Description string `json:"description"`
253 Enabled bool `json:"enabled"`
254 Location string `json:"location"` // local or remote
255 Units []string `json:"units,omitempty"`
256 Stream string `json:"stream,omitempty"` // a stream a producer exports
257 StateFile string `json:"state,omitempty"` // the state a producer exports
258 Reporter string `json:"reporter,omitempty"` // a remote source's reporting principal
259 StaleAfter int `json:"stale_after_s,omitempty"`
260 Configured map[string]string `json:"configured,omitempty"`
261 Instruments []string `json:"instruments,omitempty"`
262 Missing []string `json:"not_instrumented,omitempty"`
263}
264
265func readManifest(path string) (manifest, error) {
266 var m manifest
267 data, err := os.ReadFile(path)
268 if err != nil {
269 return m, err
270 }
271 d := json.NewDecoder(strings.NewReader(string(data)))
272 d.DisallowUnknownFields()
273 if err := d.Decode(&m); err != nil {
274 return m, err
275 }
276 if m.V != 1 {
277 return m, fmt.Errorf("manifest version %d is not 1", m.V)
278 }
279 for _, s := range m.Sources {
280 if !telemetry.ValidSource(s.Name) || strings.HasPrefix(s.Name, "report.") {
281 return m, fmt.Errorf("%q is not a source name", s.Name)
282 }
283 }
284 return m, nil
285}
286
287// readGrants reads the telemetry grants: lines of a grant and a
288// principal, as the push grants are written.
289func readGrants(path string) (map[string]map[string]bool, error) {
290 data, err := os.ReadFile(path)
291 if err != nil {
292 return nil, err
293 }
294 g := map[string]map[string]bool{}
295 for n, line := range strings.Split(string(data), "\n") {
296 line = strings.TrimSpace(line)
297 if line == "" || strings.HasPrefix(line, "#") {
298 continue
299 }
300 f := strings.Fields(line)
301 if len(f) != 2 {
302 return nil, fmt.Errorf("%s:%d is not a grant and a principal", path, n+1)
303 }
304 if g[f[1]] == nil {
305 g[f[1]] = map[string]bool{}
306 }
307 g[f[1]][f[0]] = true
308 }
309 return g, nil
310}
311
312// output writes response lines, and stops at MaxResponseBytes or at the
313// first write that fails or takes more than writeDeadline.
314type output struct {
315 w io.Writer
316 conn net.Conn
317 bytes int
318 truncated bool
319 err error
320}
321
322const writeDeadline = 10 * time.Second
323
324func newOutput(conn net.Conn) *output { return &output{w: conn, conn: conn} }
325
326// send writes one line, and reports whether the response has room for
327// more.
328func (o *output) send(v any) bool {
329 if o.err != nil || o.truncated {
330 return false
331 }
332 line, err := json.Marshal(v)
333 if err != nil {
334 o.err = err
335 return false
336 }
337 if o.bytes+len(line) > telemetry.MaxResponseBytes-1024 {
338 o.truncated = true
339 return false
340 }
341 if o.conn != nil {
342 o.conn.SetWriteDeadline(time.Now().Add(writeDeadline))
343 }
344 n, err := o.w.Write(append(line, '\n'))
345 o.bytes += n
346 if err != nil {
347 o.err = err
348 return false
349 }
350 return true
351}
352
353func (o *output) fail(format string, args ...any) {
354 o.truncated = false
355 o.send(map[string]any{"kind": "error", "error": fmt.Sprintf(format, args...)})
356}
357
358// end is the last line of a response that ended as it should: where a
359// reader resumes from, and whether the response was cut short.
360func (o *output) end(cur telemetry.Cursor) {
361 t := o.truncated
362 o.truncated = false
363 line := map[string]any{"kind": "end", "truncated": t, "bytes": o.bytes}
364 if cur != nil {
365 line["cursor"] = cur.String()
366 }
367 o.send(line)
368}