19 "git.arvados.org/arvados.git/lib/cmd"
20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
22 "git.arvados.org/arvados.git/sdk/go/keepclient"
23 "github.com/klauspost/pgzip"
24 log "github.com/sirupsen/logrus"
25 "golang.org/x/crypto/blake2b"
26 "golang.org/x/net/websocket"
29 type eventMessage struct {
31 ObjectUUID string `json:"object_uuid"`
32 EventType string `json:"event_type"`
38 type arvadosClient struct {
40 notifying map[string]map[chan<- eventMessage]int
41 wantClose chan struct{}
42 wsconn *websocket.Conn
46 // Listen for events concerning the given uuids. When an event occurs
47 // (and after connecting/reconnecting to the event stream), send each
48 // uuid to ch. If a {ch, uuid} pair is subscribed twice, the uuid will
49 // be sent only once for each update, but two Unsubscribe calls will
50 // be needed to stop sending them.
51 func (client *arvadosClient) Subscribe(ch chan<- eventMessage, uuid string) {
53 defer client.mtx.Unlock()
54 if client.notifying == nil {
55 client.notifying = map[string]map[chan<- eventMessage]int{}
56 client.wantClose = make(chan struct{})
57 go client.runNotifier()
59 chmap := client.notifying[uuid]
61 chmap = map[chan<- eventMessage]int{}
62 client.notifying[uuid] = chmap
65 for _, nch := range chmap {
72 if needSub && client.wsconn != nil {
73 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
74 "method": "subscribe",
75 "filters": [][]interface{}{
76 {"object_uuid", "=", uuid},
77 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
83 func (client *arvadosClient) Unsubscribe(ch chan<- eventMessage, uuid string) {
85 defer client.mtx.Unlock()
86 chmap := client.notifying[uuid]
87 if n := chmap[ch] - 1; n == 0 {
90 delete(client.notifying, uuid)
92 if client.wsconn != nil {
93 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
94 "method": "unsubscribe",
95 "filters": [][]interface{}{
96 {"object_uuid", "=", uuid},
97 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
106 func (client *arvadosClient) Close() {
108 defer client.mtx.Unlock()
109 if client.notifying != nil {
110 client.notifying = nil
111 close(client.wantClose)
115 func (client *arvadosClient) runNotifier() {
118 var cluster arvados.Cluster
119 err := client.RequestAndDecode(&cluster, "GET", arvados.EndpointConfigGet.Path, nil, nil)
121 log.Warnf("error getting cluster config: %s", err)
122 time.Sleep(5 * time.Second)
125 wsURL := cluster.Services.Websocket.ExternalURL
126 wsURL.Scheme = strings.Replace(wsURL.Scheme, "http", "ws", 1)
127 wsURL.Path = "/websocket"
128 wsURLNoToken := wsURL.String()
129 wsURL.RawQuery = url.Values{"api_token": []string{client.AuthToken}}.Encode()
130 conn, err := websocket.Dial(wsURL.String(), "", cluster.Services.Controller.ExternalURL.String())
132 log.Warnf("websocket connection error: %s", err)
133 time.Sleep(5 * time.Second)
136 log.Printf("connected to websocket at %s", wsURLNoToken)
140 resubscribe := make([]string, 0, len(client.notifying))
141 for uuid := range client.notifying {
142 resubscribe = append(resubscribe, uuid)
147 w := json.NewEncoder(conn)
148 for _, uuid := range resubscribe {
149 w.Encode(map[string]interface{}{
150 "method": "subscribe",
151 "filters": [][]interface{}{
152 {"object_uuid", "=", uuid},
153 {"event_type", "in", []string{"stderr", "crunch-run", "crunchstat", "update"}},
159 r := json.NewDecoder(conn)
162 err := r.Decode(&msg)
164 case <-client.wantClose:
168 log.Printf("error decoding websocket message: %s", err)
176 for ch := range client.notifying[msg.ObjectUUID] {
185 var refreshTicker = time.NewTicker(5 * time.Second)
187 type arvadosContainerRunner struct {
188 Client *arvados.Client
195 Prog string // if empty, run /proc/self/exe
197 Mounts map[string]map[string]interface{}
199 KeepCache int // cache buffers per VCPU (0 for default)
202 func (runner *arvadosContainerRunner) Run() (string, error) {
203 return runner.RunContext(context.Background())
206 func (runner *arvadosContainerRunner) RunContext(ctx context.Context) (string, error) {
207 if runner.ProjectUUID == "" {
208 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
211 mounts := map[string]map[string]interface{}{
213 "kind": "collection",
217 for path, mnt := range runner.Mounts {
223 prog = "/mnt/cmd/lightning"
224 cmdUUID, err := runner.makeCommandCollection()
228 mounts["/mnt/cmd"] = map[string]interface{}{
229 "kind": "collection",
233 command := append([]string{prog}, runner.Args...)
235 priority := runner.Priority
239 keepCache := runner.KeepCache
243 rc := arvados.RuntimeConstraints{
244 API: &runner.APIAccess,
247 KeepCacheRAM: (1 << 26) * int64(keepCache) * int64(runner.VCPUs),
249 outname := &runner.OutputName
253 var cr arvados.ContainerRequest
254 err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
255 "container_request": map[string]interface{}{
256 "owner_uuid": runner.ProjectUUID,
258 "container_image": "lightning-runtime",
261 "use_existing": true,
262 "output_path": "/mnt/output",
263 "output_name": outname,
264 "runtime_constraints": rc,
265 "priority": runner.Priority,
266 "state": arvados.ContainerRequestStateCommitted,
267 "scheduling_parameters": arvados.SchedulingParameters{
269 Partitions: []string{},
276 log.Printf("container request UUID: %s", cr.UUID)
277 log.Printf("container UUID: %s", cr.ContainerUUID)
279 logch := make(chan eventMessage)
280 client := arvadosClient{Client: runner.Client}
284 if subscribedUUID != "" {
285 client.Unsubscribe(logch, subscribedUUID)
291 lastState := cr.State
292 refreshCR := func() {
293 err = runner.Client.RequestAndDecode(&cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
295 fmt.Fprint(os.Stderr, neednewline)
296 log.Printf("error getting container request: %s", err)
299 if lastState != cr.State {
300 fmt.Fprint(os.Stderr, neednewline)
301 log.Printf("container request state: %s", cr.State)
304 if subscribedUUID != cr.ContainerUUID {
305 fmt.Fprint(os.Stderr, neednewline)
307 if subscribedUUID != "" {
308 client.Unsubscribe(logch, subscribedUUID)
310 client.Subscribe(logch, cr.ContainerUUID)
311 subscribedUUID = cr.ContainerUUID
315 var reCrunchstat = regexp.MustCompile(`mem .* rss`)
317 for cr.State != arvados.ContainerRequestStateFinal {
320 err := runner.Client.RequestAndDecode(&cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
321 "container_request": map[string]interface{}{
326 log.Errorf("error while trying to cancel container request %s: %s", cr.UUID, err)
329 case <-refreshTicker.C:
332 switch msg.EventType {
336 for _, line := range strings.Split(msg.Properties.Text, "\n") {
338 fmt.Fprint(os.Stderr, neednewline)
344 for _, line := range strings.Split(msg.Properties.Text, "\n") {
345 mem := reCrunchstat.FindString(line)
347 fmt.Fprintf(os.Stderr, "%s \r", mem)
354 fmt.Fprint(os.Stderr, neednewline)
356 if err := ctx.Err(); err != nil {
360 var c arvados.Container
361 err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
364 } else if c.State != arvados.ContainerStateComplete {
365 return "", fmt.Errorf("container did not complete: %s", c.State)
366 } else if c.ExitCode != 0 {
367 return "", fmt.Errorf("container exited %d", c.ExitCode)
369 return cr.OutputUUID, err
372 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
374 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
375 if runner.Mounts == nil {
376 runner.Mounts = make(map[string]map[string]interface{})
378 for _, path := range paths {
379 if *path == "" || *path == "-" {
382 m := collectionInPathRe.FindStringSubmatch(*path)
384 return fmt.Errorf("cannot find uuid in path: %q", *path)
387 mnt, ok := runner.Mounts["/mnt/"+uuid]
389 mnt = map[string]interface{}{
390 "kind": "collection",
393 runner.Mounts["/mnt/"+uuid] = mnt
395 *path = "/mnt/" + uuid + m[3]
400 var mtxMakeCommandCollection sync.Mutex
402 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
403 mtxMakeCommandCollection.Lock()
404 defer mtxMakeCommandCollection.Unlock()
405 exe, err := ioutil.ReadFile("/proc/self/exe")
409 b2 := blake2b.Sum256(exe)
410 cname := "lightning " + cmd.Version.String() // must build with "make", not just "go install"
411 var existing arvados.CollectionList
412 err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
415 Filters: []arvados.Filter{
416 {Attr: "name", Operator: "=", Operand: cname},
417 {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
418 {Attr: "properties.blake2b", Operator: "=", Operand: fmt.Sprintf("%x", b2)},
424 if len(existing.Items) > 0 {
425 coll := existing.Items[0]
426 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"])
427 return coll.UUID, nil
429 log.Printf("writing lightning binary to new collection %q", cname)
430 ac, err := arvadosclient.New(runner.Client)
434 kc := keepclient.New(ac)
435 var coll arvados.Collection
436 fs, err := coll.FileSystem(runner.Client, kc)
440 f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
444 _, err = f.Write(exe)
452 mtxt, err := fs.MarshalManifest(".")
456 err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
457 "collection": map[string]interface{}{
458 "owner_uuid": runner.ProjectUUID,
459 "manifest_text": mtxt,
461 "properties": map[string]interface{}{
462 "blake2b": fmt.Sprintf("%x", b2),
469 log.Printf("stored lightning binary in new collection %s", coll.UUID)
470 return coll.UUID, nil
473 // zopen returns a reader for the given file, using the arvados API
474 // instead of arv-mount/fuse where applicable, and transparently
475 // decompressing the input if fnm ends with ".gz".
476 func zopen(fnm string) (io.ReadCloser, error) {
478 if err != nil || !strings.HasSuffix(fnm, ".gz") {
481 rdr, err := pgzip.NewReader(bufio.NewReaderSize(f, 4*1024*1024))
486 return gzipr{rdr, f}, nil
489 // gzipr wraps a ReadCloser and a Closer, presenting a single Close()
490 // method that closes both wrapped objects.
496 func (gr gzipr) Close() error {
497 e1 := gr.ReadCloser.Close()
498 e2 := gr.Closer.Close()
506 arvadosClientFromEnv = arvados.NewClientFromEnv()
507 siteFS arvados.CustomFileSystem
511 func open(fnm string) (io.ReadCloser, error) {
512 if os.Getenv("ARVADOS_API_HOST") == "" {
515 m := collectionInPathRe.FindStringSubmatch(fnm)
520 mnt := "/mnt/" + uuid + "/"
521 if !strings.HasPrefix(fnm, mnt) {
526 defer siteFSMtx.Unlock()
528 log.Info("setting up Arvados client")
529 ac, err := arvadosclient.New(arvadosClientFromEnv)
533 ac.Client = arvados.DefaultSecureClient
534 kc := keepclient.New(ac)
535 // Don't use keepclient's default short timeouts.
536 kc.HTTPClient = arvados.DefaultSecureClient
537 // Guess max concurrent readers, hope to avoid cache
539 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: runtime.NumCPU() * 3}
540 siteFS = arvadosClientFromEnv.SiteFileSystem(kc)
543 log.Infof("reading %q from %s using Arvados client", fnm[len(mnt):], uuid)
544 return siteFS.Open("by_id/" + uuid + "/" + fnm[len(mnt):])