9437: gofmt
[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 updating container zzzzz-dz642-xxxxxxxxxxxxxx1 to state \"Locked\"")
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"] =
127                 arvadostest.StubResponse{200, string(`{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx2", "state":"Running", "priority":1, "locked_by_uuid": "` + arvadostest.Dispatch1AuthUUID + `"}`)}
128
129         testWithServerStub(c, apiStubResponses, "echo",
130                 `After echo process termination, container state for Running is "zzzzz-dz642-xxxxxxxxxxxxxx2".  Updating it to "Cancelled"`)
131 }
132
133 func (s *MockArvadosServerSuite) Test_ErrorRunningContainer(c *C) {
134         apiStubResponses := make(map[string]arvadostest.StubResponse)
135         apiStubResponses["/arvados/v1/containers"] =
136                 arvadostest.StubResponse{200, string(`{"items_available":1, "items":[{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx3","State":"Queued","Priority":1}]}`)}
137
138         apiStubResponses["/arvados/v1/containers/zzzzz-dz642-xxxxxxxxxxxxxx3"] =
139                 arvadostest.StubResponse{200, string(`{"uuid":"zzzzz-dz642-xxxxxxxxxxxxxx3", "state":"Running", "priority":1}`)}
140
141         testWithServerStub(c, apiStubResponses, "nosuchcommand", "Error starting nosuchcommand for zzzzz-dz642-xxxxxxxxxxxxxx3")
142 }
143
144 func testWithServerStub(c *C, apiStubResponses map[string]arvadostest.StubResponse, crunchCmd string, expected string) {
145         apiStubResponses["/arvados/v1/api_client_authorizations/current"] =
146                 arvadostest.StubResponse{200, string(`{"uuid": "` + arvadostest.Dispatch1AuthUUID + `", "api_token": "xyz"}`)}
147
148         apiStub := arvadostest.ServerStub{apiStubResponses}
149
150         api := httptest.NewServer(&apiStub)
151         defer api.Close()
152
153         arv := arvadosclient.ArvadosClient{
154                 Scheme:    "http",
155                 ApiServer: api.URL[7:],
156                 ApiToken:  "abc123",
157                 Client:    &http.Client{Transport: &http.Transport{}},
158                 Retries:   0,
159         }
160
161         buf := bytes.NewBuffer(nil)
162         log.SetOutput(io.MultiWriter(buf, os.Stderr))
163         defer log.SetOutput(os.Stderr)
164
165         *crunchRunCommand = crunchCmd
166
167         doneProcessing := make(chan struct{})
168         dispatcher := dispatch.Dispatcher{
169                 Arv:          arv,
170                 PollInterval: time.Duration(1) * time.Second,
171                 RunContainer: func(dispatcher *dispatch.Dispatcher,
172                         container arvados.Container,
173                         status chan arvados.Container) {
174                         run(dispatcher, container, status)
175                         doneProcessing <- struct{}{}
176                 },
177                 DoneProcessing: doneProcessing}
178
179         startCmd = func(container arvados.Container, cmd *exec.Cmd) error {
180                 dispatcher.UpdateState(container.UUID, "Running")
181                 dispatcher.UpdateState(container.UUID, "Complete")
182                 return cmd.Start()
183         }
184
185         go func() {
186                 for i := 0; i < 80 && !strings.Contains(buf.String(), expected); i++ {
187                         time.Sleep(100 * time.Millisecond)
188                 }
189                 dispatcher.DoneProcessing <- struct{}{}
190         }()
191
192         err := dispatcher.RunDispatcher()
193         c.Assert(err, IsNil)
194
195         // Wait for all running crunch jobs to complete / terminate
196         waitGroup.Wait()
197
198         c.Check(buf.String(), Matches, `(?ms).*`+expected+`.*`)
199 }