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