-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_migration.go
327 lines (272 loc) · 7.97 KB
/
db_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
package portal
import (
"context"
"errors"
"fmt"
"github.com/amacneil/dbmate/v2/pkg/dbmate"
_ "github.com/amacneil/dbmate/v2/pkg/dbmate"
_ "github.com/amacneil/dbmate/v2/pkg/driver/mysql"
_ "github.com/amacneil/dbmate/v2/pkg/driver/sqlite"
clientv3 "go.etcd.io/etcd/client/v3"
"go.lumeweb.com/portal/config"
"go.lumeweb.com/portal/core"
"go.lumeweb.com/portal/db"
"go.uber.org/zap"
"gorm.io/gorm"
"io/fs"
"net/url"
"reflect"
"strings"
"time"
)
const (
migrationLockKey = "/discovery/portal/migrations/lock"
migrationLockTTL = 5 * time.Minute // Generous timeout for migrations
)
type MigrationManager struct {
ctx core.Context
etcdMgr *config.EtcdManager
logger *core.Logger
}
func NewMigrationManager(ctx core.Context) (*MigrationManager, error) {
if !ctx.Config().Config().Core.ClusterEnabled() {
return &MigrationManager{
ctx: ctx,
logger: ctx.Logger(),
}, nil
}
etcdManager, err := ctx.Config().Config().Core.Clustered.Etcd.GetManager(ctx.Logger().Logger)
if err != nil {
return nil, fmt.Errorf("failed to get etcd manager: %w", err)
}
return &MigrationManager{
ctx: ctx,
etcdMgr: etcdManager,
logger: ctx.Logger(),
}, nil
}
func (m *MigrationManager) RunMigrations(db *gorm.DB) error {
// Only attempt migrations in cluster mode
if !m.ctx.Config().Config().Core.ClusterEnabled() {
return m.executeMigrations(db)
}
// Try to acquire migration lock
lease, err := m.acquireMigrationLock()
if err != nil {
if errors.Is(err, ErrLockAcquireFailed) {
m.logger.Info("Another instance is handling migrations, skipping...")
return nil
}
return fmt.Errorf("failed to acquire migration lock: %w", err)
}
defer lease.Close()
return m.executeMigrations(db)
}
func (m *MigrationManager) acquireMigrationLock() (*etcdLease, error) {
// Create lease
client := m.etcdMgr.Client()
resp, err := client.Grant(context.Background(), int64(migrationLockTTL.Seconds()))
if err != nil {
return nil, fmt.Errorf("failed to create lease: %w", err)
}
// Try to acquire lock using lease
txn := m.etcdMgr.Client().Txn(context.Background())
txn = txn.If(clientv3.Compare(clientv3.CreateRevision(migrationLockKey), "=", 0))
txn = txn.Then(clientv3.OpPut(migrationLockKey, "", clientv3.WithLease(resp.ID)))
txn = txn.Else(clientv3.OpGet(migrationLockKey))
txnResp, err := txn.Commit()
if err != nil {
return nil, fmt.Errorf("failed to execute transaction: %w", err)
}
if !txnResp.Succeeded {
return nil, ErrLockAcquireFailed
}
// Create lease keeper
lease := &etcdLease{
client: m.etcdMgr.Client(),
id: resp.ID,
logger: m.logger,
done: make(chan struct{}),
}
// Start lease keepalive
go lease.keepalive()
return lease, nil
}
func (m *MigrationManager) executeMigrations(_ *gorm.DB) error {
m.logger.Info("Starting database migrations")
m.logger.Debug("Running dbmate migrations")
cfg := m.ctx.Config()
dbConfig := cfg.Config().Core.DB
dbType := dbConfig.Type
compositFs := newCompositeFS()
compositFs.Mount("0_core", getMigrationsByType(dbType, db.GetCoreMigrations()))
pluginMigrations, migrationOrder, err := getMigrations()
if err != nil {
return err
}
for idx, plugin := range migrationOrder {
migrations := getMigrationsByType(dbType, pluginMigrations[plugin])
if migrations == nil {
continue
}
compositFs.Mount(fmt.Sprintf("%d_%s", idx+1, plugin), migrations)
}
dbUrl, err := getDbMateUrl(cfg)
if err != nil {
return err
}
dbMateMigration := dbmate.New(dbUrl)
dbMateMigration.FS = compositFs
dbMateMigration.MigrationsDir = compositFs.Mounts()
dbMateMigration.AutoDumpSchema = false
err = dbMateMigration.CreateAndMigrate()
if err != nil {
return err
}
m.logger.Info("Database migrations completed successfully")
return nil
}
// etcdLease handles lease keepalive and cleanup
type etcdLease struct {
client *clientv3.Client
id clientv3.LeaseID
logger *core.Logger
done chan struct{}
}
func (l *etcdLease) keepalive() {
// Get the keep alive channel
ch, err := l.client.KeepAlive(context.Background(), l.id)
if err != nil {
l.logger.Error("Failed to setup lease keepalive", zap.Error(err))
return
}
for {
select {
case <-l.done:
return
case resp := <-ch:
if resp == nil {
l.logger.Error("Lease keepalive channel closed")
return
}
}
}
}
func (l *etcdLease) Close() {
close(l.done)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Revoke lease
_, err := l.client.Revoke(ctx, l.id)
if err != nil {
l.logger.Error("Failed to revoke lease", zap.Error(err))
}
}
// Helper to get all models that need migration
func getModels(ctx core.Context) ([]interface{}, error) {
plugins := core.GetPlugins()
models := make([]interface{}, 0)
for _, plugin := range plugins {
if plugin.Models != nil && len(plugin.Models) > 0 {
for _, model := range plugin.Models {
typ := reflect.TypeOf(model)
if typ.Kind() != reflect.Ptr {
ctx.Logger().Error("Model must be a pointer", zap.String("model", typ.Name()))
return nil, core.ErrInvalidModel
}
}
models = append(models, plugin.Models...)
}
}
// Add plugin models
for _, plugin := range core.GetPlugins() {
models = append(models, plugin.Models...)
}
return models, nil
}
func getMigrations() (map[string]core.DBMigration, []string, error) {
plugins := core.GetPlugins()
migrations := make(map[string]core.DBMigration)
order := make([]string, 0)
for _, plugin := range plugins {
if plugin.Migrations != nil && len(plugin.Migrations) > 0 {
migrations[plugin.ID] = plugin.Migrations
order = append(order, plugin.ID)
}
}
return migrations, order, nil
}
func getMigrationsByType(typ string, migrations core.DBMigration) fs.FS {
switch typ {
case "sqlite":
return migrations["sqlite"]
case "mysql":
return migrations["mysql"]
default:
return nil
}
}
// getDbMateUrl generates a database connection URL for dbmate based on the provided configuration.
// Returns a *url.URL object and any error that occurred during URL generation.
func getDbMateUrl(cfg config.Manager) (*url.URL, error) {
databaseConfig := cfg.Config().Core.DB
if databaseConfig.Type == "" {
return nil, errors.New("database type is required")
}
var urlStr string
switch strings.ToLower(databaseConfig.Type) {
case "sqlite":
if databaseConfig.File == "" {
return nil, errors.New("sqlite database requires a file path")
}
urlStr = "sqlite://" + db.GetSQLiteDBFile(cfg)
case "mysql":
if databaseConfig.Host == "" {
return nil, errors.New("mysql database requires a host")
}
if databaseConfig.Name == "" {
return nil, errors.New("mysql database requires a database name")
}
// For MySQL, dbmate expects the format:
// mysql://username:password@host:port/dbname?param1=value1
// NOT using the tcp() wrapper that's used in Go's sql.Open
// Handle default port if not specified
port := databaseConfig.Port
if port == 0 {
port = 3306 // Default MySQL port
}
// Build query parameters
params := make(url.Values)
// Add charset if specified
if databaseConfig.Charset != "" {
params.Add("charset", databaseConfig.Charset)
}
// Add TLS parameters if enabled
if databaseConfig.TLSEnabled {
if databaseConfig.TLSSkipVerify {
params.Add("tls", "skip-verify")
} else {
params.Add("tls", "true")
}
}
// Create a standard URL that url.Parse can handle
// Format: mysql://username:password@host:port/dbname?params
u := &url.URL{
Scheme: "mysql",
User: url.UserPassword(databaseConfig.Username, databaseConfig.Password),
Host: fmt.Sprintf("%s:%d", databaseConfig.Host, port),
Path: "/" + databaseConfig.Name,
RawQuery: params.Encode(),
}
return u, nil
default:
return nil, fmt.Errorf("unsupported database type: %s", databaseConfig.Type)
}
// For SQLite, we need to parse the URL string
parsedURL, err := url.Parse(urlStr)
if err != nil {
return nil, fmt.Errorf("failed to parse URL: %w", err)
}
return parsedURL, nil
}
var ErrLockAcquireFailed = errors.New("failed to acquire migration lock")