-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
94 lines (81 loc) · 2.25 KB
/
runner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package cbcm
import (
"log"
"time"
gocb "gopkg.in/couchbase/gocb.v1"
)
const changelogDocKey = "dbchangelog"
// Runner is a runner of changesets on couchbase cluster/bucket.
type Runner struct {
cluster *gocb.Cluster
}
// New instantiates a new isntance of Runner. Returns an error if connSpecStr is not valid.
func New(connSpecStr string) (*Runner, error) {
cluster, err := gocb.Connect(connSpecStr)
if err != nil {
return nil, err
}
r := Runner{
cluster: cluster,
}
return &r, nil
}
// Execute executes changesets on a bucket.
func (r *Runner) Execute(bucket, password string, changes []ChangeSet) error {
b, err := r.cluster.OpenBucket(bucket, password)
if err != nil {
return err
}
defer b.Close()
m := b.Manager(bucket, password)
return execute(b, m, changes)
}
func execute(b *gocb.Bucket, m *gocb.BucketManager, changes []ChangeSet) error {
if err := validate(changes); err != nil {
return err
}
changelog := changeLogDocument{}
if _, err := b.Get(changelogDocKey, &changelog); err != nil && err != gocb.ErrKeyNotFound {
return err
}
defer b.Upsert(changelogDocKey, &changelog, 0)
for _, changeset := range changes {
if _, ok := changelog[changeset.ID]; ok {
log.Printf("Skipping changeset: \"%s\"", changeset)
} else {
log.Printf("Executing changeset \"%s\"", changeset)
err := changeset.Execute(b, m)
if err != nil {
log.Printf("Changeset \"%s\" execution has failed. %s", changeset, err)
return err
}
info := changeSetInfo{
ID: changeset.ID,
Author: changeset.Author,
AppliedAt: uint64(time.Now().UnixNano() / int64(time.Millisecond)),
}
changelog[changeset.ID] = info
log.Printf("Changeset \"%s\" execution has finished", changeset)
}
}
return nil
}
func validate(changes []ChangeSet) error {
m := make(map[string]bool)
for _, changeset := range changes {
if changeset.ID == "" {
log.Printf("ID is not allowed: \"%s\"", changeset)
return ErrNotAllowedChangesetID
}
if changeset.Execute == nil {
log.Printf("Execute is nil: \"%s\"", changeset)
return ErrNilChangesetExecute
}
if _, ok := m[changeset.ID]; ok {
log.Printf("Duplicate change has found: \"%s\"", changeset.ID)
return ErrNotUniqueChangeSets
}
m[changeset.ID] = true
}
return nil
}