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{},
275 log.Printf("container request UUID: %s", cr.UUID)
276 log.Printf("container UUID: %s", cr.ContainerUUID)
278 logch := make(chan eventMessage)
279 client := arvadosClient{Client: runner.Client}
283 if subscribedUUID != "" {
284 log.Printf("unsubscribe container UUID: %s", 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 log.Printf("unsubscribe container UUID: %s", subscribedUUID)
309 client.Unsubscribe(logch, subscribedUUID)
311 log.Printf("subscribe container UUID: %s", cr.ContainerUUID)
312 client.Subscribe(logch, cr.ContainerUUID)
313 subscribedUUID = cr.ContainerUUID
317 var reCrunchstat = regexp.MustCompile(`mem .* rss`)
319 for cr.State != arvados.ContainerRequestStateFinal {
322 err := runner.Client.RequestAndDecode(&cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
323 "container_request": map[string]interface{}{
328 log.Errorf("error while trying to cancel container request %s: %s", cr.UUID, err)
331 case <-refreshTicker.C:
334 switch msg.EventType {
338 for _, line := range strings.Split(msg.Properties.Text, "\n") {
340 fmt.Fprint(os.Stderr, neednewline)
346 for _, line := range strings.Split(msg.Properties.Text, "\n") {
347 mem := reCrunchstat.FindString(line)
349 fmt.Fprintf(os.Stderr, "%s \r", mem)
356 fmt.Fprint(os.Stderr, neednewline)
358 if err := ctx.Err(); err != nil {
362 var c arvados.Container
363 err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
366 } else if c.State != arvados.ContainerStateComplete {
367 return "", fmt.Errorf("container did not complete: %s", c.State)
368 } else if c.ExitCode != 0 {
369 return "", fmt.Errorf("container exited %d", c.ExitCode)
371 return cr.OutputUUID, err
374 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
376 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
377 if runner.Mounts == nil {
378 runner.Mounts = make(map[string]map[string]interface{})
380 for _, path := range paths {
381 if *path == "" || *path == "-" {
384 m := collectionInPathRe.FindStringSubmatch(*path)
386 return fmt.Errorf("cannot find uuid in path: %q", *path)
389 mnt, ok := runner.Mounts["/mnt/"+uuid]
391 mnt = map[string]interface{}{
392 "kind": "collection",
395 runner.Mounts["/mnt/"+uuid] = mnt
397 *path = "/mnt/" + uuid + m[3]
402 var mtxMakeCommandCollection sync.Mutex
404 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
405 mtxMakeCommandCollection.Lock()
406 defer mtxMakeCommandCollection.Unlock()
407 exe, err := ioutil.ReadFile("/proc/self/exe")
411 b2 := blake2b.Sum256(exe)
412 cname := "lightning " + cmd.Version.String() // must build with "make", not just "go install"
413 var existing arvados.CollectionList
414 err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
417 Filters: []arvados.Filter{
418 {Attr: "name", Operator: "=", Operand: cname},
419 {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
420 {Attr: "properties.blake2b", Operator: "=", Operand: fmt.Sprintf("%x", b2)},
426 if len(existing.Items) > 0 {
427 coll := existing.Items[0]
428 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"])
429 return coll.UUID, nil
431 log.Printf("writing lightning binary to new collection %q", cname)
432 ac, err := arvadosclient.New(runner.Client)
436 kc := keepclient.New(ac)
437 var coll arvados.Collection
438 fs, err := coll.FileSystem(runner.Client, kc)
442 f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
446 _, err = f.Write(exe)
454 mtxt, err := fs.MarshalManifest(".")
458 err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
459 "collection": map[string]interface{}{
460 "owner_uuid": runner.ProjectUUID,
461 "manifest_text": mtxt,
463 "properties": map[string]interface{}{
464 "blake2b": fmt.Sprintf("%x", b2),
471 log.Printf("stored lightning binary in new collection %s", coll.UUID)
472 return coll.UUID, nil
475 // zopen returns a reader for the given file, using the arvados API
476 // instead of arv-mount/fuse where applicable, and transparently
477 // decompressing the input if fnm ends with ".gz".
478 func zopen(fnm string) (io.ReadCloser, error) {
480 if err != nil || !strings.HasSuffix(fnm, ".gz") {
483 rdr, err := pgzip.NewReader(bufio.NewReaderSize(f, 4*1024*1024))
488 return gzipr{rdr, f}, nil
491 // gzipr wraps a ReadCloser and a Closer, presenting a single Close()
492 // method that closes both wrapped objects.
498 func (gr gzipr) Close() error {
499 e1 := gr.ReadCloser.Close()
500 e2 := gr.Closer.Close()
508 arvadosClientFromEnv = arvados.NewClientFromEnv()
509 keepClient *keepclient.KeepClient
510 siteFS arvados.CustomFileSystem
514 func open(fnm string) (io.ReadCloser, error) {
515 if os.Getenv("ARVADOS_API_HOST") == "" {
518 m := collectionInPathRe.FindStringSubmatch(fnm)
523 mnt := "/mnt/" + uuid + "/"
524 if !strings.HasPrefix(fnm, mnt) {
529 defer siteFSMtx.Unlock()
531 log.Info("setting up Arvados client")
532 ac, err := arvadosclient.New(arvadosClientFromEnv)
536 ac.Client = arvados.DefaultSecureClient
537 keepClient = keepclient.New(ac)
538 // Don't use keepclient's default short timeouts.
539 keepClient.HTTPClient = arvados.DefaultSecureClient
540 keepClient.BlockCache = &keepclient.BlockCache{MaxBlocks: 4}
541 siteFS = arvadosClientFromEnv.SiteFileSystem(keepClient)
543 keepClient.BlockCache.MaxBlocks++
546 log.Infof("reading %q from %s using Arvados client", fnm[len(mnt):], uuid)
547 return siteFS.Open("by_id/" + uuid + "/" + fnm[len(mnt):])