gunk-dev/the-valley

main.go

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