/
migration.go
376 lines (311 loc) · 9.13 KB
/
migration.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package migration
import (
"context"
"encoding/json"
"fmt"
"os"
"time"
"github.com/influxdata/influxdb/v2/kit/migration"
"github.com/influxdata/influxdb/v2/kit/platform"
"github.com/influxdata/influxdb/v2/kv"
"go.uber.org/zap"
)
var migrationBucket = []byte("migrationsv1")
type Store = kv.SchemaStore
// MigrationState is a type for describing the state of a migration.
type MigrationState uint
const (
// DownMigrationState is for a migration not yet applied.
DownMigrationState MigrationState = iota
// UpMigration State is for a migration which has been applied.
UpMigrationState
)
// String returns a string representation for a migration state.
func (s MigrationState) String() string {
switch s {
case DownMigrationState:
return "down"
case UpMigrationState:
return "up"
default:
return "unknown"
}
}
// Migration is a record of a particular migration.
type Migration struct {
ID platform.ID `json:"id"`
Name string `json:"name"`
State MigrationState `json:"-"`
StartedAt *time.Time `json:"started_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
// Spec is a specification for a particular migration.
// It describes the name of the migration and up and down operations
// needed to fulfill the migration.
type Spec interface {
MigrationName() string
Up(ctx context.Context, store kv.SchemaStore) error
Down(ctx context.Context, store kv.SchemaStore) error
}
// Migrator is a type which manages migrations.
// It takes a list of migration specifications and undo (down) all or apply (up) outstanding migrations.
// It records the state of the world in store under the migrations bucket.
type Migrator struct {
logger *zap.Logger
store Store
Specs []Spec
now func() time.Time
backupPath string
}
// NewMigrator constructs and configures a new Migrator.
func NewMigrator(logger *zap.Logger, store Store, ms ...Spec) (*Migrator, error) {
m := &Migrator{
logger: logger,
store: store,
now: func() time.Time {
return time.Now().UTC()
},
}
// create migration bucket if it does not exist
if err := store.CreateBucket(context.Background(), migrationBucket); err != nil {
return nil, err
}
m.AddMigrations(ms...)
return m, nil
}
// AddMigrations appends the provided migration specs onto the Migrator.
func (m *Migrator) AddMigrations(ms ...Spec) {
m.Specs = append(m.Specs, ms...)
}
// SetBackupPath records the filepath where pre-migration state should be written prior to running migrations.
func (m *Migrator) SetBackupPath(path string) {
m.backupPath = path
}
// List returns a list of migrations and their states within the provided store.
func (m *Migrator) List(ctx context.Context) (migrations []Migration, _ error) {
if err := m.walk(ctx, m.store, func(id platform.ID, m Migration) {
migrations = append(migrations, m)
}); err != nil {
return nil, err
}
migrationsLen := len(migrations)
for idx, spec := range m.Specs[migrationsLen:] {
migration := Migration{
ID: platform.ID(migrationsLen + idx + 1),
Name: spec.MigrationName(),
}
migrations = append(migrations, migration)
}
return
}
// Up applies each outstanding migration in order.
// Migrations are applied in order from the lowest indexed migration in a down state.
//
// For example, given:
// 0001 add bucket foo | (up)
// 0002 add bucket bar | (down)
// 0003 add index "foo on baz" | (down)
//
// Up would apply migration 0002 and then 0003.
func (m *Migrator) Up(ctx context.Context) error {
wrapErr := func(err error) error {
if err == nil {
return nil
}
return fmt.Errorf("up: %w", err)
}
var lastMigration int
if err := m.walk(ctx, m.store, func(id platform.ID, mig Migration) {
// we're interested in the last up migration
if mig.State == UpMigrationState {
lastMigration = int(id)
}
}); err != nil {
return wrapErr(err)
}
migrationsToDo := len(m.Specs[lastMigration:])
if migrationsToDo == 0 {
return nil
}
if m.backupPath != "" && lastMigration != 0 {
m.logger.Info("Backing up pre-migration metadata", zap.String("backup_path", m.backupPath))
if err := func() error {
out, err := os.Create(m.backupPath)
if err != nil {
return err
}
defer out.Close()
if err := m.store.Backup(ctx, out); err != nil {
return err
}
return nil
}(); err != nil {
return fmt.Errorf("failed to back up pre-migration metadata: %w", err)
}
}
m.logger.Info("Bringing up metadata migrations", zap.Int("migration_count", migrationsToDo))
for idx, spec := range m.Specs[lastMigration:] {
startedAt := m.now()
migration := Migration{
ID: platform.ID(lastMigration + idx + 1),
Name: spec.MigrationName(),
StartedAt: &startedAt,
}
m.logMigrationEvent(UpMigrationState, migration, "started")
if err := m.putMigration(ctx, m.store, migration); err != nil {
return wrapErr(err)
}
if err := spec.Up(ctx, m.store); err != nil {
return wrapErr(err)
}
finishedAt := m.now()
migration.FinishedAt = &finishedAt
migration.State = UpMigrationState
if err := m.putMigration(ctx, m.store, migration); err != nil {
return wrapErr(err)
}
m.logMigrationEvent(UpMigrationState, migration, "completed")
}
return nil
}
// Down applies the down operation of each currently applied migration.
// Migrations are applied in reverse order from the highest indexed migration in a down state.
//
// For example, given:
// 0001 add bucket foo | (up)
// 0002 add bucket bar | (up)
// 0003 add index "foo on baz" | (down)
//
// Down would call down() on 0002 and then on 0001.
func (m *Migrator) Down(ctx context.Context, untilMigration int) (err error) {
wrapErr := func(err error) error {
if err == nil {
return nil
}
return fmt.Errorf("down: %w", err)
}
var migrations []struct {
Spec
Migration
}
if err := m.walk(ctx, m.store, func(id platform.ID, mig Migration) {
migrations = append(
migrations,
struct {
Spec
Migration
}{
m.Specs[int(id)-1],
mig,
},
)
}); err != nil {
return wrapErr(err)
}
migrationsToDo := len(migrations) - untilMigration
if migrationsToDo == 0 {
return nil
}
if migrationsToDo < 0 {
m.logger.Warn("KV metadata is already on a schema older than target, nothing to do")
return nil
}
if m.backupPath != "" {
m.logger.Info("Backing up pre-migration metadata", zap.String("backup_path", m.backupPath))
if err := func() error {
out, err := os.Create(m.backupPath)
if err != nil {
return err
}
defer out.Close()
if err := m.store.Backup(ctx, out); err != nil {
return err
}
return nil
}(); err != nil {
return fmt.Errorf("failed to back up pre-migration metadata: %w", err)
}
}
m.logger.Info("Tearing down metadata migrations", zap.Int("migration_count", migrationsToDo))
for i := len(migrations) - 1; i >= untilMigration; i-- {
migration := migrations[i]
m.logMigrationEvent(DownMigrationState, migration.Migration, "started")
if err := migration.Spec.Down(ctx, m.store); err != nil {
return wrapErr(err)
}
if err := m.deleteMigration(ctx, m.store, migration.Migration); err != nil {
return wrapErr(err)
}
m.logMigrationEvent(DownMigrationState, migration.Migration, "completed")
}
return nil
}
func (m *Migrator) logMigrationEvent(state MigrationState, mig Migration, event string) {
m.logger.Debug(
"Executing metadata migration",
zap.String("migration_name", mig.Name),
zap.String("target_state", state.String()),
zap.String("migration_event", event),
)
}
func (m *Migrator) walk(ctx context.Context, store kv.Store, fn func(id platform.ID, m Migration)) error {
if err := store.View(ctx, func(tx kv.Tx) error {
bkt, err := tx.Bucket(migrationBucket)
if err != nil {
return err
}
cursor, err := bkt.ForwardCursor(nil)
if err != nil {
return err
}
return kv.WalkCursor(ctx, cursor, func(k, v []byte) (bool, error) {
var id platform.ID
if err := id.Decode(k); err != nil {
return false, fmt.Errorf("decoding migration id: %w", err)
}
var mig Migration
if err := json.Unmarshal(v, &mig); err != nil {
return false, err
}
idx := int(id) - 1
if idx >= len(m.Specs) {
return false, migration.ErrInvalidMigration(mig.Name)
}
if spec := m.Specs[idx]; spec.MigrationName() != mig.Name {
return false, fmt.Errorf("expected migration %q, found %q", spec.MigrationName(), mig.Name)
}
if mig.FinishedAt != nil {
mig.State = UpMigrationState
}
fn(id, mig)
return true, nil
})
}); err != nil {
return fmt.Errorf("reading migrations: %w", err)
}
return nil
}
func (m *Migrator) putMigration(ctx context.Context, store kv.Store, migration Migration) error {
return store.Update(ctx, func(tx kv.Tx) error {
bkt, err := tx.Bucket(migrationBucket)
if err != nil {
return err
}
data, err := json.Marshal(migration)
if err != nil {
return err
}
id, _ := migration.ID.Encode()
return bkt.Put(id, data)
})
}
func (m *Migrator) deleteMigration(ctx context.Context, store kv.Store, migration Migration) error {
return store.Update(ctx, func(tx kv.Tx) error {
bkt, err := tx.Bucket(migrationBucket)
if err != nil {
return err
}
id, _ := migration.ID.Encode()
return bkt.Delete(id)
})
}