gunk-dev/the-valley

main.go

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