1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
26 "git.arvados.org/arvados.git/sdk/go/arvados"
29 type singularityExecutor struct {
30 logf func(string, ...interface{})
31 sudo bool // use sudo to run singularity (only used by tests)
35 imageFilename string // "sif" image
38 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
39 tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
43 return &singularityExecutor{
49 func (e *singularityExecutor) Runtime() string {
50 buf, err := exec.Command("singularity", "--version").CombinedOutput()
52 return "singularity (unknown version)"
54 return strings.TrimSuffix(string(buf), "\n")
57 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
58 var gp arvados.GroupList
59 err := containerClient.RequestAndDecode(&gp,
60 arvados.EndpointGroupList.Method,
61 arvados.EndpointGroupList.Path,
62 nil, arvados.ListOptions{Filters: []arvados.Filter{
63 arvados.Filter{"owner_uuid", "=", ownerUuid},
64 arvados.Filter{"name", "=", name},
65 arvados.Filter{"group_class", "=", "project"},
71 if len(gp.Items) == 1 {
72 return &gp.Items[0], nil
75 var rgroup arvados.Group
76 err = containerClient.RequestAndDecode(&rgroup,
77 arvados.EndpointGroupCreate.Method,
78 arvados.EndpointGroupCreate.Path,
79 nil, map[string]interface{}{
80 "group": map[string]string{
81 "owner_uuid": ownerUuid,
83 "group_class": "project",
92 func (e *singularityExecutor) getImageCacheProject(userUUID string, containerClient *arvados.Client) (*arvados.Group, error) {
93 cacheProject, err := e.getOrCreateProject(userUUID, ".cache", containerClient)
95 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
97 imageProject, err := e.getOrCreateProject(cacheProject.UUID, "auto-generated singularity images", containerClient)
99 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
101 return imageProject, nil
104 func (e *singularityExecutor) imageCacheExp() time.Time {
105 return time.Now().Add(e.imageCacheTTL()).UTC()
108 func (e *singularityExecutor) imageCacheTTL() time.Duration {
109 return 24 * 7 * 2 * time.Hour
112 // getCacheCollection returns an existing collection with a cached
113 // singularity image with the given name, or nil if none exists.
115 // Note that if there is no existing collection, this is not
116 // considered an error -- all return values will be nil/empty.
117 func (e *singularityExecutor) getCacheCollection(collectionName string, containerClient *arvados.Client, cacheProject *arvados.Group, arvMountPoint string) (collection *arvados.Collection, imageFile string, err error) {
118 var cl arvados.CollectionList
119 err = containerClient.RequestAndDecode(&cl,
120 arvados.EndpointCollectionList.Method,
121 arvados.EndpointCollectionList.Path,
122 nil, arvados.ListOptions{Filters: []arvados.Filter{
123 arvados.Filter{"owner_uuid", "=", cacheProject.UUID},
124 arvados.Filter{"name", "=", collectionName},
128 return nil, "", fmt.Errorf("error querying for collection %q in project %s: %w", collectionName, cacheProject.UUID, err)
130 if len(cl.Items) == 0 {
131 // Successfully discovered that there's no cached
135 // Check that the collection actually contains an "image.sif"
136 // file. If not, we can't use it, and trying to create a new
137 // cache collection will probably fail too, so the caller
138 // should not bother trying.
140 sifFile := path.Join(arvMountPoint, "by_id", coll.PortableDataHash, "image.sif")
141 _, err = os.Stat(sifFile)
143 return nil, "", fmt.Errorf("found collection %s (%s), but it did not contain an image file: %s", coll.UUID, coll.PortableDataHash, err)
145 if coll.TrashAt != nil && coll.TrashAt.Sub(time.Now()) < e.imageCacheTTL()*9/10 {
146 // If the remaining TTL is less than 90% of our target
147 // TTL, extend trash_at. This avoids prematurely
148 // trashing and re-converting images that are being
150 err = containerClient.RequestAndDecode(nil,
151 arvados.EndpointCollectionUpdate.Method,
152 "arvados/v1/collections/"+coll.UUID,
153 nil, map[string]interface{}{
154 "collection": map[string]string{
155 "trash_at": e.imageCacheExp().Format(time.RFC3339),
159 e.logf("could not update expiry time of cached image collection (proceeding anyway): %s", err)
162 return &coll, sifFile, nil
165 func (e *singularityExecutor) createCacheCollection(collectionName string, containerClient *arvados.Client, cacheProject *arvados.Group) (*arvados.Collection, error) {
166 var coll arvados.Collection
167 err := containerClient.RequestAndDecode(&coll,
168 arvados.EndpointCollectionCreate.Method,
169 arvados.EndpointCollectionCreate.Path,
170 nil, map[string]interface{}{
171 "collection": map[string]string{
172 "owner_uuid": cacheProject.UUID,
173 "name": collectionName,
174 "trash_at": e.imageCacheExp().Format(time.RFC3339),
176 "ensure_unique_name": true,
179 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
184 func (e *singularityExecutor) convertDockerImage(srcPath, dstPath string) error {
185 // Make sure the docker image is readable.
186 if _, err := os.Stat(srcPath); err != nil {
190 e.logf("building singularity image")
191 // "singularity build" does not accept a
192 // docker-archive://... filename containing a ":" character,
193 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
194 // symlink that doesn't have ":" chars.
195 err := os.Symlink(srcPath, e.tmpdir+"/image.tar")
200 // Set up a cache and tmp dir for singularity build
201 err = os.Mkdir(e.tmpdir+"/cache", 0700)
205 defer os.RemoveAll(e.tmpdir + "/cache")
206 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
210 defer os.RemoveAll(e.tmpdir + "/tmp")
212 build := exec.Command("singularity", "build", dstPath, "docker-archive://"+e.tmpdir+"/image.tar")
213 build.Env = os.Environ()
214 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
215 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
216 e.logf("%v", build.Args)
217 out, err := build.CombinedOutput()
218 // INFO: Starting build...
219 // Getting image source signatures
220 // Copying blob ab15617702de done
221 // Copying config 651e02b8a2 done
222 // Writing manifest to image destination
223 // Storing signatures
224 // 2021/04/22 14:42:14 info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
225 // INFO: Creating SIF file...
226 // INFO: Build complete: arvados-jobs.latest.sif
231 // LoadImage converts the given docker image to a singularity
234 // If containerClient is not nil, LoadImage first tries to use an
235 // existing image (in Home -> .cache -> auto-generated singularity
236 // images) and, if none was found there and the image was converted on
237 // the fly, tries to save the converted image to the cache so it can
238 // be reused next time.
240 // If containerClient is nil or a cache project/collection cannot be
241 // found or created, LoadImage converts the image on the fly and
242 // writes it to the local filesystem instead.
243 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string, containerClient *arvados.Client) error {
244 convertWithoutCache := func(err error) error {
246 e.logf("cannot use singularity image cache: %s", err)
248 e.imageFilename = path.Join(e.tmpdir, "image.sif")
249 return e.convertDockerImage(imageTarballPath, e.imageFilename)
252 if containerClient == nil {
253 return convertWithoutCache(nil)
255 cacheProject, err := e.getImageCacheProject(container.RuntimeUserUUID, containerClient)
257 return convertWithoutCache(err)
259 cacheCollectionName := fmt.Sprintf("singularity image for %s", dockerImageID)
260 existingCollection, sifFile, err := e.getCacheCollection(cacheCollectionName, containerClient, cacheProject, arvMountPoint)
262 return convertWithoutCache(err)
264 if existingCollection != nil {
265 e.imageFilename = sifFile
269 newCollection, err := e.createCacheCollection("converting "+cacheCollectionName, containerClient, cacheProject)
271 return convertWithoutCache(err)
273 dstDir := path.Join(arvMountPoint, "by_uuid", newCollection.UUID)
274 dstFile := path.Join(dstDir, "image.sif")
275 err = e.convertDockerImage(imageTarballPath, dstFile)
279 buf, err := os.ReadFile(path.Join(dstDir, ".arvados#collection"))
281 return fmt.Errorf("could not sync image collection: %w", err)
283 var synced arvados.Collection
284 err = json.Unmarshal(buf, &synced)
286 return fmt.Errorf("could not parse .arvados#collection: %w", err)
288 e.logf("saved converted image in %s with PDH %s", newCollection.UUID, synced.PortableDataHash)
289 e.imageFilename = path.Join(arvMountPoint, "by_id", synced.PortableDataHash, "image.sif")
291 if errRename := containerClient.RequestAndDecode(nil,
292 arvados.EndpointCollectionUpdate.Method,
293 "arvados/v1/collections/"+newCollection.UUID,
294 nil, map[string]interface{}{
295 "collection": map[string]string{
296 "name": cacheCollectionName,
298 }); errRename != nil {
299 // Error is probably a name collision caused by
300 // another crunch-run process is converting the same
301 // image concurrently. In that case, we prefer to use
302 // the one that won the race -- the resulting images
303 // should be equivalent, but if they do differ at all,
304 // it's better if all containers use the same
306 if existingCollection, sifFile, err := e.getCacheCollection(cacheCollectionName, containerClient, cacheProject, arvMountPoint); err == nil {
307 e.logf("lost race -- abandoning our conversion in %s (%s) and using image from %s (%s) instead", newCollection.UUID, synced.PortableDataHash, existingCollection.UUID, existingCollection.PortableDataHash)
308 e.imageFilename = sifFile
310 e.logf("using newly converted image anyway, despite error renaming collection: %v", errRename)
316 func (e *singularityExecutor) Create(spec containerSpec) error {
321 func (e *singularityExecutor) execCmd(path string) *exec.Cmd {
322 args := []string{path, "exec", "--containall", "--cleanenv", "--pwd=" + e.spec.WorkingDir}
323 if !e.spec.EnableNetwork {
324 args = append(args, "--net", "--network=none")
325 } else if u, err := user.Current(); err == nil && u.Uid == "0" || e.sudo {
326 // Specifying --network=bridge fails unless
327 // singularity is running as root.
329 // Note this used to be possible with --fakeroot, or
330 // configuring singularity like so:
332 // singularity config global --set 'allow net networks' bridge
333 // singularity config global --set 'allow net groups' mygroup
335 // However, these options no longer work (as of debian
336 // bookworm) because iptables now refuses to run in a
337 // setuid environment.
338 args = append(args, "--net", "--network=bridge")
340 // If we don't pass a --net argument at all, the
341 // container will be in the same network namespace as
344 // Note this allows the container to listen on the
345 // host's external ports.
347 if e.spec.GPUStack == "cuda" && e.spec.GPUDeviceCount > 0 {
348 args = append(args, "--nv")
350 if e.spec.GPUStack == "rocm" && e.spec.GPUDeviceCount > 0 {
351 args = append(args, "--rocm")
354 // If we ask for resource limits that aren't supported,
355 // singularity will not run the container at all. So we probe
356 // for support first, and only apply the limits that appear to
359 // Default debian configuration lets non-root users set memory
360 // limits but not CPU limits, so we enable/disable those
361 // limits independently.
363 // https://rootlesscontaine.rs/getting-started/common/cgroup2/
364 checkCgroupSupport(e.logf)
365 if e.spec.VCPUs > 0 {
366 if cgroupSupport["cpu"] {
367 args = append(args, "--cpus", fmt.Sprintf("%d", e.spec.VCPUs))
369 e.logf("cpu limits are not supported by current systemd/cgroup configuration, not setting --cpu %d", e.spec.VCPUs)
373 if cgroupSupport["memory"] {
374 args = append(args, "--memory", fmt.Sprintf("%d", e.spec.RAM))
376 e.logf("memory limits are not supported by current systemd/cgroup configuration, not setting --memory %d", e.spec.RAM)
380 readonlyflag := map[bool]string{
385 for path, _ := range e.spec.BindMounts {
386 binds = append(binds, path)
389 for _, path := range binds {
390 mount := e.spec.BindMounts[path]
391 if path == e.spec.Env["HOME"] {
392 // Singularity treats $HOME as special case
393 args = append(args, "--home", mount.HostPath+":"+path)
395 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
399 // This is for singularity 3.5.2. There are some behaviors
400 // that will change in singularity 3.6, please see:
401 // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
402 // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
403 env := make([]string, 0, len(e.spec.Env))
404 for k, v := range e.spec.Env {
406 // Singularity treats $HOME as special case,
407 // this is handled with --home above
410 env = append(env, "SINGULARITYENV_"+k+"="+v)
413 // Singularity always makes all nvidia devices visible to the
414 // container. If a resource manager such as slurm or LSF told
415 // us to select specific devices we need to propagate that.
416 if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
417 // If a resource manager such as slurm or LSF told
418 // us to select specific devices we need to propagate that.
419 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
421 // Singularity's default behavior is to evaluate each
422 // SINGULARITYENV_* env var with a shell as a double-quoted
423 // string and pass the result to the contained
424 // process. Singularity 3.10+ has an option to pass env vars
425 // through literally without evaluating, which is what we
426 // want. See https://github.com/sylabs/singularity/pull/704
427 // and https://dev.arvados.org/issues/19081
428 env = append(env, "SINGULARITY_NO_EVAL=1")
430 // If we don't propagate XDG_RUNTIME_DIR and
431 // DBUS_SESSION_BUS_ADDRESS, singularity resource limits fail
432 // with "FATAL: container creation failed: while applying
433 // cgroups config: system configuration does not support
434 // cgroup management" or "FATAL: container creation failed:
435 // while applying cgroups config: rootless cgroups require a
436 // D-Bus session - check that XDG_RUNTIME_DIR and
437 // DBUS_SESSION_BUS_ADDRESS are set".
438 env = append(env, "XDG_RUNTIME_DIR="+os.Getenv("XDG_RUNTIME_DIR"))
439 env = append(env, "DBUS_SESSION_BUS_ADDRESS="+os.Getenv("DBUS_SESSION_BUS_ADDRESS"))
441 args = append(args, e.imageFilename)
442 args = append(args, e.spec.Command...)
449 Stdout: e.spec.Stdout,
450 Stderr: e.spec.Stderr,
454 func (e *singularityExecutor) Start() error {
455 path, err := exec.LookPath("singularity")
459 child := e.execCmd(path)
461 child.Args = append([]string{child.Path}, child.Args...)
462 child.Path, err = exec.LookPath("sudo")
475 func (e *singularityExecutor) Pid() int {
476 childproc, err := e.containedProcess()
483 func (e *singularityExecutor) Stop() error {
484 if e.child == nil || e.child.Process == nil {
485 // no process started, or Wait already called
488 if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
489 // process already exited
492 return e.child.Process.Signal(syscall.SIGKILL)
495 func (e *singularityExecutor) Wait(context.Context) (int, error) {
496 err := e.child.Wait()
497 if err, ok := err.(*exec.ExitError); ok {
498 return err.ProcessState.ExitCode(), nil
503 return e.child.ProcessState.ExitCode(), nil
506 func (e *singularityExecutor) Close() {
507 err := os.RemoveAll(e.tmpdir)
509 e.logf("error removing temp dir: %s", err)
513 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
514 target, err := e.containedProcess()
518 return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
522 errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
525 func (e *singularityExecutor) IPAddress() (string, error) {
526 target, err := e.containedProcess()
530 targetIPs, err := processIPs(target)
534 selfIPs, err := processIPs(os.Getpid())
538 for ip := range targetIPs {
543 return "", errContainerHasNoIPAddress
546 func processIPs(pid int) (map[string]bool, error) {
547 fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
552 addrs := map[string]bool{}
553 // When we see a pair of lines like this:
558 // ...we set addrs["10.1.2.3"] = true
559 lines := bytes.Split(fibtrie, []byte{'\n'})
560 for linenumber, line := range lines {
561 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
567 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
568 if i < 0 || i >= len(line)-7 {
571 addr := string(lines[linenumber-1][i+1:])
572 if net.ParseIP(addr).To4() != nil {
580 errContainerNotStarted = errors.New("container has not started yet")
581 errCannotFindChild = errors.New("failed to find any process inside the container")
582 reProcStatusPPid = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
585 // Return the PID of a process that is inside the container (not
586 // necessarily the topmost/pid=1 process in the container).
587 func (e *singularityExecutor) containedProcess() (int, error) {
588 if e.child == nil || e.child.Process == nil {
589 return 0, errContainerNotStarted
591 cmd := exec.Command("lsns")
593 cmd = exec.Command("sudo", "lsns")
595 lsns, err := cmd.CombinedOutput()
597 return 0, fmt.Errorf("lsns: %w", err)
599 for _, line := range bytes.Split(lsns, []byte{'\n'}) {
600 fields := bytes.Fields(line)
604 if !bytes.Equal(fields[1], []byte("pid")) {
607 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
609 return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
611 for parent := pid; ; {
612 procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
616 m := reProcStatusPPid.FindSubmatch(procstatus)
620 parent, err = strconv.ParseInt(string(m[1]), 10, 64)
624 if int(parent) == e.child.Process.Pid {
629 return 0, errCannotFindChild