1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
|
// Copyright (c) 2020, Control Command Inc. All rights reserved.
// Copyright (c) 2018-2023, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package cli
import (
"context"
"errors"
"fmt"
"os"
"strings"
"github.com/containers/image/v5/types"
"github.com/spf13/cobra"
"github.com/sylabs/singularity/v4/docs"
"github.com/sylabs/singularity/v4/internal/pkg/cache"
"github.com/sylabs/singularity/v4/internal/pkg/client/library"
"github.com/sylabs/singularity/v4/internal/pkg/client/net"
"github.com/sylabs/singularity/v4/internal/pkg/client/oci"
ocisifclient "github.com/sylabs/singularity/v4/internal/pkg/client/ocisif"
"github.com/sylabs/singularity/v4/internal/pkg/client/oras"
"github.com/sylabs/singularity/v4/internal/pkg/client/shub"
"github.com/sylabs/singularity/v4/internal/pkg/runtime/launcher"
"github.com/sylabs/singularity/v4/internal/pkg/runtime/launcher/native"
ocilauncher "github.com/sylabs/singularity/v4/internal/pkg/runtime/launcher/oci"
"github.com/sylabs/singularity/v4/internal/pkg/util/uri"
bndocisif "github.com/sylabs/singularity/v4/pkg/ocibundle/ocisif"
"github.com/sylabs/singularity/v4/pkg/syfs"
"github.com/sylabs/singularity/v4/pkg/sylog"
useragent "github.com/sylabs/singularity/v4/pkg/util/user-agent"
)
const (
defaultPath = "/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
)
func getCacheHandle(cfg cache.Config) *cache.Handle {
h, err := cache.New(cache.Config{
ParentDir: os.Getenv(cache.DirEnv),
Disable: cfg.Disable,
})
if err != nil {
sylog.Fatalf("Failed to create an image cache handle: %s", err)
}
return h
}
type contextKey string
const (
keyOrigImageURI contextKey = "origImageURI"
)
// actionPreRun will:
// - do the proper path unsetting;
// - and implement flag inferences for:
// --compat
// --hostname
// - run replaceURIWithImage;
func actionPreRun(cmd *cobra.Command, args []string) {
// For compatibility - we still set USER_PATH so it will be visible in the
// container, and can be used there if needed. USER_PATH is not used by
// singularity itself in 3.9+
userPath := strings.Join([]string{os.Getenv("PATH"), defaultPath}, ":")
os.Setenv("USER_PATH", userPath)
// --compat infers other options that give increased OCI / Docker compatibility
// Excludes uts/user/net namespaces as these are restrictive for many Singularity
// installs.
if isCompat {
if noCompat {
sylog.Fatalf("Cannot use --no-compat with --compat: incompatible options")
}
isContainAll = true
isWritableTmpfs = true
noInit = true
noUmask = true
noEval = true
}
// --hostname requires UTS namespace
if len(hostname) > 0 {
utsNamespace = true
}
origImageURI := replaceURIWithImage(cmd.Context(), cmd, args)
cmd.SetContext(context.WithValue(cmd.Context(), keyOrigImageURI, &origImageURI))
}
func handleOCI(ctx context.Context, imgCache *cache.Handle, cmd *cobra.Command, pullFrom string) (string, error) {
ociAuth, err := makeDockerCredentials(cmd)
if err != nil {
sylog.Fatalf("While creating Docker credentials: %v", err)
}
pullOpts := oci.PullOptions{
TmpDir: tmpDir,
OciAuth: ociAuth,
DockerHost: dockerHost,
NoHTTPS: noHTTPS,
OciSif: isOCI,
}
return oci.Pull(ctx, imgCache, pullFrom, pullOpts)
}
func handleOras(ctx context.Context, imgCache *cache.Handle, cmd *cobra.Command, pullFrom string) (string, error) {
ociAuth, err := makeDockerCredentials(cmd)
if err != nil {
return "", fmt.Errorf("while creating docker credentials: %v", err)
}
return oras.Pull(ctx, imgCache, pullFrom, tmpDir, ociAuth)
}
func handleLibrary(ctx context.Context, imgCache *cache.Handle, pullFrom string) (string, error) {
r, err := library.NormalizeLibraryRef(pullFrom)
if err != nil {
return "", err
}
// Default "" = use current remote endpoint
var libraryURI string
if r.Host != "" {
if noHTTPS {
libraryURI = "http://" + r.Host
} else {
libraryURI = "https://" + r.Host
}
}
c, err := getLibraryClientConfig(libraryURI)
if err != nil {
return "", err
}
pullOpts := library.PullOptions{
Endpoint: currentRemoteEndpoint,
LibraryConfig: c,
// false to allow OCI execution of native SIF from library
RequireOciSif: false,
TmpDir: tmpDir,
Platform: getOCIPlatform(),
}
return library.Pull(ctx, imgCache, r, pullOpts)
}
func handleShub(ctx context.Context, imgCache *cache.Handle, pullFrom string) (string, error) {
return shub.Pull(ctx, imgCache, pullFrom, tmpDir, noHTTPS)
}
func handleNet(ctx context.Context, imgCache *cache.Handle, pullFrom string) (string, error) {
return net.Pull(ctx, imgCache, pullFrom, tmpDir)
}
func replaceURIWithImage(ctx context.Context, cmd *cobra.Command, args []string) string {
origImageURI := args[0]
t, _ := uri.Split(origImageURI)
// If joining an instance (instance://xxx), or we have a bare filename then
// no retrieval / conversion is required.
if t == "instance" || t == "" {
return origImageURI
}
var image string
var err error
// Create a cache handle only when we know we are using a URI
imgCache := getCacheHandle(cache.Config{Disable: disableCache})
if imgCache == nil {
sylog.Fatalf("failed to create a new image cache handle")
}
switch t {
case uri.Library:
image, err = handleLibrary(ctx, imgCache, origImageURI)
case uri.Oras:
image, err = handleOras(ctx, imgCache, cmd, origImageURI)
case uri.Shub:
image, err = handleShub(ctx, imgCache, origImageURI)
case oci.IsSupported(t):
image, err = handleOCI(ctx, imgCache, cmd, origImageURI)
case uri.HTTP:
image, err = handleNet(ctx, imgCache, origImageURI)
case uri.HTTPS:
image, err = handleNet(ctx, imgCache, origImageURI)
default:
sylog.Fatalf("Unsupported transport type: %s", t)
}
// If we are in OCI mode, then we can still attempt to run from a directory
// bundle if tar->squashfs conversion in OCI-SIF creation fails. This
// fallback is important while sqfstar/tar2sqfs are not bundled, and not
// available in common distros.
if errors.Is(err, ocisifclient.ErrFailedSquashfsConversion) {
if !canUseTmpSandbox {
sylog.Errorf("%v", err)
sylog.Fatalf("OCI-SIF could not be created, and fallback to temporary sandbox dir disallowed")
}
sylog.Warningf("%v", err)
sylog.Warningf("OCI-SIF could not be created, falling back to unpacking OCI bundle in temporary sandbox dir")
return origImageURI
}
if err != nil {
sylog.Fatalf("Unable to handle %s uri: %v", origImageURI, err)
}
// TODO - drop once we have implemented prefix-less oci-sif vs native sif detection.
if isOCI {
image = "oci-sif:" + image
}
args[0] = image
return origImageURI
}
// ExecCmd represents the exec command
var ExecCmd = &cobra.Command{
DisableFlagsInUseLine: true,
TraverseChildren: true,
Args: cobra.MinimumNArgs(2),
PreRun: actionPreRun,
Run: func(cmd *cobra.Command, args []string) {
// singularity exec <image> <command> [args...]
ep := launcher.ExecParams{
Image: args[0],
Action: "exec",
Process: args[1],
Args: args[2:],
}
if err := launchContainer(cmd, ep); err != nil {
sylog.Fatalf("%s", err)
}
},
Use: docs.ExecUse,
Short: docs.ExecShort,
Long: docs.ExecLong,
Example: docs.ExecExamples,
}
// ShellCmd represents the shell command
var ShellCmd = &cobra.Command{
DisableFlagsInUseLine: true,
TraverseChildren: true,
Args: cobra.MinimumNArgs(1),
PreRun: actionPreRun,
Run: func(cmd *cobra.Command, args []string) {
// singularity shell <image>
ep := launcher.ExecParams{
Image: args[0],
Action: "shell",
}
if err := launchContainer(cmd, ep); err != nil {
sylog.Fatalf("%s", err)
}
},
Use: docs.ShellUse,
Short: docs.ShellShort,
Long: docs.ShellLong,
Example: docs.ShellExamples,
}
// RunCmd represents the run command
var RunCmd = &cobra.Command{
DisableFlagsInUseLine: true,
TraverseChildren: true,
Args: cobra.MinimumNArgs(1),
PreRun: actionPreRun,
Run: func(cmd *cobra.Command, args []string) {
// singularity run <image> [args...]
ep := launcher.ExecParams{
Image: args[0],
Action: "run",
Args: args[1:],
}
if err := launchContainer(cmd, ep); err != nil {
sylog.Fatalf("%s", err)
}
},
Use: docs.RunUse,
Short: docs.RunShort,
Long: docs.RunLong,
Example: docs.RunExamples,
}
// TestCmd represents the test command
var TestCmd = &cobra.Command{
DisableFlagsInUseLine: true,
TraverseChildren: true,
Args: cobra.MinimumNArgs(1),
PreRun: actionPreRun,
Run: func(cmd *cobra.Command, args []string) {
// singularity test <image> [args...]
ep := launcher.ExecParams{
Image: args[0],
Action: "test",
Args: args[1:],
}
if err := launchContainer(cmd, ep); err != nil {
sylog.Fatalf("%s", err)
}
},
Use: docs.RunTestUse,
Short: docs.RunTestShort,
Long: docs.RunTestLong,
Example: docs.RunTestExample,
}
func launchContainer(cmd *cobra.Command, ep launcher.ExecParams) error {
ns := launcher.Namespaces{
User: userNamespace,
UTS: utsNamespace,
PID: pidNamespace,
IPC: ipcNamespace,
Net: netNamespace,
NoPID: noPidNamespace,
}
cgJSON, err := getCgroupsJSON()
if err != nil {
return err
}
if cgJSON != "" && strings.HasPrefix(ep.Image, "instance://") {
cgJSON = ""
sylog.Warningf("Resource limits & cgroups configuration are only applied to instances at instance start.")
}
ki, err := getEncryptionMaterial(cmd)
if err != nil {
return err
}
opts := []launcher.Option{
launcher.OptWritable(isWritable),
launcher.OptWritableTmpfs(isWritableTmpfs),
launcher.OptOverlayPaths(overlayPath),
launcher.OptScratchDirs(scratchPath),
launcher.OptWorkDir(workdirPath),
launcher.OptHome(
homePath,
cmd.Flag(actionHomeFlag.Name).Changed,
noHome,
),
launcher.OptMounts(bindPaths, mounts, fuseMount),
launcher.OptNoMount(noMount),
launcher.OptNvidia(nvidia, nvCCLI),
launcher.OptNoNvidia(noNvidia),
launcher.OptRocm(rocm),
launcher.OptNoRocm(noRocm),
launcher.OptContainLibs(containLibsPath),
launcher.OptProot(proot),
launcher.OptEnv(singularityEnv, singularityEnvFile, isCleanEnv),
launcher.OptNoEval(noEval),
launcher.OptNamespaces(ns),
launcher.OptNetwork(network, networkArgs),
launcher.OptHostname(hostname),
launcher.OptDNS(dns),
launcher.OptCaps(addCaps, dropCaps),
launcher.OptAllowSUID(allowSUID),
launcher.OptKeepPrivs(keepPrivs),
launcher.OptNoPrivs(noPrivs),
launcher.OptSecurity(security),
launcher.OptNoUmask(noUmask),
launcher.OptCgroupsJSON(cgJSON),
launcher.OptConfigFile(configurationFile),
launcher.OptShellPath(shellPath),
launcher.OptCwdPath(cwdPath),
launcher.OptFakeroot(isFakeroot),
launcher.OptNoSetgroups(noSetgroups),
launcher.OptBoot(isBoot),
launcher.OptNoInit(noInit),
launcher.OptContain(isContained),
launcher.OptContainAll(isContainAll),
launcher.OptAppName(appName),
launcher.OptKeyInfo(ki),
launcher.OptSIFFuse(sifFUSE),
launcher.OptCacheDisabled(disableCache),
launcher.OptDevice(device),
launcher.OptCdiDirs(cdiDirs),
launcher.OptNoCompat(noCompat),
launcher.OptNoTmpSandbox(noTmpSandbox),
}
// Explicitly use the interface type here, as we will add alternative launchers later...
var l launcher.Launcher
if isOCI {
sylog.Debugf("Using OCI runtime launcher.")
sysCtx := &types.SystemContext{
OCIInsecureSkipTLSVerify: noHTTPS,
DockerAuthConfig: &dockerAuthConfig,
DockerDaemonHost: dockerHost,
OSChoice: "linux",
AuthFilePath: syfs.DockerConf(),
DockerRegistryUserAgent: useragent.Value(),
}
if noHTTPS {
sysCtx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(true)
}
opts = append(opts, launcher.OptSysContext(sysCtx))
l, err = ocilauncher.NewLauncher(opts...)
if err != nil {
return fmt.Errorf("while configuring container: %s", err)
}
} else {
sylog.Debugf("Using native runtime launcher.")
l, err = native.NewLauncher(opts...)
if err != nil {
return fmt.Errorf("while configuring container: %s", err)
}
}
execErr := l.Exec(cmd.Context(), ep)
// Check if we are using an OCI-SIF *and* the exec error indicates that a
// direct mount bundle is unavailable (squashfs mount failure etc). If both
// are true, we will try a fallback path extracting to a sandbox dir
// bundle.
var mountErr bndocisif.UnavailableError
if !(errors.As(execErr, &mountErr) && strings.HasPrefix(ep.Image, "oci-sif:")) {
// Any other situation is a failure
return execErr
}
if !canUseTmpSandbox {
sylog.Errorf("%v", execErr)
return fmt.Errorf("OCI-SIF could not be used, and fallback to temporary sandbox dir disallowed")
}
sylog.Warningf("%v", execErr)
sylog.Warningf("OCI-SIF could not be used, falling back to unpacking OCI bundle in temporary sandbox dir")
// Create a cache handle only when we know we are using a URI
imgCache := getCacheHandle(cache.Config{Disable: disableCache})
if imgCache == nil {
sylog.Fatalf("failed to create a new image cache handle")
}
origImageURIPtr := cmd.Context().Value(keyOrigImageURI)
if origImageURIPtr == nil {
return fmt.Errorf("unable to recover original image URI from context")
}
origImageURI, ok := origImageURIPtr.(*string)
if !ok {
return fmt.Errorf("unable to recover original image URI (expected string, found: %T) from context", origImageURIPtr)
}
ep.Image = *origImageURI
return l.Exec(cmd.Context(), ep)
}
|