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