18513: Decipher status code in crunch-run.txt log.
[arvados.git] / lib / crunchrun / integration_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         "encoding/json"
10         "fmt"
11         "io"
12         "io/ioutil"
13         "os"
14         "os/exec"
15         "strings"
16
17         "git.arvados.org/arvados.git/lib/config"
18         "git.arvados.org/arvados.git/sdk/go/arvados"
19         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
20         "git.arvados.org/arvados.git/sdk/go/arvadostest"
21         "git.arvados.org/arvados.git/sdk/go/ctxlog"
22         "git.arvados.org/arvados.git/sdk/go/keepclient"
23         . "gopkg.in/check.v1"
24 )
25
26 var _ = Suite(&integrationSuite{})
27
28 type integrationSuite struct {
29         engine string
30         image  arvados.Collection
31         input  arvados.Collection
32         stdin  bytes.Buffer
33         stdout bytes.Buffer
34         stderr bytes.Buffer
35         cr     arvados.ContainerRequest
36         client *arvados.Client
37         ac     *arvadosclient.ArvadosClient
38         kc     *keepclient.KeepClient
39
40         logCollection    arvados.Collection
41         outputCollection arvados.Collection
42 }
43
44 func (s *integrationSuite) SetUpSuite(c *C) {
45         _, err := exec.LookPath("docker")
46         if err != nil {
47                 c.Skip("looks like docker is not installed")
48         }
49
50         arvadostest.StartKeep(2, true)
51
52         out, err := exec.Command("docker", "load", "--input", busyboxDockerImage(c)).CombinedOutput()
53         c.Log(string(out))
54         c.Assert(err, IsNil)
55         out, err = exec.Command("arv-keepdocker", "--no-resume", "busybox:uclibc").Output()
56         imageUUID := strings.TrimSpace(string(out))
57         c.Logf("image uuid %s", imageUUID)
58         if !c.Check(err, IsNil) {
59                 if err, ok := err.(*exec.ExitError); ok {
60                         c.Logf("%s", err.Stderr)
61                 }
62                 c.Fail()
63         }
64         err = arvados.NewClientFromEnv().RequestAndDecode(&s.image, "GET", "arvados/v1/collections/"+imageUUID, nil, nil)
65         c.Assert(err, IsNil)
66         c.Logf("image pdh %s", s.image.PortableDataHash)
67
68         s.client = arvados.NewClientFromEnv()
69         s.ac, err = arvadosclient.New(s.client)
70         c.Assert(err, IsNil)
71         s.kc = keepclient.New(s.ac)
72         fs, err := s.input.FileSystem(s.client, s.kc)
73         c.Assert(err, IsNil)
74         f, err := fs.OpenFile("inputfile", os.O_CREATE|os.O_WRONLY, 0755)
75         c.Assert(err, IsNil)
76         _, err = f.Write([]byte("inputdata"))
77         c.Assert(err, IsNil)
78         err = f.Close()
79         c.Assert(err, IsNil)
80         s.input.ManifestText, err = fs.MarshalManifest(".")
81         c.Assert(err, IsNil)
82         err = s.client.RequestAndDecode(&s.input, "POST", "arvados/v1/collections", nil, map[string]interface{}{
83                 "ensure_unique_name": true,
84                 "collection": map[string]interface{}{
85                         "manifest_text": s.input.ManifestText,
86                 },
87         })
88         c.Assert(err, IsNil)
89         c.Logf("input pdh %s", s.input.PortableDataHash)
90 }
91
92 func (s *integrationSuite) TearDownSuite(c *C) {
93         os.Unsetenv("ARVADOS_KEEP_SERVICES")
94         if s.client == nil {
95                 // didn't set up
96                 return
97         }
98         err := s.client.RequestAndDecode(nil, "POST", "database/reset", nil, nil)
99         c.Check(err, IsNil)
100 }
101
102 func (s *integrationSuite) SetUpTest(c *C) {
103         os.Unsetenv("ARVADOS_KEEP_SERVICES")
104         s.engine = "docker"
105         s.stdin = bytes.Buffer{}
106         s.stdout = bytes.Buffer{}
107         s.stderr = bytes.Buffer{}
108         s.logCollection = arvados.Collection{}
109         s.outputCollection = arvados.Collection{}
110         s.cr = arvados.ContainerRequest{
111                 Priority:       1,
112                 State:          "Committed",
113                 OutputPath:     "/mnt/out",
114                 ContainerImage: s.image.PortableDataHash,
115                 Mounts: map[string]arvados.Mount{
116                         "/mnt/json": {
117                                 Kind: "json",
118                                 Content: []interface{}{
119                                         "foo",
120                                         map[string]string{"foo": "bar"},
121                                         nil,
122                                 },
123                         },
124                         "/mnt/in": {
125                                 Kind:             "collection",
126                                 PortableDataHash: s.input.PortableDataHash,
127                         },
128                         "/mnt/out": {
129                                 Kind:     "tmp",
130                                 Capacity: 1000,
131                         },
132                 },
133                 RuntimeConstraints: arvados.RuntimeConstraints{
134                         RAM:   128000000,
135                         VCPUs: 1,
136                         API:   true,
137                 },
138         }
139 }
140
141 func (s *integrationSuite) setup(c *C) {
142         err := s.client.RequestAndDecode(&s.cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
143                 "priority":            s.cr.Priority,
144                 "state":               s.cr.State,
145                 "command":             s.cr.Command,
146                 "output_path":         s.cr.OutputPath,
147                 "container_image":     s.cr.ContainerImage,
148                 "mounts":              s.cr.Mounts,
149                 "runtime_constraints": s.cr.RuntimeConstraints,
150                 "use_existing":        false,
151         }})
152         c.Assert(err, IsNil)
153         c.Assert(s.cr.ContainerUUID, Not(Equals), "")
154         err = s.client.RequestAndDecode(nil, "POST", "arvados/v1/containers/"+s.cr.ContainerUUID+"/lock", nil, nil)
155         c.Assert(err, IsNil)
156 }
157
158 func (s *integrationSuite) TestRunTrivialContainerWithDocker(c *C) {
159         s.engine = "docker"
160         s.testRunTrivialContainer(c)
161 }
162
163 func (s *integrationSuite) TestRunTrivialContainerWithSingularity(c *C) {
164         s.engine = "singularity"
165         s.testRunTrivialContainer(c)
166 }
167
168 func (s *integrationSuite) TestRunTrivialContainerWithLocalKeepstore(c *C) {
169         for _, trial := range []struct {
170                 logConfig           string
171                 matchGetReq         Checker
172                 matchPutReq         Checker
173                 matchStartupMessage Checker
174         }{
175                 {"none", Not(Matches), Not(Matches), Not(Matches)},
176                 {"all", Matches, Matches, Matches},
177                 {"errors", Not(Matches), Not(Matches), Matches},
178         } {
179                 c.Logf("=== testing with Containers.LocalKeepLogsToContainerLog: %q", trial.logConfig)
180                 s.SetUpTest(c)
181
182                 cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
183                 c.Assert(err, IsNil)
184                 cluster, err := cfg.GetCluster("")
185                 c.Assert(err, IsNil)
186                 for uuid, volume := range cluster.Volumes {
187                         volume.AccessViaHosts = nil
188                         volume.Replication = 2
189                         cluster.Volumes[uuid] = volume
190                 }
191                 cluster.Containers.LocalKeepLogsToContainerLog = trial.logConfig
192
193                 s.stdin.Reset()
194                 err = json.NewEncoder(&s.stdin).Encode(ConfigData{
195                         Env:         nil,
196                         KeepBuffers: 1,
197                         Cluster:     cluster,
198                 })
199                 c.Assert(err, IsNil)
200
201                 s.engine = "docker"
202                 s.testRunTrivialContainer(c)
203
204                 fs, err := s.logCollection.FileSystem(s.client, s.kc)
205                 c.Assert(err, IsNil)
206                 f, err := fs.Open("keepstore.txt")
207                 if trial.logConfig == "none" {
208                         c.Check(err, NotNil)
209                         c.Check(os.IsNotExist(err), Equals, true)
210                 } else {
211                         c.Assert(err, IsNil)
212                         buf, err := ioutil.ReadAll(f)
213                         c.Assert(err, IsNil)
214                         c.Check(string(buf), trial.matchGetReq, `(?ms).*"reqMethod":"GET".*`)
215                         c.Check(string(buf), trial.matchPutReq, `(?ms).*"reqMethod":"PUT".*,"reqPath":"0e3bcff26d51c895a60ea0d4585e134d".*`)
216                 }
217         }
218 }
219
220 func (s *integrationSuite) testRunTrivialContainer(c *C) {
221         if err := exec.Command("which", s.engine).Run(); err != nil {
222                 c.Skip(fmt.Sprintf("%s: %s", s.engine, err))
223         }
224         s.cr.Command = []string{"sh", "-c", "cat /mnt/in/inputfile >/mnt/out/inputfile && cat /mnt/json >/mnt/out/json && ! touch /mnt/in/shouldbereadonly && mkdir /mnt/out/emptydir"}
225         s.setup(c)
226
227         args := []string{
228                 "-runtime-engine=" + s.engine,
229                 "-enable-memory-limit=false",
230                 s.cr.ContainerUUID,
231         }
232         if s.stdin.Len() > 0 {
233                 args = append([]string{"-stdin-config=true"}, args...)
234         }
235         code := command{}.RunCommand("crunch-run", args, &s.stdin, io.MultiWriter(&s.stdout, os.Stderr), io.MultiWriter(&s.stderr, os.Stderr))
236         c.Logf("\n===== stdout =====\n%s", s.stdout.String())
237         c.Logf("\n===== stderr =====\n%s", s.stderr.String())
238         c.Check(code, Equals, 0)
239         err := s.client.RequestAndDecode(&s.cr, "GET", "arvados/v1/container_requests/"+s.cr.UUID, nil, nil)
240         c.Assert(err, IsNil)
241         c.Logf("Finished container request: %#v", s.cr)
242
243         var log arvados.Collection
244         err = s.client.RequestAndDecode(&log, "GET", "arvados/v1/collections/"+s.cr.LogUUID, nil, nil)
245         c.Assert(err, IsNil)
246         fs, err := log.FileSystem(s.client, s.kc)
247         c.Assert(err, IsNil)
248         if d, err := fs.Open("/"); c.Check(err, IsNil) {
249                 fis, err := d.Readdir(-1)
250                 c.Assert(err, IsNil)
251                 for _, fi := range fis {
252                         if fi.IsDir() {
253                                 continue
254                         }
255                         f, err := fs.Open(fi.Name())
256                         c.Assert(err, IsNil)
257                         buf, err := ioutil.ReadAll(f)
258                         c.Assert(err, IsNil)
259                         c.Logf("\n===== %s =====\n%s", fi.Name(), buf)
260                 }
261         }
262         s.logCollection = log
263
264         var output arvados.Collection
265         err = s.client.RequestAndDecode(&output, "GET", "arvados/v1/collections/"+s.cr.OutputUUID, nil, nil)
266         c.Assert(err, IsNil)
267         fs, err = output.FileSystem(s.client, s.kc)
268         c.Assert(err, IsNil)
269         if f, err := fs.Open("inputfile"); c.Check(err, IsNil) {
270                 defer f.Close()
271                 buf, err := ioutil.ReadAll(f)
272                 c.Check(err, IsNil)
273                 c.Check(string(buf), Equals, "inputdata")
274         }
275         if f, err := fs.Open("json"); c.Check(err, IsNil) {
276                 defer f.Close()
277                 buf, err := ioutil.ReadAll(f)
278                 c.Check(err, IsNil)
279                 c.Check(string(buf), Equals, `["foo",{"foo":"bar"},null]`)
280         }
281         if fi, err := fs.Stat("emptydir"); c.Check(err, IsNil) {
282                 c.Check(fi.IsDir(), Equals, true)
283         }
284         if d, err := fs.Open("emptydir"); c.Check(err, IsNil) {
285                 defer d.Close()
286                 fis, err := d.Readdir(-1)
287                 c.Assert(err, IsNil)
288                 // crunch-run still saves a ".keep" file to preserve
289                 // empty dirs even though that shouldn't be
290                 // necessary. Ideally we would do:
291                 // c.Check(fis, HasLen, 0)
292                 for _, fi := range fis {
293                         c.Check(fi.Name(), Equals, ".keep")
294                 }
295         }
296         s.outputCollection = output
297 }