Exit non-zero if container is cancelled.
[lightning.git] / arvados.go
1 package main
2
3 import (
4         "encoding/json"
5         "errors"
6         "fmt"
7         "io/ioutil"
8         "net/url"
9         "os"
10         "regexp"
11         "strings"
12         "sync"
13         "time"
14
15         "git.arvados.org/arvados.git/sdk/go/arvados"
16         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
17         "git.arvados.org/arvados.git/sdk/go/keepclient"
18         log "github.com/sirupsen/logrus"
19         "golang.org/x/crypto/blake2b"
20         "golang.org/x/net/websocket"
21 )
22
23 type eventMessage struct {
24         Status     int
25         ObjectUUID string `json:"object_uuid"`
26         EventType  string `json:"event_type"`
27         Properties struct {
28                 Text string
29         }
30 }
31
32 type arvadosClient struct {
33         *arvados.Client
34         notifying map[string]map[chan<- eventMessage]int
35         wantClose chan struct{}
36         wsconn    *websocket.Conn
37         mtx       sync.Mutex
38 }
39
40 // Listen for events concerning the given uuids. When an event occurs
41 // (and after connecting/reconnecting to the event stream), send each
42 // uuid to ch. If a {ch, uuid} pair is subscribed twice, the uuid will
43 // be sent only once for each update, but two Unsubscribe calls will
44 // be needed to stop sending them.
45 func (client *arvadosClient) Subscribe(ch chan<- eventMessage, uuid string) {
46         client.mtx.Lock()
47         defer client.mtx.Unlock()
48         if client.notifying == nil {
49                 client.notifying = map[string]map[chan<- eventMessage]int{}
50                 client.wantClose = make(chan struct{})
51                 go client.runNotifier()
52         }
53         chmap := client.notifying[uuid]
54         if chmap == nil {
55                 chmap = map[chan<- eventMessage]int{}
56                 client.notifying[uuid] = chmap
57         }
58         needSub := true
59         for _, nch := range chmap {
60                 if nch > 0 {
61                         needSub = false
62                         break
63                 }
64         }
65         chmap[ch]++
66         if needSub && client.wsconn != nil {
67                 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
68                         "method": "subscribe",
69                         "filters": [][]interface{}{
70                                 {"object_uuid", "=", uuid},
71                                 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
72                         },
73                 })
74         }
75 }
76
77 func (client *arvadosClient) Unsubscribe(ch chan<- eventMessage, uuid string) {
78         client.mtx.Lock()
79         defer client.mtx.Unlock()
80         chmap := client.notifying[uuid]
81         if n := chmap[ch] - 1; n == 0 {
82                 delete(chmap, ch)
83                 if len(chmap) == 0 {
84                         delete(client.notifying, uuid)
85                 }
86                 if client.wsconn != nil {
87                         go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
88                                 "method": "unsubscribe",
89                                 "filters": [][]interface{}{
90                                         {"object_uuid", "=", uuid},
91                                         {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
92                                 },
93                         })
94                 }
95         } else if n > 0 {
96                 chmap[ch] = n
97         }
98 }
99
100 func (client *arvadosClient) Close() {
101         client.mtx.Lock()
102         defer client.mtx.Unlock()
103         if client.notifying != nil {
104                 client.notifying = nil
105                 close(client.wantClose)
106         }
107 }
108
109 func (client *arvadosClient) runNotifier() {
110 reconnect:
111         for {
112                 var cluster arvados.Cluster
113                 err := client.RequestAndDecode(&cluster, "GET", arvados.EndpointConfigGet.Path, nil, nil)
114                 if err != nil {
115                         log.Warnf("error getting cluster config: %s", err)
116                         time.Sleep(5 * time.Second)
117                         continue reconnect
118                 }
119                 wsURL := cluster.Services.Websocket.ExternalURL
120                 wsURL.Scheme = strings.Replace(wsURL.Scheme, "http", "ws", 1)
121                 wsURL.Path = "/websocket"
122                 wsURL.RawQuery = url.Values{"api_token": []string{client.AuthToken}}.Encode()
123                 conn, err := websocket.Dial(wsURL.String(), "", cluster.Services.Controller.ExternalURL.String())
124                 if err != nil {
125                         log.Warnf("websocket connection error: %s", err)
126                         time.Sleep(5 * time.Second)
127                         continue reconnect
128                 }
129                 client.mtx.Lock()
130                 client.wsconn = conn
131                 client.mtx.Unlock()
132
133                 w := json.NewEncoder(conn)
134                 for uuid := range client.notifying {
135                         w.Encode(map[string]interface{}{
136                                 "method": "subscribe",
137                                 "filters": [][]interface{}{
138                                         {"object_uuid", "=", uuid},
139                                         {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
140                                 },
141                         })
142                 }
143
144                 r := json.NewDecoder(conn)
145                 for {
146                         var msg eventMessage
147                         err := r.Decode(&msg)
148                         select {
149                         case <-client.wantClose:
150                                 return
151                         default:
152                                 if err != nil {
153                                         log.Printf("error decoding websocket message: %s", err)
154                                         client.mtx.Lock()
155                                         client.wsconn = nil
156                                         client.mtx.Unlock()
157                                         go conn.Close()
158                                         continue reconnect
159                                 }
160                                 for ch := range client.notifying[msg.ObjectUUID] {
161                                         ch <- msg
162                                 }
163                         }
164                 }
165         }
166 }
167
168 type arvadosContainerRunner struct {
169         Client      *arvados.Client
170         Name        string
171         ProjectUUID string
172         VCPUs       int
173         RAM         int64
174         Prog        string // if empty, run /proc/self/exe
175         Args        []string
176         Mounts      map[string]map[string]interface{}
177         Priority    int
178 }
179
180 func (runner *arvadosContainerRunner) Run() (string, error) {
181         if runner.ProjectUUID == "" {
182                 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
183         }
184
185         mounts := map[string]map[string]interface{}{
186                 "/mnt/output": {
187                         "kind":     "collection",
188                         "writable": true,
189                 },
190         }
191         for path, mnt := range runner.Mounts {
192                 mounts[path] = mnt
193         }
194
195         prog := runner.Prog
196         if prog == "" {
197                 prog = "/mnt/cmd/lightning"
198                 cmdUUID, err := runner.makeCommandCollection()
199                 if err != nil {
200                         return "", err
201                 }
202                 mounts["/mnt/cmd"] = map[string]interface{}{
203                         "kind": "collection",
204                         "uuid": cmdUUID,
205                 }
206         }
207         command := append([]string{prog}, runner.Args...)
208
209         priority := runner.Priority
210         if priority < 1 {
211                 priority = 500
212         }
213         rc := arvados.RuntimeConstraints{
214                 VCPUs:        runner.VCPUs,
215                 RAM:          runner.RAM,
216                 KeepCacheRAM: (1 << 26) * 2 * int64(runner.VCPUs),
217         }
218         var cr arvados.ContainerRequest
219         err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
220                 "container_request": map[string]interface{}{
221                         "owner_uuid":          runner.ProjectUUID,
222                         "name":                runner.Name,
223                         "container_image":     "lightning-runtime",
224                         "command":             command,
225                         "mounts":              mounts,
226                         "use_existing":        true,
227                         "output_path":         "/mnt/output",
228                         "runtime_constraints": rc,
229                         "priority":            runner.Priority,
230                         "state":               arvados.ContainerRequestStateCommitted,
231                 },
232         })
233         if err != nil {
234                 return "", err
235         }
236         log.Printf("container request UUID: %s", cr.UUID)
237         log.Printf("container UUID: %s", cr.ContainerUUID)
238
239         logch := make(chan eventMessage)
240         client := arvadosClient{Client: runner.Client}
241         defer client.Close()
242         subscribedUUID := ""
243         defer func() {
244                 if subscribedUUID != "" {
245                         client.Unsubscribe(logch, subscribedUUID)
246                 }
247         }()
248
249         ticker := time.NewTicker(5 * time.Second)
250         defer ticker.Stop()
251
252         lastState := cr.State
253         refreshCR := func() {
254                 err = runner.Client.RequestAndDecode(&cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
255                 if err != nil {
256                         log.Printf("error getting container request: %s", err)
257                         return
258                 }
259                 if lastState != cr.State {
260                         log.Printf("container request state: %s", cr.State)
261                         lastState = cr.State
262                 }
263                 if subscribedUUID != cr.ContainerUUID {
264                         if subscribedUUID != "" {
265                                 client.Unsubscribe(logch, subscribedUUID)
266                         }
267                         client.Subscribe(logch, cr.ContainerUUID)
268                         subscribedUUID = cr.ContainerUUID
269                 }
270         }
271
272         for cr.State != arvados.ContainerRequestStateFinal {
273                 select {
274                 case <-ticker.C:
275                         refreshCR()
276                 case msg := <-logch:
277                         switch msg.EventType {
278                         case "update":
279                                 refreshCR()
280                         default:
281                                 for _, line := range strings.Split(msg.Properties.Text, "\n") {
282                                         if line != "" {
283                                                 log.Print(line)
284                                         }
285                                 }
286                         }
287                 }
288         }
289
290         var c arvados.Container
291         err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
292         if err != nil {
293                 return "", err
294         } else if c.State != arvados.ContainerStateComplete {
295                 return "", fmt.Errorf("container did not complete: %s", c.State)
296         } else if c.ExitCode != 0 {
297                 return "", fmt.Errorf("container exited %d", c.ExitCode)
298         }
299         return cr.OutputUUID, err
300 }
301
302 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
303
304 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
305         if runner.Mounts == nil {
306                 runner.Mounts = make(map[string]map[string]interface{})
307         }
308         for _, path := range paths {
309                 if *path == "" || *path == "-" {
310                         continue
311                 }
312                 m := collectionInPathRe.FindStringSubmatch(*path)
313                 if m == nil {
314                         return fmt.Errorf("cannot find uuid in path: %q", *path)
315                 }
316                 uuid := m[2]
317                 mnt, ok := runner.Mounts["/mnt/"+uuid]
318                 if !ok {
319                         mnt = map[string]interface{}{
320                                 "kind": "collection",
321                                 "uuid": uuid,
322                         }
323                         runner.Mounts["/mnt/"+uuid] = mnt
324                 }
325                 *path = "/mnt/" + uuid + m[3]
326         }
327         return nil
328 }
329
330 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
331         exe, err := ioutil.ReadFile("/proc/self/exe")
332         if err != nil {
333                 return "", err
334         }
335         b2 := blake2b.Sum256(exe)
336         cname := fmt.Sprintf("lightning-%x", b2)
337         var existing arvados.CollectionList
338         err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
339                 Limit: 1,
340                 Count: "none",
341                 Filters: []arvados.Filter{
342                         {Attr: "name", Operator: "=", Operand: cname},
343                         {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
344                 },
345         })
346         if err != nil {
347                 return "", err
348         }
349         if len(existing.Items) > 0 {
350                 uuid := existing.Items[0].UUID
351                 log.Printf("using lightning binary in existing collection %s (name is %q; did not verify whether content matches)", uuid, cname)
352                 return uuid, nil
353         }
354         log.Printf("writing lightning binary to new collection %q", cname)
355         ac, err := arvadosclient.New(runner.Client)
356         if err != nil {
357                 return "", err
358         }
359         kc := keepclient.New(ac)
360         var coll arvados.Collection
361         fs, err := coll.FileSystem(runner.Client, kc)
362         if err != nil {
363                 return "", err
364         }
365         f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
366         if err != nil {
367                 return "", err
368         }
369         _, err = f.Write(exe)
370         if err != nil {
371                 return "", err
372         }
373         err = f.Close()
374         if err != nil {
375                 return "", err
376         }
377         mtxt, err := fs.MarshalManifest(".")
378         if err != nil {
379                 return "", err
380         }
381         err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
382                 "collection": map[string]interface{}{
383                         "owner_uuid":    runner.ProjectUUID,
384                         "manifest_text": mtxt,
385                         "name":          cname,
386                 },
387         })
388         if err != nil {
389                 return "", err
390         }
391         log.Printf("stored lightning binary in new collection %s", coll.UUID)
392         return coll.UUID, nil
393 }