17816: Set the current working directory in the singularity container
[arvados.git] / lib / crunchrun / singularity.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package crunchrun
6
7 import (
8         "io/ioutil"
9         "os"
10         "os/exec"
11         "syscall"
12
13         "golang.org/x/net/context"
14 )
15
16 type singularityExecutor struct {
17         logf          func(string, ...interface{})
18         spec          containerSpec
19         tmpdir        string
20         child         *exec.Cmd
21         imageFilename string // "sif" image
22 }
23
24 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
25         tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
26         if err != nil {
27                 return nil, err
28         }
29         return &singularityExecutor{
30                 logf:   logf,
31                 tmpdir: tmpdir,
32         }, nil
33 }
34
35 func (e *singularityExecutor) ImageLoaded(string) bool {
36         return false
37 }
38
39 // LoadImage will satisfy ContainerExecuter interface transforming
40 // containerImage into a sif file for later use.
41 func (e *singularityExecutor) LoadImage(imageTarballPath string) error {
42         e.logf("building singularity image")
43         // "singularity build" does not accept a
44         // docker-archive://... filename containing a ":" character,
45         // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
46         // symlink that doesn't have ":" chars.
47         err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
48         if err != nil {
49                 return err
50         }
51         e.imageFilename = e.tmpdir + "/image.sif"
52         build := exec.Command("singularity", "build", e.imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
53         e.logf("%v", build.Args)
54         out, err := build.CombinedOutput()
55         // INFO:    Starting build...
56         // Getting image source signatures
57         // Copying blob ab15617702de done
58         // Copying config 651e02b8a2 done
59         // Writing manifest to image destination
60         // Storing signatures
61         // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
62         // INFO:    Creating SIF file...
63         // INFO:    Build complete: arvados-jobs.latest.sif
64         e.logf("%s", out)
65         if err != nil {
66                 return err
67         }
68         return nil
69 }
70
71 func (e *singularityExecutor) Create(spec containerSpec) error {
72         e.spec = spec
73         return nil
74 }
75
76 func (e *singularityExecutor) Start() error {
77         args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv", "--pwd", e.spec.WorkingDir}
78         if !e.spec.EnableNetwork {
79                 args = append(args, "--net", "--network=none")
80         }
81         readonlyflag := map[bool]string{
82                 false: "rw",
83                 true:  "ro",
84         }
85         for path, mount := range e.spec.BindMounts {
86                 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
87         }
88         args = append(args, e.imageFilename)
89         args = append(args, e.spec.Command...)
90
91         // This is for singularity 3.5.2. There are some behaviors
92         // that will change in singularity 3.6, please see:
93         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
94         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
95         env := make([]string, 0, len(e.spec.Env))
96         for k, v := range e.spec.Env {
97                 env = append(env, "SINGULARITYENV_"+k+"="+v)
98         }
99
100         path, err := exec.LookPath(args[0])
101         if err != nil {
102                 return err
103         }
104         child := &exec.Cmd{
105                 Path:   path,
106                 Args:   args,
107                 Env:    env,
108                 Stdin:  e.spec.Stdin,
109                 Stdout: e.spec.Stdout,
110                 Stderr: e.spec.Stderr,
111         }
112         err = child.Start()
113         if err != nil {
114                 return err
115         }
116         e.child = child
117         return nil
118 }
119
120 func (e *singularityExecutor) CgroupID() string {
121         return ""
122 }
123
124 func (e *singularityExecutor) Stop() error {
125         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
126                 // process already exited
127                 return nil
128         }
129         return e.child.Process.Signal(syscall.SIGKILL)
130 }
131
132 func (e *singularityExecutor) Wait(context.Context) (int, error) {
133         err := e.child.Wait()
134         if err, ok := err.(*exec.ExitError); ok {
135                 return err.ProcessState.ExitCode(), nil
136         }
137         if err != nil {
138                 return 0, err
139         }
140         return e.child.ProcessState.ExitCode(), nil
141 }
142
143 func (e *singularityExecutor) Close() {
144         err := os.RemoveAll(e.tmpdir)
145         if err != nil {
146                 e.logf("error removing temp dir: %s", err)
147         }
148 }