308fb7bfc4e8322bc92c16ed5a77f43d2270ae03
[arvados.git] / lib / crunchrun / executor_test.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         "fmt"
10         "io"
11         "io/ioutil"
12         "net"
13         "net/http"
14         "os"
15         "strings"
16         "time"
17
18         "git.arvados.org/arvados.git/sdk/go/arvados"
19         "golang.org/x/net/context"
20         . "gopkg.in/check.v1"
21 )
22
23 func busyboxDockerImage(c *C) string {
24         fnm := "busybox_uclibc.tar"
25         cachedir := c.MkDir()
26         cachefile := cachedir + "/" + fnm
27         if _, err := os.Stat(cachefile); err == nil {
28                 return cachefile
29         }
30
31         f, err := ioutil.TempFile(cachedir, "")
32         c.Assert(err, IsNil)
33         defer f.Close()
34         defer os.Remove(f.Name())
35
36         resp, err := http.Get("https://cache.arvados.org/" + fnm)
37         c.Assert(err, IsNil)
38         defer resp.Body.Close()
39         _, err = io.Copy(f, resp.Body)
40         c.Assert(err, IsNil)
41         err = f.Close()
42         c.Assert(err, IsNil)
43         err = os.Rename(f.Name(), cachefile)
44         c.Assert(err, IsNil)
45
46         return cachefile
47 }
48
49 type nopWriteCloser struct{ io.Writer }
50
51 func (nopWriteCloser) Close() error { return nil }
52
53 // embedded by dockerSuite and singularitySuite so they can share
54 // tests.
55 type executorSuite struct {
56         newExecutor func(*C) // embedding struct's SetUpSuite method must set this
57         executor    containerExecutor
58         spec        containerSpec
59         stdout      bytes.Buffer
60         stderr      bytes.Buffer
61 }
62
63 func (s *executorSuite) SetUpTest(c *C) {
64         s.newExecutor(c)
65         s.stdout = bytes.Buffer{}
66         s.stderr = bytes.Buffer{}
67         s.spec = containerSpec{
68                 Image:       "busybox:uclibc",
69                 VCPUs:       1,
70                 WorkingDir:  "",
71                 Env:         map[string]string{"PATH": "/bin:/usr/bin"},
72                 NetworkMode: "default",
73                 Stdout:      nopWriteCloser{&s.stdout},
74                 Stderr:      nopWriteCloser{&s.stderr},
75         }
76         err := s.executor.LoadImage("", busyboxDockerImage(c), arvados.Container{}, "", nil)
77         c.Assert(err, IsNil)
78 }
79
80 func (s *executorSuite) TearDownTest(c *C) {
81         s.executor.Close()
82 }
83
84 func (s *executorSuite) TestExecTrivialContainer(c *C) {
85         s.spec.Command = []string{"echo", "ok"}
86         s.checkRun(c, 0)
87         c.Check(s.stdout.String(), Equals, "ok\n")
88         c.Check(s.stderr.String(), Equals, "")
89 }
90
91 func (s *executorSuite) TestExitStatus(c *C) {
92         s.spec.Command = []string{"false"}
93         s.checkRun(c, 1)
94 }
95
96 func (s *executorSuite) TestSignalExitStatus(c *C) {
97         if _, isdocker := s.executor.(*dockerExecutor); isdocker {
98                 // It's not quite this easy to make busybox kill
99                 // itself in docker where it's pid 1.
100                 c.Skip("kill -9 $$ doesn't work on busybox with pid=1 in docker")
101                 return
102         }
103         s.spec.Command = []string{"sh", "-c", "kill -9 $$"}
104         s.checkRun(c, 0x80+9)
105 }
106
107 func (s *executorSuite) TestExecStop(c *C) {
108         s.spec.Command = []string{"sh", "-c", "sleep 10; echo ok"}
109         err := s.executor.Create(s.spec)
110         c.Assert(err, IsNil)
111         err = s.executor.Start()
112         c.Assert(err, IsNil)
113         go func() {
114                 time.Sleep(time.Second / 10)
115                 s.executor.Stop()
116         }()
117         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
118         defer cancel()
119         code, err := s.executor.Wait(ctx)
120         c.Check(code, Not(Equals), 0)
121         c.Check(err, IsNil)
122         c.Check(s.stdout.String(), Equals, "")
123         c.Check(s.stderr.String(), Equals, "")
124 }
125
126 func (s *executorSuite) TestExecCleanEnv(c *C) {
127         s.spec.Command = []string{"env"}
128         s.checkRun(c, 0)
129         c.Check(s.stderr.String(), Equals, "")
130         got := map[string]string{}
131         for _, kv := range strings.Split(s.stdout.String(), "\n") {
132                 if kv == "" {
133                         continue
134                 }
135                 kv := strings.SplitN(kv, "=", 2)
136                 switch kv[0] {
137                 case "HOSTNAME", "HOME":
138                         // docker sets these by itself
139                 case "LD_LIBRARY_PATH", "SINGULARITY_NAME", "PWD", "LANG", "SHLVL", "SINGULARITY_INIT", "SINGULARITY_CONTAINER":
140                         // singularity sets these by itself (cf. https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html)
141                 case "SINGULARITY_APPNAME":
142                         // singularity also sets this by itself (v3.5.2, but not v3.7.4)
143                 case "PROMPT_COMMAND", "PS1", "SINGULARITY_BIND", "SINGULARITY_COMMAND", "SINGULARITY_ENVIRONMENT":
144                         // singularity also sets these by itself (v3.7.4)
145                 default:
146                         got[kv[0]] = kv[1]
147                 }
148         }
149         c.Check(got, DeepEquals, s.spec.Env)
150 }
151 func (s *executorSuite) TestExecEnableNetwork(c *C) {
152         for _, enable := range []bool{false, true} {
153                 s.SetUpTest(c)
154                 s.spec.Command = []string{"ip", "route"}
155                 s.spec.EnableNetwork = enable
156                 s.checkRun(c, 0)
157                 if enable {
158                         c.Check(s.stdout.String(), Matches, "(?ms).*default via.*")
159                 } else {
160                         c.Check(s.stdout.String(), Equals, "")
161                 }
162         }
163 }
164
165 func (s *executorSuite) TestExecWorkingDir(c *C) {
166         s.spec.WorkingDir = "/tmp"
167         s.spec.Command = []string{"sh", "-c", "pwd"}
168         s.checkRun(c, 0)
169         c.Check(s.stdout.String(), Equals, "/tmp\n")
170 }
171
172 func (s *executorSuite) TestExecStdoutStderr(c *C) {
173         s.spec.Command = []string{"sh", "-c", "echo foo; echo -n bar >&2; echo baz; echo waz >&2"}
174         s.checkRun(c, 0)
175         c.Check(s.stdout.String(), Equals, "foo\nbaz\n")
176         c.Check(s.stderr.String(), Equals, "barwaz\n")
177 }
178
179 func (s *executorSuite) TestIPAddress(c *C) {
180         s.spec.Command = []string{"nc", "-l", "-p", "1951", "-e", "printf", `HTTP/1.1 418 I'm a teapot\r\n\r\n`}
181         s.spec.EnableNetwork = true
182         c.Assert(s.executor.Create(s.spec), IsNil)
183         c.Assert(s.executor.Start(), IsNil)
184         starttime := time.Now()
185
186         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
187         defer cancel()
188
189         for ctx.Err() == nil {
190                 time.Sleep(time.Second / 10)
191                 _, err := s.executor.IPAddress()
192                 if err == nil {
193                         break
194                 }
195         }
196         ip, err := s.executor.IPAddress()
197         if c.Check(err, IsNil) && c.Check(ip, Not(Equals), "") {
198                 req, err := http.NewRequest("BREW", "http://"+net.JoinHostPort(ip, "1951"), nil)
199                 c.Assert(err, IsNil)
200                 resp, err := http.DefaultClient.Do(req)
201                 c.Assert(err, IsNil)
202                 c.Check(resp.StatusCode, Equals, http.StatusTeapot)
203         }
204
205         s.executor.Stop()
206         code, _ := s.executor.Wait(ctx)
207         c.Logf("container ran for %v", time.Now().Sub(starttime))
208         c.Check(code, Equals, -1)
209
210         c.Logf("stdout:\n%s\n\n", s.stdout.String())
211         c.Logf("stderr:\n%s\n\n", s.stderr.String())
212 }
213
214 func (s *executorSuite) TestInject(c *C) {
215         hostdir := c.MkDir()
216         c.Assert(os.WriteFile(hostdir+"/testfile", []byte("first tube"), 0777), IsNil)
217         mountdir := fmt.Sprintf("/injecttest-%d", os.Getpid())
218         s.spec.Command = []string{"sleep", "10"}
219         s.spec.BindMounts = map[string]bindmount{mountdir: {HostPath: hostdir, ReadOnly: true}}
220         c.Assert(s.executor.Create(s.spec), IsNil)
221         c.Assert(s.executor.Start(), IsNil)
222         starttime := time.Now()
223
224         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second))
225         defer cancel()
226
227         // Allow InjectCommand to fail a few times while the container
228         // is starting
229         for ctx.Err() == nil {
230                 _, err := s.executor.InjectCommand(ctx, "", "root", false, []string{"true"})
231                 if err == nil {
232                         break
233                 }
234                 time.Sleep(time.Second / 10)
235         }
236
237         injectcmd := []string{"cat", mountdir + "/testfile"}
238         cmd, err := s.executor.InjectCommand(ctx, "", "root", false, injectcmd)
239         c.Assert(err, IsNil)
240         out, err := cmd.CombinedOutput()
241         c.Logf("inject %s => %q", injectcmd, out)
242         c.Check(err, IsNil)
243         c.Check(string(out), Equals, "first tube")
244
245         s.executor.Stop()
246         code, _ := s.executor.Wait(ctx)
247         c.Logf("container ran for %v", time.Now().Sub(starttime))
248         c.Check(code, Equals, -1)
249 }
250
251 func (s *executorSuite) checkRun(c *C, expectCode int) {
252         c.Assert(s.executor.Create(s.spec), IsNil)
253         c.Assert(s.executor.Start(), IsNil)
254         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
255         defer cancel()
256         code, err := s.executor.Wait(ctx)
257         c.Assert(err, IsNil)
258         c.Check(code, Equals, expectCode)
259 }