17296: Disentangle docker-specific code, add singularity option.
[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         e.imageFilename = e.tmpdir + "/image.sif"
44         build := exec.Command("singularity", "build", e.imageFilename, "docker-archive://"+imageTarballPath)
45         e.logf("%v", build.Args)
46         out, err := build.CombinedOutput()
47         // INFO:    Starting build...
48         // Getting image source signatures
49         // Copying blob ab15617702de done
50         // Copying config 651e02b8a2 done
51         // Writing manifest to image destination
52         // Storing signatures
53         // 2021/04/22 14:42:14  info unpack layer: sha256:21cbfd3a344c52b197b9fa36091e66d9cbe52232703ff78d44734f85abb7ccd3
54         // INFO:    Creating SIF file...
55         // INFO:    Build complete: arvados-jobs.latest.sif
56         e.logf("%s", out)
57         if err != nil {
58                 return err
59         }
60         return nil
61 }
62
63 func (e *singularityExecutor) Create(spec containerSpec) error {
64         e.spec = spec
65         return nil
66 }
67
68 func (e *singularityExecutor) Start() error {
69         args := []string{"singularity", "exec", "--containall", "--no-home", "--cleanenv"}
70         if !e.spec.EnableNetwork {
71                 args = append(args, "--net", "--network=none")
72         }
73         readonlyflag := map[bool]string{
74                 false: "rw",
75                 true:  "ro",
76         }
77         for path, mount := range e.spec.BindMounts {
78                 args = append(args, "--bind", mount.HostPath+":"+path+":"+readonlyflag[mount.ReadOnly])
79         }
80         args = append(args, e.imageFilename)
81         args = append(args, e.spec.Command...)
82
83         // This is for singularity 3.5.2. There are some behaviors
84         // that will change in singularity 3.6, please see:
85         // https://sylabs.io/guides/3.7/user-guide/environment_and_metadata.html
86         // https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html
87         env := make([]string, 0, len(e.spec.Env))
88         for k, v := range e.spec.Env {
89                 env = append(env, "SINGULARITYENV_"+k+"="+v)
90         }
91
92         path, err := exec.LookPath(args[0])
93         if err != nil {
94                 return err
95         }
96         child := &exec.Cmd{
97                 Path:   path,
98                 Args:   args,
99                 Env:    env,
100                 Stdin:  e.spec.Stdin,
101                 Stdout: e.spec.Stdout,
102                 Stderr: e.spec.Stderr,
103         }
104         err = child.Start()
105         if err != nil {
106                 return err
107         }
108         e.child = child
109         return nil
110 }
111
112 func (e *singularityExecutor) CgroupID() string {
113         return ""
114 }
115
116 func (e *singularityExecutor) Stop() error {
117         if err := e.child.Process.Signal(syscall.Signal(0)); err != nil {
118                 // process already exited
119                 return nil
120         }
121         return e.child.Process.Signal(syscall.SIGKILL)
122 }
123
124 func (e *singularityExecutor) Wait(context.Context) (int, error) {
125         err := e.child.Wait()
126         if err, ok := err.(*exec.ExitError); ok {
127                 return err.ProcessState.ExitCode(), nil
128         }
129         if err != nil {
130                 return 0, err
131         }
132         return e.child.ProcessState.ExitCode(), nil
133 }
134
135 func (e *singularityExecutor) Close() {
136         err := os.RemoveAll(e.tmpdir)
137         if err != nil {
138                 e.logf("error removing temp dir: %s", err)
139         }
140 }