18 "git.arvados.org/arvados.git/lib/cmd"
19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
21 "git.arvados.org/arvados.git/sdk/go/keepclient"
22 "github.com/klauspost/pgzip"
23 log "github.com/sirupsen/logrus"
24 "golang.org/x/crypto/blake2b"
25 "golang.org/x/net/websocket"
28 type eventMessage struct {
30 ObjectUUID string `json:"object_uuid"`
31 EventType string `json:"event_type"`
37 type arvadosClient struct {
39 notifying map[string]map[chan<- eventMessage]int
40 wantClose chan struct{}
41 wsconn *websocket.Conn
45 // Listen for events concerning the given uuids. When an event occurs
46 // (and after connecting/reconnecting to the event stream), send each
47 // uuid to ch. If a {ch, uuid} pair is subscribed twice, the uuid will
48 // be sent only once for each update, but two Unsubscribe calls will
49 // be needed to stop sending them.
50 func (client *arvadosClient) Subscribe(ch chan<- eventMessage, uuid string) {
52 defer client.mtx.Unlock()
53 if client.notifying == nil {
54 client.notifying = map[string]map[chan<- eventMessage]int{}
55 client.wantClose = make(chan struct{})
56 go client.runNotifier()
58 chmap := client.notifying[uuid]
60 chmap = map[chan<- eventMessage]int{}
61 client.notifying[uuid] = chmap
64 for _, nch := range chmap {
71 if needSub && client.wsconn != nil {
72 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
73 "method": "subscribe",
74 "filters": [][]interface{}{
75 {"object_uuid", "=", uuid},
76 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
82 func (client *arvadosClient) Unsubscribe(ch chan<- eventMessage, uuid string) {
84 defer client.mtx.Unlock()
85 chmap := client.notifying[uuid]
86 if n := chmap[ch] - 1; n == 0 {
89 delete(client.notifying, uuid)
91 if client.wsconn != nil {
92 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
93 "method": "unsubscribe",
94 "filters": [][]interface{}{
95 {"object_uuid", "=", uuid},
96 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
105 func (client *arvadosClient) Close() {
107 defer client.mtx.Unlock()
108 if client.notifying != nil {
109 client.notifying = nil
110 close(client.wantClose)
114 func (client *arvadosClient) runNotifier() {
117 var cluster arvados.Cluster
118 err := client.RequestAndDecode(&cluster, "GET", arvados.EndpointConfigGet.Path, nil, nil)
120 log.Warnf("error getting cluster config: %s", err)
121 time.Sleep(5 * time.Second)
124 wsURL := cluster.Services.Websocket.ExternalURL
125 wsURL.Scheme = strings.Replace(wsURL.Scheme, "http", "ws", 1)
126 wsURL.Path = "/websocket"
127 wsURLNoToken := wsURL.String()
128 wsURL.RawQuery = url.Values{"api_token": []string{client.AuthToken}}.Encode()
129 conn, err := websocket.Dial(wsURL.String(), "", cluster.Services.Controller.ExternalURL.String())
131 log.Warnf("websocket connection error: %s", err)
132 time.Sleep(5 * time.Second)
135 log.Printf("connected to websocket at %s", wsURLNoToken)
139 resubscribe := make([]string, 0, len(client.notifying))
140 for uuid := range client.notifying {
141 resubscribe = append(resubscribe, uuid)
146 w := json.NewEncoder(conn)
147 for _, uuid := range resubscribe {
148 w.Encode(map[string]interface{}{
149 "method": "subscribe",
150 "filters": [][]interface{}{
151 {"object_uuid", "=", uuid},
152 {"event_type", "in", []string{"stderr", "crunch-run", "crunchstat", "update"}},
158 r := json.NewDecoder(conn)
161 err := r.Decode(&msg)
163 case <-client.wantClose:
167 log.Printf("error decoding websocket message: %s", err)
175 for ch := range client.notifying[msg.ObjectUUID] {
184 var refreshTicker = time.NewTicker(5 * time.Second)
186 type arvadosContainerRunner struct {
187 Client *arvados.Client
194 Prog string // if empty, run /proc/self/exe
196 Mounts map[string]map[string]interface{}
198 KeepCache int // cache buffers per VCPU (0 for default)
201 func (runner *arvadosContainerRunner) Run() (string, error) {
202 return runner.RunContext(context.Background())
205 func (runner *arvadosContainerRunner) RunContext(ctx context.Context) (string, error) {
206 if runner.ProjectUUID == "" {
207 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
210 mounts := map[string]map[string]interface{}{
212 "kind": "collection",
216 for path, mnt := range runner.Mounts {
222 prog = "/mnt/cmd/lightning"
223 cmdUUID, err := runner.makeCommandCollection()
227 mounts["/mnt/cmd"] = map[string]interface{}{
228 "kind": "collection",
232 command := append([]string{prog}, runner.Args...)
234 priority := runner.Priority
238 keepCache := runner.KeepCache
242 rc := arvados.RuntimeConstraints{
243 API: &runner.APIAccess,
246 KeepCacheRAM: (1 << 26) * int64(keepCache) * int64(runner.VCPUs),
248 outname := &runner.OutputName
252 var cr arvados.ContainerRequest
253 err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
254 "container_request": map[string]interface{}{
255 "owner_uuid": runner.ProjectUUID,
257 "container_image": "lightning-runtime",
260 "use_existing": true,
261 "output_path": "/mnt/output",
262 "output_name": outname,
263 "runtime_constraints": rc,
264 "priority": runner.Priority,
265 "state": arvados.ContainerRequestStateCommitted,
266 "scheduling_parameters": arvados.SchedulingParameters{
268 Partitions: []string{},
270 "environment": map[string]string{
271 "GOMAXPROCS": fmt.Sprintf("%d", rc.VCPUs),
278 log.Printf("container request UUID: %s", cr.UUID)
279 log.Printf("container UUID: %s", cr.ContainerUUID)
281 logch := make(chan eventMessage)
282 client := arvadosClient{Client: runner.Client}
286 if subscribedUUID != "" {
287 log.Printf("unsubscribe container UUID: %s", subscribedUUID)
288 client.Unsubscribe(logch, subscribedUUID)
294 lastState := cr.State
295 refreshCR := func() {
296 err = runner.Client.RequestAndDecode(&cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
298 fmt.Fprint(os.Stderr, neednewline)
299 log.Printf("error getting container request: %s", err)
302 if lastState != cr.State {
303 fmt.Fprint(os.Stderr, neednewline)
304 log.Printf("container request state: %s", cr.State)
307 if subscribedUUID != cr.ContainerUUID {
308 fmt.Fprint(os.Stderr, neednewline)
310 if subscribedUUID != "" {
311 log.Printf("unsubscribe container UUID: %s", subscribedUUID)
312 client.Unsubscribe(logch, subscribedUUID)
314 log.Printf("subscribe container UUID: %s", cr.ContainerUUID)
315 client.Subscribe(logch, cr.ContainerUUID)
316 subscribedUUID = cr.ContainerUUID
320 var reCrunchstat = regexp.MustCompile(`mem .* rss`)
322 for cr.State != arvados.ContainerRequestStateFinal {
325 err := runner.Client.RequestAndDecode(&cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
326 "container_request": map[string]interface{}{
331 log.Errorf("error while trying to cancel container request %s: %s", cr.UUID, err)
334 case <-refreshTicker.C:
337 switch msg.EventType {
341 for _, line := range strings.Split(msg.Properties.Text, "\n") {
343 fmt.Fprint(os.Stderr, neednewline)
349 for _, line := range strings.Split(msg.Properties.Text, "\n") {
350 mem := reCrunchstat.FindString(line)
352 fmt.Fprintf(os.Stderr, "%s \r", mem)
359 fmt.Fprint(os.Stderr, neednewline)
361 if err := ctx.Err(); err != nil {
365 var c arvados.Container
366 err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
369 } else if c.State != arvados.ContainerStateComplete {
370 return "", fmt.Errorf("container did not complete: %s", c.State)
371 } else if c.ExitCode != 0 {
372 return "", fmt.Errorf("container exited %d", c.ExitCode)
374 return cr.OutputUUID, err
377 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
379 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
380 if runner.Mounts == nil {
381 runner.Mounts = make(map[string]map[string]interface{})
383 for _, path := range paths {
384 if *path == "" || *path == "-" {
387 m := collectionInPathRe.FindStringSubmatch(*path)
389 return fmt.Errorf("cannot find uuid in path: %q", *path)
392 mnt, ok := runner.Mounts["/mnt/"+uuid]
394 mnt = map[string]interface{}{
395 "kind": "collection",
398 runner.Mounts["/mnt/"+uuid] = mnt
400 *path = "/mnt/" + uuid + m[3]
405 var mtxMakeCommandCollection sync.Mutex
407 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
408 mtxMakeCommandCollection.Lock()
409 defer mtxMakeCommandCollection.Unlock()
410 exe, err := ioutil.ReadFile("/proc/self/exe")
414 b2 := blake2b.Sum256(exe)
415 cname := "lightning " + cmd.Version.String() // must build with "make", not just "go install"
416 var existing arvados.CollectionList
417 err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
420 Filters: []arvados.Filter{
421 {Attr: "name", Operator: "=", Operand: cname},
422 {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
423 {Attr: "properties.blake2b", Operator: "=", Operand: fmt.Sprintf("%x", b2)},
429 if len(existing.Items) > 0 {
430 coll := existing.Items[0]
431 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"])
432 return coll.UUID, nil
434 log.Printf("writing lightning binary to new collection %q", cname)
435 ac, err := arvadosclient.New(runner.Client)
439 kc := keepclient.New(ac)
440 var coll arvados.Collection
441 fs, err := coll.FileSystem(runner.Client, kc)
445 f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
449 _, err = f.Write(exe)
457 mtxt, err := fs.MarshalManifest(".")
461 err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
462 "collection": map[string]interface{}{
463 "owner_uuid": runner.ProjectUUID,
464 "manifest_text": mtxt,
466 "properties": map[string]interface{}{
467 "blake2b": fmt.Sprintf("%x", b2),
474 log.Printf("stored lightning binary in new collection %s", coll.UUID)
475 return coll.UUID, nil
478 // zopen returns a reader for the given file, using the arvados API
479 // instead of arv-mount/fuse where applicable, and transparently
480 // decompressing the input if fnm ends with ".gz".
481 func zopen(fnm string) (io.ReadCloser, error) {
483 if err != nil || !strings.HasSuffix(fnm, ".gz") {
486 rdr, err := pgzip.NewReader(bufio.NewReaderSize(f, 4*1024*1024))
491 return gzipr{rdr, f}, nil
494 // gzipr wraps a ReadCloser and a Closer, presenting a single Close()
495 // method that closes both wrapped objects.
501 func (gr gzipr) Close() error {
502 e1 := gr.ReadCloser.Close()
503 e2 := gr.Closer.Close()
511 arvadosClientFromEnv = arvados.NewClientFromEnv()
512 keepClient *keepclient.KeepClient
513 siteFS arvados.CustomFileSystem
517 type file interface {
519 Readdir(n int) ([]os.FileInfo, error)
522 func open(fnm string) (file, error) {
523 if os.Getenv("ARVADOS_API_HOST") == "" {
526 m := collectionInPathRe.FindStringSubmatch(fnm)
531 mnt := "/mnt/" + uuid + "/"
532 if !strings.HasPrefix(fnm, mnt) {
537 defer siteFSMtx.Unlock()
539 log.Info("setting up Arvados client")
540 ac, err := arvadosclient.New(arvadosClientFromEnv)
544 ac.Client = arvados.DefaultSecureClient
545 keepClient = keepclient.New(ac)
546 // Don't use keepclient's default short timeouts.
547 keepClient.HTTPClient = arvados.DefaultSecureClient
548 keepClient.BlockCache = &keepclient.BlockCache{MaxBlocks: 4}
549 siteFS = arvadosClientFromEnv.SiteFileSystem(keepClient)
551 keepClient.BlockCache.MaxBlocks++
554 log.Infof("reading %q from %s using Arvados client", fnm[len(mnt):], uuid)
555 return siteFS.Open("by_id/" + uuid + "/" + fnm[len(mnt):])