v0.2.0 playground/runner/runner.go

44 lines1.1 KiB

package runner
import (
"bytes"
"context"
"errors"
"os/exec"
)
// ErrBusy means every slot is taken; the caller queues the run.
var ErrBusy = errors.New("busy")
type Result struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Exit int `json:"exit"`
}
type Pool struct{ slots chan struct{} }
func NewPool(n int) *Pool { return &Pool{slots: make(chan struct{}, n)} }
func (p *Pool) Run(ctx context.Context, lang, code string) (*Result, error) {
select {
case p.slots <- struct{}{}:
defer func() { <-p.slots }()
default:
return nil, ErrBusy
}
ctx, cancel := context.WithTimeout(ctx, Limits.Wall)
defer cancel()
cmd := exec.CommandContext(ctx, "docker", append(Limits.DockerArgs(), image(lang))...)
cmd.Stdin = bytes.NewBufferString(code)
var out, errOut bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errOut
err := cmd.Run()
res := &Result{Stdout: out.String(), Stderr: errOut.String()}
if exit, ok := err.(*exec.ExitError); ok {
res.Exit = exit.ExitCode()
}
return res, nil
}
func image(lang string) string { return "glibcode/run-" + lang + ":latest" }