Repository navigation
Fix drivers not satisfying drivers.Lockable, which silently disabled locking #37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
01dc369
d7bf1c1
223a3c4
79a6f7d
5b06bb8
8cfe9d5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,6 +12,13 @@ import ( | |
| "github.com/mattermost/morph/drivers" | ||
| ) | ||
|
|
||
| // Compile-time checks: morph.New only acquires the migration lock when the driver | ||
| // satisfies drivers.Lockable, so a signature drift here would silently disable locking. | ||
| var ( | ||
| _ drivers.Lockable = (*MySQL)(nil) | ||
| _ drivers.Locker = (*Mutex)(nil) | ||
| ) | ||
|
|
||
| // Mutex is similar to sync.Mutex, except usable by morph to lock the db. | ||
| // | ||
| // Pick a unique name for each mutex your plugin requires. | ||
|
|
@@ -34,7 +41,7 @@ type Mutex struct { | |
| // NewMutex creates a mutex with the given key name. | ||
| // | ||
| // returns error if key is empty. | ||
| func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (*Mutex, error) { | ||
| func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (drivers.Locker, error) { | ||
| key, err := drivers.MakeLockKey(key) | ||
| if err != nil { | ||
| return nil, err | ||
|
|
@@ -43,13 +50,14 @@ func (driver *MySQL) NewMutex(key string, logger drivers.Logger) (*Mutex, error) | |
| ctx, cancel := context.WithTimeout(context.Background(), drivers.TTL) | ||
| defer cancel() | ||
|
|
||
| conn, err := driver.db.Conn(context.Background()) | ||
| conn, err := driver.db.Conn(ctx) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| createTableIfNotExistsQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (Id varchar(64) NOT NULL, ExpireAt bigint(20) NOT NULL, PRIMARY KEY (Id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", drivers.MutexTableName) | ||
| if _, err = conn.ExecContext(ctx, createTableIfNotExistsQuery); err != nil { | ||
| _ = conn.Close() | ||
| return nil, err | ||
| } | ||
|
|
||
|
|
@@ -101,7 +109,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { | |
| } | ||
| defer m.finalizeTx(tx) | ||
|
|
||
| e, err := m.getExpireAt(tx) | ||
| e, err := m.getExpireAt(ctx, tx) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
@@ -111,7 +119,7 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { | |
| } | ||
|
|
||
| query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName) | ||
| if err = executeTx(tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil { | ||
| if err = executeTx(ctx, tx, query, t.Add(drivers.TTL).Unix(), m.key); err != nil { | ||
| return err | ||
| } | ||
|
|
||
|
|
@@ -123,10 +131,10 @@ func (m *Mutex) releaseLock(ctx context.Context, t time.Time) error { | |
| return nil | ||
| } | ||
|
|
||
| func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { | ||
| func (m *Mutex) getExpireAt(ctx context.Context, tx *sql.Tx) (int64, error) { | ||
| var expireAt int64 | ||
| query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ?", drivers.MutexTableName) | ||
| err := tx.QueryRow(query, m.key).Scan(&expireAt) | ||
| query := fmt.Sprintf("SELECT ExpireAt FROM %s WHERE Id = ? FOR UPDATE", drivers.MutexTableName) | ||
| err := tx.QueryRowContext(ctx, query, m.key).Scan(&expireAt) | ||
| if err != nil { | ||
| return -1, fmt.Errorf("failed to fetch mutex from db: %w", err) | ||
| } | ||
|
|
@@ -136,20 +144,21 @@ func (m *Mutex) getExpireAt(tx *sql.Tx) (int64, error) { | |
|
|
||
| // refreshLock rewrites the lock key value with a new expiry, returning nil only if successful. | ||
| func (m *Mutex) refreshLock(ctx context.Context) error { | ||
| ctx, cancel := context.WithTimeout(ctx, drivers.RefreshInterval) | ||
| defer cancel() | ||
|
Comment on lines
+147
to
+148
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Handle connection invalidation before retrying renewal. If a renewal exceeds Before this change, a slow renewal had no deadline and could finish. The new timeout turns a temporary delay into permanent renewal failure. Keep the timeout. Replace the connection when a renewal fails because its context was cancelled. Before renewal resumes, the holder must treat an expired lease as lost. Normal renewals must keep the existing connection. Apply the same handling to |
||
|
|
||
| tx, err := m.conn.BeginTx(ctx, nil) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| defer m.finalizeTx(tx) | ||
|
|
||
| e, err := m.getExpireAt(tx) | ||
| if err != nil { | ||
| if _, err = m.getExpireAt(ctx, tx); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| tmp := time.Unix(e, 0) | ||
| query := fmt.Sprintf("UPDATE %s SET ExpireAt = ? WHERE Id = ?", drivers.MutexTableName) | ||
| if err = executeTx(tx, query, tmp.Add(drivers.TTL).Unix(), m.key); err != nil { | ||
| if err = executeTx(ctx, tx, query, time.Now().Add(drivers.TTL).Unix(), m.key); err != nil { | ||
| return err | ||
| } | ||
|
|
||
|
|
@@ -172,6 +181,7 @@ func (m *Mutex) Lock(ctx context.Context) error { | |
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| _ = m.conn.Close() | ||
| return ctx.Err() | ||
| case <-time.After(waitInterval): | ||
| } | ||
|
|
@@ -188,15 +198,19 @@ func (m *Mutex) Lock(ctx context.Context) error { | |
|
|
||
| stop := make(chan bool) | ||
| done := make(chan bool) | ||
| // The refresh must outlive the caller's context: it is only meant to bound lock | ||
| // acquisition, and the lock has to stay alive until Unlock. | ||
| refreshCtx := context.WithoutCancel(ctx) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make renewal cancellable by Unlock.
Give renewal an engine-owned cancellation function. Call it before waiting for
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 8cfe9d5: each renewal now runs under a RefreshInterval timeout and the tx queries take the context, so Unlock waits at most one interval. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Analysis chain
Please bound these operations and test a stalled connection for both drivers. I’m not marking the finding as addressed. You are interacting with an AI system. |
||
| go func() { | ||
| defer close(done) | ||
| t := time.NewTicker(drivers.RefreshInterval) | ||
| defer t.Stop() | ||
| for { | ||
| select { | ||
| case <-t.C: | ||
| err := m.refreshLock(ctx) | ||
| if err != nil { | ||
| return | ||
| // Keep trying on errors: giving up would let the lock expire while it's held. | ||
| if err := m.refreshLock(refreshCtx); err != nil { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check lease ownership before retrying renewal. If A's renewal fails until its lease expires, B can acquire the same key. A now retries instead of stopping. Its Store a unique acquisition token. Require that token on renewal and deletion, and treat an ownership mismatch as lease loss. This protects a successor independently of the deferred engine notification work.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Leaving as is for this PR: an owner token needs a schema change to |
||
| m.logger.Printf("Failed to refresh lock: %v\n", err) | ||
| } | ||
| case <-stop: | ||
| return | ||
|
|
@@ -235,8 +249,8 @@ func (m *Mutex) Unlock() error { | |
| return err | ||
| } | ||
|
|
||
| func executeTx(tx *sql.Tx, query string, args ...interface{}) error { | ||
| if _, err := tx.Exec(query, args...); err != nil { | ||
| func executeTx(ctx context.Context, tx *sql.Tx, query string, args ...interface{}) error { | ||
| if _, err := tx.ExecContext(ctx, query, args...); err != nil { | ||
| return err | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| //go:build !sources && drivers | ||
| // +build !sources,drivers | ||
|
|
||
| package postgres_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "database/sql" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/mattermost/morph" | ||
| "github.com/mattermost/morph/drivers/postgres" | ||
| ) | ||
|
|
||
| // TestEngineAcquiresLock checks that morph.New takes the db lock through the | ||
| // postgres driver instead of silently skipping it. | ||
| func TestEngineAcquiresLock(t *testing.T) { | ||
| const connURL = "postgres://morph:morph@localhost:6432/morph_test?sslmode=disable" | ||
|
|
||
| driver, err := postgres.Open(connURL) | ||
| require.NoError(t, err) | ||
|
|
||
| engine, err := morph.New(context.Background(), driver, nil, morph.WithLock("engine-lock-test")) | ||
| if err != nil { | ||
| _ = driver.Close() | ||
| } | ||
| require.NoError(t, err) | ||
|
hanzei marked this conversation as resolved.
Resolved
|
||
|
|
||
| db, err := sql.Open("postgres", connURL) | ||
| require.NoError(t, err) | ||
| defer db.Close() | ||
|
|
||
| lockHeld := func() bool { | ||
| var held bool | ||
| err := db.QueryRow("SELECT EXISTS (SELECT 1 FROM db_lock WHERE id = 'engine-lock-test')").Scan(&held) | ||
| require.NoError(t, err) | ||
| return held | ||
| } | ||
|
|
||
| require.True(t, lockHeld(), "morph.New should hold the lock") | ||
|
|
||
| require.NoError(t, engine.Close()) | ||
| require.False(t, lockHeld(), "Close should release the lock") | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -90,9 +90,9 @@ func SetDryRun(enable bool) EngineOption { | |
| } | ||
|
|
||
| // New creates a new instance of the migrations engine from an existing db instance and a migrations source. | ||
| // If the driver implements the Lockable interface, it will also wait until it has acquired a lock. | ||
| // The context is propagated to the drivers lock method (if the driver implements divers.Locker interface) and | ||
| // it can be used to cancel the lock acquisition. | ||
| // If WithLock is set, it waits until it has acquired the lock, and returns an error if the driver | ||
| // does not implement the drivers.Lockable interface. | ||
| // The context is propagated to the lock method and it can be used to cancel the lock acquisition. | ||
| func New(ctx context.Context, driver drivers.Driver, source sources.Source, options ...EngineOption) (*Morph, error) { | ||
| engine := &Morph{ | ||
| config: &Config{ | ||
|
|
@@ -114,7 +114,12 @@ func New(ctx context.Context, driver drivers.Driver, source sources.Source, opti | |
| return nil, err | ||
| } | ||
|
|
||
| if impl, ok := driver.(drivers.Lockable); ok && engine.config.LockKey != "" { | ||
| if engine.config.LockKey != "" { | ||
| impl, ok := driver.(drivers.Lockable) | ||
| if !ok { | ||
| return nil, fmt.Errorf("driver %T does not support locking", driver) | ||
| } | ||
|
Comment on lines
+117
to
+121
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This avoids that people shoot themself in the foot by not locking
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| mx, err := impl.NewMutex(engine.config.LockKey, engine.config.Logger) | ||
| if err != nil { | ||
| return nil, err | ||
|
|
@@ -132,14 +137,16 @@ func New(ctx context.Context, driver drivers.Driver, source sources.Source, opti | |
|
|
||
| // Close closes the underlying database connection of the engine. | ||
| func (m *Morph) Close() error { | ||
| var unlockErr error | ||
| if m.mutex != nil { | ||
| err := m.mutex.Unlock() | ||
| if err != nil { | ||
| return err | ||
| } | ||
| unlockErr = m.mutex.Unlock() | ||
| } | ||
|
|
||
| if err := m.driver.Close(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| return m.driver.Close() | ||
| return unlockErr | ||
| } | ||
|
|
||
| func (m *Morph) apply(migration *models.Migration, saveVersion, dryRun bool) error { | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.