Fix 2.4.1 release date refs #19017
[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         c.Logf("Using container runtime: %s", s.executor.Runtime())
86         s.spec.Command = []string{"echo", "ok"}
87         s.checkRun(c, 0)
88         c.Check(s.stdout.String(), Equals, "ok\n")
89         c.Check(s.stderr.String(), Equals, "")
90 }
91
92 func (s *executorSuite) TestExitStatus(c *C) {
93         s.spec.Command = []string{"false"}
94         s.checkRun(c, 1)
95 }
96
97 func (s *executorSuite) TestSignalExitStatus(c *C) {
98         if _, isdocker := s.executor.(*dockerExecutor); isdocker {
99                 // It's not quite this easy to make busybox kill
100                 // itself in docker where it's pid 1.
101                 c.Skip("kill -9 $$ doesn't work on busybox with pid=1 in docker")
102                 return
103         }
104         s.spec.Command = []string{"sh", "-c", "kill -9 $$"}
105         s.checkRun(c, 0x80+9)
106 }
107
108 func (s *executorSuite) TestExecStop(c *C) {
109         s.spec.Command = []string{"sh", "-c", "sleep 10; echo ok"}
110         err := s.executor.Create(s.spec)
111         c.Assert(err, IsNil)
112         err = s.executor.Start()
113         c.Assert(err, IsNil)
114         go func() {
115                 time.Sleep(time.Second / 10)
116                 s.executor.Stop()
117         }()
118         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
119         defer cancel()
120         code, err := s.executor.Wait(ctx)
121         c.Check(code, Not(Equals), 0)
122         c.Check(err, IsNil)
123         c.Check(s.stdout.String(), Equals, "")
124         c.Check(s.stderr.String(), Equals, "")
125 }
126
127 func (s *executorSuite) TestExecCleanEnv(c *C) {
128         s.spec.Command = []string{"env"}
129         s.checkRun(c, 0)
130         c.Check(s.stderr.String(), Equals, "")
131         got := map[string]string{}
132         for _, kv := range strings.Split(s.stdout.String(), "\n") {
133                 if kv == "" {
134                         continue
135                 }
136                 kv := strings.SplitN(kv, "=", 2)
137                 switch kv[0] {
138                 case "HOSTNAME", "HOME":
139                         // docker sets these by itself
140                 case "LD_LIBRARY_PATH", "SINGULARITY_NAME", "PWD", "LANG", "SHLVL", "SINGULARITY_INIT", "SINGULARITY_CONTAINER":
141                         // singularity sets these by itself (cf. https://sylabs.io/guides/3.5/user-guide/environment_and_metadata.html)
142                 case "SINGULARITY_APPNAME":
143                         // singularity also sets this by itself (v3.5.2, but not v3.7.4)
144                 case "PROMPT_COMMAND", "PS1", "SINGULARITY_BIND", "SINGULARITY_COMMAND", "SINGULARITY_ENVIRONMENT":
145                         // singularity also sets these by itself (v3.7.4)
146                 default:
147                         got[kv[0]] = kv[1]
148                 }
149         }
150         c.Check(got, DeepEquals, s.spec.Env)
151 }
152 func (s *executorSuite) TestExecEnableNetwork(c *C) {
153         for _, enable := range []bool{false, true} {
154                 s.SetUpTest(c)
155                 s.spec.Command = []string{"ip", "route"}
156                 s.spec.EnableNetwork = enable
157                 s.checkRun(c, 0)
158                 if enable {
159                         c.Check(s.stdout.String(), Matches, "(?ms).*default via.*")
160                 } else {
161                         c.Check(s.stdout.String(), Equals, "")
162                 }
163         }
164 }
165
166 func (s *executorSuite) TestExecWorkingDir(c *C) {
167         s.spec.WorkingDir = "/tmp"
168         s.spec.Command = []string{"sh", "-c", "pwd"}
169         s.checkRun(c, 0)
170         c.Check(s.stdout.String(), Equals, "/tmp\n")
171 }
172
173 func (s *executorSuite) TestExecStdoutStderr(c *C) {
174         s.spec.Command = []string{"sh", "-c", "echo foo; echo -n bar >&2; echo baz; echo waz >&2"}
175         s.checkRun(c, 0)
176         c.Check(s.stdout.String(), Equals, "foo\nbaz\n")
177         c.Check(s.stderr.String(), Equals, "barwaz\n")
178 }
179
180 func (s *executorSuite) TestIPAddress(c *C) {
181         // Listen on an available port on the host.
182         ln, err := net.Listen("tcp", net.JoinHostPort("0.0.0.0", "0"))
183         c.Assert(err, IsNil)
184         defer ln.Close()
185         _, port, err := net.SplitHostPort(ln.Addr().String())
186         c.Assert(err, IsNil)
187
188         // Start a container that listens on the same port number that
189         // is already in use on the host.
190         s.spec.Command = []string{"nc", "-l", "-p", port, "-e", "printf", `HTTP/1.1 418 I'm a teapot\r\n\r\n`}
191         s.spec.EnableNetwork = true
192         c.Assert(s.executor.Create(s.spec), IsNil)
193         c.Assert(s.executor.Start(), IsNil)
194         starttime := time.Now()
195
196         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
197         defer cancel()
198
199         for ctx.Err() == nil {
200                 time.Sleep(time.Second / 10)
201                 _, err := s.executor.IPAddress()
202                 if err == nil {
203                         break
204                 }
205         }
206         // When we connect to the port using s.executor.IPAddress(),
207         // we should reach the nc process running inside the
208         // container, not the net.Listen() running outside the
209         // container, even though both listen on the same port.
210         ip, err := s.executor.IPAddress()
211         if c.Check(err, IsNil) && c.Check(ip, Not(Equals), "") {
212                 req, err := http.NewRequest("BREW", "http://"+net.JoinHostPort(ip, port), nil)
213                 c.Assert(err, IsNil)
214                 resp, err := http.DefaultClient.Do(req)
215                 c.Assert(err, IsNil)
216                 c.Check(resp.StatusCode, Equals, http.StatusTeapot)
217         }
218
219         s.executor.Stop()
220         code, _ := s.executor.Wait(ctx)
221         c.Logf("container ran for %v", time.Now().Sub(starttime))
222         c.Check(code, Equals, -1)
223
224         c.Logf("stdout:\n%s\n\n", s.stdout.String())
225         c.Logf("stderr:\n%s\n\n", s.stderr.String())
226 }
227
228 func (s *executorSuite) TestInject(c *C) {
229         hostdir := c.MkDir()
230         c.Assert(os.WriteFile(hostdir+"/testfile", []byte("first tube"), 0777), IsNil)
231         mountdir := fmt.Sprintf("/injecttest-%d", os.Getpid())
232         s.spec.Command = []string{"sleep", "10"}
233         s.spec.BindMounts = map[string]bindmount{mountdir: {HostPath: hostdir, ReadOnly: true}}
234         c.Assert(s.executor.Create(s.spec), IsNil)
235         c.Assert(s.executor.Start(), IsNil)
236         starttime := time.Now()
237
238         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second))
239         defer cancel()
240
241         // Allow InjectCommand to fail a few times while the container
242         // is starting
243         for ctx.Err() == nil {
244                 _, err := s.executor.InjectCommand(ctx, "", "root", false, []string{"true"})
245                 if err == nil {
246                         break
247                 }
248                 time.Sleep(time.Second / 10)
249         }
250
251         injectcmd := []string{"cat", mountdir + "/testfile"}
252         cmd, err := s.executor.InjectCommand(ctx, "", "root", false, injectcmd)
253         c.Assert(err, IsNil)
254         out, err := cmd.CombinedOutput()
255         c.Logf("inject %s => %q", injectcmd, out)
256         c.Check(err, IsNil)
257         c.Check(string(out), Equals, "first tube")
258
259         s.executor.Stop()
260         code, _ := s.executor.Wait(ctx)
261         c.Logf("container ran for %v", time.Now().Sub(starttime))
262         c.Check(code, Equals, -1)
263 }
264
265 func (s *executorSuite) checkRun(c *C, expectCode int) {
266         c.Assert(s.executor.Create(s.spec), IsNil)
267         c.Assert(s.executor.Start(), IsNil)
268         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Second))
269         defer cancel()
270         code, err := s.executor.Wait(ctx)
271         c.Assert(err, IsNil)
272         c.Check(code, Equals, expectCode)
273 }