16347: Add LocalKeepLogsToContainerLog config (none/errors/all).
[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         if s.client == nil {
94                 // didn't set up
95                 return
96         }
97         err := s.client.RequestAndDecode(nil, "POST", "database/reset", nil, nil)
98         c.Check(err, IsNil)
99 }
100
101 func (s *integrationSuite) SetUpTest(c *C) {
102         s.engine = "docker"
103         s.stdin = bytes.Buffer{}
104         s.stdout = bytes.Buffer{}
105         s.stderr = bytes.Buffer{}
106         s.logCollection = arvados.Collection{}
107         s.outputCollection = arvados.Collection{}
108         s.cr = arvados.ContainerRequest{
109                 Priority:       1,
110                 State:          "Committed",
111                 OutputPath:     "/mnt/out",
112                 ContainerImage: s.image.PortableDataHash,
113                 Mounts: map[string]arvados.Mount{
114                         "/mnt/json": {
115                                 Kind: "json",
116                                 Content: []interface{}{
117                                         "foo",
118                                         map[string]string{"foo": "bar"},
119                                         nil,
120                                 },
121                         },
122                         "/mnt/in": {
123                                 Kind:             "collection",
124                                 PortableDataHash: s.input.PortableDataHash,
125                         },
126                         "/mnt/out": {
127                                 Kind:     "tmp",
128                                 Capacity: 1000,
129                         },
130                 },
131                 RuntimeConstraints: arvados.RuntimeConstraints{
132                         RAM:   128000000,
133                         VCPUs: 1,
134                         API:   true,
135                 },
136         }
137 }
138
139 func (s *integrationSuite) setup(c *C) {
140         err := s.client.RequestAndDecode(&s.cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
141                 "priority":            s.cr.Priority,
142                 "state":               s.cr.State,
143                 "command":             s.cr.Command,
144                 "output_path":         s.cr.OutputPath,
145                 "container_image":     s.cr.ContainerImage,
146                 "mounts":              s.cr.Mounts,
147                 "runtime_constraints": s.cr.RuntimeConstraints,
148                 "use_existing":        false,
149         }})
150         c.Assert(err, IsNil)
151         c.Assert(s.cr.ContainerUUID, Not(Equals), "")
152         err = s.client.RequestAndDecode(nil, "POST", "arvados/v1/containers/"+s.cr.ContainerUUID+"/lock", nil, nil)
153         c.Assert(err, IsNil)
154 }
155
156 func (s *integrationSuite) TestRunTrivialContainerWithDocker(c *C) {
157         s.engine = "docker"
158         s.testRunTrivialContainer(c)
159 }
160
161 func (s *integrationSuite) TestRunTrivialContainerWithSingularity(c *C) {
162         s.engine = "singularity"
163         s.testRunTrivialContainer(c)
164 }
165
166 func (s *integrationSuite) TestRunTrivialContainerWithLocalKeepstore(c *C) {
167         for _, trial := range []struct {
168                 logConfig           string
169                 matchGetReq         Checker
170                 matchPutReq         Checker
171                 matchStartupMessage Checker
172         }{
173                 {"none", Not(Matches), Not(Matches), Not(Matches)},
174                 {"all", Matches, Matches, Matches},
175                 {"errors", Not(Matches), Not(Matches), Matches},
176         } {
177                 c.Logf("=== testing with Containers.LocalKeepLogsToContainerLog: %q", trial.logConfig)
178                 s.SetUpTest(c)
179
180                 cfg, err := config.NewLoader(nil, ctxlog.TestLogger(c)).Load()
181                 c.Assert(err, IsNil)
182                 cluster, err := cfg.GetCluster("")
183                 c.Assert(err, IsNil)
184                 for uuid, volume := range cluster.Volumes {
185                         volume.AccessViaHosts = nil
186                         volume.Replication = 2
187                         cluster.Volumes[uuid] = volume
188                 }
189                 cluster.Containers.LocalKeepLogsToContainerLog = trial.logConfig
190
191                 s.stdin.Reset()
192                 err = json.NewEncoder(&s.stdin).Encode(ConfigData{
193                         Env:         nil,
194                         KeepBuffers: 1,
195                         Cluster:     cluster,
196                 })
197                 c.Assert(err, IsNil)
198
199                 s.engine = "docker"
200                 s.testRunTrivialContainer(c)
201
202                 fs, err := s.logCollection.FileSystem(s.client, s.kc)
203                 c.Assert(err, IsNil)
204                 f, err := fs.Open("keepstore.txt")
205                 if trial.logConfig == "none" {
206                         c.Check(err, NotNil)
207                         c.Check(os.IsNotExist(err), Equals, true)
208                 } else {
209                         c.Assert(err, IsNil)
210                         buf, err := ioutil.ReadAll(f)
211                         c.Assert(err, IsNil)
212                         c.Check(string(buf), trial.matchGetReq, `(?ms).*"reqMethod":"GET".*`)
213                         c.Check(string(buf), trial.matchPutReq, `(?ms).*"reqMethod":"PUT".*,"reqPath":"0e3bcff26d51c895a60ea0d4585e134d".*`)
214                 }
215         }
216 }
217
218 func (s *integrationSuite) testRunTrivialContainer(c *C) {
219         if err := exec.Command("which", s.engine).Run(); err != nil {
220                 c.Skip(fmt.Sprintf("%s: %s", s.engine, err))
221         }
222         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"}
223         s.setup(c)
224
225         args := []string{
226                 "-runtime-engine=" + s.engine,
227                 "-enable-memory-limit=false",
228                 s.cr.ContainerUUID,
229         }
230         if s.stdin.Len() > 0 {
231                 args = append([]string{"-stdin-config=true"}, args...)
232         }
233         code := command{}.RunCommand("crunch-run", args, &s.stdin, io.MultiWriter(&s.stdout, os.Stderr), io.MultiWriter(&s.stderr, os.Stderr))
234         c.Logf("\n===== stdout =====\n%s", s.stdout.String())
235         c.Logf("\n===== stderr =====\n%s", s.stderr.String())
236         c.Check(code, Equals, 0)
237         err := s.client.RequestAndDecode(&s.cr, "GET", "arvados/v1/container_requests/"+s.cr.UUID, nil, nil)
238         c.Assert(err, IsNil)
239         c.Logf("Finished container request: %#v", s.cr)
240
241         var log arvados.Collection
242         err = s.client.RequestAndDecode(&log, "GET", "arvados/v1/collections/"+s.cr.LogUUID, nil, nil)
243         c.Assert(err, IsNil)
244         fs, err := log.FileSystem(s.client, s.kc)
245         c.Assert(err, IsNil)
246         if d, err := fs.Open("/"); c.Check(err, IsNil) {
247                 fis, err := d.Readdir(-1)
248                 c.Assert(err, IsNil)
249                 for _, fi := range fis {
250                         if fi.IsDir() {
251                                 continue
252                         }
253                         f, err := fs.Open(fi.Name())
254                         c.Assert(err, IsNil)
255                         buf, err := ioutil.ReadAll(f)
256                         c.Assert(err, IsNil)
257                         c.Logf("\n===== %s =====\n%s", fi.Name(), buf)
258                 }
259         }
260         s.logCollection = log
261
262         var output arvados.Collection
263         err = s.client.RequestAndDecode(&output, "GET", "arvados/v1/collections/"+s.cr.OutputUUID, nil, nil)
264         c.Assert(err, IsNil)
265         fs, err = output.FileSystem(s.client, s.kc)
266         c.Assert(err, IsNil)
267         if f, err := fs.Open("inputfile"); c.Check(err, IsNil) {
268                 defer f.Close()
269                 buf, err := ioutil.ReadAll(f)
270                 c.Check(err, IsNil)
271                 c.Check(string(buf), Equals, "inputdata")
272         }
273         if f, err := fs.Open("json"); c.Check(err, IsNil) {
274                 defer f.Close()
275                 buf, err := ioutil.ReadAll(f)
276                 c.Check(err, IsNil)
277                 c.Check(string(buf), Equals, `["foo",{"foo":"bar"},null]`)
278         }
279         if fi, err := fs.Stat("emptydir"); c.Check(err, IsNil) {
280                 c.Check(fi.IsDir(), Equals, true)
281         }
282         if d, err := fs.Open("emptydir"); c.Check(err, IsNil) {
283                 defer d.Close()
284                 fis, err := d.Readdir(-1)
285                 c.Assert(err, IsNil)
286                 // crunch-run still saves a ".keep" file to preserve
287                 // empty dirs even though that shouldn't be
288                 // necessary. Ideally we would do:
289                 // c.Check(fis, HasLen, 0)
290                 for _, fi := range fis {
291                         c.Check(fi.Name(), Equals, ".keep")
292                 }
293         }
294         s.outputCollection = output
295 }