7709: Merge branch 'master' into 7709-api-rails4
[arvados.git] / services / ws / event.go
1 package main
2
3 import (
4         "database/sql"
5         "sync"
6         "time"
7
8         "git.curoverse.com/arvados.git/sdk/go/arvados"
9         "github.com/ghodss/yaml"
10 )
11
12 type eventSink interface {
13         Channel() <-chan *event
14         Stop()
15 }
16
17 type eventSource interface {
18         NewSink() eventSink
19         DB() *sql.DB
20 }
21
22 type event struct {
23         LogID    uint64
24         Received time.Time
25         Ready    time.Time
26         Serial   uint64
27
28         db     *sql.DB
29         logRow *arvados.Log
30         err    error
31         mtx    sync.Mutex
32 }
33
34 // Detail returns the database row corresponding to the event. It can
35 // be called safely from multiple goroutines. Only one attempt will be
36 // made. If the database row cannot be retrieved, Detail returns nil.
37 func (e *event) Detail() *arvados.Log {
38         e.mtx.Lock()
39         defer e.mtx.Unlock()
40         if e.logRow != nil || e.err != nil {
41                 return e.logRow
42         }
43         var logRow arvados.Log
44         var propYAML []byte
45         e.err = e.db.QueryRow(`SELECT id, uuid, object_uuid, COALESCE(object_owner_uuid,''), COALESCE(event_type,''), event_at, created_at, properties FROM logs WHERE id = $1`, e.LogID).Scan(
46                 &logRow.ID,
47                 &logRow.UUID,
48                 &logRow.ObjectUUID,
49                 &logRow.ObjectOwnerUUID,
50                 &logRow.EventType,
51                 &logRow.EventAt,
52                 &logRow.CreatedAt,
53                 &propYAML)
54         if e.err != nil {
55                 logger(nil).WithField("LogID", e.LogID).WithError(e.err).Error("QueryRow failed")
56                 return nil
57         }
58         e.err = yaml.Unmarshal(propYAML, &logRow.Properties)
59         if e.err != nil {
60                 logger(nil).WithField("LogID", e.LogID).WithError(e.err).Error("yaml decode failed")
61                 return nil
62         }
63         e.logRow = &logRow
64         return e.logRow
65 }