forked from vmware-archive/voyager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
voyager.go
355 lines (301 loc) · 8.47 KB
/
voyager.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package voyager
import (
"database/sql"
"errors"
"fmt"
"os"
"sort"
"sync"
"time"
"code.cloudfoundry.org/lager"
"github.com/hashicorp/go-multierror"
_ "github.com/lib/pq"
"github.com/concourse/voyager/runner"
)
type Migrator interface {
CurrentVersion() (int, error)
SupportedVersion() (int, error)
Migrate(version int) error
Up() error
Migrations() ([]migration, []int, error)
}
func NewMigrator(logger lager.Logger, db *sql.DB, lockID int, source Source, migrationsRunner runner.MigrationsRunner, adapter SchemaAdapter) Migrator {
if logger == nil {
logger = lager.NewLogger("voyager")
logger.RegisterSink(lager.NewWriterSink(os.Stdout, lager.DEBUG))
}
return &migrator{
logger,
db,
lockID,
source,
migrationsRunner,
adapter,
&sync.Mutex{},
}
}
type migrator struct {
logger lager.Logger
db *sql.DB
lockID int
source Source
goMigrationsRunner runner.MigrationsRunner
adapter SchemaAdapter
*sync.Mutex
}
//go:generate counterfeiter . SchemaAdapter
type SchemaAdapter interface {
MigrateFromOldSchema(*sql.DB) (int, error)
MigrateToOldSchema(*sql.DB, int) error
OldSchemaLastVersion() int
}
func (m *migrator) SupportedVersion() (int, error) {
matches := []migration{}
assets := m.source.AssetNames()
var parser = NewParser(m.source)
for _, match := range assets {
if migration, err := parser.ParseMigrationFilename(match); err == nil {
matches = append(matches, migration)
}
}
sortMigrations(matches)
return matches[len(matches)-1].Version, nil
}
func (m *migrator) CurrentVersion() (int, error) {
var migrationHistoryExists bool
err := m.db.QueryRow("SELECT EXISTS (SELECT 1 FROM information_schema.tables where table_name='migrations_history')").Scan(&migrationHistoryExists)
if err != nil {
if err == sql.ErrNoRows {
return 0, nil
}
return -1, err
}
if !migrationHistoryExists && m.adapter != nil {
return m.adapter.OldSchemaLastVersion(), nil
}
var currentVersion int
var direction string
var dirty bool
err = m.db.QueryRow("SELECT version, direction, dirty FROM migrations_history WHERE status!='failed' ORDER BY tstamp DESC LIMIT 1").Scan(¤tVersion, &direction, &dirty)
if err != nil {
if err == sql.ErrNoRows {
return 0, nil
}
return -1, err
}
if dirty {
return -1, errors.New("could not determine current migration version. Database is in a dirty state")
}
for direction == "down" {
err := m.db.QueryRow("SELECT version, direction FROM migrations_history WHERE status!='failed' AND version < $1 ORDER BY tstamp DESC LIMIT 1", currentVersion).Scan(¤tVersion, &direction)
if err != nil {
return -1, multierror.Append(errors.New("could not determine current migration version"), err)
}
}
return currentVersion, nil
}
func (m *migrator) Migrate(toVersion int) error {
acquired, err := m.acquireLock()
if err != nil {
return err
}
if acquired {
//TODO: Add log line here once logging is added
defer func() { _, _ = m.releaseLock() }()
}
var existingDBVersion int
if m.adapter != nil {
existingDBVersion, err = m.adapter.MigrateFromOldSchema(m.db)
if err != nil {
return err
}
}
_, err = m.db.Exec("CREATE TABLE IF NOT EXISTS migrations_history (version bigint, tstamp timestamp with time zone, direction varchar, status varchar, dirty boolean)")
if err != nil {
return err
}
if existingDBVersion > 0 {
var containsOldMigrationInfo bool
err = m.db.QueryRow("SELECT EXISTS (SELECT 1 FROM migrations_history where version=$1)", existingDBVersion).Scan(&containsOldMigrationInfo)
if err != nil {
return err
}
if !containsOldMigrationInfo {
_, err = m.db.Exec("INSERT INTO migrations_history (version, tstamp, direction, status, dirty) VALUES ($1, current_timestamp, 'up', 'passed', false)", existingDBVersion)
if err != nil {
return err
}
}
}
currentVersion, err := m.CurrentVersion()
if err != nil {
return err
}
migrations, versions, err := m.Migrations()
if err != nil {
return err
}
isValidVersion := false
if toVersion == 0 {
toVersion = versions[len(versions)-1]
isValidVersion = true
} else {
for _, v := range versions {
if v == toVersion {
isValidVersion = true
break
}
}
}
if !isValidVersion {
return fmt.Errorf("could not find migration version %v. No changes were made", toVersion)
}
if currentVersion <= toVersion {
for _, migration := range migrations {
if currentVersion < migration.Version && migration.Version <= toVersion && migration.Direction == "up" {
err = m.runMigration(migration)
if err != nil {
return err
}
}
}
} else {
for i := len(migrations) - 1; i >= 0; i-- {
if currentVersion >= migrations[i].Version && migrations[i].Version > toVersion && migrations[i].Direction == "down" {
err = m.runMigration(migrations[i])
if err != nil {
return err
}
}
}
if m.adapter != nil {
err = m.adapter.MigrateToOldSchema(m.db, toVersion)
if err != nil {
return err
}
}
}
return nil
}
type Strategy int
const (
GoMigration Strategy = iota
SQLTransaction
SQLNoTransaction
)
type migration struct {
Name string
Version int
Direction string
Statements []string
Strategy Strategy
}
func (m *migrator) recordMigrationFailure(migration migration, err error, dirty bool) error {
_, dbErr := m.db.Exec("INSERT INTO migrations_history (version, tstamp, direction, status, dirty) VALUES ($1, current_timestamp, $2, 'failed', $3)", migration.Version, migration.Direction, dirty)
return multierror.Append(fmt.Errorf("Migration '%s' failed: %v", migration.Name, err), dbErr)
}
func (m *migrator) runMigration(migration migration) error {
var err error
switch migration.Strategy {
case GoMigration:
err = m.goMigrationsRunner.Run(migration.Name)
if err != nil {
return m.recordMigrationFailure(migration, err, false)
}
case SQLTransaction:
tx, err := m.db.Begin()
if err != nil {
return m.recordMigrationFailure(migration, err, false)
}
for _, statement := range migration.Statements {
_, err = tx.Exec(statement)
if err != nil {
rollbackErr := tx.Rollback()
if rollbackErr != nil {
err = multierror.Append(fmt.Errorf("Transaction %v failed, failed to roll back the migration", statement), rollbackErr)
return m.recordMigrationFailure(migration, err, false)
}
err = multierror.Append(fmt.Errorf("Transaction %v failed, rolled back the migration", statement), err)
if err != nil {
return m.recordMigrationFailure(migration, err, false)
}
}
}
err = tx.Commit()
if err != nil {
return m.recordMigrationFailure(migration, err, true)
}
case SQLNoTransaction:
for _, statement := range migration.Statements {
_, err = m.db.Exec(statement)
if err != nil {
return m.recordMigrationFailure(migration, err, true)
}
}
}
_, err = m.db.Exec("INSERT INTO migrations_history (version, tstamp, direction, status, dirty) VALUES ($1, current_timestamp, $2, 'passed', false)", migration.Version, migration.Direction)
return err
}
func (m *migrator) Migrations() ([]migration, []int, error) {
migrationList := []migration{}
versionList := []int{}
assets := m.source.AssetNames()
var parser = NewParser(m.source)
for _, assetName := range assets {
parsedMigration, err := parser.ParseFileToMigration(assetName)
if err != nil {
return nil, nil, err
}
versionList = append(versionList, parsedMigration.Version)
migrationList = append(migrationList, parsedMigration)
}
sortMigrations(migrationList)
sort.Ints(versionList)
return migrationList, versionList, nil
}
func (m *migrator) Up() error {
_, versions, err := m.Migrations()
if err != nil {
return err
}
return m.Migrate(versions[len(versions)-1])
}
func (m *migrator) acquireLock() (bool, error) {
var acquired bool
for {
m.Lock()
err := m.db.QueryRow(`SELECT pg_try_advisory_lock($1)`, m.lockID).Scan(&acquired)
if err != nil {
m.Unlock()
return false, err
}
if acquired {
m.Unlock()
return acquired, nil
}
m.Unlock()
time.Sleep(1 * time.Second)
}
}
func (m *migrator) releaseLock() (bool, error) {
var released bool
for {
m.Lock()
err := m.db.QueryRow(`SELECT pg_advisory_unlock($1)`, m.lockID).Scan(&released)
if err != nil {
m.Unlock()
return false, err
}
if released {
m.Unlock()
return released, nil
}
m.Unlock()
time.Sleep(1 * time.Second)
}
}
func sortMigrations(migrationList []migration) {
sort.Slice(migrationList, func(i, j int) bool {
return migrationList[i].Version < migrationList[j].Version
})
}