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
|
// 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 sources
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/containers/image/v5/types"
imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/sylabs/singularity/v4/internal/pkg/cache"
"github.com/sylabs/singularity/v4/internal/pkg/ociimage"
"github.com/sylabs/singularity/v4/internal/pkg/util/shell"
sytypes "github.com/sylabs/singularity/v4/pkg/build/types"
"github.com/sylabs/singularity/v4/pkg/image"
"github.com/sylabs/singularity/v4/pkg/syfs"
"github.com/sylabs/singularity/v4/pkg/sylog"
useragent "github.com/sylabs/singularity/v4/pkg/util/user-agent"
)
type ociRunscriptData struct {
PrependCmd string
PrependEntrypoint string
}
//nolint:dupword
const ociRunscript = `
# When SINGULARITY_NO_EVAL set, use OCI compatible behavior that does
# not evaluate resolved CMD / ENTRYPOINT / ARGS through the shell, and
# does not modify expected quoting behavior of args.
if [ -n "$SINGULARITY_NO_EVAL" ]; then
# ENTRYPOINT only - run entrypoint plus args
if [ -z "$OCI_CMD" ] && [ -n "$OCI_ENTRYPOINT" ]; then
{{.PrependEntrypoint}}
exec "$@"
fi
# CMD only - run CMD or override with args
if [ -n "$OCI_CMD" ] && [ -z "$OCI_ENTRYPOINT" ]; then
if [ $# -eq 0 ]; then
{{.PrependCmd}}
:
fi
exec "$@"
fi
# ENTRYPOINT and CMD - run ENTRYPOINT with CMD as default args
# override with user provided args
if [ $# -gt 0 ]; then
{{.PrependEntrypoint}}
:
else
{{.PrependCmd}}
{{.PrependEntrypoint}}
:
fi
exec "$@"
fi
# Standard Singularity behavior evaluates CMD / ENTRYPOINT / ARGS
# combination through shell before exec, and requires special quoting
# due to concatenation of CMDLINE_ARGS.
CMDLINE_ARGS=""
# prepare command line arguments for evaluation
for arg in "$@"; do
CMDLINE_ARGS="${CMDLINE_ARGS} \"$arg\""
done
# ENTRYPOINT only - run entrypoint plus args
if [ -z "$OCI_CMD" ] && [ -n "$OCI_ENTRYPOINT" ]; then
if [ $# -gt 0 ]; then
SINGULARITY_OCI_RUN="${OCI_ENTRYPOINT} ${CMDLINE_ARGS}"
else
SINGULARITY_OCI_RUN="${OCI_ENTRYPOINT}"
fi
fi
# CMD only - run CMD or override with args
if [ -n "$OCI_CMD" ] && [ -z "$OCI_ENTRYPOINT" ]; then
if [ $# -gt 0 ]; then
SINGULARITY_OCI_RUN="${CMDLINE_ARGS}"
else
SINGULARITY_OCI_RUN="${OCI_CMD}"
fi
fi
# ENTRYPOINT and CMD - run ENTRYPOINT with CMD as default args
# override with user provided args
if [ $# -gt 0 ]; then
SINGULARITY_OCI_RUN="${OCI_ENTRYPOINT} ${CMDLINE_ARGS}"
else
SINGULARITY_OCI_RUN="${OCI_ENTRYPOINT} ${OCI_CMD}"
fi
# Evaluate shell expressions first and set arguments accordingly,
# then execute final command as first container process
eval "set ${SINGULARITY_OCI_RUN}"
exec "$@"
`
// OCIConveyorPacker holds stuff that needs to be packed into the bundle
type OCIConveyorPacker struct {
srcRef types.ImageReference
b *sytypes.Bundle
imgConfig imgspecv1.ImageConfig
sysCtx *types.SystemContext
}
// Get downloads container information from the specified source
func (cp *OCIConveyorPacker) Get(ctx context.Context, b *sytypes.Bundle) (err error) {
cp.b = b
// DockerInsecureSkipTLSVerify is set only if --no-https is specified to honor
// configuration from /etc/containers/registries.conf because DockerInsecureSkipTLSVerify
// can have three possible values true/false and undefined, so we left it as undefined instead
// of forcing it to false in order to delegate decision to /etc/containers/registries.conf:
// https://github.com/sylabs/singularity/issues/5172
cp.sysCtx = &types.SystemContext{
OCIInsecureSkipTLSVerify: cp.b.Opts.NoHTTPS,
DockerAuthConfig: cp.b.Opts.DockerAuthConfig,
DockerDaemonHost: cp.b.Opts.DockerDaemonHost,
AuthFilePath: syfs.DockerConf(),
DockerRegistryUserAgent: useragent.Value(),
BigFilesTemporaryDir: b.TmpDir,
OSChoice: cp.b.Opts.Platform.OS,
ArchitectureChoice: cp.b.Opts.Platform.Architecture,
VariantChoice: cp.b.Opts.Platform.Variant,
}
if cp.b.Opts.NoHTTPS {
cp.sysCtx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(true)
}
// Add registry and namespace to image reference if specified
ref := b.Recipe.Header["from"]
if b.Recipe.Header["namespace"] != "" {
ref = b.Recipe.Header["namespace"] + "/" + ref
}
if b.Recipe.Header["registry"] != "" {
ref = b.Recipe.Header["registry"] + "/" + ref
}
// Docker sources are docker://<from>, not docker:<from>
if b.Recipe.Header["bootstrap"] == "docker" {
ref = "//" + ref
}
// Prefix bootstrap type to image reference
ref = b.Recipe.Header["bootstrap"] + ":" + ref
var imgCache *cache.Handle
if !cp.b.Opts.NoCache {
imgCache = cp.b.Opts.ImgCache
}
// Fetch the image into a temporary containers/image oci layout dir.
cp.srcRef, _, err = ociimage.FetchLayout(ctx, cp.sysCtx, imgCache, ref, b.TmpDir)
if err != nil {
return err
}
cp.imgConfig, err = cp.getConfig(ctx)
if err != nil {
return err
}
return nil
}
// Pack puts relevant objects in a Bundle.
func (cp *OCIConveyorPacker) Pack(ctx context.Context) (*sytypes.Bundle, error) {
err := cp.unpackTmpfs(ctx)
if err != nil {
return nil, fmt.Errorf("while unpacking tmpfs: %v", err)
}
err = cp.insertBaseEnv()
if err != nil {
return nil, fmt.Errorf("while inserting base environment: %v", err)
}
err = cp.insertRunScript()
if err != nil {
return nil, fmt.Errorf("while inserting runscript: %v", err)
}
err = cp.insertEnv()
if err != nil {
return nil, fmt.Errorf("while inserting docker specific environment: %v", err)
}
err = cp.insertOCIConfig()
if err != nil {
return nil, fmt.Errorf("while inserting oci config: %v", err)
}
err = cp.insertOCILabels()
if err != nil {
return nil, fmt.Errorf("while inserting oci labels: %v", err)
}
return cp.b, nil
}
func (cp *OCIConveyorPacker) getConfig(ctx context.Context) (imgspecv1.ImageConfig, error) {
img, err := cp.srcRef.NewImage(ctx, cp.sysCtx)
if err != nil {
return imgspecv1.ImageConfig{}, err
}
defer img.Close()
imgSpec, err := img.OCIConfig(ctx)
if err != nil {
return imgspecv1.ImageConfig{}, err
}
return imgspecv1.ImageConfig(imgSpec.Config), nil
}
func (cp *OCIConveyorPacker) insertOCIConfig() error {
conf, err := json.Marshal(cp.imgConfig)
if err != nil {
return err
}
cp.b.JSONObjects[image.SIFDescOCIConfigJSON] = conf
return nil
}
func (cp *OCIConveyorPacker) unpackTmpfs(ctx context.Context) error {
imageSource, err := cp.srcRef.NewImageSource(ctx, cp.sysCtx)
if err != nil {
return fmt.Errorf("error creating image source: %s", err)
}
manifestData, mediaType, err := imageSource.GetManifest(ctx, nil)
if err != nil {
return fmt.Errorf("error obtaining manifest source: %s", err)
}
if mediaType != imgspecv1.MediaTypeImageManifest {
return fmt.Errorf("error verifying manifest media type: %s", mediaType)
}
var manifest imgspecv1.Manifest
json.Unmarshal(manifestData, &manifest)
if err := ociimage.UnpackRootfs(ctx, cp.b.TmpDir, manifest, cp.b.RootfsPath); err != nil {
return err
}
// If the `--fix-perms` flag was used, then modify the permissions so that
// content has owner rwX and we're done
if cp.b.Opts.FixPerms {
sylog.Warningf("The --fix-perms option modifies the filesystem permissions on the resulting container.")
sylog.Debugf("Modifying permissions for file/directory owners")
return ociimage.FixPerms(cp.b.RootfsPath)
}
// If `--fix-perms` was not used and this is a sandbox, scan for restrictive
// perms that would stop the user doing an `rm` without a chmod first,
// and warn if they exist
if cp.b.Opts.SandboxTarget {
sylog.Debugf("Scanning for restrictive permissions")
return ociimage.CheckPerms(cp.b.RootfsPath)
}
return nil
}
func (cp *OCIConveyorPacker) insertBaseEnv() (err error) {
if err = makeBaseEnv(cp.b.RootfsPath); err != nil {
sylog.Errorf("%v", err)
}
return
}
func (cp *OCIConveyorPacker) insertRunScript() error {
f, err := os.Create(cp.b.RootfsPath + "/.singularity.d/runscript")
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString("#!/bin/sh\n")
if err != nil {
return err
}
if len(cp.imgConfig.Entrypoint) > 0 {
_, err = f.WriteString("OCI_ENTRYPOINT='" +
shell.EscapeSingleQuotes(shell.ArgsQuoted(cp.imgConfig.Entrypoint)) +
"'\n")
if err != nil {
return err
}
} else {
_, err = f.WriteString("OCI_ENTRYPOINT=''\n")
if err != nil {
return err
}
}
if len(cp.imgConfig.Cmd) > 0 {
_, err = f.WriteString("OCI_CMD='" +
shell.EscapeSingleQuotes(shell.ArgsQuoted(cp.imgConfig.Cmd)) +
"'\n")
if err != nil {
return err
}
} else {
_, err = f.WriteString("OCI_CMD=''\n")
if err != nil {
return err
}
}
// prependCmd is a set of shell commands necessary to prepend each CMD entry to $@
prependCmd := ""
for i := len(cp.imgConfig.Cmd) - 1; i >= 0; i-- {
prependCmd = prependCmd + fmt.Sprintf("set -- '%s' \"$@\"\n", shell.EscapeSingleQuotes(cp.imgConfig.Cmd[i]))
}
// prependCmd is a set of shell commands necessary to prepend each ENTRYPOINT entry to $@
prependEP := ""
for i := len(cp.imgConfig.Entrypoint) - 1; i >= 0; i-- {
prependEP = prependEP + fmt.Sprintf("set -- '%s' \"$@\"\n", shell.EscapeSingleQuotes(cp.imgConfig.Entrypoint[i]))
}
data := ociRunscriptData{
PrependCmd: prependCmd,
PrependEntrypoint: prependEP,
}
tmpl, err := template.New("runscript").Parse(ociRunscript)
if err != nil {
return fmt.Errorf("while parsing runscript template: %w", err)
}
var runscript bytes.Buffer
err = tmpl.Execute(&runscript, data)
if err != nil {
return fmt.Errorf("while generating runscript template: %w", err)
}
_, err = f.WriteString(runscript.String())
if err != nil {
return err
}
f.Sync()
err = os.Chmod(cp.b.RootfsPath+"/.singularity.d/runscript", 0o755)
if err != nil {
return err
}
return nil
}
func (cp *OCIConveyorPacker) insertEnv() error {
f, err := os.Create(cp.b.RootfsPath + "/.singularity.d/env/10-docker2singularity.sh")
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString("#!/bin/sh\n")
if err != nil {
return err
}
for _, element := range cp.imgConfig.Env {
export := ""
envParts := strings.SplitN(element, "=", 2)
if len(envParts) == 1 {
export = fmt.Sprintf("export %s=\"${%s:-}\"\n", envParts[0], envParts[0])
} else {
if envParts[0] == "PATH" {
export = fmt.Sprintf("export %s=%q\n", envParts[0], shell.Escape(envParts[1]))
} else {
export = fmt.Sprintf("export %s=\"${%s:-%q}\"\n", envParts[0], envParts[0], shell.Escape(envParts[1]))
}
}
_, err = f.WriteString(export)
if err != nil {
return err
}
}
f.Sync()
err = os.Chmod(cp.b.RootfsPath+"/.singularity.d/env/10-docker2singularity.sh", 0o755)
if err != nil {
return err
}
return nil
}
func (cp *OCIConveyorPacker) insertOCILabels() (err error) {
labels := cp.imgConfig.Labels
var text []byte
// make new map into json
text, err = json.MarshalIndent(labels, "", "\t")
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(cp.b.RootfsPath, "/.singularity.d/labels.json"), []byte(text), 0o644)
return err
}
// CleanUp removes any tmpfs owned by the conveyorPacker on the filesystem
func (cp *OCIConveyorPacker) CleanUp() {
cp.b.Remove()
}
|