1// SPDX-License-Identifier: MIT
2
3// Package disk creates the per-job scratch disks (sparse ext4 files) and, for
4// the container mode, loop-mounts them. Both isolation modes size a job's
5// writable space the same way: a sparse file of ERMITE_RUNNER_JOB_DISK.
6package disk
7
8import (
9 "context"
10 "fmt"
11 "os"
12 "regexp"
13 "strconv"
14 "strings"
15 "syscall"
16
17 "bnema.dev/ermite-runner/internal/cmdrun"
18)
19
20// CreateScratch creates the sparse scratch disk of sizeMiB at path and formats
21// it. The file is created exclusively without following symlinks and handed to
22// owner (fchown on the open descriptor, never by path) when owner >= 0.
23func CreateScratch(ctx context.Context, run cmdrun.Runner, path string, sizeMiB, owner int) error {
24 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW, 0o600)
25 if err != nil {
26 return err
27 }
28 if owner >= 0 {
29 if err := f.Chown(owner, owner); err != nil {
30 _ = f.Close()
31 return fmt.Errorf("chown scratch disk: %w", err)
32 }
33 }
34 if err := f.Truncate(int64(sizeMiB) << 20); err != nil {
35 _ = f.Close()
36 return err
37 }
38 if err := f.Close(); err != nil {
39 return err
40 }
41 // No journal and no reserved blocks: it is a throw-away disk. Lazy table
42 // initialisation keeps creation instant and the file sparse.
43 if _, err := run.Run(ctx, nil, "mkfs.ext4", "-q", "-F", "-L", "ermite-scratch", "-m", "0",
44 "-O", "^has_journal,^resize_inode", "-E", "lazy_itable_init=1,nodiscard", path); err != nil {
45 return fmt.Errorf("format scratch disk: %w", err)
46 }
47 return nil
48}
49
50var mkfsVersionRe = regexp.MustCompile(`(?m)^mke2fs (\d+)\.(\d+)(?:\.(\d+))?`)
51
52// MinMkfs is the oldest e2fsprogs the runner accepts: mkfs.ext4 -d (populate
53// from a directory, without root) appeared in 1.43. scripts/build-image.sh needs
54// 1.47.1 to populate from a tarball.
55const MinMkfs = "1.43"
56
57// CheckMkfs fails when mkfs.ext4 is missing or older than MinMkfs.
58func CheckMkfs(ctx context.Context, run cmdrun.Runner) error {
59 out, err := run.Run(ctx, nil, "mkfs.ext4", "-V")
60 // mke2fs prints its version on stderr and exits 0 or 1 depending on the
61 // release: judge by the output, not by the exit status.
62 maj, min, ok := parseMkfsVersion(string(out))
63 if !ok {
64 if err != nil {
65 return fmt.Errorf("mkfs.ext4 not usable (install e2fsprogs >= %s): %w", MinMkfs, err)
66 }
67 return fmt.Errorf("cannot read the mkfs.ext4 version from %q (need e2fsprogs >= %s)", strings.TrimSpace(string(out)), MinMkfs)
68 }
69 if maj < 1 || (maj == 1 && min < 43) {
70 return fmt.Errorf("mkfs.ext4 is e2fsprogs %d.%d, need >= %s for mkfs.ext4 -d", maj, min, MinMkfs)
71 }
72 return nil
73}
74
75func parseMkfsVersion(s string) (maj, min int, ok bool) {
76 m := mkfsVersionRe.FindStringSubmatch(s)
77 if m == nil {
78 return 0, 0, false
79 }
80 maj, _ = strconv.Atoi(m[1])
81 min, _ = strconv.Atoi(m[2])
82 return maj, min, true
83}