gunk-dev/the-valley

main.go

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