1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
23 "git.arvados.org/arvados.git/lib/cmd"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26 "git.arvados.org/arvados.git/sdk/go/keepclient"
27 "github.com/klauspost/pgzip"
28 log "github.com/sirupsen/logrus"
29 "golang.org/x/crypto/blake2b"
30 "golang.org/x/net/websocket"
33 type eventMessage struct {
35 ObjectUUID string `json:"object_uuid"`
36 EventType string `json:"event_type"`
42 type arvadosClient struct {
44 notifying map[string]map[chan<- eventMessage]int
45 wantClose chan struct{}
46 wsconn *websocket.Conn
50 // Listen for events concerning the given uuids. When an event occurs
51 // (and after connecting/reconnecting to the event stream), send each
52 // uuid to ch. If a {ch, uuid} pair is subscribed twice, the uuid will
53 // be sent only once for each update, but two Unsubscribe calls will
54 // be needed to stop sending them.
55 func (client *arvadosClient) Subscribe(ch chan<- eventMessage, uuid string) {
57 defer client.mtx.Unlock()
58 if client.notifying == nil {
59 client.notifying = map[string]map[chan<- eventMessage]int{}
60 client.wantClose = make(chan struct{})
61 go client.runNotifier()
63 chmap := client.notifying[uuid]
65 chmap = map[chan<- eventMessage]int{}
66 client.notifying[uuid] = chmap
69 for _, nch := range chmap {
76 if needSub && client.wsconn != nil {
77 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
78 "method": "subscribe",
79 "filters": [][]interface{}{
80 {"object_uuid", "=", uuid},
81 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
87 func (client *arvadosClient) Unsubscribe(ch chan<- eventMessage, uuid string) {
89 defer client.mtx.Unlock()
90 chmap := client.notifying[uuid]
91 if n := chmap[ch] - 1; n == 0 {
94 delete(client.notifying, uuid)
96 if client.wsconn != nil {
97 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
98 "method": "unsubscribe",
99 "filters": [][]interface{}{
100 {"object_uuid", "=", uuid},
101 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
110 func (client *arvadosClient) Close() {
112 defer client.mtx.Unlock()
113 if client.notifying != nil {
114 client.notifying = nil
115 close(client.wantClose)
119 func (client *arvadosClient) runNotifier() {
122 var cluster arvados.Cluster
123 err := client.RequestAndDecode(&cluster, "GET", arvados.EndpointConfigGet.Path, nil, nil)
125 log.Warnf("error getting cluster config: %s", err)
126 time.Sleep(5 * time.Second)
129 wsURL := cluster.Services.Websocket.ExternalURL
130 wsURL.Scheme = strings.Replace(wsURL.Scheme, "http", "ws", 1)
131 wsURL.Path = "/websocket"
132 wsURLNoToken := wsURL.String()
133 wsURL.RawQuery = url.Values{"api_token": []string{client.AuthToken}}.Encode()
134 conn, err := websocket.Dial(wsURL.String(), "", cluster.Services.Controller.ExternalURL.String())
136 log.Warnf("websocket connection error: %s", err)
137 time.Sleep(5 * time.Second)
140 log.Printf("connected to websocket at %s", wsURLNoToken)
144 resubscribe := make([]string, 0, len(client.notifying))
145 for uuid := range client.notifying {
146 resubscribe = append(resubscribe, uuid)
151 w := json.NewEncoder(conn)
152 for _, uuid := range resubscribe {
153 w.Encode(map[string]interface{}{
154 "method": "subscribe",
155 "filters": [][]interface{}{
156 {"object_uuid", "=", uuid},
157 {"event_type", "in", []string{"stderr", "crunch-run", "crunchstat", "update"}},
163 r := json.NewDecoder(conn)
166 err := r.Decode(&msg)
168 case <-client.wantClose:
172 log.Printf("error decoding websocket message: %s", err)
180 for ch := range client.notifying[msg.ObjectUUID] {
181 go func() { ch <- msg }()
189 var refreshTicker = time.NewTicker(5 * time.Second)
191 type arvadosContainerRunner struct {
192 Client *arvados.Client
199 Prog string // if empty, run /proc/self/exe
201 Mounts map[string]map[string]interface{}
203 KeepCache int // cache buffers per VCPU (0 for default)
207 func (runner *arvadosContainerRunner) Run() (string, error) {
208 return runner.RunContext(context.Background())
211 func (runner *arvadosContainerRunner) RunContext(ctx context.Context) (string, error) {
212 if runner.ProjectUUID == "" {
213 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
216 mounts := map[string]map[string]interface{}{
218 "kind": "collection",
222 for path, mnt := range runner.Mounts {
228 prog = "/mnt/cmd/lightning"
229 cmdUUID, err := runner.makeCommandCollection()
233 mounts["/mnt/cmd"] = map[string]interface{}{
234 "kind": "collection",
238 command := append([]string{prog}, runner.Args...)
240 priority := runner.Priority
244 keepCache := runner.KeepCache
248 rc := arvados.RuntimeConstraints{
249 API: runner.APIAccess,
252 KeepCacheRAM: (1 << 26) * int64(keepCache) * int64(runner.VCPUs),
254 outname := &runner.OutputName
258 var cr arvados.ContainerRequest
259 err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
260 "container_request": map[string]interface{}{
261 "owner_uuid": runner.ProjectUUID,
263 "container_image": "lightning-runtime",
266 "use_existing": true,
267 "output_path": "/mnt/output",
268 "output_name": outname,
269 "runtime_constraints": rc,
270 "priority": runner.Priority,
271 "state": arvados.ContainerRequestStateCommitted,
272 "scheduling_parameters": arvados.SchedulingParameters{
273 Preemptible: runner.Preemptible,
274 Partitions: []string{},
276 "environment": map[string]string{
277 "GOMAXPROCS": fmt.Sprintf("%d", rc.VCPUs),
284 log.Printf("container request UUID: %s", cr.UUID)
285 log.Printf("container UUID: %s", cr.ContainerUUID)
287 logch := make(chan eventMessage)
288 client := arvadosClient{Client: runner.Client}
292 if subscribedUUID != "" {
293 log.Printf("unsubscribe container UUID: %s", subscribedUUID)
294 client.Unsubscribe(logch, subscribedUUID)
300 lastState := cr.State
301 refreshCR := func() {
302 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Minute))
304 err = runner.Client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
306 fmt.Fprint(os.Stderr, neednewline)
308 log.Printf("error getting container request: %s", err)
311 if lastState != cr.State {
312 fmt.Fprint(os.Stderr, neednewline)
314 log.Printf("container request state: %s", cr.State)
317 if subscribedUUID != cr.ContainerUUID {
318 fmt.Fprint(os.Stderr, neednewline)
320 if subscribedUUID != "" {
321 log.Printf("unsubscribe container UUID: %s", subscribedUUID)
322 client.Unsubscribe(logch, subscribedUUID)
324 log.Printf("subscribe container UUID: %s", cr.ContainerUUID)
325 client.Subscribe(logch, cr.ContainerUUID)
326 subscribedUUID = cr.ContainerUUID
330 var reCrunchstat = regexp.MustCompile(`mem .* (\d+) rss`)
332 for cr.State != arvados.ContainerRequestStateFinal {
335 err := runner.Client.RequestAndDecode(&cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
336 "container_request": map[string]interface{}{
341 log.Errorf("error while trying to cancel container request %s: %s", cr.UUID, err)
344 case <-refreshTicker.C:
347 switch msg.EventType {
351 for _, line := range strings.Split(msg.Properties.Text, "\n") {
353 fmt.Fprint(os.Stderr, neednewline)
359 for _, line := range strings.Split(msg.Properties.Text, "\n") {
360 m := reCrunchstat.FindStringSubmatch(line)
362 rss, _ := strconv.ParseInt(m[1], 10, 64)
363 fmt.Fprintf(os.Stderr, "%s rss %.3f GB \r", cr.UUID, float64(rss)/1e9)
370 fmt.Fprint(os.Stderr, neednewline)
372 if err := ctx.Err(); err != nil {
376 var c arvados.Container
377 err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
380 } else if c.State != arvados.ContainerStateComplete {
381 return "", fmt.Errorf("container did not complete: %s", c.State)
382 } else if c.ExitCode != 0 {
383 return "", fmt.Errorf("container exited %d", c.ExitCode)
385 return cr.OutputUUID, err
388 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
390 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
391 if runner.Mounts == nil {
392 runner.Mounts = make(map[string]map[string]interface{})
394 for _, path := range paths {
395 if *path == "" || *path == "-" {
398 m := collectionInPathRe.FindStringSubmatch(*path)
400 return fmt.Errorf("cannot find uuid in path: %q", *path)
403 mnt, ok := runner.Mounts["/mnt/"+collID]
405 mnt = map[string]interface{}{
406 "kind": "collection",
408 if len(collID) == 27 {
411 mnt["portable_data_hash"] = collID
413 runner.Mounts["/mnt/"+collID] = mnt
415 *path = "/mnt/" + collID + m[3]
420 var mtxMakeCommandCollection sync.Mutex
422 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
423 mtxMakeCommandCollection.Lock()
424 defer mtxMakeCommandCollection.Unlock()
425 exe, err := ioutil.ReadFile("/proc/self/exe")
429 b2 := blake2b.Sum256(exe)
430 cname := "lightning " + cmd.Version.String() // must build with "make", not just "go install"
431 var existing arvados.CollectionList
432 err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
435 Filters: []arvados.Filter{
436 {Attr: "name", Operator: "=", Operand: cname},
437 {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
438 {Attr: "properties.blake2b", Operator: "=", Operand: fmt.Sprintf("%x", b2)},
444 if len(existing.Items) > 0 {
445 coll := existing.Items[0]
446 log.Printf("using lightning binary in existing collection %s (name is %q, hash is %q; did not verify whether content matches)", coll.UUID, cname, coll.Properties["blake2b"])
447 return coll.UUID, nil
449 log.Printf("writing lightning binary to new collection %q", cname)
450 ac, err := arvadosclient.New(runner.Client)
454 kc := keepclient.New(ac)
455 var coll arvados.Collection
456 fs, err := coll.FileSystem(runner.Client, kc)
460 f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
464 _, err = f.Write(exe)
472 mtxt, err := fs.MarshalManifest(".")
476 err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
477 "collection": map[string]interface{}{
478 "owner_uuid": runner.ProjectUUID,
479 "manifest_text": mtxt,
481 "properties": map[string]interface{}{
482 "blake2b": fmt.Sprintf("%x", b2),
489 log.Printf("stored lightning binary in new collection %s", coll.UUID)
490 return coll.UUID, nil
493 // zopen returns a reader for the given file, using the arvados API
494 // instead of arv-mount/fuse where applicable, and transparently
495 // decompressing the input if fnm ends with ".gz".
496 func zopen(fnm string) (io.ReadCloser, error) {
498 if err != nil || !strings.HasSuffix(fnm, ".gz") {
501 rdr, err := pgzip.NewReader(bufio.NewReaderSize(f, 4*1024*1024))
506 return gzipr{rdr, f}, nil
509 // gzipr wraps a ReadCloser and a Closer, presenting a single Close()
510 // method that closes both wrapped objects.
516 func (gr gzipr) Close() error {
517 e1 := gr.ReadCloser.Close()
518 e2 := gr.Closer.Close()
526 arvadosClientFromEnv = arvados.NewClientFromEnv()
527 keepClient *keepclient.KeepClient
528 siteFS arvados.CustomFileSystem
532 type file interface {
535 Readdir(n int) ([]os.FileInfo, error)
538 func open(fnm string) (file, error) {
539 if os.Getenv("ARVADOS_API_HOST") == "" {
542 m := collectionInPathRe.FindStringSubmatch(fnm)
546 collectionUUID := m[2]
547 collectionPath := m[3]
550 defer siteFSMtx.Unlock()
552 log.Info("setting up Arvados client")
553 ac, err := arvadosclient.New(arvadosClientFromEnv)
557 ac.Client = arvados.DefaultSecureClient
558 keepClient = keepclient.New(ac)
559 // Don't use keepclient's default short timeouts.
560 keepClient.HTTPClient = arvados.DefaultSecureClient
561 keepClient.BlockCache = &keepclient.BlockCache{MaxBlocks: 4}
562 siteFS = arvadosClientFromEnv.SiteFileSystem(keepClient)
564 keepClient.BlockCache.MaxBlocks += 2
567 log.Infof("reading %q from %s using Arvados client", collectionPath, collectionUUID)
568 f, err := siteFS.Open("by_id/" + collectionUUID + collectionPath)
572 return &reduceCacheOnClose{file: f}, nil
575 type reduceCacheOnClose struct {
580 func (rc *reduceCacheOnClose) Close() error {
581 rc.once.Do(func() { keepClient.BlockCache.MaxBlocks -= 2 })
582 return rc.file.Close()