Merge branch '19099-singularity-container-shell'
[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         "bytes"
9         "errors"
10         "fmt"
11         "io/ioutil"
12         "net"
13         "os"
14         "os/exec"
15         "os/user"
16         "regexp"
17         "sort"
18         "strconv"
19         "strings"
20         "syscall"
21         "time"
22
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "golang.org/x/net/context"
25 )
26
27 type singularityExecutor struct {
28         logf          func(string, ...interface{})
29         fakeroot      bool // use --fakeroot flag, allow --network=bridge when non-root (currently only used by tests)
30         spec          containerSpec
31         tmpdir        string
32         child         *exec.Cmd
33         imageFilename string // "sif" image
34 }
35
36 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
37         tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
38         if err != nil {
39                 return nil, err
40         }
41         return &singularityExecutor{
42                 logf:   logf,
43                 tmpdir: tmpdir,
44         }, nil
45 }
46
47 func (e *singularityExecutor) Runtime() string {
48         buf, err := exec.Command("singularity", "--version").CombinedOutput()
49         if err != nil {
50                 return "singularity (unknown version)"
51         }
52         return strings.TrimSuffix(string(buf), "\n")
53 }
54
55 func (e *singularityExecutor) getOrCreateProject(ownerUuid string, name string, containerClient *arvados.Client) (*arvados.Group, error) {
56         var gp arvados.GroupList
57         err := containerClient.RequestAndDecode(&gp,
58                 arvados.EndpointGroupList.Method,
59                 arvados.EndpointGroupList.Path,
60                 nil, arvados.ListOptions{Filters: []arvados.Filter{
61                         arvados.Filter{"owner_uuid", "=", ownerUuid},
62                         arvados.Filter{"name", "=", name},
63                         arvados.Filter{"group_class", "=", "project"},
64                 },
65                         Limit: 1})
66         if err != nil {
67                 return nil, err
68         }
69         if len(gp.Items) == 1 {
70                 return &gp.Items[0], nil
71         }
72
73         var rgroup arvados.Group
74         err = containerClient.RequestAndDecode(&rgroup,
75                 arvados.EndpointGroupCreate.Method,
76                 arvados.EndpointGroupCreate.Path,
77                 nil, map[string]interface{}{
78                         "group": map[string]string{
79                                 "owner_uuid":  ownerUuid,
80                                 "name":        name,
81                                 "group_class": "project",
82                         },
83                 })
84         if err != nil {
85                 return nil, err
86         }
87         return &rgroup, nil
88 }
89
90 func (e *singularityExecutor) checkImageCache(dockerImageID string, container arvados.Container, arvMountPoint string,
91         containerClient *arvados.Client) (collection *arvados.Collection, err error) {
92
93         // Cache the image to keep
94         cacheGroup, err := e.getOrCreateProject(container.RuntimeUserUUID, ".cache", containerClient)
95         if err != nil {
96                 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
97         }
98         imageGroup, err := e.getOrCreateProject(cacheGroup.UUID, "auto-generated singularity images", containerClient)
99         if err != nil {
100                 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
101         }
102
103         collectionName := fmt.Sprintf("singularity image for %v", dockerImageID)
104         var cl arvados.CollectionList
105         err = containerClient.RequestAndDecode(&cl,
106                 arvados.EndpointCollectionList.Method,
107                 arvados.EndpointCollectionList.Path,
108                 nil, arvados.ListOptions{Filters: []arvados.Filter{
109                         arvados.Filter{"owner_uuid", "=", imageGroup.UUID},
110                         arvados.Filter{"name", "=", collectionName},
111                 },
112                         Limit: 1})
113         if err != nil {
114                 return nil, fmt.Errorf("error querying for collection '%v': %v", collectionName, err)
115         }
116         var imageCollection arvados.Collection
117         if len(cl.Items) == 1 {
118                 imageCollection = cl.Items[0]
119         } else {
120                 collectionName := "converting " + collectionName
121                 exp := time.Now().Add(24 * 7 * 2 * time.Hour)
122                 err = containerClient.RequestAndDecode(&imageCollection,
123                         arvados.EndpointCollectionCreate.Method,
124                         arvados.EndpointCollectionCreate.Path,
125                         nil, map[string]interface{}{
126                                 "collection": map[string]string{
127                                         "owner_uuid": imageGroup.UUID,
128                                         "name":       collectionName,
129                                         "trash_at":   exp.UTC().Format(time.RFC3339),
130                                 },
131                                 "ensure_unique_name": true,
132                         })
133                 if err != nil {
134                         return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
135                 }
136
137         }
138
139         return &imageCollection, nil
140 }
141
142 // LoadImage will satisfy ContainerExecuter interface transforming
143 // containerImage into a sif file for later use.
144 func (e *singularityExecutor) LoadImage(dockerImageID string, imageTarballPath string, container arvados.Container, arvMountPoint string,
145         containerClient *arvados.Client) error {
146
147         var imageFilename string
148         var sifCollection *arvados.Collection
149         var err error
150         if containerClient != nil {
151                 sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
152                 if err != nil {
153                         return err
154                 }
155                 imageFilename = fmt.Sprintf("%s/by_uuid/%s/image.sif", arvMountPoint, sifCollection.UUID)
156         } else {
157                 imageFilename = e.tmpdir + "/image.sif"
158         }
159
160         if _, err := os.Stat(imageFilename); os.IsNotExist(err) {
161                 // Make sure the docker image is readable, and error
162                 // out if not.
163                 if _, err := os.Stat(imageTarballPath); err != nil {
164                         return err
165                 }
166
167                 e.logf("building singularity image")
168                 // "singularity build" does not accept a
169                 // docker-archive://... filename containing a ":" character,
170                 // as in "/path/to/sha256:abcd...1234.tar". Workaround: make a
171                 // symlink that doesn't have ":" chars.
172                 err := os.Symlink(imageTarballPath, e.tmpdir+"/image.tar")
173                 if err != nil {
174                         return err
175                 }
176
177                 // Set up a cache and tmp dir for singularity build
178                 err = os.Mkdir(e.tmpdir+"/cache", 0700)
179                 if err != nil {
180                         return err
181                 }
182                 defer os.RemoveAll(e.tmpdir + "/cache")
183                 err = os.Mkdir(e.tmpdir+"/tmp", 0700)
184                 if err != nil {
185                         return err
186                 }
187                 defer os.RemoveAll(e.tmpdir + "/tmp")
188
189                 build := exec.Command("singularity", "build", imageFilename, "docker-archive://"+e.tmpdir+"/image.tar")
190                 build.Env = os.Environ()
191                 build.Env = append(build.Env, "SINGULARITY_CACHEDIR="+e.tmpdir+"/cache")
192                 build.Env = append(build.Env, "SINGULARITY_TMPDIR="+e.tmpdir+"/tmp")
193                 e.logf("%v", build.Args)
194                 out, err := build.CombinedOutput()
195                 // INFO:    Starting build...
196                 // Getting image source signatures
197                 // Copying blob ab15617702de done
198                 // Copying config 651e02b8a2 done
199                 // Writing manifest to image destination
200                 // Storing signatures
201                 // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
202                 // INFO:    Creating SIF file...
203                 // INFO:    Build complete: arvados-jobs.latest.sif
204                 e.logf("%s", out)
205                 if err != nil {
206                         return err
207                 }
208         }
209
210         if containerClient == nil {
211                 e.imageFilename = imageFilename
212                 return nil
213         }
214
215         // update TTL to now + two weeks
216         exp := time.Now().Add(24 * 7 * 2 * time.Hour)
217
218         uuidPath, err := containerClient.PathForUUID("update", sifCollection.UUID)
219         if err != nil {
220                 e.logf("error PathForUUID: %v", err)
221                 return nil
222         }
223         var imageCollection arvados.Collection
224         err = containerClient.RequestAndDecode(&imageCollection,
225                 arvados.EndpointCollectionUpdate.Method,
226                 uuidPath,
227                 nil, map[string]interface{}{
228                         "collection": map[string]string{
229                                 "name":     fmt.Sprintf("singularity image for %v", dockerImageID),
230                                 "trash_at": exp.UTC().Format(time.RFC3339),
231                         },
232                 })
233         if err == nil {
234                 // If we just wrote the image to the cache, the
235                 // response also returns the updated PDH
236                 e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, imageCollection.PortableDataHash)
237                 return nil
238         }
239
240         e.logf("error updating/renaming collection for cached sif image: %v", err)
241         // Failed to update but maybe it lost a race and there is
242         // another cached collection in the same place, so check the cache
243         // again
244         sifCollection, err = e.checkImageCache(dockerImageID, container, arvMountPoint, containerClient)
245         if err != nil {
246                 return err
247         }
248         e.imageFilename = fmt.Sprintf("%s/by_id/%s/image.sif", arvMountPoint, sifCollection.PortableDataHash)
249
250         return nil
251 }
252
253 func (e *singularityExecutor) Create(spec containerSpec) error {
254         e.spec = spec
255         return nil
256 }
257
258 func (e *singularityExecutor) execCmd(path string) *exec.Cmd {
259         args := []string{path, "exec", "--containall", "--cleanenv", "--pwd=" + e.spec.WorkingDir}
260         if e.fakeroot {
261                 args = append(args, "--fakeroot")
262         }
263         if !e.spec.EnableNetwork {
264                 args = append(args, "--net", "--network=none")
265         } else if u, err := user.Current(); err == nil && u.Uid == "0" || e.fakeroot {
266                 // Specifying --network=bridge fails unless (a) we are
267                 // root, (b) we are using --fakeroot, or (c)
268                 // singularity has been configured to allow our
269                 // uid/gid to use it like so:
270                 //
271                 // singularity config global --set 'allow net networks' bridge
272                 // singularity config global --set 'allow net groups' mygroup
273                 args = append(args, "--net", "--network=bridge")
274         }
275         if e.spec.CUDADeviceCount != 0 {
276                 args = append(args, "--nv")
277         }
278
279         readonlyflag := map[bool]string{
280                 false: "rw",
281                 true:  "ro",
282         }
283         var binds []string
284         for path, _ := range e.spec.BindMounts {
285                 binds = append(binds, path)
286         }
287         sort.Strings(binds)
288         for _, path := range binds {
289                 mount := e.spec.BindMounts[path]
290                 if path == e.spec.Env["HOME"] {
291                         // Singularity treats $HOME as special case
292                         args = append(args, "--home", mount.HostPath+":"+path)
293                 } else {
294                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
295                 }
296         }
297
298         // This is for singularity 3.5.2. There are some behaviors
299         // that will change in singularity 3.6, please see:
300         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
301         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
302         env := make([]string, 0, len(e.spec.Env))
303         for k, v := range e.spec.Env {
304                 if k == "HOME" {
305                         // Singularity treats $HOME as special case,
306                         // this is handled with --home above
307                         continue
308                 }
309                 env = append(env, "SINGULARITYENV_"+k+"="+v)
310         }
311
312         // Singularity always makes all nvidia devices visible to the
313         // container.  If a resource manager such as slurm or LSF told
314         // us to select specific devices we need to propagate that.
315         if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
316                 // If a resource manager such as slurm or LSF told
317                 // us to select specific devices we need to propagate that.
318                 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
319         }
320         // Singularity's default behavior is to evaluate each
321         // SINGULARITYENV_* env var with a shell as a double-quoted
322         // string and pass the result to the contained
323         // process. Singularity 3.10+ has an option to pass env vars
324         // through literally without evaluating, which is what we
325         // want. See https://github.com/sylabs/singularity/pull/704
326         // and https://dev.arvados.org/issues/19081
327         env = append(env, "SINGULARITY_NO_EVAL=1")
328
329         args = append(args, e.imageFilename)
330         args = append(args, e.spec.Command...)
331
332         return &exec.Cmd{
333                 Path:   path,
334                 Args:   args,
335                 Env:    env,
336                 Stdin:  e.spec.Stdin,
337                 Stdout: e.spec.Stdout,
338                 Stderr: e.spec.Stderr,
339         }
340 }
341
342 func (e *singularityExecutor) Start() error {
343         path, err := exec.LookPath("singularity")
344         if err != nil {
345                 return err
346         }
347         child := e.execCmd(path)
348         err = child.Start()
349         if err != nil {
350                 return err
351         }
352         e.child = child
353         return nil
354 }
355
356 func (e *singularityExecutor) CgroupID() string {
357         return ""
358 }
359
360 func (e *singularityExecutor) Stop() error {
361         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
362                 // process already exited
363                 return nil
364         }
365         return e.child.Process.Signal(syscall.SIGKILL)
366 }
367
368 func (e *singularityExecutor) Wait(context.Context) (int, error) {
369         err := e.child.Wait()
370         if err, ok := err.(*exec.ExitError); ok {
371                 return err.ProcessState.ExitCode(), nil
372         }
373         if err != nil {
374                 return 0, err
375         }
376         return e.child.ProcessState.ExitCode(), nil
377 }
378
379 func (e *singularityExecutor) Close() {
380         err := os.RemoveAll(e.tmpdir)
381         if err != nil {
382                 e.logf("error removing temp dir: %s", err)
383         }
384 }
385
386 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
387         target, err := e.containedProcess()
388         if err != nil {
389                 return nil, err
390         }
391         return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
392 }
393
394 var (
395         errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
396 )
397
398 func (e *singularityExecutor) IPAddress() (string, error) {
399         target, err := e.containedProcess()
400         if err != nil {
401                 return "", err
402         }
403         targetIPs, err := processIPs(target)
404         if err != nil {
405                 return "", err
406         }
407         selfIPs, err := processIPs(os.Getpid())
408         if err != nil {
409                 return "", err
410         }
411         for ip := range targetIPs {
412                 if !selfIPs[ip] {
413                         return ip, nil
414                 }
415         }
416         return "", errContainerHasNoIPAddress
417 }
418
419 func processIPs(pid int) (map[string]bool, error) {
420         fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
421         if err != nil {
422                 return nil, err
423         }
424
425         addrs := map[string]bool{}
426         // When we see a pair of lines like this:
427         //
428         //              |-- 10.1.2.3
429         //                 /32 host LOCAL
430         //
431         // ...we set addrs["10.1.2.3"] = true
432         lines := bytes.Split(fibtrie, []byte{'\n'})
433         for linenumber, line := range lines {
434                 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
435                         continue
436                 }
437                 if linenumber < 1 {
438                         continue
439                 }
440                 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
441                 if i < 0 || i >= len(line)-7 {
442                         continue
443                 }
444                 addr := string(lines[linenumber-1][i+1:])
445                 if net.ParseIP(addr).To4() != nil {
446                         addrs[addr] = true
447                 }
448         }
449         return addrs, nil
450 }
451
452 var (
453         errContainerNotStarted = errors.New("container has not started yet")
454         errCannotFindChild     = errors.New("failed to find any process inside the container")
455         reProcStatusPPid       = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
456 )
457
458 // Return the PID of a process that is inside the container (not
459 // necessarily the topmost/pid=1 process in the container).
460 func (e *singularityExecutor) containedProcess() (int, error) {
461         if e.child == nil || e.child.Process == nil {
462                 return 0, errContainerNotStarted
463         }
464         lsns, err := exec.Command("lsns").CombinedOutput()
465         if err != nil {
466                 return 0, fmt.Errorf("lsns: %w", err)
467         }
468         for _, line := range bytes.Split(lsns, []byte{'\n'}) {
469                 fields := bytes.Fields(line)
470                 if len(fields) < 4 {
471                         continue
472                 }
473                 if !bytes.Equal(fields[1], []byte("pid")) {
474                         continue
475                 }
476                 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
477                 if err != nil {
478                         return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
479                 }
480                 for parent := pid; ; {
481                         procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
482                         if err != nil {
483                                 break
484                         }
485                         m := reProcStatusPPid.FindSubmatch(procstatus)
486                         if m == nil {
487                                 break
488                         }
489                         parent, err = strconv.ParseInt(string(m[1]), 10, 64)
490                         if err != nil {
491                                 break
492                         }
493                         if int(parent) == e.child.Process.Pid {
494                                 return int(pid), nil
495                         }
496                 }
497         }
498         return 0, errCannotFindChild
499 }