// Package app wires the runner and controls its lifecycle. package app import ( "context" "crypto/tls" "errors" "fmt" "log/slog" "net" "net/http" "os" "os/signal" "syscall" "time" "lincodex/runner/internal/config" "lincodex/runner/internal/jobs" "lincodex/runner/internal/judge" "lincodex/runner/internal/sandbox" "lincodex/runner/internal/server" ) // HTTP server bounds. Request bodies are bounded separately by // RUNNER_MAX_REQUEST_BYTES. const ( readHeaderTimeout = 5 * time.Second readTimeout = 30 * time.Second writeTimeout = 30 * time.Second idleTimeout = 60 * time.Second maxHeaderBytes = 16 << 10 healthcheckWait = 2 * time.Second ) // Sandbox settings that belong to the runner image rather than to a // deployment. const ( stderrCaptureBytes = 16 << 10 pollInterval = 10 * time.Millisecond ) // sandboxMounts are the read-only host paths the interpreter needs: the // Python installation under /usr/local and the musl loader and libraries. var sandboxMounts = []string{"/usr", "/lib"} // sandboxEnv is the whole environment of a jailed program. var sandboxEnv = []string{ "PATH=/usr/local/bin:/usr/bin:/bin", "HOME=" + sandbox.ScratchPath, "LANG=C.UTF-8", "PYTHONIOENCODING=utf-8", "PYTHONDONTWRITEBYTECODE=1", } // Run starts the runner and blocks until SIGINT or SIGTERM. func Run() error { cfg, err := config.Load() if err != nil { return err } logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel})) executor, err := sandbox.New(SandboxConfig(cfg)) if err != nil { return fmt.Errorf("app.Run - prepare sandbox: %w", err) } languages := Languages(cfg) if err := checkLanguageFiles(languages); err != nil { return err } evaluator := judge.New(executor, logger, languages...) manager, err := jobs.NewManager(jobs.Config{ MaxConcurrent: cfg.MaxConcurrentRuns, ResultTTL: cfg.ResultTTL, MaxRetained: cfg.MaxRetainedRuns, }, evaluator, logger) if err != nil { return err } handler := server.NewHandler(manager, evaluator.Supports, func() bool { return !manager.Draining() }, cfg.RetryAfter, logger) httpHandler, err := server.New(handler, cfg.APIToken, cfg.MaxRequestBytes, logger) if err != nil { return err } httpServer := &http.Server{ Addr: cfg.ListenAddress, Handler: httpHandler, ReadHeaderTimeout: readHeaderTimeout, ReadTimeout: readTimeout, WriteTimeout: writeTimeout, IdleTimeout: idleTimeout, MaxHeaderBytes: maxHeaderBytes, TLSConfig: &tls.Config{MinVersion: tls.VersionTLS13}, ErrorLog: slog.NewLogLogger(logger.Handler(), slog.LevelWarn), } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() serveErr := make(chan error, 1) go func() { serveErr <- serve(httpServer, cfg, logger) }() logger.InfoContext(ctx, "runner started", slog.String("address", cfg.ListenAddress), slog.Bool("tls", !cfg.AllowPlaintextHTTP), slog.Int("max_concurrent_runs", cfg.MaxConcurrentRuns), ) select { case err := <-serveErr: return errors.Join(err, manager.Close(context.Background())) case <-ctx.Done(): } logger.InfoContext(ctx, "runner stopping") shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout) defer cancel() return errors.Join(httpServer.Shutdown(shutdownCtx), manager.Close(shutdownCtx)) } func serve(httpServer *http.Server, cfg config.Config, logger *slog.Logger) error { var err error if cfg.AllowPlaintextHTTP { logger.Warn("serving plaintext HTTP; this switch is for local development only") err = httpServer.ListenAndServe() } else { err = httpServer.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile) } if errors.Is(err, http.ErrServerClosed) { return nil } return fmt.Errorf("app.serve - listen: %w", err) } // Languages returns the languages of the runner for cfg. func Languages(cfg config.Config) []judge.Language { return []judge.Language{judge.Python3(cfg.PythonPath), judge.Go(cfg.GoToolDir)} } // checkLanguageFiles fails startup when a toolchain file is missing, so a // broken image is not ready instead of failing every run. func checkLanguageFiles(languages []judge.Language) error { for _, language := range languages { for _, path := range language.Requires { if _, err := os.Stat(path); err != nil { return fmt.Errorf("app.checkLanguageFiles - %s: %w", language.ID, err) } } } return nil } // SandboxConfig returns the sandbox settings of the runner for cfg. func SandboxConfig(cfg config.Config) sandbox.Config { return sandbox.Config{ NsjailPath: cfg.NsjailPath, CgroupRoot: cfg.CgroupRoot, WorkRoot: cfg.WorkDir, SandboxUID: cfg.SandboxUID, SandboxGID: cfg.SandboxUID, MaxProcesses: cfg.MaxProcesses, MemoryOverheadBytes: cfg.MemoryOverheadBytes, TmpfsBytes: cfg.TmpfsBytes, FileSizeBytes: cfg.FileSizeBytes, OpenFiles: cfg.OpenFiles, StderrCaptureBytes: stderrCaptureBytes, ReadOnlyMounts: sandboxMounts, Env: sandboxEnv, PollInterval: pollInterval, } } // Healthcheck requests /healthz of the local process and returns the exit // status for a container health check. It sends no token. func Healthcheck() int { cfg, err := config.Load() if err != nil { return 1 } _, port, err := net.SplitHostPort(cfg.ListenAddress) if err != nil { return 1 } scheme := "https" if cfg.AllowPlaintextHTTP { scheme = "http" } client := &http.Client{ Timeout: healthcheckWait, Transport: &http.Transport{ // The probe talks to its own process over loopback and sends no // secret; the certificate names the private host, not 127.0.0.1. TLSClientConfig: &tls.Config{InsecureSkipVerify: true, MinVersion: tls.VersionTLS13}, //nolint:gosec // Loopback liveness probe only. }, } ctx, cancel := context.WithTimeout(context.Background(), healthcheckWait) defer cancel() request, err := http.NewRequestWithContext(ctx, http.MethodGet, scheme+"://"+net.JoinHostPort("127.0.0.1", port)+"/healthz", http.NoBody) if err != nil { return 1 } response, err := client.Do(request) if err != nil { return 1 } _ = response.Body.Close() // Only the status matters. if response.StatusCode != http.StatusOK { return 1 } return 0 }