Skip to content

Commit 7a7e790

Browse files
authored
Merge pull request #3446 from dtrudg/pick-oci-fixes
Pick OCI-mode XDG var handling improvements (release-4.2)
2 parents a2e1249 + f5010b1 commit 7a7e790

File tree

5 files changed

+136
-24
lines changed

5 files changed

+136
-24
lines changed

CHANGELOG.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@
66

77
- Fix regression from 4.1.5 that overwrites source image runscript, environment
88
etc. in build from local image.
9+
- Fall back to `$TMPDIR` as singularity-buildkitd root directory if
10+
`~/.singularity` is on a filesystem that does not fully support overlay.
11+
- Add more intuitive error message for rootless `build --oci` when required
12+
`XDG_RUNTIME_DIR` env var is not set.
13+
14+
### New Features & Functionality
15+
16+
- In OCI-Mode, accommodate systems configured so that they do not create a
17+
`/run/user` session directory. OCI-Mode will now attempt to use
18+
`$TMPDIR/singularity-oci-<uid>` for runtime state on systems where
19+
`$XDG_RUNTIME_DIR` is not set and the default user session path of
20+
`/run/user/<uid>` does not exist. Note that the `$TMPDIR/singularity-oci-<uid>`
21+
directory is shared between concurrent `--oci` mode invocations, and will not
22+
be removed on exit - an empty directory will remain.
923

1024
## 4.2.1 \[2024-09-13\]
1125

cmd/singularity-buildkitd/main.go

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,27 @@ import (
99
"context"
1010
"os"
1111

12+
"github.com/spf13/pflag"
1213
bkdaemon "github.com/sylabs/singularity/v4/internal/pkg/build/buildkit/daemon"
1314
"github.com/sylabs/singularity/v4/internal/pkg/buildcfg"
1415
"github.com/sylabs/singularity/v4/pkg/sylog"
1516
"github.com/sylabs/singularity/v4/pkg/util/singularityconf"
1617
)
1718

