Merge branch '14196-api-v2-tokens' refs #14196
[arvados.git] / services / crunch-run / crunchrun_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "bufio"
9         "bytes"
10         "crypto/md5"
11         "encoding/json"
12         "errors"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "os"
18         "os/exec"
19         "runtime/pprof"
20         "sort"
21         "strings"
22         "sync"
23         "syscall"
24         "testing"
25         "time"
26
27         "git.curoverse.com/arvados.git/sdk/go/arvados"
28         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
29         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
30         "git.curoverse.com/arvados.git/sdk/go/manifest"
31         "golang.org/x/net/context"
32
33         dockertypes "github.com/docker/docker/api/types"
34         dockercontainer "github.com/docker/docker/api/types/container"
35         dockernetwork "github.com/docker/docker/api/types/network"
36         . "gopkg.in/check.v1"
37 )
38
39 // Gocheck boilerplate
40 func TestCrunchExec(t *testing.T) {
41         TestingT(t)
42 }
43
44 // Gocheck boilerplate
45 var _ = Suite(&TestSuite{})
46
47 type TestSuite struct {
48         client *arvados.Client
49         docker *TestDockerClient
50 }
51
52 func (s *TestSuite) SetUpTest(c *C) {
53         s.client = arvados.NewClientFromEnv()
54         s.docker = NewTestDockerClient()
55 }
56
57 type ArvTestClient struct {
58         Total   int64
59         Calls   int
60         Content []arvadosclient.Dict
61         arvados.Container
62         secretMounts []byte
63         Logs         map[string]*bytes.Buffer
64         sync.Mutex
65         WasSetRunning bool
66         callraw       bool
67 }
68
69 type KeepTestClient struct {
70         Called  bool
71         Content []byte
72 }
73
74 var hwManifest = ". 82ab40c24fc8df01798e57ba66795bb1+841216+Aa124ac75e5168396c73c0a18eda641a4f41791c0@569fa8c3 0:841216:9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7.tar\n"
75 var hwPDH = "a45557269dcb65a6b78f9ac061c0850b+120"
76 var hwImageId = "9c31ee32b3d15268a0754e8edc74d4f815ee014b693bc5109058e431dd5caea7"
77
78 var otherManifest = ". 68a84f561b1d1708c6baff5e019a9ab3+46+Ae5d0af96944a3690becb1decdf60cc1c937f556d@5693216f 0:46:md5sum.txt\n"
79 var otherPDH = "a3e8f74c6f101eae01fa08bfb4e49b3a+54"
80
81 var normalizedManifestWithSubdirs = `. 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 0:9:file1_in_main.txt 9:18:file2_in_main.txt 0:27:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt
82 ./subdir1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
83 ./subdir1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
84 `
85
86 var normalizedWithSubdirsPDH = "a0def87f80dd594d4675809e83bd4f15+367"
87
88 var denormalizedManifestWithSubdirs = ". 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 0:9:file1_in_main.txt 9:18:file2_in_main.txt 0:27:zzzzz-8i9sb-bcdefghijkdhvnk.log.txt 0:10:subdir1/file1_in_subdir1.txt 10:17:subdir1/file2_in_subdir1.txt\n"
89 var denormalizedWithSubdirsPDH = "b0def87f80dd594d4675809e83bd4f15+367"
90
91 var fakeAuthUUID = "zzzzz-gj3su-55pqoyepgi2glem"
92 var fakeAuthToken = "a3ltuwzqcu2u4sc0q7yhpc2w7s00fdcqecg5d6e0u3pfohmbjt"
93
94 type TestDockerClient struct {
95         imageLoaded string
96         logReader   io.ReadCloser
97         logWriter   io.WriteCloser
98         fn          func(t *TestDockerClient)
99         exitCode    int
100         stop        chan bool
101         cwd         string
102         env         []string
103         api         *ArvTestClient
104         realTemp    string
105         calledWait  bool
106 }
107
108 func NewTestDockerClient() *TestDockerClient {
109         t := &TestDockerClient{}
110         t.logReader, t.logWriter = io.Pipe()
111         t.stop = make(chan bool, 1)
112         t.cwd = "/"
113         return t
114 }
115
116 type MockConn struct {
117         net.Conn
118 }
119
120 func (m *MockConn) Write(b []byte) (int, error) {
121         return len(b), nil
122 }
123
124 func NewMockConn() *MockConn {
125         c := &MockConn{}
126         return c
127 }
128
129 func (t *TestDockerClient) ContainerAttach(ctx context.Context, container string, options dockertypes.ContainerAttachOptions) (dockertypes.HijackedResponse, error) {
130         return dockertypes.HijackedResponse{Conn: NewMockConn(), Reader: bufio.NewReader(t.logReader)}, nil
131 }
132
133 func (t *TestDockerClient) ContainerCreate(ctx context.Context, config *dockercontainer.Config, hostConfig *dockercontainer.HostConfig, networkingConfig *dockernetwork.NetworkingConfig, containerName string) (dockercontainer.ContainerCreateCreatedBody, error) {
134         if config.WorkingDir != "" {
135                 t.cwd = config.WorkingDir
136         }
137         t.env = config.Env
138         return dockercontainer.ContainerCreateCreatedBody{ID: "abcde"}, nil
139 }
140
141 func (t *TestDockerClient) ContainerStart(ctx context.Context, container string, options dockertypes.ContainerStartOptions) error {
142         if t.exitCode == 3 {
143                 return errors.New(`Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:54: mounting \\\"/tmp/keep453790790/by_id/99999999999999999999999999999999+99999/myGenome\\\" to rootfs \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged\\\" at \\\"/tmp/docker/overlay2/9999999999999999999999999999999999999999999999999999999999999999/merged/keep/99999999999999999999999999999999+99999/myGenome\\\" caused \\\"no such file or directory\\\"\""`)
144         }
145         if t.exitCode == 4 {
146                 return errors.New(`panic: standard_init_linux.go:175: exec user process caused "no such file or directory"`)
147         }
148         if t.exitCode == 5 {
149                 return errors.New(`Error response from daemon: Cannot start container 41f26cbc43bcc1280f4323efb1830a394ba8660c9d1c2b564ba42bf7f7694845: [8] System error: no such file or directory`)
150         }
151         if t.exitCode == 6 {
152                 return errors.New(`Error response from daemon: Cannot start container 58099cd76c834f3dc2a4fb76c8028f049ae6d4fdf0ec373e1f2cfea030670c2d: [8] System error: exec: "foobar": executable file not found in $PATH`)
153         }
154
155         if container == "abcde" {
156                 // t.fn gets executed in ContainerWait
157                 return nil
158         } else {
159                 return errors.New("Invalid container id")
160         }
161 }
162
163 func (t *TestDockerClient) ContainerRemove(ctx context.Context, container string, options dockertypes.ContainerRemoveOptions) error {
164         t.stop <- true
165         return nil
166 }
167
168 func (t *TestDockerClient) ContainerWait(ctx context.Context, container string, condition dockercontainer.WaitCondition) (<-chan dockercontainer.ContainerWaitOKBody, <-chan error) {
169         t.calledWait = true
170         body := make(chan dockercontainer.ContainerWaitOKBody, 1)
171         err := make(chan error)
172         go func() {
173                 t.fn(t)
174                 body <- dockercontainer.ContainerWaitOKBody{StatusCode: int64(t.exitCode)}
175         }()
176         return body, err
177 }
178
179 func (t *TestDockerClient) ImageInspectWithRaw(ctx context.Context, image string) (dockertypes.ImageInspect, []byte, error) {
180         if t.exitCode == 2 {
181                 return dockertypes.ImageInspect{}, nil, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
182         }
183
184         if t.imageLoaded == image {
185                 return dockertypes.ImageInspect{}, nil, nil
186         } else {
187                 return dockertypes.ImageInspect{}, nil, errors.New("")
188         }
189 }
190
191 func (t *TestDockerClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (dockertypes.ImageLoadResponse, error) {
192         if t.exitCode == 2 {
193                 return dockertypes.ImageLoadResponse{}, fmt.Errorf("Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?")
194         }
195         _, err := io.Copy(ioutil.Discard, input)
196         if err != nil {
197                 return dockertypes.ImageLoadResponse{}, err
198         } else {
199                 t.imageLoaded = hwImageId
200                 return dockertypes.ImageLoadResponse{Body: ioutil.NopCloser(input)}, nil
201         }
202 }
203
204 func (*TestDockerClient) ImageRemove(ctx context.Context, image string, options dockertypes.ImageRemoveOptions) ([]dockertypes.ImageDeleteResponseItem, error) {
205         return nil, nil
206 }
207
208 func (client *ArvTestClient) Create(resourceType string,
209         parameters arvadosclient.Dict,
210         output interface{}) error {
211
212         client.Mutex.Lock()
213         defer client.Mutex.Unlock()
214
215         client.Calls++
216         client.Content = append(client.Content, parameters)
217
218         if resourceType == "logs" {
219                 et := parameters["log"].(arvadosclient.Dict)["event_type"].(string)
220                 if client.Logs == nil {
221                         client.Logs = make(map[string]*bytes.Buffer)
222                 }
223                 if client.Logs[et] == nil {
224                         client.Logs[et] = &bytes.Buffer{}
225                 }
226                 client.Logs[et].Write([]byte(parameters["log"].(arvadosclient.Dict)["properties"].(map[string]string)["text"]))
227         }
228
229         if resourceType == "collections" && output != nil {
230                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
231                 outmap := output.(*arvados.Collection)
232                 outmap.PortableDataHash = fmt.Sprintf("%x+%d", md5.Sum([]byte(mt)), len(mt))
233                 outmap.UUID = fmt.Sprintf("zzzzz-4zz18-%15.15x", md5.Sum([]byte(mt)))
234         }
235
236         return nil
237 }
238
239 func (client *ArvTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
240         switch {
241         case method == "GET" && resourceType == "containers" && action == "auth":
242                 return json.Unmarshal([]byte(`{
243                         "kind": "arvados#api_client_authorization",
244                         "uuid": "`+fakeAuthUUID+`",
245                         "api_token": "`+fakeAuthToken+`"
246                         }`), output)
247         case method == "GET" && resourceType == "containers" && action == "secret_mounts":
248                 if client.secretMounts != nil {
249                         return json.Unmarshal(client.secretMounts, output)
250                 } else {
251                         return json.Unmarshal([]byte(`{"secret_mounts":{}}`), output)
252                 }
253         default:
254                 return fmt.Errorf("Not found")
255         }
256 }
257
258 func (client *ArvTestClient) CallRaw(method, resourceType, uuid, action string,
259         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
260         var j []byte
261         if method == "GET" && resourceType == "nodes" && uuid == "" && action == "" {
262                 j = []byte(`{
263                         "kind": "arvados#nodeList",
264                         "items": [{
265                                 "uuid": "zzzzz-7ekkf-2z3mc76g2q73aio",
266                                 "hostname": "compute2",
267                                 "properties": {"total_cpu_cores": 16}
268                         }]}`)
269         } else if method == "GET" && resourceType == "containers" && action == "" && !client.callraw {
270                 if uuid == "" {
271                         j, err = json.Marshal(map[string]interface{}{
272                                 "items": []interface{}{client.Container},
273                                 "kind":  "arvados#nodeList",
274                         })
275                 } else {
276                         j, err = json.Marshal(client.Container)
277                 }
278         } else {
279                 j = []byte(`{
280                         "command": ["sleep", "1"],
281                         "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
282                         "cwd": ".",
283                         "environment": {},
284                         "mounts": {"/tmp": {"kind": "tmp"}, "/json": {"kind": "json", "content": {"number": 123456789123456789}}},
285                         "output_path": "/tmp",
286                         "priority": 1,
287                         "runtime_constraints": {}
288                 }`)
289         }
290         return ioutil.NopCloser(bytes.NewReader(j)), err
291 }
292
293 func (client *ArvTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
294         if resourceType == "collections" {
295                 if uuid == hwPDH {
296                         output.(*arvados.Collection).ManifestText = hwManifest
297                 } else if uuid == otherPDH {
298                         output.(*arvados.Collection).ManifestText = otherManifest
299                 } else if uuid == normalizedWithSubdirsPDH {
300                         output.(*arvados.Collection).ManifestText = normalizedManifestWithSubdirs
301                 } else if uuid == denormalizedWithSubdirsPDH {
302                         output.(*arvados.Collection).ManifestText = denormalizedManifestWithSubdirs
303                 }
304         }
305         if resourceType == "containers" {
306                 (*output.(*arvados.Container)) = client.Container
307         }
308         return nil
309 }
310
311 func (client *ArvTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
312         client.Mutex.Lock()
313         defer client.Mutex.Unlock()
314         client.Calls++
315         client.Content = append(client.Content, parameters)
316         if resourceType == "containers" {
317                 if parameters["container"].(arvadosclient.Dict)["state"] == "Running" {
318                         client.WasSetRunning = true
319                 }
320         } else if resourceType == "collections" {
321                 mt := parameters["collection"].(arvadosclient.Dict)["manifest_text"].(string)
322                 output.(*arvados.Collection).UUID = uuid
323                 output.(*arvados.Collection).PortableDataHash = fmt.Sprintf("%x", md5.Sum([]byte(mt)))
324         }
325         return nil
326 }
327
328 var discoveryMap = map[string]interface{}{
329         "defaultTrashLifetime":               float64(1209600),
330         "crunchLimitLogBytesPerJob":          float64(67108864),
331         "crunchLogThrottleBytes":             float64(65536),
332         "crunchLogThrottlePeriod":            float64(60),
333         "crunchLogThrottleLines":             float64(1024),
334         "crunchLogPartialLineThrottlePeriod": float64(5),
335         "crunchLogBytesPerEvent":             float64(4096),
336         "crunchLogSecondsBetweenEvents":      float64(1),
337 }
338
339 func (client *ArvTestClient) Discovery(key string) (interface{}, error) {
340         return discoveryMap[key], nil
341 }
342
343 // CalledWith returns the parameters from the first API call whose
344 // parameters match jpath/string. E.g., CalledWith(c, "foo.bar",
345 // "baz") returns parameters with parameters["foo"]["bar"]=="baz". If
346 // no call matches, it returns nil.
347 func (client *ArvTestClient) CalledWith(jpath string, expect interface{}) arvadosclient.Dict {
348 call:
349         for _, content := range client.Content {
350                 var v interface{} = content
351                 for _, k := range strings.Split(jpath, ".") {
352                         if dict, ok := v.(arvadosclient.Dict); !ok {
353                                 continue call
354                         } else {
355                                 v = dict[k]
356                         }
357                 }
358                 if v == expect {
359                         return content
360                 }
361         }
362         return nil
363 }
364
365 func (client *KeepTestClient) PutB(buf []byte) (string, int, error) {
366         client.Content = buf
367         return fmt.Sprintf("%x+%d", md5.Sum(buf), len(buf)), len(buf), nil
368 }
369
370 func (client *KeepTestClient) ReadAt(string, []byte, int) (int, error) {
371         return 0, errors.New("not implemented")
372 }
373
374 func (client *KeepTestClient) ClearBlockCache() {
375 }
376
377 func (client *KeepTestClient) Close() {
378         client.Content = nil
379 }
380
381 type FileWrapper struct {
382         io.ReadCloser
383         len int64
384 }
385
386 func (fw FileWrapper) Readdir(n int) ([]os.FileInfo, error) {
387         return nil, errors.New("not implemented")
388 }
389
390 func (fw FileWrapper) Seek(int64, int) (int64, error) {
391         return 0, errors.New("not implemented")
392 }
393
394 func (fw FileWrapper) Size() int64 {
395         return fw.len
396 }
397
398 func (fw FileWrapper) Stat() (os.FileInfo, error) {
399         return nil, errors.New("not implemented")
400 }
401
402 func (fw FileWrapper) Truncate(int64) error {
403         return errors.New("not implemented")
404 }
405
406 func (fw FileWrapper) Write([]byte) (int, error) {
407         return 0, errors.New("not implemented")
408 }
409
410 func (fw FileWrapper) Sync() error {
411         return errors.New("not implemented")
412 }
413
414 func (client *KeepTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
415         if filename == hwImageId+".tar" {
416                 rdr := ioutil.NopCloser(&bytes.Buffer{})
417                 client.Called = true
418                 return FileWrapper{rdr, 1321984}, nil
419         } else if filename == "/file1_in_main.txt" {
420                 rdr := ioutil.NopCloser(strings.NewReader("foo"))
421                 client.Called = true
422                 return FileWrapper{rdr, 3}, nil
423         }
424         return nil, nil
425 }
426
427 func (s *TestSuite) TestLoadImage(c *C) {
428         kc := &KeepTestClient{}
429         defer kc.Close()
430         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
431         c.Assert(err, IsNil)
432
433         _, err = cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
434         c.Check(err, IsNil)
435
436         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
437         c.Check(err, NotNil)
438
439         cr.Container.ContainerImage = hwPDH
440
441         // (1) Test loading image from keep
442         c.Check(kc.Called, Equals, false)
443         c.Check(cr.ContainerConfig.Image, Equals, "")
444
445         err = cr.LoadImage()
446
447         c.Check(err, IsNil)
448         defer func() {
449                 cr.Docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
450         }()
451
452         c.Check(kc.Called, Equals, true)
453         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
454
455         _, _, err = cr.Docker.ImageInspectWithRaw(nil, hwImageId)
456         c.Check(err, IsNil)
457
458         // (2) Test using image that's already loaded
459         kc.Called = false
460         cr.ContainerConfig.Image = ""
461
462         err = cr.LoadImage()
463         c.Check(err, IsNil)
464         c.Check(kc.Called, Equals, false)
465         c.Check(cr.ContainerConfig.Image, Equals, hwImageId)
466
467 }
468
469 type ArvErrorTestClient struct{}
470
471 func (ArvErrorTestClient) Create(resourceType string,
472         parameters arvadosclient.Dict,
473         output interface{}) error {
474         return nil
475 }
476
477 func (ArvErrorTestClient) Call(method, resourceType, uuid, action string, parameters arvadosclient.Dict, output interface{}) error {
478         return errors.New("ArvError")
479 }
480
481 func (ArvErrorTestClient) CallRaw(method, resourceType, uuid, action string,
482         parameters arvadosclient.Dict) (reader io.ReadCloser, err error) {
483         return nil, errors.New("ArvError")
484 }
485
486 func (ArvErrorTestClient) Get(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) error {
487         return errors.New("ArvError")
488 }
489
490 func (ArvErrorTestClient) Update(resourceType string, uuid string, parameters arvadosclient.Dict, output interface{}) (err error) {
491         return nil
492 }
493
494 func (ArvErrorTestClient) Discovery(key string) (interface{}, error) {
495         return discoveryMap[key], nil
496 }
497
498 type KeepErrorTestClient struct {
499         KeepTestClient
500 }
501
502 func (*KeepErrorTestClient) ManifestFileReader(manifest.Manifest, string) (arvados.File, error) {
503         return nil, errors.New("KeepError")
504 }
505
506 func (*KeepErrorTestClient) PutB(buf []byte) (string, int, error) {
507         return "", 0, errors.New("KeepError")
508 }
509
510 type KeepReadErrorTestClient struct {
511         KeepTestClient
512 }
513
514 func (*KeepReadErrorTestClient) ReadAt(string, []byte, int) (int, error) {
515         return 0, errors.New("KeepError")
516 }
517
518 type ErrorReader struct {
519         FileWrapper
520 }
521
522 func (ErrorReader) Read(p []byte) (n int, err error) {
523         return 0, errors.New("ErrorReader")
524 }
525
526 func (ErrorReader) Seek(int64, int) (int64, error) {
527         return 0, errors.New("ErrorReader")
528 }
529
530 func (KeepReadErrorTestClient) ManifestFileReader(m manifest.Manifest, filename string) (arvados.File, error) {
531         return ErrorReader{}, nil
532 }
533
534 func (s *TestSuite) TestLoadImageArvError(c *C) {
535         // (1) Arvados error
536         kc := &KeepTestClient{}
537         defer kc.Close()
538         cr, err := NewContainerRunner(s.client, ArvErrorTestClient{}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
539         c.Assert(err, IsNil)
540         cr.Container.ContainerImage = hwPDH
541
542         err = cr.LoadImage()
543         c.Check(err.Error(), Equals, "While getting container image collection: ArvError")
544 }
545
546 func (s *TestSuite) TestLoadImageKeepError(c *C) {
547         // (2) Keep error
548         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
549         c.Assert(err, IsNil)
550         cr.Container.ContainerImage = hwPDH
551
552         err = cr.LoadImage()
553         c.Assert(err, NotNil)
554         c.Check(err.Error(), Equals, "While creating ManifestFileReader for container image: KeepError")
555 }
556
557 func (s *TestSuite) TestLoadImageCollectionError(c *C) {
558         // (3) Collection doesn't contain image
559         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
560         c.Assert(err, IsNil)
561         cr.Container.ContainerImage = otherPDH
562
563         err = cr.LoadImage()
564         c.Check(err.Error(), Equals, "First file in the container image collection does not end in .tar")
565 }
566
567 func (s *TestSuite) TestLoadImageKeepReadError(c *C) {
568         // (4) Collection doesn't contain image
569         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, &KeepReadErrorTestClient{}, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
570         c.Assert(err, IsNil)
571         cr.Container.ContainerImage = hwPDH
572
573         err = cr.LoadImage()
574         c.Check(err, NotNil)
575 }
576
577 type ClosableBuffer struct {
578         bytes.Buffer
579 }
580
581 func (*ClosableBuffer) Close() error {
582         return nil
583 }
584
585 type TestLogs struct {
586         Stdout ClosableBuffer
587         Stderr ClosableBuffer
588 }
589
590 func (tl *TestLogs) NewTestLoggingWriter(logstr string) (io.WriteCloser, error) {
591         if logstr == "stdout" {
592                 return &tl.Stdout, nil
593         }
594         if logstr == "stderr" {
595                 return &tl.Stderr, nil
596         }
597         return nil, errors.New("???")
598 }
599
600 func dockerLog(fd byte, msg string) []byte {
601         by := []byte(msg)
602         header := make([]byte, 8+len(by))
603         header[0] = fd
604         header[7] = byte(len(by))
605         copy(header[8:], by)
606         return header
607 }
608
609 func (s *TestSuite) TestRunContainer(c *C) {
610         s.docker.fn = func(t *TestDockerClient) {
611                 t.logWriter.Write(dockerLog(1, "Hello world\n"))
612                 t.logWriter.Close()
613         }
614         kc := &KeepTestClient{}
615         defer kc.Close()
616         cr, err := NewContainerRunner(s.client, &ArvTestClient{}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
617         c.Assert(err, IsNil)
618
619         var logs TestLogs
620         cr.NewLogWriter = logs.NewTestLoggingWriter
621         cr.Container.ContainerImage = hwPDH
622         cr.Container.Command = []string{"./hw"}
623         err = cr.LoadImage()
624         c.Check(err, IsNil)
625
626         err = cr.CreateContainer()
627         c.Check(err, IsNil)
628
629         err = cr.StartContainer()
630         c.Check(err, IsNil)
631
632         err = cr.WaitFinish()
633         c.Check(err, IsNil)
634
635         c.Check(strings.HasSuffix(logs.Stdout.String(), "Hello world\n"), Equals, true)
636         c.Check(logs.Stderr.String(), Equals, "")
637 }
638
639 func (s *TestSuite) TestCommitLogs(c *C) {
640         api := &ArvTestClient{}
641         kc := &KeepTestClient{}
642         defer kc.Close()
643         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
644         c.Assert(err, IsNil)
645         cr.CrunchLog.Timestamper = (&TestTimestamper{}).Timestamp
646
647         cr.CrunchLog.Print("Hello world!")
648         cr.CrunchLog.Print("Goodbye")
649         cr.finalState = "Complete"
650
651         err = cr.CommitLogs()
652         c.Check(err, IsNil)
653
654         c.Check(api.Calls, Equals, 2)
655         c.Check(api.Content[1]["ensure_unique_name"], Equals, true)
656         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["name"], Equals, "logs for zzzzz-zzzzz-zzzzzzzzzzzzzzz")
657         c.Check(api.Content[1]["collection"].(arvadosclient.Dict)["manifest_text"], Equals, ". 744b2e4553123b02fa7b452ec5c18993+123 0:123:crunch-run.txt\n")
658         c.Check(*cr.LogsPDH, Equals, "63da7bdacf08c40f604daad80c261e9a+60")
659 }
660
661 func (s *TestSuite) TestUpdateContainerRunning(c *C) {
662         api := &ArvTestClient{}
663         kc := &KeepTestClient{}
664         defer kc.Close()
665         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
666         c.Assert(err, IsNil)
667
668         err = cr.UpdateContainerRunning()
669         c.Check(err, IsNil)
670
671         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Running")
672 }
673
674 func (s *TestSuite) TestUpdateContainerComplete(c *C) {
675         api := &ArvTestClient{}
676         kc := &KeepTestClient{}
677         defer kc.Close()
678         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
679         c.Assert(err, IsNil)
680
681         cr.LogsPDH = new(string)
682         *cr.LogsPDH = "d3a229d2fe3690c2c3e75a71a153c6a3+60"
683
684         cr.ExitCode = new(int)
685         *cr.ExitCode = 42
686         cr.finalState = "Complete"
687
688         err = cr.UpdateContainerFinal()
689         c.Check(err, IsNil)
690
691         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], Equals, *cr.LogsPDH)
692         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], Equals, *cr.ExitCode)
693         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Complete")
694 }
695
696 func (s *TestSuite) TestUpdateContainerCancelled(c *C) {
697         api := &ArvTestClient{}
698         kc := &KeepTestClient{}
699         defer kc.Close()
700         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
701         c.Assert(err, IsNil)
702         cr.cCancelled = true
703         cr.finalState = "Cancelled"
704
705         err = cr.UpdateContainerFinal()
706         c.Check(err, IsNil)
707
708         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["log"], IsNil)
709         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["exit_code"], IsNil)
710         c.Check(api.Content[0]["container"].(arvadosclient.Dict)["state"], Equals, "Cancelled")
711 }
712
713 // Used by the TestFullRun*() test below to DRY up boilerplate setup to do full
714 // dress rehearsal of the Run() function, starting from a JSON container record.
715 func (s *TestSuite) fullRunHelper(c *C, record string, extraMounts []string, exitCode int, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, realTemp string) {
716         rec := arvados.Container{}
717         err := json.Unmarshal([]byte(record), &rec)
718         c.Check(err, IsNil)
719
720         var sm struct {
721                 SecretMounts map[string]arvados.Mount `json:"secret_mounts"`
722         }
723         err = json.Unmarshal([]byte(record), &sm)
724         c.Check(err, IsNil)
725         secretMounts, err := json.Marshal(sm)
726         c.Logf("%s %q", sm, secretMounts)
727         c.Check(err, IsNil)
728
729         s.docker.exitCode = exitCode
730         s.docker.fn = fn
731         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
732
733         api = &ArvTestClient{Container: rec}
734         s.docker.api = api
735         kc := &KeepTestClient{}
736         defer kc.Close()
737         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
738         c.Assert(err, IsNil)
739         cr.statInterval = 100 * time.Millisecond
740         am := &ArvMountCmdLine{}
741         cr.RunArvMount = am.ArvMountTest
742
743         realTemp, err = ioutil.TempDir("", "crunchrun_test1-")
744         c.Assert(err, IsNil)
745         defer os.RemoveAll(realTemp)
746
747         s.docker.realTemp = realTemp
748
749         tempcount := 0
750         cr.MkTempDir = func(_ string, prefix string) (string, error) {
751                 tempcount++
752                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, tempcount)
753                 err := os.Mkdir(d, os.ModePerm)
754                 if err != nil && strings.Contains(err.Error(), ": file exists") {
755                         // Test case must have pre-populated the tempdir
756                         err = nil
757                 }
758                 return d, err
759         }
760         cr.MkArvClient = func(token string) (IArvadosClient, error) {
761                 return &ArvTestClient{secretMounts: secretMounts}, nil
762         }
763
764         if extraMounts != nil && len(extraMounts) > 0 {
765                 err := cr.SetupArvMountPoint("keep")
766                 c.Check(err, IsNil)
767
768                 for _, m := range extraMounts {
769                         os.MkdirAll(cr.ArvMountPoint+"/by_id/"+m, os.ModePerm)
770                 }
771         }
772
773         err = cr.Run()
774         if api.CalledWith("container.state", "Complete") != nil {
775                 c.Check(err, IsNil)
776         }
777         if exitCode != 2 {
778                 c.Check(api.WasSetRunning, Equals, true)
779                 c.Check(api.Content[api.Calls-2]["container"].(arvadosclient.Dict)["log"], NotNil)
780         }
781
782         if err != nil {
783                 for k, v := range api.Logs {
784                         c.Log(k)
785                         c.Log(v.String())
786                 }
787         }
788
789         return
790 }
791
792 func (s *TestSuite) TestFullRunHello(c *C) {
793         api, _, _ := s.fullRunHelper(c, `{
794     "command": ["echo", "hello world"],
795     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
796     "cwd": ".",
797     "environment": {},
798     "mounts": {"/tmp": {"kind": "tmp"} },
799     "output_path": "/tmp",
800     "priority": 1,
801         "runtime_constraints": {}
802 }`, nil, 0, func(t *TestDockerClient) {
803                 t.logWriter.Write(dockerLog(1, "hello world\n"))
804                 t.logWriter.Close()
805         })
806
807         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
808         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
809         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello world\n"), Equals, true)
810
811 }
812
813 func (s *TestSuite) TestRunTimeExceeded(c *C) {
814         api, _, _ := s.fullRunHelper(c, `{
815     "command": ["sleep", "3"],
816     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
817     "cwd": ".",
818     "environment": {},
819     "mounts": {"/tmp": {"kind": "tmp"} },
820     "output_path": "/tmp",
821     "priority": 1,
822         "runtime_constraints": {},
823         "scheduling_parameters":{"max_run_time": 1}
824 }`, nil, 0, func(t *TestDockerClient) {
825                 time.Sleep(3 * time.Second)
826                 t.logWriter.Close()
827         })
828
829         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
830         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*maximum run time exceeded.*")
831 }
832
833 func (s *TestSuite) TestCrunchstat(c *C) {
834         api, _, _ := s.fullRunHelper(c, `{
835                 "command": ["sleep", "1"],
836                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
837                 "cwd": ".",
838                 "environment": {},
839                 "mounts": {"/tmp": {"kind": "tmp"} },
840                 "output_path": "/tmp",
841                 "priority": 1,
842                 "runtime_constraints": {}
843         }`, nil, 0, func(t *TestDockerClient) {
844                 time.Sleep(time.Second)
845                 t.logWriter.Close()
846         })
847
848         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
849         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
850
851         // We didn't actually start a container, so crunchstat didn't
852         // find accounting files and therefore didn't log any stats.
853         // It should have logged a "can't find accounting files"
854         // message after one poll interval, though, so we can confirm
855         // it's alive:
856         c.Assert(api.Logs["crunchstat"], NotNil)
857         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files have not appeared after 100ms.*`)
858
859         // The "files never appeared" log assures us that we called
860         // (*crunchstat.Reporter)Stop(), and that we set it up with
861         // the correct container ID "abcde":
862         c.Check(api.Logs["crunchstat"].String(), Matches, `(?ms).*cgroup stats files never appeared for abcde\n`)
863 }
864
865 func (s *TestSuite) TestNodeInfoLog(c *C) {
866         os.Setenv("SLURMD_NODENAME", "compute2")
867         api, _, _ := s.fullRunHelper(c, `{
868                 "command": ["sleep", "1"],
869                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
870                 "cwd": ".",
871                 "environment": {},
872                 "mounts": {"/tmp": {"kind": "tmp"} },
873                 "output_path": "/tmp",
874                 "priority": 1,
875                 "runtime_constraints": {}
876         }`, nil, 0,
877                 func(t *TestDockerClient) {
878                         time.Sleep(time.Second)
879                         t.logWriter.Close()
880                 })
881
882         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
883         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
884
885         c.Assert(api.Logs["node"], NotNil)
886         json := api.Logs["node"].String()
887         c.Check(json, Matches, `(?ms).*"uuid": *"zzzzz-7ekkf-2z3mc76g2q73aio".*`)
888         c.Check(json, Matches, `(?ms).*"total_cpu_cores": *16.*`)
889         c.Check(json, Not(Matches), `(?ms).*"info":.*`)
890
891         c.Assert(api.Logs["node-info"], NotNil)
892         json = api.Logs["node-info"].String()
893         c.Check(json, Matches, `(?ms).*Host Information.*`)
894         c.Check(json, Matches, `(?ms).*CPU Information.*`)
895         c.Check(json, Matches, `(?ms).*Memory Information.*`)
896         c.Check(json, Matches, `(?ms).*Disk Space.*`)
897         c.Check(json, Matches, `(?ms).*Disk INodes.*`)
898 }
899
900 func (s *TestSuite) TestContainerRecordLog(c *C) {
901         api, _, _ := s.fullRunHelper(c, `{
902                 "command": ["sleep", "1"],
903                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
904                 "cwd": ".",
905                 "environment": {},
906                 "mounts": {"/tmp": {"kind": "tmp"} },
907                 "output_path": "/tmp",
908                 "priority": 1,
909                 "runtime_constraints": {}
910         }`, nil, 0,
911                 func(t *TestDockerClient) {
912                         time.Sleep(time.Second)
913                         t.logWriter.Close()
914                 })
915
916         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
917         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
918
919         c.Assert(api.Logs["container"], NotNil)
920         c.Check(api.Logs["container"].String(), Matches, `(?ms).*container_image.*`)
921 }
922
923 func (s *TestSuite) TestFullRunStderr(c *C) {
924         api, _, _ := s.fullRunHelper(c, `{
925     "command": ["/bin/sh", "-c", "echo hello ; echo world 1>&2 ; exit 1"],
926     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
927     "cwd": ".",
928     "environment": {},
929     "mounts": {"/tmp": {"kind": "tmp"} },
930     "output_path": "/tmp",
931     "priority": 1,
932     "runtime_constraints": {}
933 }`, nil, 1, func(t *TestDockerClient) {
934                 t.logWriter.Write(dockerLog(1, "hello\n"))
935                 t.logWriter.Write(dockerLog(2, "world\n"))
936                 t.logWriter.Close()
937         })
938
939         final := api.CalledWith("container.state", "Complete")
940         c.Assert(final, NotNil)
941         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
942         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
943
944         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "hello\n"), Equals, true)
945         c.Check(strings.HasSuffix(api.Logs["stderr"].String(), "world\n"), Equals, true)
946 }
947
948 func (s *TestSuite) TestFullRunDefaultCwd(c *C) {
949         api, _, _ := s.fullRunHelper(c, `{
950     "command": ["pwd"],
951     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
952     "cwd": ".",
953     "environment": {},
954     "mounts": {"/tmp": {"kind": "tmp"} },
955     "output_path": "/tmp",
956     "priority": 1,
957     "runtime_constraints": {}
958 }`, nil, 0, func(t *TestDockerClient) {
959                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
960                 t.logWriter.Close()
961         })
962
963         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
964         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
965         c.Log(api.Logs["stdout"])
966         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/\n"), Equals, true)
967 }
968
969 func (s *TestSuite) TestFullRunSetCwd(c *C) {
970         api, _, _ := s.fullRunHelper(c, `{
971     "command": ["pwd"],
972     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
973     "cwd": "/bin",
974     "environment": {},
975     "mounts": {"/tmp": {"kind": "tmp"} },
976     "output_path": "/tmp",
977     "priority": 1,
978     "runtime_constraints": {}
979 }`, nil, 0, func(t *TestDockerClient) {
980                 t.logWriter.Write(dockerLog(1, t.cwd+"\n"))
981                 t.logWriter.Close()
982         })
983
984         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
985         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
986         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "/bin\n"), Equals, true)
987 }
988
989 func (s *TestSuite) TestStopOnSignal(c *C) {
990         s.testStopContainer(c, func(cr *ContainerRunner) {
991                 go func() {
992                         for !s.docker.calledWait {
993                                 time.Sleep(time.Millisecond)
994                         }
995                         cr.SigChan <- syscall.SIGINT
996                 }()
997         })
998 }
999
1000 func (s *TestSuite) TestStopOnArvMountDeath(c *C) {
1001         s.testStopContainer(c, func(cr *ContainerRunner) {
1002                 cr.ArvMountExit = make(chan error)
1003                 go func() {
1004                         cr.ArvMountExit <- exec.Command("true").Run()
1005                         close(cr.ArvMountExit)
1006                 }()
1007         })
1008 }
1009
1010 func (s *TestSuite) testStopContainer(c *C, setup func(cr *ContainerRunner)) {
1011         record := `{
1012     "command": ["/bin/sh", "-c", "echo foo && sleep 30 && echo bar"],
1013     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1014     "cwd": ".",
1015     "environment": {},
1016     "mounts": {"/tmp": {"kind": "tmp"} },
1017     "output_path": "/tmp",
1018     "priority": 1,
1019     "runtime_constraints": {}
1020 }`
1021
1022         rec := arvados.Container{}
1023         err := json.Unmarshal([]byte(record), &rec)
1024         c.Check(err, IsNil)
1025
1026         s.docker.fn = func(t *TestDockerClient) {
1027                 <-t.stop
1028                 t.logWriter.Write(dockerLog(1, "foo\n"))
1029                 t.logWriter.Close()
1030         }
1031         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1032
1033         api := &ArvTestClient{Container: rec}
1034         kc := &KeepTestClient{}
1035         defer kc.Close()
1036         cr, err := NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1037         c.Assert(err, IsNil)
1038         cr.RunArvMount = func([]string, string) (*exec.Cmd, error) { return nil, nil }
1039         cr.MkArvClient = func(token string) (IArvadosClient, error) {
1040                 return &ArvTestClient{}, nil
1041         }
1042         setup(cr)
1043
1044         done := make(chan error)
1045         go func() {
1046                 done <- cr.Run()
1047         }()
1048         select {
1049         case <-time.After(20 * time.Second):
1050                 pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
1051                 c.Fatal("timed out")
1052         case err = <-done:
1053                 c.Check(err, IsNil)
1054         }
1055         for k, v := range api.Logs {
1056                 c.Log(k)
1057                 c.Log(v.String())
1058         }
1059
1060         c.Check(api.CalledWith("container.log", nil), NotNil)
1061         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1062         c.Check(api.Logs["stdout"].String(), Matches, "(?ms).*foo\n$")
1063 }
1064
1065 func (s *TestSuite) TestFullRunSetEnv(c *C) {
1066         api, _, _ := s.fullRunHelper(c, `{
1067     "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1068     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1069     "cwd": "/bin",
1070     "environment": {"FROBIZ": "bilbo"},
1071     "mounts": {"/tmp": {"kind": "tmp"} },
1072     "output_path": "/tmp",
1073     "priority": 1,
1074     "runtime_constraints": {}
1075 }`, nil, 0, func(t *TestDockerClient) {
1076                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1077                 t.logWriter.Close()
1078         })
1079
1080         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1081         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1082         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "bilbo\n"), Equals, true)
1083 }
1084
1085 type ArvMountCmdLine struct {
1086         Cmd   []string
1087         token string
1088 }
1089
1090 func (am *ArvMountCmdLine) ArvMountTest(c []string, token string) (*exec.Cmd, error) {
1091         am.Cmd = c
1092         am.token = token
1093         return nil, nil
1094 }
1095
1096 func stubCert(temp string) string {
1097         path := temp + "/ca-certificates.crt"
1098         crt, _ := os.Create(path)
1099         crt.Close()
1100         arvadosclient.CertFiles = []string{path}
1101         return path
1102 }
1103
1104 func (s *TestSuite) TestSetupMounts(c *C) {
1105         api := &ArvTestClient{}
1106         kc := &KeepTestClient{}
1107         defer kc.Close()
1108         cr, err := NewContainerRunner(s.client, api, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1109         c.Assert(err, IsNil)
1110         am := &ArvMountCmdLine{}
1111         cr.RunArvMount = am.ArvMountTest
1112
1113         realTemp, err := ioutil.TempDir("", "crunchrun_test1-")
1114         c.Assert(err, IsNil)
1115         certTemp, err := ioutil.TempDir("", "crunchrun_test2-")
1116         c.Assert(err, IsNil)
1117         stubCertPath := stubCert(certTemp)
1118
1119         cr.parentTemp = realTemp
1120
1121         defer os.RemoveAll(realTemp)
1122         defer os.RemoveAll(certTemp)
1123
1124         i := 0
1125         cr.MkTempDir = func(_ string, prefix string) (string, error) {
1126                 i++
1127                 d := fmt.Sprintf("%s/%s%d", realTemp, prefix, i)
1128                 err := os.Mkdir(d, os.ModePerm)
1129                 if err != nil && strings.Contains(err.Error(), ": file exists") {
1130                         // Test case must have pre-populated the tempdir
1131                         err = nil
1132                 }
1133                 return d, err
1134         }
1135
1136         checkEmpty := func() {
1137                 // Should be deleted.
1138                 _, err := os.Stat(realTemp)
1139                 c.Assert(os.IsNotExist(err), Equals, true)
1140
1141                 // Now recreate it for the next test.
1142                 c.Assert(os.Mkdir(realTemp, 0777), IsNil)
1143         }
1144
1145         {
1146                 i = 0
1147                 cr.ArvMountPoint = ""
1148                 cr.Container.Mounts = make(map[string]arvados.Mount)
1149                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1150                 cr.Container.OutputPath = "/tmp"
1151                 cr.statInterval = 5 * time.Second
1152                 err := cr.SetupMounts()
1153                 c.Check(err, IsNil)
1154                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1155                         "--read-write", "--crunchstat-interval=5",
1156                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1157                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp"})
1158                 os.RemoveAll(cr.ArvMountPoint)
1159                 cr.CleanupDirs()
1160                 checkEmpty()
1161         }
1162
1163         {
1164                 i = 0
1165                 cr.ArvMountPoint = ""
1166                 cr.Container.Mounts = make(map[string]arvados.Mount)
1167                 cr.Container.Mounts["/out"] = arvados.Mount{Kind: "tmp"}
1168                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1169                 cr.Container.OutputPath = "/out"
1170
1171                 err := cr.SetupMounts()
1172                 c.Check(err, IsNil)
1173                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1174                         "--read-write", "--crunchstat-interval=5",
1175                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1176                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/out", realTemp + "/tmp3:/tmp"})
1177                 os.RemoveAll(cr.ArvMountPoint)
1178                 cr.CleanupDirs()
1179                 checkEmpty()
1180         }
1181
1182         {
1183                 i = 0
1184                 cr.ArvMountPoint = ""
1185                 cr.Container.Mounts = make(map[string]arvados.Mount)
1186                 cr.Container.Mounts["/tmp"] = arvados.Mount{Kind: "tmp"}
1187                 cr.Container.OutputPath = "/tmp"
1188
1189                 apiflag := true
1190                 cr.Container.RuntimeConstraints.API = &apiflag
1191
1192                 err := cr.SetupMounts()
1193                 c.Check(err, IsNil)
1194                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1195                         "--read-write", "--crunchstat-interval=5",
1196                         "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1197                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", stubCertPath + ":/etc/arvados/ca-certificates.crt:ro"})
1198                 os.RemoveAll(cr.ArvMountPoint)
1199                 cr.CleanupDirs()
1200                 checkEmpty()
1201
1202                 apiflag = false
1203         }
1204
1205         {
1206                 i = 0
1207                 cr.ArvMountPoint = ""
1208                 cr.Container.Mounts = map[string]arvados.Mount{
1209                         "/keeptmp": {Kind: "collection", Writable: true},
1210                 }
1211                 cr.Container.OutputPath = "/keeptmp"
1212
1213                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1214
1215                 err := cr.SetupMounts()
1216                 c.Check(err, IsNil)
1217                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1218                         "--read-write", "--crunchstat-interval=5",
1219                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1220                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/tmp0:/keeptmp"})
1221                 os.RemoveAll(cr.ArvMountPoint)
1222                 cr.CleanupDirs()
1223                 checkEmpty()
1224         }
1225
1226         {
1227                 i = 0
1228                 cr.ArvMountPoint = ""
1229                 cr.Container.Mounts = map[string]arvados.Mount{
1230                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1231                         "/keepout": {Kind: "collection", Writable: true},
1232                 }
1233                 cr.Container.OutputPath = "/keepout"
1234
1235                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1236                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1237
1238                 err := cr.SetupMounts()
1239                 c.Check(err, IsNil)
1240                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1241                         "--read-write", "--crunchstat-interval=5",
1242                         "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1243                 sort.StringSlice(cr.Binds).Sort()
1244                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1245                         realTemp + "/keep1/tmp0:/keepout"})
1246                 os.RemoveAll(cr.ArvMountPoint)
1247                 cr.CleanupDirs()
1248                 checkEmpty()
1249         }
1250
1251         {
1252                 i = 0
1253                 cr.ArvMountPoint = ""
1254                 cr.Container.RuntimeConstraints.KeepCacheRAM = 512
1255                 cr.Container.Mounts = map[string]arvados.Mount{
1256                         "/keepinp": {Kind: "collection", PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53"},
1257                         "/keepout": {Kind: "collection", Writable: true},
1258                 }
1259                 cr.Container.OutputPath = "/keepout"
1260
1261                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1262                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1263
1264                 err := cr.SetupMounts()
1265                 c.Check(err, IsNil)
1266                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1267                         "--read-write", "--crunchstat-interval=5",
1268                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1269                 sort.StringSlice(cr.Binds).Sort()
1270                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53:/keepinp:ro",
1271                         realTemp + "/keep1/tmp0:/keepout"})
1272                 os.RemoveAll(cr.ArvMountPoint)
1273                 cr.CleanupDirs()
1274                 checkEmpty()
1275         }
1276
1277         for _, test := range []struct {
1278                 in  interface{}
1279                 out string
1280         }{
1281                 {in: "foo", out: `"foo"`},
1282                 {in: nil, out: `null`},
1283                 {in: map[string]int64{"foo": 123456789123456789}, out: `{"foo":123456789123456789}`},
1284         } {
1285                 i = 0
1286                 cr.ArvMountPoint = ""
1287                 cr.Container.Mounts = map[string]arvados.Mount{
1288                         "/mnt/test.json": {Kind: "json", Content: test.in},
1289                 }
1290                 err := cr.SetupMounts()
1291                 c.Check(err, IsNil)
1292                 sort.StringSlice(cr.Binds).Sort()
1293                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/json2/mountdata.json:/mnt/test.json:ro"})
1294                 content, err := ioutil.ReadFile(realTemp + "/json2/mountdata.json")
1295                 c.Check(err, IsNil)
1296                 c.Check(content, DeepEquals, []byte(test.out))
1297                 os.RemoveAll(cr.ArvMountPoint)
1298                 cr.CleanupDirs()
1299                 checkEmpty()
1300         }
1301
1302         for _, test := range []struct {
1303                 in  interface{}
1304                 out string
1305         }{
1306                 {in: "foo", out: `foo`},
1307                 {in: nil, out: "error"},
1308                 {in: map[string]int64{"foo": 123456789123456789}, out: "error"},
1309         } {
1310                 i = 0
1311                 cr.ArvMountPoint = ""
1312                 cr.Container.Mounts = map[string]arvados.Mount{
1313                         "/mnt/test.txt": {Kind: "text", Content: test.in},
1314                 }
1315                 err := cr.SetupMounts()
1316                 if test.out == "error" {
1317                         c.Check(err.Error(), Equals, "content for mount \"/mnt/test.txt\" must be a string")
1318                 } else {
1319                         c.Check(err, IsNil)
1320                         sort.StringSlice(cr.Binds).Sort()
1321                         c.Check(cr.Binds, DeepEquals, []string{realTemp + "/text2/mountdata.text:/mnt/test.txt:ro"})
1322                         content, err := ioutil.ReadFile(realTemp + "/text2/mountdata.text")
1323                         c.Check(err, IsNil)
1324                         c.Check(content, DeepEquals, []byte(test.out))
1325                 }
1326                 os.RemoveAll(cr.ArvMountPoint)
1327                 cr.CleanupDirs()
1328                 checkEmpty()
1329         }
1330
1331         // Read-only mount points are allowed underneath output_dir mount point
1332         {
1333                 i = 0
1334                 cr.ArvMountPoint = ""
1335                 cr.Container.Mounts = make(map[string]arvados.Mount)
1336                 cr.Container.Mounts = map[string]arvados.Mount{
1337                         "/tmp":     {Kind: "tmp"},
1338                         "/tmp/foo": {Kind: "collection"},
1339                 }
1340                 cr.Container.OutputPath = "/tmp"
1341
1342                 os.MkdirAll(realTemp+"/keep1/tmp0", os.ModePerm)
1343
1344                 err := cr.SetupMounts()
1345                 c.Check(err, IsNil)
1346                 c.Check(am.Cmd, DeepEquals, []string{"--foreground", "--allow-other",
1347                         "--read-write", "--crunchstat-interval=5",
1348                         "--file-cache", "512", "--mount-tmp", "tmp0", "--mount-by-pdh", "by_id", realTemp + "/keep1"})
1349                 c.Check(cr.Binds, DeepEquals, []string{realTemp + "/tmp2:/tmp", realTemp + "/keep1/tmp0:/tmp/foo:ro"})
1350                 os.RemoveAll(cr.ArvMountPoint)
1351                 cr.CleanupDirs()
1352                 checkEmpty()
1353         }
1354
1355         // Writable mount points copied to output_dir mount point
1356         {
1357                 i = 0
1358                 cr.ArvMountPoint = ""
1359                 cr.Container.Mounts = make(map[string]arvados.Mount)
1360                 cr.Container.Mounts = map[string]arvados.Mount{
1361                         "/tmp": {Kind: "tmp"},
1362                         "/tmp/foo": {Kind: "collection",
1363                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541c+53",
1364                                 Writable:         true},
1365                         "/tmp/bar": {Kind: "collection",
1366                                 PortableDataHash: "59389a8f9ee9d399be35462a0f92541d+53",
1367                                 Path:             "baz",
1368                                 Writable:         true},
1369                 }
1370                 cr.Container.OutputPath = "/tmp"
1371
1372                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541c+53", os.ModePerm)
1373                 os.MkdirAll(realTemp+"/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz", os.ModePerm)
1374
1375                 rf, _ := os.Create(realTemp + "/keep1/by_id/59389a8f9ee9d399be35462a0f92541d+53/baz/quux")
1376                 rf.Write([]byte("bar"))
1377                 rf.Close()
1378
1379                 err := cr.SetupMounts()
1380                 c.Check(err, IsNil)
1381                 _, err = os.Stat(cr.HostOutputDir + "/foo")
1382                 c.Check(err, IsNil)
1383                 _, err = os.Stat(cr.HostOutputDir + "/bar/quux")
1384                 c.Check(err, IsNil)
1385                 os.RemoveAll(cr.ArvMountPoint)
1386                 cr.CleanupDirs()
1387                 checkEmpty()
1388         }
1389
1390         // Only mount points of kind 'collection' are allowed underneath output_dir mount point
1391         {
1392                 i = 0
1393                 cr.ArvMountPoint = ""
1394                 cr.Container.Mounts = make(map[string]arvados.Mount)
1395                 cr.Container.Mounts = map[string]arvados.Mount{
1396                         "/tmp":     {Kind: "tmp"},
1397                         "/tmp/foo": {Kind: "tmp"},
1398                 }
1399                 cr.Container.OutputPath = "/tmp"
1400
1401                 err := cr.SetupMounts()
1402                 c.Check(err, NotNil)
1403                 c.Check(err, ErrorMatches, `Only mount points of kind 'collection', 'text' or 'json' are supported underneath the output_path.*`)
1404                 os.RemoveAll(cr.ArvMountPoint)
1405                 cr.CleanupDirs()
1406                 checkEmpty()
1407         }
1408
1409         // Only mount point of kind 'collection' is allowed for stdin
1410         {
1411                 i = 0
1412                 cr.ArvMountPoint = ""
1413                 cr.Container.Mounts = make(map[string]arvados.Mount)
1414                 cr.Container.Mounts = map[string]arvados.Mount{
1415                         "stdin": {Kind: "tmp"},
1416                 }
1417
1418                 err := cr.SetupMounts()
1419                 c.Check(err, NotNil)
1420                 c.Check(err, ErrorMatches, `Unsupported mount kind 'tmp' for stdin.*`)
1421                 os.RemoveAll(cr.ArvMountPoint)
1422                 cr.CleanupDirs()
1423                 checkEmpty()
1424         }
1425
1426         // git_tree mounts
1427         {
1428                 i = 0
1429                 cr.ArvMountPoint = ""
1430                 (*GitMountSuite)(nil).useTestGitServer(c)
1431                 cr.token = arvadostest.ActiveToken
1432                 cr.Container.Mounts = make(map[string]arvados.Mount)
1433                 cr.Container.Mounts = map[string]arvados.Mount{
1434                         "/tip": {
1435                                 Kind:   "git_tree",
1436                                 UUID:   arvadostest.Repository2UUID,
1437                                 Commit: "fd3531f42995344f36c30b79f55f27b502f3d344",
1438                                 Path:   "/",
1439                         },
1440                         "/non-tip": {
1441                                 Kind:   "git_tree",
1442                                 UUID:   arvadostest.Repository2UUID,
1443                                 Commit: "5ebfab0522851df01fec11ec55a6d0f4877b542e",
1444                                 Path:   "/",
1445                         },
1446                 }
1447                 cr.Container.OutputPath = "/tmp"
1448
1449                 err := cr.SetupMounts()
1450                 c.Check(err, IsNil)
1451
1452                 // dirMap[mountpoint] == tmpdir
1453                 dirMap := make(map[string]string)
1454                 for _, bind := range cr.Binds {
1455                         tokens := strings.Split(bind, ":")
1456                         dirMap[tokens[1]] = tokens[0]
1457
1458                         if cr.Container.Mounts[tokens[1]].Writable {
1459                                 c.Check(len(tokens), Equals, 2)
1460                         } else {
1461                                 c.Check(len(tokens), Equals, 3)
1462                                 c.Check(tokens[2], Equals, "ro")
1463                         }
1464                 }
1465
1466                 data, err := ioutil.ReadFile(dirMap["/tip"] + "/dir1/dir2/file with mode 0644")
1467                 c.Check(err, IsNil)
1468                 c.Check(string(data), Equals, "\000\001\002\003")
1469                 _, err = ioutil.ReadFile(dirMap["/tip"] + "/file only on testbranch")
1470                 c.Check(err, FitsTypeOf, &os.PathError{})
1471                 c.Check(os.IsNotExist(err), Equals, true)
1472
1473                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/dir1/dir2/file with mode 0644")
1474                 c.Check(err, IsNil)
1475                 c.Check(string(data), Equals, "\000\001\002\003")
1476                 data, err = ioutil.ReadFile(dirMap["/non-tip"] + "/file only on testbranch")
1477                 c.Check(err, IsNil)
1478                 c.Check(string(data), Equals, "testfile\n")
1479
1480                 cr.CleanupDirs()
1481                 checkEmpty()
1482         }
1483 }
1484
1485 func (s *TestSuite) TestStdout(c *C) {
1486         helperRecord := `{
1487                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1488                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1489                 "cwd": "/bin",
1490                 "environment": {"FROBIZ": "bilbo"},
1491                 "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"} },
1492                 "output_path": "/tmp",
1493                 "priority": 1,
1494                 "runtime_constraints": {}
1495         }`
1496
1497         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1498                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1499                 t.logWriter.Close()
1500         })
1501
1502         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1503         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1504         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1505 }
1506
1507 // Used by the TestStdoutWithWrongPath*()
1508 func (s *TestSuite) stdoutErrorRunHelper(c *C, record string, fn func(t *TestDockerClient)) (api *ArvTestClient, cr *ContainerRunner, err error) {
1509         rec := arvados.Container{}
1510         err = json.Unmarshal([]byte(record), &rec)
1511         c.Check(err, IsNil)
1512
1513         s.docker.fn = fn
1514         s.docker.ImageRemove(nil, hwImageId, dockertypes.ImageRemoveOptions{})
1515
1516         api = &ArvTestClient{Container: rec}
1517         kc := &KeepTestClient{}
1518         defer kc.Close()
1519         cr, err = NewContainerRunner(s.client, api, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1520         c.Assert(err, IsNil)
1521         am := &ArvMountCmdLine{}
1522         cr.RunArvMount = am.ArvMountTest
1523         cr.MkArvClient = func(token string) (IArvadosClient, error) {
1524                 return &ArvTestClient{}, nil
1525         }
1526
1527         err = cr.Run()
1528         return
1529 }
1530
1531 func (s *TestSuite) TestStdoutWithWrongPath(c *C) {
1532         _, _, err := s.stdoutErrorRunHelper(c, `{
1533     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "file", "path":"/tmpa.out"} },
1534     "output_path": "/tmp"
1535 }`, func(t *TestDockerClient) {})
1536
1537         c.Check(err, NotNil)
1538         c.Check(strings.Contains(err.Error(), "Stdout path does not start with OutputPath"), Equals, true)
1539 }
1540
1541 func (s *TestSuite) TestStdoutWithWrongKindTmp(c *C) {
1542         _, _, err := s.stdoutErrorRunHelper(c, `{
1543     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "tmp", "path":"/tmp/a.out"} },
1544     "output_path": "/tmp"
1545 }`, func(t *TestDockerClient) {})
1546
1547         c.Check(err, NotNil)
1548         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'tmp' for stdout"), Equals, true)
1549 }
1550
1551 func (s *TestSuite) TestStdoutWithWrongKindCollection(c *C) {
1552         _, _, err := s.stdoutErrorRunHelper(c, `{
1553     "mounts": {"/tmp": {"kind": "tmp"}, "stdout": {"kind": "collection", "path":"/tmp/a.out"} },
1554     "output_path": "/tmp"
1555 }`, func(t *TestDockerClient) {})
1556
1557         c.Check(err, NotNil)
1558         c.Check(strings.Contains(err.Error(), "Unsupported mount kind 'collection' for stdout"), Equals, true)
1559 }
1560
1561 func (s *TestSuite) TestFullRunWithAPI(c *C) {
1562         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1563         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1564         api, _, _ := s.fullRunHelper(c, `{
1565     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1566     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1567     "cwd": "/bin",
1568     "environment": {},
1569     "mounts": {"/tmp": {"kind": "tmp"} },
1570     "output_path": "/tmp",
1571     "priority": 1,
1572     "runtime_constraints": {"API": true}
1573 }`, nil, 0, func(t *TestDockerClient) {
1574                 t.logWriter.Write(dockerLog(1, t.env[1][17:]+"\n"))
1575                 t.logWriter.Close()
1576         })
1577
1578         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1579         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1580         c.Check(strings.HasSuffix(api.Logs["stdout"].String(), "test.arvados.org\n"), Equals, true)
1581         c.Check(api.CalledWith("container.output", "d41d8cd98f00b204e9800998ecf8427e+0"), NotNil)
1582 }
1583
1584 func (s *TestSuite) TestFullRunSetOutput(c *C) {
1585         defer os.Setenv("ARVADOS_API_HOST", os.Getenv("ARVADOS_API_HOST"))
1586         os.Setenv("ARVADOS_API_HOST", "test.arvados.org")
1587         api, _, _ := s.fullRunHelper(c, `{
1588     "command": ["/bin/sh", "-c", "echo $ARVADOS_API_HOST"],
1589     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1590     "cwd": "/bin",
1591     "environment": {},
1592     "mounts": {"/tmp": {"kind": "tmp"} },
1593     "output_path": "/tmp",
1594     "priority": 1,
1595     "runtime_constraints": {"API": true}
1596 }`, nil, 0, func(t *TestDockerClient) {
1597                 t.api.Container.Output = "d4ab34d3d4f8a72f5c4973051ae69fab+122"
1598                 t.logWriter.Close()
1599         })
1600
1601         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1602         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1603         c.Check(api.CalledWith("container.output", "d4ab34d3d4f8a72f5c4973051ae69fab+122"), NotNil)
1604 }
1605
1606 func (s *TestSuite) TestStdoutWithExcludeFromOutputMountPointUnderOutputDir(c *C) {
1607         helperRecord := `{
1608                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1609                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1610                 "cwd": "/bin",
1611                 "environment": {"FROBIZ": "bilbo"},
1612                 "mounts": {
1613         "/tmp": {"kind": "tmp"},
1614         "/tmp/foo": {"kind": "collection",
1615                      "portable_data_hash": "a3e8f74c6f101eae01fa08bfb4e49b3a+54",
1616                      "exclude_from_output": true
1617         },
1618         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1619     },
1620                 "output_path": "/tmp",
1621                 "priority": 1,
1622                 "runtime_constraints": {}
1623         }`
1624
1625         extraMounts := []string{"a3e8f74c6f101eae01fa08bfb4e49b3a+54"}
1626
1627         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1628                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1629                 t.logWriter.Close()
1630         })
1631
1632         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1633         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1634         c.Check(api.CalledWith("collection.manifest_text", "./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out\n"), NotNil)
1635 }
1636
1637 func (s *TestSuite) TestStdoutWithMultipleMountPointsUnderOutputDir(c *C) {
1638         helperRecord := `{
1639                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1640                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1641                 "cwd": "/bin",
1642                 "environment": {"FROBIZ": "bilbo"},
1643                 "mounts": {
1644         "/tmp": {"kind": "tmp"},
1645         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/file2_in_main.txt"},
1646         "/tmp/foo/sub1": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1"},
1647         "/tmp/foo/sub1file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/file2_in_subdir1.txt"},
1648         "/tmp/foo/baz/sub2file2": {"kind": "collection", "portable_data_hash": "a0def87f80dd594d4675809e83bd4f15+367", "path":"/subdir1/subdir2/file2_in_subdir2.txt"},
1649         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1650     },
1651                 "output_path": "/tmp",
1652                 "priority": 1,
1653                 "runtime_constraints": {}
1654         }`
1655
1656         extraMounts := []string{
1657                 "a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt",
1658                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1659                 "a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt",
1660         }
1661
1662         api, runner, realtemp := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1663                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1664                 t.logWriter.Close()
1665         })
1666
1667         c.Check(runner.Binds, DeepEquals, []string{realtemp + "/tmp2:/tmp",
1668                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/file2_in_main.txt:/tmp/foo/bar:ro",
1669                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/subdir2/file2_in_subdir2.txt:/tmp/foo/baz/sub2file2:ro",
1670                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1:/tmp/foo/sub1:ro",
1671                 realtemp + "/keep1/by_id/a0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt:/tmp/foo/sub1file2:ro",
1672         })
1673
1674         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1675         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1676         for _, v := range api.Content {
1677                 if v["collection"] != nil {
1678                         c.Check(v["ensure_unique_name"], Equals, true)
1679                         collection := v["collection"].(arvadosclient.Dict)
1680                         if strings.Index(collection["name"].(string), "output") == 0 {
1681                                 manifest := collection["manifest_text"].(string)
1682
1683                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1684 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 9:18:bar 36:18:sub1file2
1685 ./foo/baz 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 9:18:sub2file2
1686 ./foo/sub1 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396cabcdefghij6419876543234@569fa8c4 0:9:file1_in_subdir1.txt 9:18:file2_in_subdir1.txt
1687 ./foo/sub1/subdir2 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0bcdefghijk544332211@569fa8c5 0:9:file1_in_subdir2.txt 9:18:file2_in_subdir2.txt
1688 `)
1689                         }
1690                 }
1691         }
1692 }
1693
1694 func (s *TestSuite) TestStdoutWithMountPointsUnderOutputDirDenormalizedManifest(c *C) {
1695         helperRecord := `{
1696                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1697                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1698                 "cwd": "/bin",
1699                 "environment": {"FROBIZ": "bilbo"},
1700                 "mounts": {
1701         "/tmp": {"kind": "tmp"},
1702         "/tmp/foo/bar": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/subdir1/file2_in_subdir1.txt"},
1703         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1704     },
1705                 "output_path": "/tmp",
1706                 "priority": 1,
1707                 "runtime_constraints": {}
1708         }`
1709
1710         extraMounts := []string{
1711                 "b0def87f80dd594d4675809e83bd4f15+367/subdir1/file2_in_subdir1.txt",
1712         }
1713
1714         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1715                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1716                 t.logWriter.Close()
1717         })
1718
1719         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1720         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1721         for _, v := range api.Content {
1722                 if v["collection"] != nil {
1723                         collection := v["collection"].(arvadosclient.Dict)
1724                         if strings.Index(collection["name"].(string), "output") == 0 {
1725                                 manifest := collection["manifest_text"].(string)
1726
1727                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1728 ./foo 3e426d509afffb85e06c4c96a7c15e91+27+Aa124ac75e5168396c73c0abcdefgh11234567890@569fa8c3 10:17:bar
1729 `)
1730                         }
1731                 }
1732         }
1733 }
1734
1735 func (s *TestSuite) TestOutputError(c *C) {
1736         helperRecord := `{
1737                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1738                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1739                 "cwd": "/bin",
1740                 "environment": {"FROBIZ": "bilbo"},
1741                 "mounts": {
1742         "/tmp": {"kind": "tmp"}
1743     },
1744                 "output_path": "/tmp",
1745                 "priority": 1,
1746                 "runtime_constraints": {}
1747         }`
1748
1749         extraMounts := []string{}
1750
1751         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1752                 os.Symlink("/etc/hosts", t.realTemp+"/tmp2/baz")
1753                 t.logWriter.Close()
1754         })
1755
1756         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1757 }
1758
1759 func (s *TestSuite) TestStdinCollectionMountPoint(c *C) {
1760         helperRecord := `{
1761                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1762                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1763                 "cwd": "/bin",
1764                 "environment": {"FROBIZ": "bilbo"},
1765                 "mounts": {
1766         "/tmp": {"kind": "tmp"},
1767         "stdin": {"kind": "collection", "portable_data_hash": "b0def87f80dd594d4675809e83bd4f15+367", "path": "/file1_in_main.txt"},
1768         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1769     },
1770                 "output_path": "/tmp",
1771                 "priority": 1,
1772                 "runtime_constraints": {}
1773         }`
1774
1775         extraMounts := []string{
1776                 "b0def87f80dd594d4675809e83bd4f15+367/file1_in_main.txt",
1777         }
1778
1779         api, _, _ := s.fullRunHelper(c, helperRecord, extraMounts, 0, func(t *TestDockerClient) {
1780                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1781                 t.logWriter.Close()
1782         })
1783
1784         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1785         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1786         for _, v := range api.Content {
1787                 if v["collection"] != nil {
1788                         collection := v["collection"].(arvadosclient.Dict)
1789                         if strings.Index(collection["name"].(string), "output") == 0 {
1790                                 manifest := collection["manifest_text"].(string)
1791                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1792 `)
1793                         }
1794                 }
1795         }
1796 }
1797
1798 func (s *TestSuite) TestStdinJsonMountPoint(c *C) {
1799         helperRecord := `{
1800                 "command": ["/bin/sh", "-c", "echo $FROBIZ"],
1801                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1802                 "cwd": "/bin",
1803                 "environment": {"FROBIZ": "bilbo"},
1804                 "mounts": {
1805         "/tmp": {"kind": "tmp"},
1806         "stdin": {"kind": "json", "content": "foo"},
1807         "stdout": {"kind": "file", "path": "/tmp/a/b/c.out"}
1808     },
1809                 "output_path": "/tmp",
1810                 "priority": 1,
1811                 "runtime_constraints": {}
1812         }`
1813
1814         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
1815                 t.logWriter.Write(dockerLog(1, t.env[0][7:]+"\n"))
1816                 t.logWriter.Close()
1817         })
1818
1819         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
1820         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
1821         for _, v := range api.Content {
1822                 if v["collection"] != nil {
1823                         collection := v["collection"].(arvadosclient.Dict)
1824                         if strings.Index(collection["name"].(string), "output") == 0 {
1825                                 manifest := collection["manifest_text"].(string)
1826                                 c.Check(manifest, Equals, `./a/b 307372fa8fd5c146b22ae7a45b49bc31+6 0:6:c.out
1827 `)
1828                         }
1829                 }
1830         }
1831 }
1832
1833 func (s *TestSuite) TestStderrMount(c *C) {
1834         api, _, _ := s.fullRunHelper(c, `{
1835     "command": ["/bin/sh", "-c", "echo hello;exit 1"],
1836     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1837     "cwd": ".",
1838     "environment": {},
1839     "mounts": {"/tmp": {"kind": "tmp"},
1840                "stdout": {"kind": "file", "path": "/tmp/a/out.txt"},
1841                "stderr": {"kind": "file", "path": "/tmp/b/err.txt"}},
1842     "output_path": "/tmp",
1843     "priority": 1,
1844     "runtime_constraints": {}
1845 }`, nil, 1, func(t *TestDockerClient) {
1846                 t.logWriter.Write(dockerLog(1, "hello\n"))
1847                 t.logWriter.Write(dockerLog(2, "oops\n"))
1848                 t.logWriter.Close()
1849         })
1850
1851         final := api.CalledWith("container.state", "Complete")
1852         c.Assert(final, NotNil)
1853         c.Check(final["container"].(arvadosclient.Dict)["exit_code"], Equals, 1)
1854         c.Check(final["container"].(arvadosclient.Dict)["log"], NotNil)
1855
1856         c.Check(api.CalledWith("collection.manifest_text", "./a b1946ac92492d2347c6235b4d2611184+6 0:6:out.txt\n./b 38af5c54926b620264ab1501150cf189+5 0:5:err.txt\n"), NotNil)
1857 }
1858
1859 func (s *TestSuite) TestNumberRoundTrip(c *C) {
1860         kc := &KeepTestClient{}
1861         defer kc.Close()
1862         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, nil, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
1863         c.Assert(err, IsNil)
1864         cr.fetchContainerRecord()
1865
1866         jsondata, err := json.Marshal(cr.Container.Mounts["/json"].Content)
1867
1868         c.Check(err, IsNil)
1869         c.Check(string(jsondata), Equals, `{"number":123456789123456789}`)
1870 }
1871
1872 func (s *TestSuite) TestFullBrokenDocker1(c *C) {
1873         tf, err := ioutil.TempFile("", "brokenNodeHook-")
1874         c.Assert(err, IsNil)
1875         defer os.Remove(tf.Name())
1876
1877         tf.Write([]byte(`#!/bin/sh
1878 exec echo killme
1879 `))
1880         tf.Close()
1881         os.Chmod(tf.Name(), 0700)
1882
1883         ech := tf.Name()
1884         brokenNodeHook = &ech
1885
1886         api, _, _ := s.fullRunHelper(c, `{
1887     "command": ["echo", "hello world"],
1888     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1889     "cwd": ".",
1890     "environment": {},
1891     "mounts": {"/tmp": {"kind": "tmp"} },
1892     "output_path": "/tmp",
1893     "priority": 1,
1894     "runtime_constraints": {}
1895 }`, nil, 2, func(t *TestDockerClient) {
1896                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1897                 t.logWriter.Close()
1898         })
1899
1900         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1901         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1902         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Running broken node hook.*")
1903         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*killme.*")
1904
1905 }
1906
1907 func (s *TestSuite) TestFullBrokenDocker2(c *C) {
1908         ech := ""
1909         brokenNodeHook = &ech
1910
1911         api, _, _ := s.fullRunHelper(c, `{
1912     "command": ["echo", "hello world"],
1913     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1914     "cwd": ".",
1915     "environment": {},
1916     "mounts": {"/tmp": {"kind": "tmp"} },
1917     "output_path": "/tmp",
1918     "priority": 1,
1919     "runtime_constraints": {}
1920 }`, nil, 2, func(t *TestDockerClient) {
1921                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1922                 t.logWriter.Close()
1923         })
1924
1925         c.Check(api.CalledWith("container.state", "Queued"), NotNil)
1926         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1927         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*No broken node hook.*")
1928 }
1929
1930 func (s *TestSuite) TestFullBrokenDocker3(c *C) {
1931         ech := ""
1932         brokenNodeHook = &ech
1933
1934         api, _, _ := s.fullRunHelper(c, `{
1935     "command": ["echo", "hello world"],
1936     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1937     "cwd": ".",
1938     "environment": {},
1939     "mounts": {"/tmp": {"kind": "tmp"} },
1940     "output_path": "/tmp",
1941     "priority": 1,
1942     "runtime_constraints": {}
1943 }`, nil, 3, func(t *TestDockerClient) {
1944                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1945                 t.logWriter.Close()
1946         })
1947
1948         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1949         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*unable to run containers.*")
1950 }
1951
1952 func (s *TestSuite) TestBadCommand1(c *C) {
1953         ech := ""
1954         brokenNodeHook = &ech
1955
1956         api, _, _ := s.fullRunHelper(c, `{
1957     "command": ["echo", "hello world"],
1958     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1959     "cwd": ".",
1960     "environment": {},
1961     "mounts": {"/tmp": {"kind": "tmp"} },
1962     "output_path": "/tmp",
1963     "priority": 1,
1964     "runtime_constraints": {}
1965 }`, nil, 4, func(t *TestDockerClient) {
1966                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1967                 t.logWriter.Close()
1968         })
1969
1970         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1971         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1972 }
1973
1974 func (s *TestSuite) TestBadCommand2(c *C) {
1975         ech := ""
1976         brokenNodeHook = &ech
1977
1978         api, _, _ := s.fullRunHelper(c, `{
1979     "command": ["echo", "hello world"],
1980     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
1981     "cwd": ".",
1982     "environment": {},
1983     "mounts": {"/tmp": {"kind": "tmp"} },
1984     "output_path": "/tmp",
1985     "priority": 1,
1986     "runtime_constraints": {}
1987 }`, nil, 5, func(t *TestDockerClient) {
1988                 t.logWriter.Write(dockerLog(1, "hello world\n"))
1989                 t.logWriter.Close()
1990         })
1991
1992         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
1993         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
1994 }
1995
1996 func (s *TestSuite) TestBadCommand3(c *C) {
1997         ech := ""
1998         brokenNodeHook = &ech
1999
2000         api, _, _ := s.fullRunHelper(c, `{
2001     "command": ["echo", "hello world"],
2002     "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2003     "cwd": ".",
2004     "environment": {},
2005     "mounts": {"/tmp": {"kind": "tmp"} },
2006     "output_path": "/tmp",
2007     "priority": 1,
2008     "runtime_constraints": {}
2009 }`, nil, 6, func(t *TestDockerClient) {
2010                 t.logWriter.Write(dockerLog(1, "hello world\n"))
2011                 t.logWriter.Close()
2012         })
2013
2014         c.Check(api.CalledWith("container.state", "Cancelled"), NotNil)
2015         c.Check(api.Logs["crunch-run"].String(), Matches, "(?ms).*Possible causes:.*is missing.*")
2016 }
2017
2018 func (s *TestSuite) TestSecretTextMountPoint(c *C) {
2019         // under normal mounts, gets captured in output, oops
2020         helperRecord := `{
2021                 "command": ["true"],
2022                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2023                 "cwd": "/bin",
2024                 "mounts": {
2025                     "/tmp": {"kind": "tmp"},
2026                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2027                 },
2028                 "secret_mounts": {
2029                 },
2030                 "output_path": "/tmp",
2031                 "priority": 1,
2032                 "runtime_constraints": {}
2033         }`
2034
2035         api, _, _ := s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2036                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2037                 c.Check(err, IsNil)
2038                 c.Check(content, DeepEquals, []byte("mypassword"))
2039                 t.logWriter.Close()
2040         })
2041
2042         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2043         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2044         c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), NotNil)
2045         c.Check(api.CalledWith("collection.manifest_text", ""), IsNil)
2046
2047         // under secret mounts, not captured in output
2048         helperRecord = `{
2049                 "command": ["true"],
2050                 "container_image": "d4ab34d3d4f8a72f5c4973051ae69fab+122",
2051                 "cwd": "/bin",
2052                 "mounts": {
2053                     "/tmp": {"kind": "tmp"}
2054                 },
2055                 "secret_mounts": {
2056                     "/tmp/secret.conf": {"kind": "text", "content": "mypassword"}
2057                 },
2058                 "output_path": "/tmp",
2059                 "priority": 1,
2060                 "runtime_constraints": {}
2061         }`
2062
2063         api, _, _ = s.fullRunHelper(c, helperRecord, nil, 0, func(t *TestDockerClient) {
2064                 content, err := ioutil.ReadFile(t.realTemp + "/tmp2/secret.conf")
2065                 c.Check(err, IsNil)
2066                 c.Check(content, DeepEquals, []byte("mypassword"))
2067                 t.logWriter.Close()
2068         })
2069
2070         c.Check(api.CalledWith("container.exit_code", 0), NotNil)
2071         c.Check(api.CalledWith("container.state", "Complete"), NotNil)
2072         c.Check(api.CalledWith("collection.manifest_text", ". 34819d7beeabb9260a5c854bc85b3e44+10 0:10:secret.conf\n"), IsNil)
2073         c.Check(api.CalledWith("collection.manifest_text", ""), NotNil)
2074 }
2075
2076 type FakeProcess struct {
2077         cmdLine []string
2078 }
2079
2080 func (fp FakeProcess) CmdlineSlice() ([]string, error) {
2081         return fp.cmdLine, nil
2082 }
2083
2084 func (s *TestSuite) helpCheckContainerd(c *C, lp func() ([]PsProcess, error)) error {
2085         kc := &KeepTestClient{}
2086         defer kc.Close()
2087         cr, err := NewContainerRunner(s.client, &ArvTestClient{callraw: true}, kc, s.docker, "zzzzz-zzzzz-zzzzzzzzzzzzzzz")
2088         cr.checkContainerd = time.Duration(100 * time.Millisecond)
2089         c.Assert(err, IsNil)
2090         cr.ListProcesses = lp
2091
2092         s.docker.fn = func(t *TestDockerClient) {
2093                 time.Sleep(1 * time.Second)
2094                 t.logWriter.Close()
2095         }
2096
2097         err = cr.CreateContainer()
2098         c.Check(err, IsNil)
2099
2100         err = cr.StartContainer()
2101         c.Check(err, IsNil)
2102
2103         err = cr.WaitFinish()
2104         return err
2105
2106 }
2107
2108 func (s *TestSuite) TestCheckContainerdPresent(c *C) {
2109         err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2110                 return []PsProcess{FakeProcess{[]string{"docker-containerd"}}}, nil
2111         })
2112         c.Check(err, IsNil)
2113 }
2114
2115 func (s *TestSuite) TestCheckContainerdMissing(c *C) {
2116         err := s.helpCheckContainerd(c, func() ([]PsProcess, error) {
2117                 return []PsProcess{FakeProcess{[]string{"abc"}}}, nil
2118         })
2119         c.Check(err, ErrorMatches, `'containerd' not found in process list.`)
2120 }