]> git.arvados.org - arvados.git/blob - lib/crunchrun/singularity.go
17209: Merge branch 'main' into 17209-http-forward
[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         "context"
10         "encoding/json"
11         "errors"
12         "fmt"
13         "io/ioutil"
14         "net"
15         "os"
16         "os/exec"
17         "os/user"
18         "path"
19         "regexp"
20         "sort"
21         "strconv"
22         "strings"
23         "syscall"
24         "time"
25
26         "git.arvados.org/arvados.git/sdk/go/arvados"
27 )
28
29 type singularityExecutor struct {
30         logf          func(string, ...interface{})
31         sudo          bool // use sudo to run singularity (only used by tests)
32         spec          containerSpec
33         tmpdir        string
34         child         *exec.Cmd
35         imageFilename string // "sif" image
36 }
37
38 func newSingularityExecutor(logf func(string, ...interface{})) (*singularityExecutor, error) {
39         tmpdir, err := ioutil.TempDir("", "crunch-run-singularity-")
40         if err != nil {
41                 return nil, err
42         }
43         return &singularityExecutor{
44                 logf:   logf,
45                 tmpdir: tmpdir,
46         }, nil
47 }
48
49 func (e *singularityExecutor) Runtime() string {
50         buf, err := exec.Command("singularity", "--version").CombinedOutput()
51         if err != nil {
52                 return "singularity (unknown version)"
53         }
54         return strings.TrimSuffix(string(buf), "\n")
55 }
56
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"},
66                 },
67                         Limit: 1})
68         if err != nil {
69                 return nil, err
70         }
71         if len(gp.Items) == 1 {
72                 return &gp.Items[0], nil
73         }
74
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,
82                                 "name":        name,
83                                 "group_class": "project",
84                         },
85                 })
86         if err != nil {
87                 return nil, err
88         }
89         return &rgroup, nil
90 }
91
92 func (e *singularityExecutor) getImageCacheProject(userUUID string, containerClient *arvados.Client) (*arvados.Group, error) {
93         cacheProject, err := e.getOrCreateProject(userUUID, ".cache", containerClient)
94         if err != nil {
95                 return nil, fmt.Errorf("error getting '.cache' project: %v", err)
96         }
97         imageProject, err := e.getOrCreateProject(cacheProject.UUID, "auto-generated singularity images", containerClient)
98         if err != nil {
99                 return nil, fmt.Errorf("error getting 'auto-generated singularity images' project: %s", err)
100         }
101         return imageProject, nil
102 }
103
104 func (e *singularityExecutor) imageCacheExp() time.Time {
105         return time.Now().Add(e.imageCacheTTL()).UTC()
106 }
107
108 func (e *singularityExecutor) imageCacheTTL() time.Duration {
109         return 24 * 7 * 2 * time.Hour
110 }
111
112 // getCacheCollection returns an existing collection with a cached
113 // singularity image with the given name, or nil if none exists.
114 //
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},
125                 },
126                         Limit: 1})
127         if err != nil {
128                 return nil, "", fmt.Errorf("error querying for collection %q in project %s: %w", collectionName, cacheProject.UUID, err)
129         }
130         if len(cl.Items) == 0 {
131                 // Successfully discovered that there's no cached
132                 // image collection.
133                 return nil, "", nil
134         }
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.
139         coll := cl.Items[0]
140         sifFile := path.Join(arvMountPoint, "by_id", coll.PortableDataHash, "image.sif")
141         _, err = os.Stat(sifFile)
142         if err != nil {
143                 return nil, "", fmt.Errorf("found collection %s (%s), but it did not contain an image file: %s", coll.UUID, coll.PortableDataHash, err)
144         }
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
149                 // used regularly.
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),
156                                 },
157                         })
158                 if err != nil {
159                         e.logf("could not update expiry time of cached image collection (proceeding anyway): %s", err)
160                 }
161         }
162         return &coll, sifFile, nil
163 }
164
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),
175                         },
176                         "ensure_unique_name": true,
177                 })
178         if err != nil {
179                 return nil, fmt.Errorf("error creating '%v' collection: %s", collectionName, err)
180         }
181         return &coll, nil
182 }
183
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 {
187                 return err
188         }
189
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")
196         if err != nil {
197                 return err
198         }
199
200         // Set up a cache and tmp dir for singularity build
201         err = os.Mkdir(e.tmpdir+"/cache", 0700)
202         if err != nil {
203                 return err
204         }
205         defer os.RemoveAll(e.tmpdir + "/cache")
206         err = os.Mkdir(e.tmpdir+"/tmp", 0700)
207         if err != nil {
208                 return err
209         }
210         defer os.RemoveAll(e.tmpdir + "/tmp")
211
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
227         e.logf("%s", out)
228         return err
229 }
230
231 // LoadImage converts the given docker image to a singularity
232 // image.
233 //
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.
239 //
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 {
245                 if err != nil {
246                         e.logf("cannot use singularity image cache: %s", err)
247                 }
248                 e.imageFilename = path.Join(e.tmpdir, "image.sif")
249                 return e.convertDockerImage(imageTarballPath, e.imageFilename)
250         }
251
252         if containerClient == nil {
253                 return convertWithoutCache(nil)
254         }
255         cacheProject, err := e.getImageCacheProject(container.RuntimeUserUUID, containerClient)
256         if err != nil {
257                 return convertWithoutCache(err)
258         }
259         cacheCollectionName := fmt.Sprintf("singularity image for %s", dockerImageID)
260         existingCollection, sifFile, err := e.getCacheCollection(cacheCollectionName, containerClient, cacheProject, arvMountPoint)
261         if err != nil {
262                 return convertWithoutCache(err)
263         }
264         if existingCollection != nil {
265                 e.imageFilename = sifFile
266                 return nil
267         }
268
269         newCollection, err := e.createCacheCollection("converting "+cacheCollectionName, containerClient, cacheProject)
270         if err != nil {
271                 return convertWithoutCache(err)
272         }
273         dstDir := path.Join(arvMountPoint, "by_uuid", newCollection.UUID)
274         dstFile := path.Join(dstDir, "image.sif")
275         err = e.convertDockerImage(imageTarballPath, dstFile)
276         if err != nil {
277                 return err
278         }
279         buf, err := os.ReadFile(path.Join(dstDir, ".arvados#collection"))
280         if err != nil {
281                 return fmt.Errorf("could not sync image collection: %w", err)
282         }
283         var synced arvados.Collection
284         err = json.Unmarshal(buf, &synced)
285         if err != nil {
286                 return fmt.Errorf("could not parse .arvados#collection: %w", err)
287         }
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")
290
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,
297                         },
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
305                 // conversion.
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
309                 } else {
310                         e.logf("using newly converted image anyway, despite error renaming collection: %v", errRename)
311                 }
312         }
313         return nil
314 }
315
316 func (e *singularityExecutor) Create(spec containerSpec) error {
317         e.spec = spec
318         return nil
319 }
320
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.
328                 //
329                 // Note this used to be possible with --fakeroot, or
330                 // configuring singularity like so:
331                 //
332                 // singularity config global --set 'allow net networks' bridge
333                 // singularity config global --set 'allow net groups' mygroup
334                 //
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")
339         } else {
340                 // If we don't pass a --net argument at all, the
341                 // container will be in the same network namespace as
342                 // the host.
343                 //
344                 // Note this allows the container to listen on the
345                 // host's external ports.
346         }
347         if e.spec.GPUStack == "cuda" && e.spec.GPUDeviceCount > 0 {
348                 args = append(args, "--nv")
349         }
350         if e.spec.GPUStack == "rocm" && e.spec.GPUDeviceCount > 0 {
351                 args = append(args, "--rocm")
352         }
353
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
357         // be supported.
358         //
359         // Default debian configuration lets non-root users set memory
360         // limits but not CPU limits, so we enable/disable those
361         // limits independently.
362         //
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))
368                 } else {
369                         e.logf("cpu limits are not supported by current systemd/cgroup configuration, not setting --cpu %d", e.spec.VCPUs)
370                 }
371         }
372         if e.spec.RAM > 0 {
373                 if cgroupSupport["memory"] {
374                         args = append(args, "--memory", fmt.Sprintf("%d", e.spec.RAM))
375                 } else {
376                         e.logf("memory limits are not supported by current systemd/cgroup configuration, not setting --memory %d", e.spec.RAM)
377                 }
378         }
379
380         readonlyflag := map[bool]string{
381                 false: "rw",
382                 true:  "ro",
383         }
384         var binds []string
385         for path, _ := range e.spec.BindMounts {
386                 binds = append(binds, path)
387         }
388         sort.Strings(binds)
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)
394                 } else {
395                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
396                 }
397         }
398
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 {
405                 if k == "HOME" {
406                         // Singularity treats $HOME as special case,
407                         // this is handled with --home above
408                         continue
409                 }
410                 env = append(env, "SINGULARITYENV_"+k+"="+v)
411         }
412
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)
420         }
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")
429
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"))
440
441         args = append(args, e.imageFilename)
442         args = append(args, e.spec.Command...)
443
444         return &exec.Cmd{
445                 Path:   path,
446                 Args:   args,
447                 Env:    env,
448                 Stdin:  e.spec.Stdin,
449                 Stdout: e.spec.Stdout,
450                 Stderr: e.spec.Stderr,
451         }
452 }
453
454 func (e *singularityExecutor) Start() error {
455         path, err := exec.LookPath("singularity")
456         if err != nil {
457                 return err
458         }
459         child := e.execCmd(path)
460         if e.sudo {
461                 child.Args = append([]string{child.Path}, child.Args...)
462                 child.Path, err = exec.LookPath("sudo")
463                 if err != nil {
464                         return err
465                 }
466         }
467         err = child.Start()
468         if err != nil {
469                 return err
470         }
471         e.child = child
472         return nil
473 }
474
475 func (e *singularityExecutor) Pid() int {
476         childproc, err := e.containedProcess()
477         if err != nil {
478                 return 0
479         }
480         return childproc
481 }
482
483 func (e *singularityExecutor) Stop() error {
484         if e.child == nil || e.child.Process == nil {
485                 // no process started, or Wait already called
486                 return nil
487         }
488         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
489                 // process already exited
490                 return nil
491         }
492         return e.child.Process.Signal(syscall.SIGKILL)
493 }
494
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
499         }
500         if err != nil {
501                 return 0, err
502         }
503         return e.child.ProcessState.ExitCode(), nil
504 }
505
506 func (e *singularityExecutor) Close() {
507         err := os.RemoveAll(e.tmpdir)
508         if err != nil {
509                 e.logf("error removing temp dir: %s", err)
510         }
511 }
512
513 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
514         target, err := e.containedProcess()
515         if err != nil {
516                 return nil, err
517         }
518         return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
519 }
520
521 var (
522         errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
523 )
524
525 func (e *singularityExecutor) IPAddress() (string, error) {
526         target, err := e.containedProcess()
527         if err != nil {
528                 return "", err
529         }
530         targetIPs, err := processIPs(target)
531         if err != nil {
532                 return "", err
533         }
534         selfIPs, err := processIPs(os.Getpid())
535         if err != nil {
536                 return "", err
537         }
538         for ip := range targetIPs {
539                 if !selfIPs[ip] {
540                         return ip, nil
541                 }
542         }
543         return "", errContainerHasNoIPAddress
544 }
545
546 func processIPs(pid int) (map[string]bool, error) {
547         fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
548         if err != nil {
549                 return nil, err
550         }
551
552         addrs := map[string]bool{}
553         // When we see a pair of lines like this:
554         //
555         //              |-- 10.1.2.3
556         //                 /32 host LOCAL
557         //
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")) {
562                         continue
563                 }
564                 if linenumber < 1 {
565                         continue
566                 }
567                 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
568                 if i < 0 || i >= len(line)-7 {
569                         continue
570                 }
571                 addr := string(lines[linenumber-1][i+1:])
572                 if net.ParseIP(addr).To4() != nil {
573                         addrs[addr] = true
574                 }
575         }
576         return addrs, nil
577 }
578
579 var (
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`)
583 )
584
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
590         }
591         cmd := exec.Command("lsns")
592         if e.sudo {
593                 cmd = exec.Command("sudo", "lsns")
594         }
595         lsns, err := cmd.CombinedOutput()
596         if err != nil {
597                 return 0, fmt.Errorf("lsns: %w", err)
598         }
599         for _, line := range bytes.Split(lsns, []byte{'\n'}) {
600                 fields := bytes.Fields(line)
601                 if len(fields) < 4 {
602                         continue
603                 }
604                 if !bytes.Equal(fields[1], []byte("pid")) {
605                         continue
606                 }
607                 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
608                 if err != nil {
609                         return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
610                 }
611                 for parent := pid; ; {
612                         procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
613                         if err != nil {
614                                 break
615                         }
616                         m := reProcStatusPPid.FindSubmatch(procstatus)
617                         if m == nil {
618                                 break
619                         }
620                         parent, err = strconv.ParseInt(string(m[1]), 10, 64)
621                         if err != nil {
622                                 break
623                         }
624                         if int(parent) == e.child.Process.Pid {
625                                 return int(pid), nil
626                         }
627                 }
628         }
629         return 0, errCannotFindChild
630 }