19+
var (
20+
rootDir string
21+
arch string
22+
bkSocket string
23+
)
24+
1825
func main() {
19-
if len(os.Args) < 2 || len(os.Args) > 3 {
20-
sylog.Fatalf("%s: usage: %s <socket-uri> [architecture]", bkdaemon.DaemonName, os.Args[0])
21-
}
26+
pflag.StringVar(&rootDir, "root", "", "buildkitd root directory")
27+
pflag.StringVar(&arch, "arch", "", "build architecture")
28+
pflag.StringVar(&bkSocket, "socket", "", "socket path")
29+
pflag.Parse()
2230

23-
bkSocket := os.Args[1]
24-
bkArch := ""
25-
if len(os.Args) == 3 {
26-
bkArch = os.Args[2]
31+
if bkSocket == "" {
32+
sylog.Fatalf("%s: usage: %s [--root <dir>] [--arch <arch>] --socket <socket-uri>", bkdaemon.DaemonName, os.Args[0])
2733
}
2834

2935
sylog.Debugf("%s: parsing configuration file %s", bkdaemon.DaemonName, buildcfg.SINGULARITY_CONF_FILE)
@@ -34,8 +40,10 @@ func main() {
3440
singularityconf.SetCurrentConfig(config)
3541

3642
daemonOpts := &bkdaemon.Opts{
37-
ReqArch: bkArch,
43+
ReqArch: arch,
44+
RootDir: rootDir,
3845
}
46+
3947
if err := bkdaemon.Run(context.Background(), daemonOpts, bkSocket); err != nil {
4048
sylog.Fatalf("%s: %v", bkdaemon.DaemonName, err)
4149
}

internal/pkg/build/buildkit/client/client.go

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,17 @@ import (
4747
"github.com/sylabs/singularity/v4/internal/pkg/ociplatform"
4848
"github.com/sylabs/singularity/v4/internal/pkg/remote/credential/ociauth"
4949
"github.com/sylabs/singularity/v4/internal/pkg/util/bin"
50+
fsoverlay "github.com/sylabs/singularity/v4/internal/pkg/util/fs/overlay"
51+
"github.com/sylabs/singularity/v4/internal/pkg/util/rootless"
52+
"github.com/sylabs/singularity/v4/pkg/syfs"
5053
"github.com/sylabs/singularity/v4/pkg/sylog"
5154
"golang.org/x/sync/errgroup"
5255
)
5356

5457
const (
5558
buildTag = "tag"
5659
bkDefaultSocket = "unix:///run/buildkit/buildkitd.sock"
57-
bkLaunchTimeout = 120 * time.Second
60+
bkLaunchTimeout = 10 * time.Second
5861
bkShutdownTimeout = 10 * time.Second
5962
bkMinVersion = "v0.12.3"
6063
)
@@ -161,13 +164,32 @@ func startBuildkitd(ctx context.Context, opts *Opts) (bkSocket string, cleanup f
161164
return "", nil, err
162165
}
163166

164-
bkSocket = generateSocketAddress()
167+
bkSocket, err = generateSocketAddress()
168+
if err != nil {
169+
return "", nil, err
170+
}
171+
172+
args := []string{}
173+
tmpRoot := ""
174+
// Check the user .singularity dir is in a location supporting overlayfs etc. If not, use a tmpdir.
175+
if err := fsoverlay.CheckUpper(syfs.ConfigDir()); err != nil {
176+
tmpRoot, err = os.MkdirTemp("", "singularity-buildkitd-")
177+
if err != nil {
178+
sylog.Fatalf("while creating singularity-buildkitd temporary root dir: %v", err)
179+
}
180+
if err := fsoverlay.CheckUpper(tmpRoot); err != nil {
181+
sylog.Fatalf("Temporary directory does not support buildkit. Please set $TMPDIR to a local filesystem.")
182+
}
183+
184+
sylog.Warningf("~/.singularity filesystem does not support buildkit. Using temporary directory %s. Layers will not be cached for future builds.", tmpRoot)
185+
args = append(args, "--root="+tmpRoot)
186+
}
165187

166-
// singularity-buildkitd <socket-uri> [architecture]
167-
args := []string{bkSocket}
168188
if opts.ReqArch != "" {
169-
args = append(args, opts.ReqArch)
189+
args = append(args, "--arch="+opts.ReqArch)
170190
}
191+
args = append(args, "--socket="+bkSocket)
192+
171193
cmd := exec.CommandContext(ctx, bkCmd, args...)
172194
cmd.WaitDelay = bkShutdownTimeout
173195
cmd.Cancel = func() error {
@@ -182,8 +204,15 @@ func startBuildkitd(ctx context.Context, opts *Opts) (bkSocket string, cleanup f
182204
sylog.Errorf("while canceling buildkit daemon process: %v", err)
183205
}
184206
cmd.Wait()
207+
if tmpRoot != "" {
208+
sylog.Warningf("removing singularity-buildkitd temporary directory %s", tmpRoot)
209+
if err := os.RemoveAll(tmpRoot); err != nil {
210+
sylog.Errorf("while removing singularity-buildkitd temp dir: %v", err)
211+
}
212+
}
185213
}
186214

215+
sylog.Debugf("starting %s %v", bkCmd, args)
187216
if err := cmd.Start(); err != nil {
188217
return "", nil, err
189218
}
@@ -378,15 +407,22 @@ func writeDockerTar(r io.Reader, outputFile *os.File) error {
378407
return err
379408
}
380409

381-
func generateSocketAddress() string {
410+
func generateSocketAddress() (string, error) {
411+
uid, err := rootless.Getuid()
412+
if err != nil {
413+
return "", err
414+
}
415+
382416
socketPath := "/run/singularity-buildkitd"
417+
if uid == 0 {
418+
return "unix://" + filepath.Join(socketPath, fmt.Sprintf("singularity-buildkitd-%d.sock", os.Getpid())), nil
419+
}
383420

384-
// pam_systemd sets XDG_RUNTIME_DIR but not other dirs.
385421
xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR")
386-
if xdgRuntimeDir != "" {
387-
dirs := strings.Split(xdgRuntimeDir, ":")
388-
socketPath = filepath.Join(dirs[0], "singularity-buildkitd")
422+
if xdgRuntimeDir == "" {
423+
return "", fmt.Errorf("rootless build --oci requires XDG_RUNTIME_DIR is set")
389424
}
390-
391-
return "unix://" + filepath.Join(socketPath, fmt.Sprintf("singularity-buildkitd-%d.sock", os.Getpid()))
425+
dirs := strings.Split(xdgRuntimeDir, ":")
426+
socketPath = filepath.Join(dirs[0], "singularity-buildkitd")
427+
return "unix://" + filepath.Join(socketPath, fmt.Sprintf("singularity-buildkitd-%d.sock", os.Getpid())), nil
392428
}

internal/pkg/build/buildkit/daemon/daemon.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ const DaemonName = "singularity-buildkitd"
8080
type Opts struct {
8181
// Requested build architecture
8282
ReqArch string
83+
// Override the location of the singularity-buildkitd root with specified directory
84+
RootDir string
8385
}
8486

8587
type workerInitializerOpt struct {
@@ -149,7 +151,7 @@ func waitLock(ctx context.Context, lockPath string) (*flock.Flock, error) {
149151
func Run(ctx context.Context, opts *Opts, socketPath string) error {
150152
// If we need to, enter a new cgroup now, to workaround an issue with crun container cgroup creation (#1538).
151153
if err := oci.CrunNestCgroup(); err != nil {
152-
sylog.Fatalf("%s: while applying crun cgroup workaround: %v", DaemonName, err)
154+
return fmt.Errorf("%s: while applying crun cgroup workaround: %v", DaemonName, err)
153155
}
154156

155157
cfg, err := config.LoadFile(defaultConfigPath())
@@ -166,6 +168,14 @@ func Run(ctx context.Context, opts *Opts, socketPath string) error {
166168

167169
server := grpc.NewServer()
168170

171+
if opts.RootDir != "" {
172+
ptr := func(v bool) *bool {
173+
return &v
174+
}
175+
cfg.Root = opts.RootDir
176+
cfg.Workers.OCI.GC = ptr(false)
177+
}
178+
169179
// relative path does not work with nightlyone/lockfile
170180
root, err := filepath.Abs(cfg.Root)
171181
if err != nil {
@@ -181,7 +191,7 @@ func Run(ctx context.Context, opts *Opts, socketPath string) error {
181191
sylog.Debugf("%s: path for buildkitd lock file: %s", DaemonName, lockPath)
182192
lock, err := waitLock(ctx, lockPath)
183193
if err != nil {
184-
sylog.Fatalf("%s: while creating lock file: %v", DaemonName, err)
194+
return fmt.Errorf("%s: while creating lock file: %v", DaemonName, err)
185195
}
186196
defer func() {
187197
lock.Unlock()

internal/pkg/runtime/launcher/oci/oci_linux.go

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) 2018-2022, Sylabs Inc. All rights reserved.
1+
// Copyright (c) 2018-2024, Sylabs Inc. All rights reserved.
22
// This software is licensed under a 3-clause BSD license. Please consult the
33
// LICENSE.md file distributed with the sources of this project regarding your
44
// rights to use or distribute this software.
@@ -13,9 +13,11 @@ import (
1313
"os"
1414
"path"
1515
"path/filepath"
16+
"syscall"
1617
"time"
1718

1819
securejoin "github.com/cyphar/filepath-securejoin"
20+
"github.com/sylabs/singularity/v4/internal/pkg/cgroups"
1921
"github.com/sylabs/singularity/v4/internal/pkg/util/bin"
2022
"github.com/sylabs/singularity/v4/internal/pkg/util/fs"
2123
"github.com/sylabs/singularity/v4/internal/pkg/util/rootless"
@@ -58,10 +60,52 @@ func runtimeStateDir() (path string, err error) {
5860
if err != nil {
5961
return "", err
6062
}
63+
64+
// Root - use our own /run directory
6165
if u.Uid == "0" {
6266
return "/run/singularity-oci", nil
6367
}
64-
return fmt.Sprintf("/run/user/%s/singularity-oci", u.Uid), nil
68+
69+
// Prefer XDG_RUNTIME_DIR for non-root, if set and usable.
70+
if ok, _ := cgroups.HasXDGRuntimeDir(); ok {
71+
d := filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "singularity-oci")
72+
sylog.Debugf("Using XDG_RUNTIME_DIR for runtime state (%s)", d)
73+
return d, nil
74+
}
75+
76+
// If no XDG_RUNTIME_DIR, then try standard user session directory location.
77+
runDir := fmt.Sprintf("/run/user/%s/", u.Uid)
78+
if fs.IsDir(runDir) {
79+
d := filepath.Join(runDir, "singularity-oci")
80+
sylog.Debugf("Using /run/user default for runtime state (%s)", d)
81+
return d, nil
82+
}
83+
84+
// If standard user session directory not available, use TMPDIR as a last resort.
85+
runDir = filepath.Join(os.TempDir(), "singularity-oci-"+u.Uid)
86+
sylog.Infof("No /run/user session directory for user. Using %q for runtime state.", runDir)
87+
88+
// Create if not present
89+
st, err := os.Stat(runDir)
90+
if os.IsNotExist(err) {
91+
return runDir, os.Mkdir(runDir, 0o700)
92+
}
93+
if err != nil {
94+
return "", err
95+
}
96+
97+
// If it exists, verify it's a directory with correct ownership, perms.
98+
if !st.IsDir() {
99+
return "", fmt.Errorf("%s exists, but is not a directory", runDir)
100+
}
101+
if st.Sys().(*syscall.Stat_t).Uid != uint32(os.Geteuid()) { //nolint:forcetypeassert
102+
return "", fmt.Errorf("%s exists, but is not owned by correct user", runDir)
103+
}
104+
if st.Mode().Perm() != 0o700 {
105+
return "", fmt.Errorf("%s exists, but does not have correct permissions (700)", runDir)
106+
}
107+
108+
return runDir, nil
65109
}
66110

67111
// stateDir returns the path to container state handled by conmon/singularity

0 commit comments

Comments
 (0)