Run code in throwaway containers

Daniel Tanaka 1 year ago
parent 2b62f45106 commit f4e2ea5b8a64b27c5b5910bbc7b218a619f875b5
2 changed files with 64 additions and 0 deletions
+20-0runner/limits.go ADDED
View File
@@ -0,0 +1,20 @@
1+package runner
2+
3+import (
4+ "strconv"
5+ "time"
6+)
7+
8+type limits struct {
9+ Wall time.Duration
10+ Memory int // MB
11+ Pids int
12+}
13+
14+// Limits apply to every run.
15+var Limits = limits{Wall: 5 * time.Second, Memory: 128, Pids: 64}
16+
17+func (l limits) DockerArgs() []string {
18+ return []string{"run", "--rm", "-i", "--network=none", "--read-only",
19+ "--memory=" + strconv.Itoa(l.Memory) + "m", "--pids-limit=" + strconv.Itoa(l.Pids), "--cpus=0.5"}
20+}
+44-0runner/runner.go ADDED
View File
@@ -0,0 +1,44 @@
1+package runner
2+
3+import (
4+ "bytes"
5+ "context"
6+ "errors"
7+ "os/exec"
8+)
9+
10+// ErrBusy means every slot is taken; the caller queues the run.
11+var ErrBusy = errors.New("busy")
12+
13+type Result struct {
14+ Stdout string `json:"stdout"`
15+ Stderr string `json:"stderr"`
16+ Exit int `json:"exit"`
17+}
18+
19+type Pool struct{ slots chan struct{} }
20+
21+func NewPool(n int) *Pool { return &Pool{slots: make(chan struct{}, n)} }
22+
23+func (p *Pool) Run(ctx context.Context, lang, code string) (*Result, error) {
24+ select {
25+ case p.slots <- struct{}{}:
26+ defer func() { <-p.slots }()
27+ default:
28+ return nil, ErrBusy
29+ }
30+ ctx, cancel := context.WithTimeout(ctx, Limits.Wall)
31+ defer cancel()
32+ cmd := exec.CommandContext(ctx, "docker", append(Limits.DockerArgs(), image(lang))...)
33+ cmd.Stdin = bytes.NewBufferString(code)
34+ var out, errOut bytes.Buffer
35+ cmd.Stdout, cmd.Stderr = &out, &errOut
36+ err := cmd.Run()
37+ res := &Result{Stdout: out.String(), Stderr: errOut.String()}
38+ if exit, ok := err.(*exec.ExitError); ok {
39+ res.Exit = exit.ExitCode()
40+ }
41+ return res, nil
42+}
43+
44+func image(lang string) string { return "glibcode/run-" + lang + ":latest" }