21750: Add "has non-loopback ip" test.
[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         "errors"
11         "fmt"
12         "io/ioutil"
13         "net"
14         "os"
15         "os/exec"
16         "os/user"
17         "regexp"
18         "sort"
19         "strconv"
20         "strings"
21         "syscall"
22         "time"
23
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25 )
26
27 type singularityExecutor struct {
28         logf          func(string, ...interface{})
29         sudo          bool // use sudo to run singularity (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.spec.EnableNetwork {
261                 args = append(args, "--net", "--network=none")
262         } else if u, err := user.Current(); err == nil && u.Uid == "0" || e.sudo {
263                 // Specifying --network=bridge fails unless
264                 // singularity is running as root.
265                 //
266                 // Note this used to be possible with --fakeroot, or
267                 // configuring singularity like so:
268                 //
269                 // singularity config global --set 'allow net networks' bridge
270                 // singularity config global --set 'allow net groups' mygroup
271                 //
272                 // However, these options no longer work (as of debian
273                 // bookworm) because iptables now refuses to run in a
274                 // setuid environment.
275                 args = append(args, "--net", "--network=bridge")
276         } else {
277                 // If we don't pass a --net argument at all, the
278                 // container will be in the same network namespace as
279                 // the host.
280                 //
281                 // Note this allows the container to listen on the
282                 // host's external ports.
283         }
284         if e.spec.CUDADeviceCount != 0 {
285                 args = append(args, "--nv")
286         }
287
288         readonlyflag := map[bool]string{
289                 false: "rw",
290                 true:  "ro",
291         }
292         var binds []string
293         for path, _ := range e.spec.BindMounts {
294                 binds = append(binds, path)
295         }
296         sort.Strings(binds)
297         for _, path := range binds {
298                 mount := e.spec.BindMounts[path]
299                 if path == e.spec.Env["HOME"] {
300                         // Singularity treats $HOME as special case
301                         args = append(args, "--home", mount.HostPath+":"+path)
302                 } else {
303                         args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
304                 }
305         }
306
307         // This is for singularity 3.5.2. There are some behaviors
308         // that will change in singularity 3.6, please see:
309         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
310         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
311         env := make([]string, 0, len(e.spec.Env))
312         for k, v := range e.spec.Env {
313                 if k == "HOME" {
314                         // Singularity treats $HOME as special case,
315                         // this is handled with --home above
316                         continue
317                 }
318                 env = append(env, "SINGULARITYENV_"+k+"="+v)
319         }
320
321         // Singularity always makes all nvidia devices visible to the
322         // container.  If a resource manager such as slurm or LSF told
323         // us to select specific devices we need to propagate that.
324         if cudaVisibleDevices := os.Getenv("CUDA_VISIBLE_DEVICES"); cudaVisibleDevices != "" {
325                 // If a resource manager such as slurm or LSF told
326                 // us to select specific devices we need to propagate that.
327                 env = append(env, "SINGULARITYENV_CUDA_VISIBLE_DEVICES="+cudaVisibleDevices)
328         }
329         // Singularity's default behavior is to evaluate each
330         // SINGULARITYENV_* env var with a shell as a double-quoted
331         // string and pass the result to the contained
332         // process. Singularity 3.10+ has an option to pass env vars
333         // through literally without evaluating, which is what we
334         // want. See https://github.com/sylabs/singularity/pull/704
335         // and https://dev.arvados.org/issues/19081
336         env = append(env, "SINGULARITY_NO_EVAL=1")
337
338         args = append(args, e.imageFilename)
339         args = append(args, e.spec.Command...)
340
341         return &exec.Cmd{
342                 Path:   path,
343                 Args:   args,
344                 Env:    env,
345                 Stdin:  e.spec.Stdin,
346                 Stdout: e.spec.Stdout,
347                 Stderr: e.spec.Stderr,
348         }
349 }
350
351 func (e *singularityExecutor) Start() error {
352         path, err := exec.LookPath("singularity")
353         if err != nil {
354                 return err
355         }
356         child := e.execCmd(path)
357         if e.sudo {
358                 child.Args = append([]string{child.Path}, child.Args...)
359                 child.Path, err = exec.LookPath("sudo")
360                 if err != nil {
361                         return err
362                 }
363         }
364         err = child.Start()
365         if err != nil {
366                 return err
367         }
368         e.child = child
369         return nil
370 }
371
372 func (e *singularityExecutor) Pid() int {
373         // see https://dev.arvados.org/issues/17244#note-21
374         return 0
375 }
376
377 func (e *singularityExecutor) Stop() error {
378         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
379                 // process already exited
380                 return nil
381         }
382         return e.child.Process.Signal(syscall.SIGKILL)
383 }
384
385 func (e *singularityExecutor) Wait(context.Context) (int, error) {
386         err := e.child.Wait()
387         if err, ok := err.(*exec.ExitError); ok {
388                 return err.ProcessState.ExitCode(), nil
389         }
390         if err != nil {
391                 return 0, err
392         }
393         return e.child.ProcessState.ExitCode(), nil
394 }
395
396 func (e *singularityExecutor) Close() {
397         err := os.RemoveAll(e.tmpdir)
398         if err != nil {
399                 e.logf("error removing temp dir: %s", err)
400         }
401 }
402
403 func (e *singularityExecutor) InjectCommand(ctx context.Context, detachKeys, username string, usingTTY bool, injectcmd []string) (*exec.Cmd, error) {
404         target, err := e.containedProcess()
405         if err != nil {
406                 return nil, err
407         }
408         return exec.CommandContext(ctx, "nsenter", append([]string{fmt.Sprintf("--target=%d", target), "--all"}, injectcmd...)...), nil
409 }
410
411 var (
412         errContainerHasNoIPAddress = errors.New("container has no IP address distinct from host")
413 )
414
415 func (e *singularityExecutor) IPAddress() (string, error) {
416         target, err := e.containedProcess()
417         if err != nil {
418                 return "", err
419         }
420         targetIPs, err := processIPs(target)
421         if err != nil {
422                 return "", err
423         }
424         selfIPs, err := processIPs(os.Getpid())
425         if err != nil {
426                 return "", err
427         }
428         for ip := range targetIPs {
429                 if !selfIPs[ip] {
430                         return ip, nil
431                 }
432         }
433         return "", errContainerHasNoIPAddress
434 }
435
436 func processIPs(pid int) (map[string]bool, error) {
437         fibtrie, err := os.ReadFile(fmt.Sprintf("/proc/%d/net/fib_trie", pid))
438         if err != nil {
439                 return nil, err
440         }
441
442         addrs := map[string]bool{}
443         // When we see a pair of lines like this:
444         //
445         //              |-- 10.1.2.3
446         //                 /32 host LOCAL
447         //
448         // ...we set addrs["10.1.2.3"] = true
449         lines := bytes.Split(fibtrie, []byte{'\n'})
450         for linenumber, line := range lines {
451                 if !bytes.HasSuffix(line, []byte("/32 host LOCAL")) {
452                         continue
453                 }
454                 if linenumber < 1 {
455                         continue
456                 }
457                 i := bytes.LastIndexByte(lines[linenumber-1], ' ')
458                 if i < 0 || i >= len(line)-7 {
459                         continue
460                 }
461                 addr := string(lines[linenumber-1][i+1:])
462                 if net.ParseIP(addr).To4() != nil {
463                         addrs[addr] = true
464                 }
465         }
466         return addrs, nil
467 }
468
469 var (
470         errContainerNotStarted = errors.New("container has not started yet")
471         errCannotFindChild     = errors.New("failed to find any process inside the container")
472         reProcStatusPPid       = regexp.MustCompile(`\nPPid:\t(\d+)\n`)
473 )
474
475 // Return the PID of a process that is inside the container (not
476 // necessarily the topmost/pid=1 process in the container).
477 func (e *singularityExecutor) containedProcess() (int, error) {
478         if e.child == nil || e.child.Process == nil {
479                 return 0, errContainerNotStarted
480         }
481         cmd := exec.Command("lsns")
482         if e.sudo {
483                 cmd = exec.Command("sudo", "lsns")
484         }
485         lsns, err := cmd.CombinedOutput()
486         if err != nil {
487                 return 0, fmt.Errorf("lsns: %w", err)
488         }
489         for _, line := range bytes.Split(lsns, []byte{'\n'}) {
490                 fields := bytes.Fields(line)
491                 if len(fields) < 4 {
492                         continue
493                 }
494                 if !bytes.Equal(fields[1], []byte("pid")) {
495                         continue
496                 }
497                 pid, err := strconv.ParseInt(string(fields[3]), 10, 64)
498                 if err != nil {
499                         return 0, fmt.Errorf("error parsing PID field in lsns output: %q", fields[3])
500                 }
501                 for parent := pid; ; {
502                         procstatus, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", parent))
503                         if err != nil {
504                                 break
505                         }
506                         m := reProcStatusPPid.FindSubmatch(procstatus)
507                         if m == nil {
508                                 break
509                         }
510                         parent, err = strconv.ParseInt(string(m[1]), 10, 64)
511                         if err != nil {
512                                 break
513                         }
514                         if int(parent) == e.child.Process.Pid {
515                                 return int(pid), nil
516                         }
517                 }
518         }
519         return 0, errCannotFindChild
520 }