gunk-dev/the-valley

main.go

sourcef83d9986905amain's published tip history
10.9 KiB
1// Command valley-web-receive is the web export receiver. It takes the
2// publisher's uploads into a state directory, by the protocol package
3// export defines, and valley-web serves what it activates.
4//
5// valley-web-receive --state DIR --listen ADDR --instance NAME
6// --destination NAME --verifiers FILE --token-file FILE
7// [--max-body SIZE] [--max-upload SIZE]
8// [--max-storage SIZE]
9//
10// It opens the state directory with export.OpenStore, which creates its
11// layout and finishes an activation a crash interrupted, and it is the
12// directory's one writer. valley-web runs beside it as a process of its
13// own, as another user, and opens the same directory with
14// export.OpenReadOnly. The two share nothing but the directory: each has
15// its own listener, its own limits and its own memory, so a saturated
16// upload leaves valley-web serving.
17//
18// Every request must carry the token in --token-file. A request without
19// it is refused as unauthenticated before anything else of it is read,
20// and takes none of the receiver's request slots. The receiver serves
21// until it is sent SIGINT or SIGTERM. It logs to standard error, and
22// prints the address it listens on once it does.
23package main
24
25import (
26 "context"
27 "errors"
28 "flag"
29 "fmt"
30 "io"
31 "log"
32 "math"
33 "net"
34 "net/http"
35 "os"
36 "os/signal"
37 "strconv"
38 "strings"
39 "sync"
40 "syscall"
41 "time"
42
43 "the-valley/note"
44 "the-valley/web/export"
45)
46
47const usage = `usage: valley-web-receive --state DIR --listen ADDR --instance NAME
48 --destination NAME --verifiers FILE --token-file FILE
49 [--max-body SIZE] [--max-upload SIZE]
50 [--max-storage SIZE]
51
52Receive web export uploads from valley-web-publish into a state directory
53that valley-web serves.
54
55 --state DIR state directory (created if missing); the receiver
56 is its only writer
57 --listen ADDR TCP address to listen on, such as 127.0.0.1:8081;
58 port 0 picks a free port
59 --instance NAME instance name required in every manifest
60 --destination NAME destination name required in every manifest (this
61 receiver's name)
62 --verifiers FILE file of publisher verifier lines, one per line, as
63 written to <state>/verifier; every manifest must
64 verify under one of them
65 --token-file FILE file holding the bearer token required in every
66 request's Authorization header: one line of 32 to
67 256 visible ASCII characters, matching the file
68 passed to the publisher's --receiver-token
69 --max-body SIZE maximum declared byte size of a single body
70 (default 1G)
71 --max-upload SIZE maximum total declared byte size of the unique
72 bodies in one manifest, each SHA-256 counted once
73 (default 2G)
74 --max-storage SIZE best-effort cap on the disk space used by the state
75 directory, including held generations, staged
76 bodies, and built repositories (default 8G)
77
78A SIZE is a positive byte count, optionally suffixed with K, M, G, or T
79for KiB, MiB, GiB, or TiB.
80
81valley-web-receive prints "valley-web-receive: listening on ADDR" once it
82listens, and stops on SIGINT or SIGTERM.
83`
84
85// How many requests and connections the receiver takes at once. An
86// authenticated request past maxRequests is answered 503 with no refusal,
87// which the publisher retries after a pause. A connection past maxConns
88// waits in the listen queue until another closes.
89const (
90 maxRequests = 4
91 maxConns = 32
92)
93
94// How long a request may take, from when its headers have been read. A
95// commit fetches and checks every bundle it was sent. A stop gives the
96// requests in flight stopTimeout to finish, and then ends them and waits
97// drainTimeout more for them, and the git they run, to stop.
98const (
99 headerTimeout = 10 * time.Second
100 shortTimeout = 10 * time.Second
101 manifestTimeout = time.Minute
102 bodyTimeout = 30 * time.Minute
103 commitTimeout = 30 * time.Minute
104 idleTimeout = time.Minute
105 stopTimeout = 10 * time.Second
106 drainTimeout = 5 * time.Second
107)
108
109func main() {
110 ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
111 defer stop()
112 err := run(ctx, os.Args[1:], os.Stderr)
113 var bad usageError
114 switch {
115 case errors.As(err, &bad):
116 fmt.Fprintf(os.Stderr, "valley-web-receive: %v\n\n%s", err, usage)
117 os.Exit(2)
118 case err != nil:
119 fmt.Fprintf(os.Stderr, "valley-web-receive: %v\n", err)
120 os.Exit(1)
121 }
122}
123
124// usageError is a command line valley-web-receive cannot run with.
125type usageError struct{ error }
126
127// run receives until ctx is done, then shuts the server down, letting
128// requests in flight finish for a few seconds. It then ends the requests
129// still running, and waits a few seconds more for them and the git they
130// run to stop. A commit stopped part way leaves the active export as it
131// was, as a crash does.
132func run(ctx context.Context, args []string, stderr io.Writer) error {
133 flags := flag.NewFlagSet("valley-web-receive", flag.ContinueOnError)
134 flags.SetOutput(io.Discard)
135 state := flags.String("state", "", "")
136 listen := flags.String("listen", "", "")
137 instance := flags.String("instance", "", "")
138 destination := flags.String("destination", "", "")
139 verifiers := flags.String("verifiers", "", "")
140 tokenFile := flags.String("token-file", "", "")
141 maxBody, maxUpload, maxStorage := byteSize(1<<30), byteSize(2<<30), byteSize(8<<30)
142 flags.Var(&maxBody, "max-body", "")
143 flags.Var(&maxUpload, "max-upload", "")
144 flags.Var(&maxStorage, "max-storage", "")
145 if err := flags.Parse(args); errors.Is(err, flag.ErrHelp) {
146 fmt.Fprint(stderr, usage)
147 return nil
148 } else if err != nil {
149 return usageError{err}
150 }
151 switch {
152 case flags.NArg() > 0:
153 return usageError{fmt.Errorf("unexpected argument %q", flags.Arg(0))}
154 case *state == "":
155 return usageError{errors.New("--state is required")}
156 case *listen == "":
157 return usageError{errors.New("--listen is required")}
158 case !export.ValidName(*instance):
159 return usageError{fmt.Errorf("--instance %q must be 1 to 64 ASCII letters, digits, dots, dashes, or underscores, starting with a letter or digit", *instance)}
160 case !export.ValidName(*destination):
161 return usageError{fmt.Errorf("--destination %q must be 1 to 64 ASCII letters, digits, dots, dashes, or underscores, starting with a letter or digit", *destination)}
162 case *verifiers == "":
163 return usageError{errors.New("--verifiers is required")}
164 case *tokenFile == "":
165 return usageError{errors.New("--token-file is required")}
166 }
167
168 token, err := export.ReadToken(*tokenFile)
169 if err != nil {
170 return err
171 }
172 data, err := os.ReadFile(*verifiers)
173 if err != nil {
174 return err
175 }
176 keys, err := note.ParseVerifierKeys(data)
177 if err != nil {
178 // The parser's error quotes the line, which would print a token
179 // given here by mistake.
180 return fmt.Errorf("cannot parse verifier lines in %s", *verifiers)
181 }
182 if len(keys) == 0 {
183 return fmt.Errorf("%s contains no verifier lines", *verifiers)
184 }
185
186 logger := log.New(stderr, "valley-web-receive: ", log.LstdFlags)
187 store, err := export.OpenStore(*state, func(err error) { logger.Print(err) })
188 if err != nil {
189 return err
190 }
191 store.MaxStorage = int64(maxStorage)
192 ln, err := net.Listen("tcp", *listen)
193 if err != nil {
194 return err
195 }
196 rv := &receiver{
197 store: store, verifiers: keys, instance: *instance, destination: *destination, token: token,
198 maxBody: int64(maxBody), maxUpload: int64(maxUpload),
199 log: logger, slots: make(chan struct{}, maxRequests),
200 }
201 srv := &http.Server{
202 Handler: rv,
203 // The server's own handler for OPTIONS * reads the body before
204 // any check, with no deadline. Every request goes to rv instead,
205 // which refuses one without the token before it reads anything.
206 DisableGeneralOptionsHandler: true,
207 ReadHeaderTimeout: headerTimeout,
208 IdleTimeout: idleTimeout,
209 MaxHeaderBytes: 16 << 10,
210 ErrorLog: logger,
211 }
212 fmt.Fprintf(stderr, "valley-web-receive: listening on %s\n", ln.Addr())
213 served := make(chan error, 1)
214 go func() { served <- srv.Serve(limitListener(ln, maxConns)) }()
215 select {
216 case err := <-served:
217 return err
218 case <-ctx.Done():
219 }
220 shutdown, cancel := context.WithTimeout(context.Background(), stopTimeout)
221 defer cancel()
222 if err := srv.Shutdown(shutdown); err != nil {
223 // Requests still running are ended: closing their connections
224 // cancels their contexts, which kills the process group of the
225 // git a commit runs.
226 // Close returns without waiting for them, and a process that
227 // exited first could leave that git running.
228 srv.Close()
229 drained, cancel := context.WithTimeout(context.Background(), drainTimeout)
230 defer cancel()
231 if !rv.drain(drained) {
232 logger.Printf("requests were still running %v after connections were closed", drainTimeout)
233 }
234 }
235 if err := <-served; !errors.Is(err, http.ErrServerClosed) {
236 return err
237 }
238 return nil
239}
240
241// limitListener accepts at most n connections at once. Accept waits for
242// one to close before it takes another, or for the listener to be closed.
243func limitListener(ln net.Listener, n int) net.Listener {
244 return &limited{Listener: ln, slots: make(chan struct{}, n), closed: make(chan struct{})}
245}
246
247type limited struct {
248 net.Listener
249 slots chan struct{}
250 closed chan struct{}
251 once sync.Once
252}
253
254// Accept returns net.ErrClosed once the listener is closed, even while it
255// waits for a slot. Server.Shutdown and Server.Close wait for Accept to
256// return, so a wait that closing the listener did not end would hold up
257// the stop for as long as every connection stayed open.
258func (l *limited) Accept() (net.Conn, error) {
259 select {
260 case l.slots <- struct{}{}:
261 case <-l.closed:
262 return nil, net.ErrClosed
263 }
264 c, err := l.Listener.Accept()
265 if err != nil {
266 <-l.slots
267 return nil, err
268 }
269 return &limitedConn{Conn: c, release: sync.OnceFunc(func() { <-l.slots })}, nil
270}
271
272func (l *limited) Close() error {
273 l.once.Do(func() { close(l.closed) })
274 return l.Listener.Close()
275}
276
277type limitedConn struct {
278 net.Conn
279 release func()
280}
281
282func (c *limitedConn) Close() error {
283 err := c.Conn.Close()
284 c.release()
285 return err
286}
287
288// byteSize is a size flag's value in bytes. It is set from a number, or a
289// number with K, M, G or T for 1024 to the first to fourth power, as
290// systemd reads a size and the publisher reads its own.
291type byteSize int64
292
293func (b *byteSize) Set(v string) error {
294 number, unit := v, int64(1)
295 if n := len(v); n > 1 {
296 if i := strings.IndexByte("KMGT", v[n-1]); i >= 0 {
297 number, unit = v[:n-1], 1<<(10*(i+1))
298 }
299 }
300 x, err := strconv.ParseInt(number, 10, 64)
301 if err != nil || x <= 0 || x > math.MaxInt64/unit {
302 return fmt.Errorf("invalid size %q: must be a positive byte count, optionally suffixed with K, M, G, or T", v)
303 }
304 *b = byteSize(x * unit)
305 return nil
306}
307
308func (b *byteSize) String() string { return strconv.FormatInt(int64(*b), 10) }