fix: replace named locks with Galera-compatible row locks
This commit is contained in:
1 parent
ee07866d1c
commit
65d16c2fc6
22 files changed
+314
-365
No files matched your search
+36
-73
@@ -12,7 +12,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
@@ -35,10 +34,12 @@ const (
|
||||
zoneLockTimeout = 10 * time.Second
|
||||
migrateLockTimeout = 30 * time.Second
|
||||
mysqlErrDupEntry = 1062
|
||||
mysqlErrLockWait = 1205
|
||||
mysqlErrDeadlock = 1213
|
||||
)
|
||||
|
||||
var (
|
||||
errLockTimeout = errors.New("named lock timeout")
|
||||
errLockTimeout = errors.New("database lock busy")
|
||||
errRowNotFound = errors.New("row not found")
|
||||
errUsernameTaken = errors.New("username already used")
|
||||
errContract = errors.New("records table contract violated")
|
||||
@@ -67,6 +68,7 @@ type tableNames struct {
|
||||
sessions string
|
||||
delegations string
|
||||
audit string
|
||||
locks string
|
||||
}
|
||||
|
||||
func newTableNames(prefix string) (tableNames, error) {
|
||||
@@ -81,6 +83,7 @@ func newTableNames(prefix string) (tableNames, error) {
|
||||
sessions: quoteIdent(prefix + "webui_sessions"),
|
||||
delegations: quoteIdent(prefix + "webui_zone_delegations"),
|
||||
audit: quoteIdent(prefix + "webui_audit"),
|
||||
locks: quoteIdent(prefix + "webui_locks"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -96,6 +99,7 @@ func (t tableNames) sql(query string) string {
|
||||
"{sessions}", t.sessions,
|
||||
"{delegations}", t.delegations,
|
||||
"{audit}", t.audit,
|
||||
"{locks}", t.locks,
|
||||
).Replace(query)
|
||||
}
|
||||
|
||||
@@ -289,83 +293,38 @@ func checkRecordsColumns(table string, columns map[string]columnInfo) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type namedLock struct {
|
||||
conn *sql.Conn
|
||||
name string
|
||||
// An upsert locks the zone until the transaction ends. Changing the row
|
||||
// also gives Galera a certification key when different writers use the zone.
|
||||
const zoneLockSQL = "INSERT INTO {locks} (`name`, `generation`) VALUES (?, 0) " +
|
||||
"ON DUPLICATE KEY UPDATE `generation` = 1 - `generation`"
|
||||
|
||||
func lockBusy(err error) bool {
|
||||
return mysqlErrorIs(err, mysqlErrLockWait) || mysqlErrorIs(err, mysqlErrDeadlock)
|
||||
}
|
||||
|
||||
func acquireNamedLock(ctx context.Context, conn *sql.Conn, name string, timeout time.Duration) (*namedLock, error) {
|
||||
seconds := int64(math.Ceil(timeout.Seconds()))
|
||||
var result sql.NullInt64
|
||||
if err := conn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", name, seconds).Scan(&result); err != nil {
|
||||
return nil, fmt.Errorf("acquire lock: %w", err)
|
||||
func lockError(ctx, waitCtx context.Context, err error) error {
|
||||
if lockBusy(err) || (ctx.Err() == nil && errors.Is(waitCtx.Err(), context.DeadlineExceeded)) {
|
||||
return fmt.Errorf("%w: %w", errLockTimeout, err)
|
||||
}
|
||||
if !result.Valid {
|
||||
return nil, errors.New("acquire lock: GET_LOCK returned NULL")
|
||||
}
|
||||
if result.Int64 != 1 {
|
||||
return nil, errLockTimeout
|
||||
}
|
||||
return &namedLock{conn: conn, name: name}, nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (l *namedLock) release(ctx context.Context) error {
|
||||
var result sql.NullInt64
|
||||
if err := l.conn.QueryRowContext(ctx, "SELECT RELEASE_LOCK(?)", l.name).Scan(&result); err != nil {
|
||||
return fmt.Errorf("release lock: %w", err)
|
||||
}
|
||||
if !result.Valid || result.Int64 != 1 {
|
||||
return errors.New("release lock: lock was not held")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type connSource interface {
|
||||
Conn(ctx context.Context) (*sql.Conn, error)
|
||||
}
|
||||
|
||||
func discardConn(conn *sql.Conn) {
|
||||
_ = conn.Raw(func(any) error { return driver.ErrBadConn })
|
||||
}
|
||||
|
||||
func withNamedLock(ctx context.Context, db connSource, name string, timeout time.Duration, log *slog.Logger, fn func(conn *sql.Conn) error) error {
|
||||
conn, err := db.Conn(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("dedicated connection: %w", err)
|
||||
}
|
||||
discard := false
|
||||
defer func() {
|
||||
if discard {
|
||||
discardConn(conn)
|
||||
return
|
||||
}
|
||||
if cerr := conn.Close(); cerr != nil {
|
||||
log.ErrorContext(ctx, "dedicated connection close failed", "lock", name, "error", cerr)
|
||||
}
|
||||
}()
|
||||
lock, err := acquireNamedLock(ctx, conn, name, timeout)
|
||||
if err != nil {
|
||||
if errors.Is(err, errLockTimeout) {
|
||||
log.WarnContext(ctx, "named lock timeout", "lock", name, "timeout", timeout)
|
||||
}
|
||||
return err
|
||||
}
|
||||
log.DebugContext(ctx, "named lock acquired", "lock", name)
|
||||
defer func() {
|
||||
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbPingAttemptTimeout)
|
||||
func runZoneTx(ctx context.Context, db txBeginner, t tableNames, zone string, log *slog.Logger, fn func(*sql.Tx) error) error {
|
||||
name := t.zoneLockName(zone)
|
||||
err := runInTx(ctx, db, func(tx *sql.Tx) error {
|
||||
waitCtx, cancel := context.WithTimeout(ctx, zoneLockTimeout)
|
||||
defer cancel()
|
||||
if rerr := lock.release(releaseCtx); rerr != nil {
|
||||
log.ErrorContext(ctx, "named lock release failed, discarding the connection", "lock", name, "error", rerr)
|
||||
discard = true
|
||||
return
|
||||
if _, err := tx.ExecContext(waitCtx, t.sql(zoneLockSQL), name); err != nil {
|
||||
return fmt.Errorf("acquire zone lock: %w", lockError(ctx, waitCtx, err))
|
||||
}
|
||||
log.DebugContext(ctx, "named lock released", "lock", name)
|
||||
}()
|
||||
return fn(conn)
|
||||
}
|
||||
|
||||
func withZoneLock(ctx context.Context, db connSource, t tableNames, zone string, log *slog.Logger, fn func(conn *sql.Conn) error) error {
|
||||
return withNamedLock(ctx, db, t.zoneLockName(zone), zoneLockTimeout, log, fn)
|
||||
log.DebugContext(ctx, "zone lock acquired", "lock", name)
|
||||
return fn(tx)
|
||||
})
|
||||
// A Galera certification failure can first surface at commit.
|
||||
if lockBusy(err) && !errors.Is(err, errLockTimeout) {
|
||||
return fmt.Errorf("%w: %w", errLockTimeout, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func runInTx(ctx context.Context, b txBeginner, fn func(tx *sql.Tx) error) (err error) {
|
||||
@@ -390,8 +349,12 @@ func runInTx(ctx context.Context, b txBeginner, fn func(tx *sql.Tx) error) (err
|
||||
}
|
||||
|
||||
func isDuplicateKey(err error) bool {
|
||||
return mysqlErrorIs(err, mysqlErrDupEntry)
|
||||
}
|
||||
|
||||
func mysqlErrorIs(err error, number uint16) bool {
|
||||
var me *mysql.MySQLError
|
||||
return errors.As(err, &me) && me.Number == mysqlErrDupEntry
|
||||
return errors.As(err, &me) && me.Number == number
|
||||
}
|
||||
|
||||
func dbTime(t time.Time) time.Time {
|
||||
|
||||
Reference in new issue
Block a user