gunk-dev/the-valley

main.go

source6453aa778a92main's published tip history
10.2 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 the web publisher's uploads into a state directory, which
53valley-web serves.
54
55 --state DIR the state directory, created if it does not exist;
56 the receiver is its one writer
57 --listen ADDR the TCP address to listen on, such as
58 127.0.0.1:8081; port 0 picks a free port
59 --instance NAME the instance every manifest must name
60 --destination NAME the destination every manifest must name: this
61 receiver's name
62 --verifiers FILE the publisher's verifier lines, one per line, as
63 the publisher writes its own to <state>/verifier;
64 a manifest must open under one of them
65 --token-file FILE the token every request must carry, in an
66 Authorization header: one line of 32 to 256 visible
67 ASCII characters, the same file the publisher's
68 --receiver-token names
69 --max-body SIZE the most bytes one body may declare (default 1G)
70 --max-upload SIZE the most bytes the bodies of one manifest may
71 declare together (default 2G)
72 --max-storage SIZE the most bytes the state directory may take on
73 disk, with every generation it holds, the staged
74 upload's bodies and each repository built from
75 them (default 8G)
76
77A SIZE is a number of bytes, or a number with K, M, G or T for KiB, MiB,
78GiB 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.
95const (
96 headerTimeout = 10 * time.Second
97 shortTimeout = 10 * time.Second
98 manifestTimeout = time.Minute
99 bodyTimeout = 30 * time.Minute
100 commitTimeout = 30 * time.Minute
101 idleTimeout = time.Minute
102 stopTimeout = 10 * time.Second
103)
104
105func main() {
106 ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
107 defer stop()
108 err := run(ctx, os.Args[1:], os.Stderr)
109 var bad usageError
110 switch {
111 case errors.As(err, &bad):
112 fmt.Fprintf(os.Stderr, "valley-web-receive: %v\n\n%s", err, usage)
113 os.Exit(2)
114 case err != nil:
115 fmt.Fprintf(os.Stderr, "valley-web-receive: %v\n", err)
116 os.Exit(1)
117 }
118}
119
120// usageError is a command line valley-web-receive cannot run with.
121type usageError struct{ error }
122
123// run receives until ctx is done, then shuts the server down, letting
124// requests in flight finish for a few seconds. A commit stopped part way
125// leaves the active export as it was, as a crash does.
126func run(ctx context.Context, args []string, stderr io.Writer) error {
127 flags := flag.NewFlagSet("valley-web-receive", flag.ContinueOnError)
128 flags.SetOutput(io.Discard)
129 state := flags.String("state", "", "")
130 listen := flags.String("listen", "", "")
131 instance := flags.String("instance", "", "")
132 destination := flags.String("destination", "", "")
133 verifiers := flags.String("verifiers", "", "")
134 tokenFile := flags.String("token-file", "", "")
135 maxBody, maxUpload, maxStorage := byteSize(1<<30), byteSize(2<<30), byteSize(8<<30)
136 flags.Var(&maxBody, "max-body", "")
137 flags.Var(&maxUpload, "max-upload", "")
138 flags.Var(&maxStorage, "max-storage", "")
139 if err := flags.Parse(args); errors.Is(err, flag.ErrHelp) {
140 fmt.Fprint(stderr, usage)
141 return nil
142 } else if err != nil {
143 return usageError{err}
144 }
145 switch {
146 case flags.NArg() > 0:
147 return usageError{fmt.Errorf("unexpected argument %q", flags.Arg(0))}
148 case *state == "":
149 return usageError{errors.New("--state is required")}
150 case *listen == "":
151 return usageError{errors.New("--listen is required")}
152 case !export.ValidName(*instance):
153 return usageError{fmt.Errorf("--instance %q is not a name: it is 1 to 64 letters, digits, dots, dashes and underscores, opening with a letter or a digit", *instance)}
154 case !export.ValidName(*destination):
155 return usageError{fmt.Errorf("--destination %q is not a name: it is 1 to 64 letters, digits, dots, dashes and underscores, opening with a letter or a digit", *destination)}
156 case *verifiers == "":
157 return usageError{errors.New("--verifiers is required")}
158 case *tokenFile == "":
159 return usageError{errors.New("--token-file is required")}
160 }
161
162 token, err := export.ReadToken(*tokenFile)
163 if err != nil {
164 return err
165 }
166 data, err := os.ReadFile(*verifiers)
167 if err != nil {
168 return err
169 }
170 keys, err := note.ParseVerifierKeys(data)
171 if err != nil {
172 // The parser's error quotes the line, which would print a token
173 // given here by mistake.
174 return fmt.Errorf("%s is not a file of verifier lines", *verifiers)
175 }
176 if len(keys) == 0 {
177 return fmt.Errorf("%s holds no verifier line", *verifiers)
178 }
179
180 logger := log.New(stderr, "valley-web-receive: ", log.LstdFlags)
181 store, err := export.OpenStore(*state, func(err error) { logger.Print(err) })
182 if err != nil {
183 return err
184 }
185 store.MaxStorage = int64(maxStorage)
186 ln, err := net.Listen("tcp", *listen)
187 if err != nil {
188 return err
189 }
190 rv := &receiver{
191 store: store, verifiers: keys, instance: *instance, destination: *destination, token: token,
192 maxBody: int64(maxBody), maxUpload: int64(maxUpload),
193 log: logger, slots: make(chan struct{}, maxRequests),
194 }
195 srv := &http.Server{
196 Handler: rv,
197 // The server's own handler for OPTIONS * reads the body before
198 // any check, with no deadline. Every request goes to rv instead,
199 // which refuses one without the token before it reads anything.
200 DisableGeneralOptionsHandler: true,
201 ReadHeaderTimeout: headerTimeout,
202 IdleTimeout: idleTimeout,
203 MaxHeaderBytes: 16 << 10,
204 ErrorLog: logger,
205 }
206 fmt.Fprintf(stderr, "valley-web-receive: listening on %s\n", ln.Addr())
207 served := make(chan error, 1)
208 go func() { served <- srv.Serve(limitListener(ln, maxConns)) }()
209 select {
210 case err := <-served:
211 return err
212 case <-ctx.Done():
213 }
214 shutdown, cancel := context.WithTimeout(context.Background(), stopTimeout)
215 defer cancel()
216 if err := srv.Shutdown(shutdown); err != nil {
217 // Requests still running are ended: closing their connections
218 // cancels their contexts, which stops the git a commit runs.
219 srv.Close()
220 }
221 if err := <-served; !errors.Is(err, http.ErrServerClosed) {
222 return err
223 }
224 return nil
225}
226
227// limitListener accepts at most n connections at once. Accept waits for
228// one to close before it takes another, or for the listener to be closed.
229func limitListener(ln net.Listener, n int) net.Listener {
230 return &limited{Listener: ln, slots: make(chan struct{}, n), closed: make(chan struct{})}
231}
232
233type limited struct {
234 net.Listener
235 slots chan struct{}
236 closed chan struct{}
237 once sync.Once
238}
239
240// Accept returns net.ErrClosed once the listener is closed, even while it
241// waits for a slot. Server.Shutdown and Server.Close wait for Accept to
242// return, so a wait that closing the listener did not end would hold up
243// the stop for as long as every connection stayed open.
244func (l *limited) Accept() (net.Conn, error) {
245 select {
246 case l.slots <- struct{}{}:
247 case <-l.closed:
248 return nil, net.ErrClosed
249 }
250 c, err := l.Listener.Accept()
251 if err != nil {
252 <-l.slots
253 return nil, err
254 }
255 return &limitedConn{Conn: c, release: sync.OnceFunc(func() { <-l.slots })}, nil
256}
257
258func (l *limited) Close() error {
259 l.once.Do(func() { close(l.closed) })
260 return l.Listener.Close()
261}
262
263type limitedConn struct {
264 net.Conn
265 release func()
266}
267
268func (c *limitedConn) Close() error {
269 err := c.Conn.Close()
270 c.release()
271 return err
272}
273
274// byteSize is a size flag's value in bytes. It is set from a number, or a
275// number with K, M, G or T for 1024 to the first to fourth power, as
276// systemd reads a size and the publisher reads its own.
277type byteSize int64
278
279func (b *byteSize) Set(v string) error {
280 number, unit := v, int64(1)
281 if n := len(v); n > 1 {
282 if i := strings.IndexByte("KMGT", v[n-1]); i >= 0 {
283 number, unit = v[:n-1], 1<<(10*(i+1))
284 }
285 }
286 x, err := strconv.ParseInt(number, 10, 64)
287 if err != nil || x <= 0 || x > math.MaxInt64/unit {
288 return fmt.Errorf("%q is not a size: a positive number of bytes, or one with K, M, G or T", v)
289 }
290 *b = byteSize(x * unit)
291 return nil
292}
293
294func (b *byteSize) String() string { return strconv.FormatInt(int64(*b), 10) }