15 "git.arvados.org/arvados.git/sdk/go/arvados"
16 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
17 "git.arvados.org/arvados.git/sdk/go/keepclient"
18 log "github.com/sirupsen/logrus"
19 "golang.org/x/crypto/blake2b"
20 "golang.org/x/net/websocket"
23 type eventMessage struct {
25 ObjectUUID string `json:"object_uuid"`
26 EventType string `json:"event_type"`
32 type arvadosClient struct {
34 notifying map[string]map[chan<- eventMessage]int
35 wantClose chan struct{}
36 wsconn *websocket.Conn
40 // Listen for events concerning the given uuids. When an event occurs
41 // (and after connecting/reconnecting to the event stream), send each
42 // uuid to ch. If a {ch, uuid} pair is subscribed twice, the uuid will
43 // be sent only once for each update, but two Unsubscribe calls will
44 // be needed to stop sending them.
45 func (client *arvadosClient) Subscribe(ch chan<- eventMessage, uuid string) {
47 defer client.mtx.Unlock()
48 if client.notifying == nil {
49 client.notifying = map[string]map[chan<- eventMessage]int{}
50 client.wantClose = make(chan struct{})
51 go client.runNotifier()
53 chmap := client.notifying[uuid]
55 chmap = map[chan<- eventMessage]int{}
56 client.notifying[uuid] = chmap
59 for _, nch := range chmap {
66 if needSub && client.wsconn != nil {
67 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
68 "method": "subscribe",
69 "filters": [][]interface{}{
70 {"object_uuid", "=", uuid},
71 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
77 func (client *arvadosClient) Unsubscribe(ch chan<- eventMessage, uuid string) {
79 defer client.mtx.Unlock()
80 chmap := client.notifying[uuid]
81 if n := chmap[ch] - 1; n == 0 {
84 delete(client.notifying, uuid)
86 if client.wsconn != nil {
87 go json.NewEncoder(client.wsconn).Encode(map[string]interface{}{
88 "method": "unsubscribe",
89 "filters": [][]interface{}{
90 {"object_uuid", "=", uuid},
91 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
100 func (client *arvadosClient) Close() {
102 defer client.mtx.Unlock()
103 if client.notifying != nil {
104 client.notifying = nil
105 close(client.wantClose)
109 func (client *arvadosClient) runNotifier() {
112 var cluster arvados.Cluster
113 err := client.RequestAndDecode(&cluster, "GET", arvados.EndpointConfigGet.Path, nil, nil)
115 log.Warnf("error getting cluster config: %s", err)
116 time.Sleep(5 * time.Second)
119 wsURL := cluster.Services.Websocket.ExternalURL
120 wsURL.Scheme = strings.Replace(wsURL.Scheme, "http", "ws", 1)
121 wsURL.Path = "/websocket"
122 wsURL.RawQuery = url.Values{"api_token": []string{client.AuthToken}}.Encode()
123 conn, err := websocket.Dial(wsURL.String(), "", cluster.Services.Controller.ExternalURL.String())
125 log.Warnf("websocket connection error: %s", err)
126 time.Sleep(5 * time.Second)
133 w := json.NewEncoder(conn)
134 for uuid := range client.notifying {
135 w.Encode(map[string]interface{}{
136 "method": "subscribe",
137 "filters": [][]interface{}{
138 {"object_uuid", "=", uuid},
139 {"event_type", "in", []string{"stderr", "crunch-run", "update"}},
144 r := json.NewDecoder(conn)
147 err := r.Decode(&msg)
149 case <-client.wantClose:
153 log.Printf("error decoding websocket message: %s", err)
160 for ch := range client.notifying[msg.ObjectUUID] {
168 type arvadosContainerRunner struct {
169 Client *arvados.Client
174 Prog string // if empty, run /proc/self/exe
176 Mounts map[string]map[string]interface{}
180 func (runner *arvadosContainerRunner) Run() (string, error) {
181 if runner.ProjectUUID == "" {
182 return "", errors.New("cannot run arvados container: ProjectUUID not provided")
185 mounts := map[string]map[string]interface{}{
189 "capacity": 100000000000,
192 for path, mnt := range runner.Mounts {
198 prog = "/mnt/cmd/lightning"
199 cmdUUID, err := runner.makeCommandCollection()
203 mounts["/mnt/cmd"] = map[string]interface{}{
204 "kind": "collection",
208 command := append([]string{prog}, runner.Args...)
210 priority := runner.Priority
214 rc := arvados.RuntimeConstraints{
217 KeepCacheRAM: (1 << 26) * 2 * int64(runner.VCPUs),
219 var cr arvados.ContainerRequest
220 err := runner.Client.RequestAndDecode(&cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{
221 "container_request": map[string]interface{}{
222 "owner_uuid": runner.ProjectUUID,
224 "container_image": "lightning-runtime",
227 "use_existing": true,
228 "output_path": "/mnt/output",
229 "runtime_constraints": rc,
230 "priority": runner.Priority,
231 "state": arvados.ContainerRequestStateCommitted,
237 log.Printf("container request UUID: %s", cr.UUID)
238 log.Printf("container UUID: %s", cr.ContainerUUID)
240 logch := make(chan eventMessage)
241 client := arvadosClient{Client: runner.Client}
245 if subscribedUUID != "" {
246 client.Unsubscribe(logch, subscribedUUID)
250 ticker := time.NewTicker(5 * time.Second)
253 lastState := cr.State
254 refreshCR := func() {
255 err = runner.Client.RequestAndDecode(&cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
257 log.Printf("error getting container request: %s", err)
260 if lastState != cr.State {
261 log.Printf("container state: %s", cr.State)
264 if subscribedUUID != cr.ContainerUUID {
265 if subscribedUUID != "" {
266 client.Unsubscribe(logch, subscribedUUID)
268 client.Subscribe(logch, cr.ContainerUUID)
269 subscribedUUID = cr.ContainerUUID
273 for cr.State != arvados.ContainerRequestStateFinal {
278 switch msg.EventType {
282 for _, line := range strings.Split(msg.Properties.Text, "\n") {
291 var c arvados.Container
292 err = runner.Client.RequestAndDecode(&c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
297 return "", fmt.Errorf("container exited %d", c.ExitCode)
299 return cr.OutputUUID, err
302 var collectionInPathRe = regexp.MustCompile(`^(.*/)?([0-9a-f]{32}\+[0-9]+|[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})(/.*)?$`)
304 func (runner *arvadosContainerRunner) TranslatePaths(paths ...*string) error {
305 if runner.Mounts == nil {
306 runner.Mounts = make(map[string]map[string]interface{})
308 for _, path := range paths {
309 if *path == "" || *path == "-" {
312 m := collectionInPathRe.FindStringSubmatch(*path)
314 return fmt.Errorf("cannot find uuid in path: %q", *path)
317 mnt, ok := runner.Mounts["/mnt/"+uuid]
319 mnt = map[string]interface{}{
320 "kind": "collection",
323 runner.Mounts["/mnt/"+uuid] = mnt
325 *path = "/mnt/" + uuid + m[3]
330 func (runner *arvadosContainerRunner) makeCommandCollection() (string, error) {
331 exe, err := ioutil.ReadFile("/proc/self/exe")
335 b2 := blake2b.Sum256(exe)
336 cname := fmt.Sprintf("lightning-%x", b2)
337 var existing arvados.CollectionList
338 err = runner.Client.RequestAndDecode(&existing, "GET", "arvados/v1/collections", nil, arvados.ListOptions{
341 Filters: []arvados.Filter{
342 {Attr: "name", Operator: "=", Operand: cname},
343 {Attr: "owner_uuid", Operator: "=", Operand: runner.ProjectUUID},
349 if len(existing.Items) > 0 {
350 uuid := existing.Items[0].UUID
351 log.Printf("using lightning binary in existing collection %s (name is %q; did not verify whether content matches)", uuid, cname)
354 log.Printf("writing lightning binary to new collection %q", cname)
355 ac, err := arvadosclient.New(runner.Client)
359 kc := keepclient.New(ac)
360 var coll arvados.Collection
361 fs, err := coll.FileSystem(runner.Client, kc)
365 f, err := fs.OpenFile("lightning", os.O_CREATE|os.O_WRONLY, 0777)
369 _, err = f.Write(exe)
377 mtxt, err := fs.MarshalManifest(".")
381 err = runner.Client.RequestAndDecode(&coll, "POST", "arvados/v1/collections", nil, map[string]interface{}{
382 "collection": map[string]interface{}{
383 "owner_uuid": runner.ProjectUUID,
384 "manifest_text": mtxt,
391 log.Printf("stored lightning binary in new collection %s", coll.UUID)
392 return coll.UUID, nil