Fix up websocket locking.
[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                 log.Printf("connected to websocket at %s", wsURL)
130
131                 client.mtx.Lock()
132                 client.wsconn = conn
133                 resubscribe := make([]string, 0, len(client.notifying))
134                 for uuid := range client.notifying {
135                         resubscribe = append(resubscribe, uuid)
136                 }
137                 client.mtx.Unlock()
138
139                 go func() {
140                         w := json.NewEncoder(conn)
141                         for _, uuid := range resubscribe {
142                                 w.Encode(map[string]interface{}{
143                                         "method": "subscribe",
144                                         "filters": [][]interface{}{
145                                                 {"object_uuid", "=", uuid},
146                                                 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
147                                         },
148                                 })
149                         }
150                 }()
151
152                 r := json.NewDecoder(conn)
153                 for {
154                         var msg eventMessage
155                         err := r.Decode(&msg)
156                         select {
157                         case <-client.wantClose:
158                                 return
159                         default:
160                                 if err != nil {
161                                         log.Printf("error decoding websocket message: %s", err)
162                                         client.mtx.Lock()
163                                         client.wsconn = nil
164                                         client.mtx.Unlock()
165                                         go conn.Close()
166                                         continue reconnect
167                                 }
168                                 client.mtx.Lock()
169                                 for ch := range client.notifying[msg.ObjectUUID] {
170                                         ch <- msg
171                                 }
172                                 client.mtx.Unlock()
173                         }
174                 }
175         }
176 }
177
178 type arvadosContainerRunner struct {
179         Client      *arvados.Client
180         Name        string
181         ProjectUUID string
182         VCPUs       int
183         RAM         int64
184         Prog        string // if empty, run /proc/self/exe
185         Args        []string
186         Mounts      map[string]map[string]interface{}
187         Priority    int
188 }
189
190 func (runner *arvadosContainerRunner) Run() (string, error) {
191         if runner.ProjectUUID == "" {
192                 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
193         }
194
195         mounts := map[string]map[string]interface{}{
196                 "/mnt/output": {
197                         "kind":     "collection",
198                         "writable": true,
199                 },
200         }
201         for path, mnt := range runner.Mounts {
202                 mounts[path] = mnt
203         }
204
205         prog := runner.Prog
206         if prog == "" {
207                 prog = "/mnt/cmd/lightning"
208                 cmdUUID, err := runner.makeCommandCollection()
209                 if err != nil {
210                         return "", err
211                 }
212                 mounts["/mnt/cmd"] = map[string]interface{}{
213                         "kind": "collection",
214                         "uuid": cmdUUID,
215                 }
216         }
217         command := append([]string{prog}, runner.Args...)
218
219         priority := runner.Priority
220         if priority < 1 {
221                 priority = 500
222         }
223         rc := arvados.RuntimeConstraints{
224                 VCPUs:        runner.VCPUs,
225                 RAM:          runner.RAM,
226                 KeepCacheRAM: (1 << 26) * 2 * int64(runner.VCPUs),
227         }
228         var cr arvados.ContainerRequest
229         err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
230                 "container_request": map[string]interface{}{
231                         "owner_uuid":          runner.ProjectUUID,
232                         "name":                runner.Name,
233                         "container_image":     "lightning-runtime",
234                         "command":             command,
235                         "mounts":              mounts,
236                         "use_existing":        true,
237                         "output_path":         "/mnt/output",
238                         "runtime_constraints": rc,
239                         "priority":            runner.Priority,
240                         "state":               arvados.ContainerRequestStateCommitted,
241                 },
242         })
243         if err != nil {
244                 return "", err
245         }
246         log.Printf("container request UUID: %s", cr.UUID)
247         log.Printf("container UUID: %s", cr.ContainerUUID)
248
249         logch := make(chan eventMessage)
250         client := arvadosClient{Client: runner.Client}
251         defer client.Close()
252         subscribedUUID := ""
253         defer func() {
254                 if subscribedUUID != "" {
255                         client.Unsubscribe(logch, subscribedUUID)
256                 }
257         }()
258
259         ticker := time.NewTicker(5 * time.Second)
260         defer ticker.Stop()
261
262         lastState := cr.State
263         refreshCR := func() {
264                 err = runner.Client.RequestAndDecode(&cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
265                 if err != nil {
266                         log.Printf("error getting container request: %s", err)
267                         return
268                 }
269                 if lastState != cr.State {
270                         log.Printf("container request state: %s", cr.State)
271                         lastState = cr.State
272                 }
273                 if subscribedUUID != cr.ContainerUUID {
274                         if subscribedUUID != "" {
275                                 client.Unsubscribe(logch, subscribedUUID)
276                         }
277                         client.Subscribe(logch, cr.ContainerUUID)
278                         subscribedUUID = cr.ContainerUUID
279                 }
280         }
281
282         for cr.State != arvados.ContainerRequestStateFinal {
283                 select {
284                 case <-ticker.C:
285                         refreshCR()
286                 case msg := <-logch:
287                         switch msg.EventType {
288                         case "update":
289                                 refreshCR()
290                         default:
291                                 for _, line := range strings.Split(msg.Properties.Text, "\n") {
292                                         if line != "" {
293                                                 log.Print(line)
294                                         }
295                                 }
296                         }
297                 }
298         }
299
300         var c arvados.Container
301         err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
302         if err != nil {
303                 return "", err
304         } else if c.State != arvados.ContainerStateComplete {
305                 return "", fmt.Errorf("container did not complete: %s", c.State)
306         } else if c.ExitCode != 0 {
307                 return "", fmt.Errorf("container exited %d", c.ExitCode)
308         }
309         return cr.OutputUUID, err
310 }
311
312 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
313
314 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
315         if runner.Mounts == nil {
316                 runner.Mounts = make(map[string]map[string]interface{})
317         }
318         for _, path := range paths {
319                 if *path == "" || *path == "-" {
320                         continue
321                 }
322                 m := collectionInPathRe.FindStringSubmatch(*path)
323                 if m == nil {
324                         return fmt.Errorf("cannot find uuid in path: %q", *path)
325                 }
326                 uuid := m[2]
327                 mnt, ok := runner.Mounts["/mnt/"+uuid]
328                 if !ok {
329                         mnt = map[string]interface{}{
330                                 "kind": "collection",
331                                 "uuid": uuid,
332                         }
333                         runner.Mounts["/mnt/"+uuid] = mnt
334                 }
335                 *path = "/mnt/" + uuid + m[3]
336         }
337         return nil
338 }
339
340 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
341         exe, err := ioutil.ReadFile("/proc/self/exe")
342         if err != nil {
343                 return "", err
344         }
345         b2 := blake2b.Sum256(exe)
346         cname := fmt.Sprintf("lightning-%x", b2)
347         var existing arvados.CollectionList
348         err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
349                 Limit: 1,
350                 Count: "none",
351                 Filters: []arvados.Filter{
352                         {Attr: "name", Operator: "=", Operand: cname},
353                         {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
354                 },
355         })
356         if err != nil {
357                 return "", err
358         }
359         if len(existing.Items) > 0 {
360                 uuid := existing.Items[0].UUID
361                 log.Printf("using lightning binary in existing collection %s (name is %q; did not verify whether content matches)", uuid, cname)
362                 return uuid, nil
363         }
364         log.Printf("writing lightning binary to new collection %q", cname)
365         ac, err := arvadosclient.New(runner.Client)
366         if err != nil {
367                 return "", err
368         }
369         kc := keepclient.New(ac)
370         var coll arvados.Collection
371         fs, err := coll.FileSystem(runner.Client, kc)
372         if err != nil {
373                 return "", err
374         }
375         f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
376         if err != nil {
377                 return "", err
378         }
379         _, err = f.Write(exe)
380         if err != nil {
381                 return "", err
382         }
383         err = f.Close()
384         if err != nil {
385                 return "", err
386         }
387         mtxt, err := fs.MarshalManifest(".")
388         if err != nil {
389                 return "", err
390         }
391         err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
392                 "collection": map[string]interface{}{
393                         "owner_uuid":    runner.ProjectUUID,
394                         "manifest_text": mtxt,
395                         "name":          cname,
396                 },
397         })
398         if err != nil {
399                 return "", err
400         }
401         log.Printf("stored lightning binary in new collection %s", coll.UUID)
402         return coll.UUID, nil
403 }