17 "git.arvados.org/arvados.git/lib/cmd"
18 "git.arvados.org/arvados.git/sdk/go/arvados"
19 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
20 "git.arvados.org/arvados.git/sdk/go/keepclient"
21 log "github.com/sirupsen/logrus"
22 "golang.org/x/crypto/blake2b"
23 "golang.org/x/net/websocket"
26 type eventMessage struct {
28 ObjectUUID string `json:"object_uuid"`
29 EventType string `json:"event_type"`
35 type arvadosClient struct {
37 notifying map[string]map[chan<- eventMessage]int
38 wantClose chan struct{}
39 wsconn *websocket.Conn
43 // Listen for events concerning the given uuids. When an event occurs
44 // (and after connecting/reconnecting to the event stream), send each
45 // uuid to ch. If a {ch, uuid} pair is subscribed twice, the uuid will
46 // be sent only once for each update, but two Unsubscribe calls will
47 // be needed to stop sending them.
48 func (client *arvadosClient) Subscribe(ch chan<- eventMessage, uuid string) {
50 defer client.mtx.Unlock()
51 if client.notifying == nil {
52 client.notifying = map[string]map[chan<- eventMessage]int{}
53 client.wantClose = make(chan struct{})
54 go client.runNotifier()
56 chmap := client.notifying[uuid]
58 chmap = map[chan<- eventMessage]int{}
59 client.notifying[uuid] = chmap
62 for _, nch := range chmap {
69 if needSub && client.wsconn != nil {
70 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
71 "method": "subscribe",
72 "filters": [][]interface{}{
73 {"object_uuid", "=", uuid},
74 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
80 func (client *arvadosClient) Unsubscribe(ch chan<- eventMessage, uuid string) {
82 defer client.mtx.Unlock()
83 chmap := client.notifying[uuid]
84 if n := chmap[ch] - 1; n == 0 {
87 delete(client.notifying, uuid)
89 if client.wsconn != nil {
90 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
91 "method": "unsubscribe",
92 "filters": [][]interface{}{
93 {"object_uuid", "=", uuid},
94 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
103 func (client *arvadosClient) Close() {
105 defer client.mtx.Unlock()
106 if client.notifying != nil {
107 client.notifying = nil
108 close(client.wantClose)
112 func (client *arvadosClient) runNotifier() {
115 var cluster arvados.Cluster
116 err := client.RequestAndDecode(&cluster, "GET", arvados.EndpointConfigGet.Path, nil, nil)
118 log.Warnf("error getting cluster config: %s", err)
119 time.Sleep(5 * time.Second)
122 wsURL := cluster.Services.Websocket.ExternalURL
123 wsURL.Scheme = strings.Replace(wsURL.Scheme, "http", "ws", 1)
124 wsURL.Path = "/websocket"
125 wsURLNoToken := wsURL.String()
126 wsURL.RawQuery = url.Values{"api_token": []string{client.AuthToken}}.Encode()
127 conn, err := websocket.Dial(wsURL.String(), "", cluster.Services.Controller.ExternalURL.String())
129 log.Warnf("websocket connection error: %s", err)
130 time.Sleep(5 * time.Second)
133 log.Printf("connected to websocket at %s", wsURLNoToken)
137 resubscribe := make([]string, 0, len(client.notifying))
138 for uuid := range client.notifying {
139 resubscribe = append(resubscribe, uuid)
144 w := json.NewEncoder(conn)
145 for _, uuid := range resubscribe {
146 w.Encode(map[string]interface{}{
147 "method": "subscribe",
148 "filters": [][]interface{}{
149 {"object_uuid", "=", uuid},
150 {"event_type", "in", []string{"stderr", "crunch-run", "crunchstat", "update"}},
156 r := json.NewDecoder(conn)
159 err := r.Decode(&msg)
161 case <-client.wantClose:
165 log.Printf("error decoding websocket message: %s", err)
173 for ch := range client.notifying[msg.ObjectUUID] {
182 var refreshTicker = time.NewTicker(5 * time.Second)
184 type arvadosContainerRunner struct {
185 Client *arvados.Client
192 Prog string // if empty, run /proc/self/exe
194 Mounts map[string]map[string]interface{}
196 KeepCache int // cache buffers per VCPU (0 for default)
199 func (runner *arvadosContainerRunner) Run() (string, error) {
200 return runner.RunContext(context.Background())
203 func (runner *arvadosContainerRunner) RunContext(ctx context.Context) (string, error) {
204 if runner.ProjectUUID == "" {
205 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
208 mounts := map[string]map[string]interface{}{
210 "kind": "collection",
214 for path, mnt := range runner.Mounts {
220 prog = "/mnt/cmd/lightning"
221 cmdUUID, err := runner.makeCommandCollection()
225 mounts["/mnt/cmd"] = map[string]interface{}{
226 "kind": "collection",
230 command := append([]string{prog}, runner.Args...)
232 priority := runner.Priority
236 keepCache := runner.KeepCache
240 rc := arvados.RuntimeConstraints{
241 API: &runner.APIAccess,
244 KeepCacheRAM: (1 << 26) * int64(keepCache) * int64(runner.VCPUs),
246 outname := &runner.OutputName
250 var cr arvados.ContainerRequest
251 err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
252 "container_request": map[string]interface{}{
253 "owner_uuid": runner.ProjectUUID,
255 "container_image": "lightning-runtime",
258 "use_existing": true,
259 "output_path": "/mnt/output",
260 "output_name": outname,
261 "runtime_constraints": rc,
262 "priority": runner.Priority,
263 "state": arvados.ContainerRequestStateCommitted,
269 log.Printf("container request UUID: %s", cr.UUID)
270 log.Printf("container UUID: %s", cr.ContainerUUID)
272 logch := make(chan eventMessage)
273 client := arvadosClient{Client: runner.Client}
277 if subscribedUUID != "" {
278 client.Unsubscribe(logch, subscribedUUID)
284 lastState := cr.State
285 refreshCR := func() {
286 err = runner.Client.RequestAndDecode(&cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
288 fmt.Fprint(os.Stderr, neednewline)
289 log.Printf("error getting container request: %s", err)
292 if lastState != cr.State {
293 fmt.Fprint(os.Stderr, neednewline)
294 log.Printf("container request state: %s", cr.State)
297 if subscribedUUID != cr.ContainerUUID {
298 fmt.Fprint(os.Stderr, neednewline)
300 if subscribedUUID != "" {
301 client.Unsubscribe(logch, subscribedUUID)
303 client.Subscribe(logch, cr.ContainerUUID)
304 subscribedUUID = cr.ContainerUUID
308 var reCrunchstat = regexp.MustCompile(`mem .* rss`)
310 for cr.State != arvados.ContainerRequestStateFinal {
313 err := runner.Client.RequestAndDecode(&cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
314 "container_request": map[string]interface{}{
319 log.Errorf("error while trying to cancel container request %s: %s", cr.UUID, err)
322 case <-refreshTicker.C:
325 switch msg.EventType {
329 for _, line := range strings.Split(msg.Properties.Text, "\n") {
331 fmt.Fprint(os.Stderr, neednewline)
337 for _, line := range strings.Split(msg.Properties.Text, "\n") {
338 mem := reCrunchstat.FindString(line)
340 fmt.Fprintf(os.Stderr, "%s \r", mem)
347 fmt.Fprint(os.Stderr, neednewline)
349 if err := ctx.Err(); err != nil {
353 var c arvados.Container
354 err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
357 } else if c.State != arvados.ContainerStateComplete {
358 return "", fmt.Errorf("container did not complete: %s", c.State)
359 } else if c.ExitCode != 0 {
360 return "", fmt.Errorf("container exited %d", c.ExitCode)
362 return cr.OutputUUID, err
365 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
367 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
368 if runner.Mounts == nil {
369 runner.Mounts = make(map[string]map[string]interface{})
371 for _, path := range paths {
372 if *path == "" || *path == "-" {
375 m := collectionInPathRe.FindStringSubmatch(*path)
377 return fmt.Errorf("cannot find uuid in path: %q", *path)
380 mnt, ok := runner.Mounts["/mnt/"+uuid]
382 mnt = map[string]interface{}{
383 "kind": "collection",
386 runner.Mounts["/mnt/"+uuid] = mnt
388 *path = "/mnt/" + uuid + m[3]
393 var mtxMakeCommandCollection sync.Mutex
395 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
396 mtxMakeCommandCollection.Lock()
397 defer mtxMakeCommandCollection.Unlock()
398 exe, err := ioutil.ReadFile("/proc/self/exe")
402 b2 := blake2b.Sum256(exe)
403 cname := "lightning " + cmd.Version.String() // must build with "make", not just "go install"
404 var existing arvados.CollectionList
405 err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
408 Filters: []arvados.Filter{
409 {Attr: "name", Operator: "=", Operand: cname},
410 {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
411 {Attr: "properties.blake2b", Operator: "=", Operand: fmt.Sprintf("%x", b2)},
417 if len(existing.Items) > 0 {
418 coll := existing.Items[0]
419 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"])
420 return coll.UUID, nil
422 log.Printf("writing lightning binary to new collection %q", cname)
423 ac, err := arvadosclient.New(runner.Client)
427 kc := keepclient.New(ac)
428 var coll arvados.Collection
429 fs, err := coll.FileSystem(runner.Client, kc)
433 f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
437 _, err = f.Write(exe)
445 mtxt, err := fs.MarshalManifest(".")
449 err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
450 "collection": map[string]interface{}{
451 "owner_uuid": runner.ProjectUUID,
452 "manifest_text": mtxt,
454 "properties": map[string]interface{}{
455 "blake2b": fmt.Sprintf("%x", b2),
462 log.Printf("stored lightning binary in new collection %s", coll.UUID)
463 return coll.UUID, nil
466 var arvadosClientFromEnv = arvados.NewClientFromEnv()
468 func open(fnm string) (io.ReadCloser, error) {
469 if os.Getenv("ARVADOS_API_HOST") == "" {
472 m := collectionInPathRe.FindStringSubmatch(fnm)
477 mnt := "/mnt/" + uuid + "/"
478 if !strings.HasPrefix(fnm, mnt) {
482 log.Infof("reading %q from %s using Arvados client library", fnm[len(mnt):], uuid)
483 ac, err := arvadosclient.New(arvadosClientFromEnv)
487 ac.Client = arvados.DefaultSecureClient
488 kc := keepclient.New(ac)
489 // Don't use keepclient's default short timeouts.
490 kc.HTTPClient = arvados.DefaultSecureClient
491 // Don't cache more than one block for this file.
492 kc.BlockCache = &keepclient.BlockCache{MaxBlocks: 1}
494 var coll arvados.Collection
495 err = arvadosClientFromEnv.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+uuid, nil, arvados.GetOptions{Select: []string{"uuid", "manifest_text"}})
499 fs, err := coll.FileSystem(arvadosClientFromEnv, kc)
503 return fs.Open(fnm[len(mnt):])