9898: update crunch-dispatch-local tests to be in sync with api server updates.
[arvados.git] / services / crunch-dispatch-local / crunch-dispatch-local_test.go
1 package main
2
3 import (
4         "bytes"
5         "git.curoverse.com/arvados.git/sdk/go/arvados"
6         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
7         "git.curoverse.com/arvados.git/sdk/go/arvadostest"
8         "git.curoverse.com/arvados.git/sdk/go/dispatch"
9         . "gopkg.in/check.v1"
10         "io"
11         "log"
12         "net/http"
13         "net/http/httptest"
14         "os"
15         "os/exec"
16         "strings"
17         "testing"
18         "time"
19 )
20
21 // Gocheck boilerplate
22 func Test(t *testing.T) {
23         TestingT(t)
24 }
25
26 var _ = Suite(&TestSuite{})
27 var _ = Suite(&MockArvadosServerSuite{})
28
29 type TestSuite struct{}
30 type MockArvadosServerSuite struct{}
31
32 var initialArgs []string
33
34 func (s *TestSuite) SetUpSuite(c *C) {
35         initialArgs = os.Args
36         arvadostest.StartAPI()
37         runningCmds = make(map[string]*exec.Cmd)
38 }
39
40 func (s *TestSuite) TearDownSuite(c *C) {
41         arvadostest.StopAPI()
42 }
43
44 func (s *TestSuite) SetUpTest(c *C) {
45         args := []string{"crunch-dispatch-local"}
46         os.Args = args
47 }
48
49 func (s *TestSuite) TearDownTest(c *C) {
50         arvadostest.ResetEnv()
51         os.Args = initialArgs
52 }
53
54 func (s *MockArvadosServerSuite) TearDownTest(c *C) {
55         arvadostest.ResetEnv()
56 }
57
58 func (s *TestSuite) TestIntegration(c *C) {
59         arv, err := arvadosclient.MakeArvadosClient()
60         c.Assert(err, IsNil)
61
62         echo := "echo"
63         crunchRunCommand = &echo
64
65         doneProcessing := make(chan struct{})
66         dispatcher := dispatch.Dispatcher{
67                 Arv:          arv,
68                 PollInterval: time.Second,
69                 RunContainer: func(dispatcher *dispatch.Dispatcher,
70                         container arvados.Container,
71                         status chan arvados.Container) {
72                         run(dispatcher, container, status)
73                         doneProcessing <- struct{}{}
74                 },
75                 DoneProcessing: doneProcessing}
76
77         startCmd = func(container arvados.Container, cmd *exec.Cmd) error {
78                 dispatcher.UpdateState(container.UUID, "Running")
79                 dispatcher.UpdateState(container.UUID, "Complete")
80                 return cmd.Start()
81         }
82
83         err = dispatcher.RunDispatcher()
84         c.Assert(err, IsNil)
85
86         // Wait for all running crunch jobs to complete / terminate
87         waitGroup.Wait()
88
89         // There should be no queued containers now
90         params := arvadosclient.Dict{
91                 "filters": [][]string{{"state", "=", "Queued"}},
92         }
93         var containers arvados.ContainerList
94         err = arv.List("containers", params, &containers)
95         c.Check(err, IsNil)
96         c.Assert(len(containers.Items), Equals, 0)
97
98         // Previously "Queued" container should now be in "Complete" state
99         var container arvados.Container
100         err = arv.Get("containers", "zzzzz-dz642-queuedcontainer", nil, &container)
101         c.Check(err, IsNil)
102         c.Check(string(container.State), Equals, "Complete")
103 }
104
105 func (s *MockArvadosServerSuite) Test_APIErrorGettingContainers(c *C) {
106         apiStubResponses := make(map[string]arvadostest.StubResponse)
107         apiStubResponses["/arvados/v1/containers"] = arvadostest.StubResponse{500, string(`{}`)}
108
109         testWithServerStub(c, apiStubResponses, "echo", "Error getting list of containers")
110 }
111
112 func (s *MockArvadosServerSuite) Test_APIErrorUpdatingContainerState(c *C) {
113         apiStubResponses := make(map[string]arvadostest.StubResponse)
114         apiStubResponses["/arvados/v1/containers"] =
115                 arvadostest.StubResponse{200, string(`{"items_available":1, "items":[{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx1","State":"Queued","Priority":1}]}`)}
116         apiStubResponses["/arvados/v1/containers/zzzzz-dz642-xxxxxxxxxxxxxx1"] =
117                 arvadostest.StubResponse{500, string(`{}`)}
118
119         testWithServerStub(c, apiStubResponses, "echo", "Error locking container zzzzz-dz642-xxxxxxxxxxxxxx1")
120 }
121
122 func (s *MockArvadosServerSuite) Test_ContainerStillInRunningAfterRun(c *C) {
123         apiStubResponses := make(map[string]arvadostest.StubResponse)
124         apiStubResponses["/arvados/v1/containers"] =
125                 arvadostest.StubResponse{200, string(`{"items_available":1, "items":[{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx2","State":"Queued","Priority":1}]}`)}
126         apiStubResponses["/arvados/v1/containers/zzzzz-dz642-xxxxxxxxxxxxxx2/lock"] =
127                 arvadostest.StubResponse{200, string(`{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx2", "state":"Locked", "priority":1, "locked_by_uuid": "` + arvadostest.Dispatch1AuthUUID + `"}`)}
128         apiStubResponses["/arvados/v1/containers/zzzzz-dz642-xxxxxxxxxxxxxx2"] =
129                 arvadostest.StubResponse{200, string(`{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx2", "state":"Running", "priority":1, "locked_by_uuid": "` + arvadostest.Dispatch1AuthUUID + `"}`)}
130
131         testWithServerStub(c, apiStubResponses, "echo",
132                 `After echo process termination, container state for Running is "zzzzz-dz642-xxxxxxxxxxxxxx2".  Updating it to "Cancelled"`)
133 }
134
135 func (s *MockArvadosServerSuite) Test_ErrorRunningContainer(c *C) {
136         apiStubResponses := make(map[string]arvadostest.StubResponse)
137         apiStubResponses["/arvados/v1/containers"] =
138                 arvadostest.StubResponse{200, string(`{"items_available":1, "items":[{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx3","State":"Queued","Priority":1}]}`)}
139
140         apiStubResponses["/arvados/v1/containers/zzzzz-dz642-xxxxxxxxxxxxxx3/lock"] =
141                 arvadostest.StubResponse{200, string(`{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx3", "state":"Locked", "priority":1}`)}
142
143         testWithServerStub(c, apiStubResponses, "nosuchcommand", "Error starting nosuchcommand for zzzzz-dz642-xxxxxxxxxxxxxx3")
144 }
145
146 func testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
147         apiStubResponses["/arvados/v1/api_client_authorizations/current"] =
148                 arvadostest.StubResponse{200, string(`{"uuid": "` + arvadostest.Dispatch1AuthUUID + `", "api_token": "xyz"}`)}
149
150         apiStub := arvadostest.ServerStub{apiStubResponses}
151
152         api := httptest.NewServer(&apiStub)
153         defer api.Close()
154
155         arv := arvadosclient.ArvadosClient{
156                 Scheme:    "http",
157                 ApiServer: api.URL[7:],
158                 ApiToken:  "abc123",
159                 Client:    &http.Client{Transport: &http.Transport{}},
160                 Retries:   0,
161         }
162
163         buf := bytes.NewBuffer(nil)
164         log.SetOutput(io.MultiWriter(buf, os.Stderr))
165         defer log.SetOutput(os.Stderr)
166
167         *crunchRunCommand = crunchCmd
168
169         doneProcessing := make(chan struct{})
170         dispatcher := dispatch.Dispatcher{
171                 Arv:          arv,
172                 PollInterval: time.Duration(1) * time.Second,
173                 RunContainer: func(dispatcher *dispatch.Dispatcher,
174                         container arvados.Container,
175                         status chan arvados.Container) {
176                         run(dispatcher, container, status)
177                         doneProcessing <- struct{}{}
178                 },
179                 DoneProcessing: doneProcessing}
180
181         startCmd = func(container arvados.Container, cmd *exec.Cmd) error {
182                 dispatcher.UpdateState(container.UUID, "Running")
183                 dispatcher.UpdateState(container.UUID, "Complete")
184                 return cmd.Start()
185         }
186
187         go func() {
188                 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
189                         time.Sleep(100 * time.Millisecond)
190                 }
191                 dispatcher.DoneProcessing <- struct{}{}
192         }()
193
194         err := dispatcher.RunDispatcher()
195         c.Assert(err, IsNil)
196
197         // Wait for all running crunch jobs to complete / terminate
198         waitGroup.Wait()
199
200         c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
201 }