From 65d16c2fc680175615344e391d11e66c8cc3bf9a Mon Sep 17 00:00:00 2001 From: Bryan Joshua Pedini Date: Fri, 20 Nov 2026 16:27:15 +0100 Subject: [PATCH] fix: replace named locks with Galera-compatible row locks --- .gitea/workflows/image.yaml | 2 + .gitea/workflows/test.yaml | 2 + PLAN.md | 5 +- README.md | 12 ++- apimatrix_backend_test.go | 4 +- apimatrix_cases_test.go | 2 +- database.go | 109 +++++++--------------- database_test.go | 170 ++++++---------------------------- dev/mysql-init.sql | 1 + e2e/stack/mysql-init.sql | 1 + handlers_api.go | 69 +++++++------- handlers_api_test.go | 34 ++++--- handlers_zone_api_test.go | 8 +- integration_db_test.go | 105 ++++++++++++--------- integration_helpers_test.go | 1 + integration_http_race_test.go | 9 +- integration_zone_api_test.go | 32 +++---- middleware.go | 6 +- middleware_test.go | 7 +- migrations.go | 51 +++++++++- migrations_test.go | 39 ++++++-- scripts/integration.sh | 10 +- 22 files changed, 314 insertions(+), 365 deletions(-) diff --git a/.gitea/workflows/image.yaml b/.gitea/workflows/image.yaml index 76f18f2..f106db9 100644 --- a/.gitea/workflows/image.yaml +++ b/.gitea/workflows/image.yaml @@ -33,6 +33,8 @@ jobs: echo "Running integration tests against $database" MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh done + echo "Running integration tests against MariaDB Galera" + IT_GALERA=1 MYSQL_IMAGE=mariadb:10.11.3 IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh - name: Build and test image id: build env: diff --git a/.gitea/workflows/test.yaml b/.gitea/workflows/test.yaml index 05f7aa1..0ce3b89 100644 --- a/.gitea/workflows/test.yaml +++ b/.gitea/workflows/test.yaml @@ -29,6 +29,8 @@ jobs: echo "Running integration tests against $database" MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh done + echo "Running integration tests against MariaDB Galera" + IT_GALERA=1 MYSQL_IMAGE=mariadb:10.11.3 IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh - name: Image and end-to-end tests run: | set -eu diff --git a/PLAN.md b/PLAN.md index b3c13b8..e83fe7d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -161,7 +161,7 @@ The connection is built with `mysql.Config` from `github.com/go-sql-driver/mysql 2. Initialize the logger and log version and commit. 3. Open the pool and ping MySQL, retrying with backoff for up to 30 seconds. 4. Verify the records table contract (section 3). -5. Apply the application's migrations (section 6) while holding the MySQL named lock `webui_migrate` (`GET_LOCK`, 30 s timeout), so several instances starting together never race. +5. Bootstrap the InnoDB lock table and apply the migrations while holding a row lock on its migration key (30 s acquisition timeout). DDL runs on a separate connection because it commits implicitly. During migrations, Galera application connections use the same writer. 6. Start a background task that deletes expired sessions every 10 minutes. 7. Register the routes and listen on `${HTTP_ADDR}:${HTTP_PORT}` with `ReadHeaderTimeout` 10 s, `ReadTimeout` 30 s, `WriteTimeout` 60 s, `IdleTimeout` 120 s and `MaxHeaderBytes` 64 KiB. 8. On `SIGINT` or `SIGTERM`, stop accepting connections, wait up to 25 seconds for running requests, stop the background task and close the pool. @@ -293,6 +293,7 @@ MySQL allows table-level grants on tables that do not exist yet when `CREATE` is ```sql CREATE USER 'coredns_webui'@'%' IDENTIFIED BY ''; GRANT SELECT, INSERT, UPDATE, DELETE ON `coredns`.`coredns_records` TO 'coredns_webui'@'%'; +GRANT SELECT, INSERT, UPDATE, CREATE ON `coredns`.`coredns_webui_locks` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_schema` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_sessions` TO 'coredns_webui'@'%'; @@ -351,7 +352,7 @@ Warnings: ### Concurrency -Every write runs on a dedicated connection: take the named lock `webui:` with `GET_LOCK` (10 s timeout, HTTP 503 "zone busy" on timeout), begin the transaction, check again that the actor may operate on the zone (the user row and, for role `user`, the delegation row read with `LOCK IN SHARE MODE`, so a concurrent revocation, demotion or deletion waits for the write or wins before it), read the zone's rows, apply the rules, write records, SOA serial and audit row, commit, release the lock. The lock serializes writers of this application; other writers of the table are detected through ETags. +Every write starts a transaction and updates its zone key in `webui_locks` (10 s acquisition timeout, HTTP 503 "zone busy" on timeout or deadlock). Changing this row supplies a Galera certification key. The application then checks again that the actor may operate on the zone (the user row and, for role `user`, the delegation row read with `LOCK IN SHARE MODE`, so a concurrent revocation, demotion or deletion waits for the write or wins before it), reads the zone's rows, applies the rules, writes the records, SOA serial and audit row, and commits, releasing the lock. The lock serializes writers of this application; other writers of the table are detected through ETags. Every record carries an ETag: the hex SHA-256 of `id`, `zone`, `name`, `ttl`, `record_type` and the raw `content`, with explicit markers for `NULL`. Updates and deletes require `If-Match`; inside the transaction the row is read with `SELECT ... FOR UPDATE` and compared. A missing `If-Match` is HTTP 428, a mismatch or a missing row is HTTP 412 and the UI offers to reload. diff --git a/README.md b/README.md index 0b63833..8f0479e 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Rows with errors are shown in the UI with their raw content and problems; editin ### Writes, locking and ETags -Every write takes a MySQL named lock per zone (`webui:`, 10 s timeout, HTTP `503` "zone busy" on timeout), runs in one transaction and writes the records, the SOA serial and the audit row together. Every record carries an ETag (the SHA-256 of its columns). Updates and deletes require `If-Match`: a missing header is HTTP `428`, a mismatch or a missing row is HTTP `412`, so concurrent changes by other writers are detected instead of overwritten. +Every zone write acquires its row in `webui_locks` within the transaction that updates the records, SOA serial and audit row. Acquisition waits up to 10 seconds. Lock timeouts and deadlocks, including Galera certification conflicts, return HTTP `503` "zone busy". Every record carries an ETag (the SHA-256 of its columns). Updates and deletes require `If-Match`: a missing header is HTTP `428`, a mismatch or a missing row is HTTP `412`, so concurrent changes by other writers are detected instead of overwritten. ### Zone files @@ -107,6 +107,7 @@ The application user needs `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the reco ```sql CREATE USER 'coredns_webui'@'%' IDENTIFIED BY ''; GRANT SELECT, INSERT, UPDATE, DELETE ON `coredns`.`coredns_records` TO 'coredns_webui'@'%'; +GRANT SELECT, INSERT, UPDATE, CREATE ON `coredns`.`coredns_webui_locks` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_schema` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_sessions` TO 'coredns_webui'@'%'; @@ -125,10 +126,11 @@ GRANT SELECT ON `coredns`.`coredns_records` TO 'coredns'@'%'; ### Application schema and migrations -Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in order. The current version is the single row of `webui_schema`. The table prefix is substituted into the SQL after validation; it is the only value ever interpolated into SQL. Migrations run while holding the MySQL named lock `webui_migrate` (`GET_LOCK`, 30 s timeout), so several instances starting together never race. +Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in order. The current version is the single row of `webui_schema`. The table prefix is substituted into the SQL after validation; it is the only value ever interpolated into SQL. Startup creates `webui_locks` if absent and locks the migration row with a 30-second acquisition budget. The migration transaction holds that row while a separate connection runs the DDL, which commits implicitly. This serializes startup on a single database writer. For Galera, route all application connections to the same writer during migrations, for example through a single-writer ProxySQL hostgroup. | Table | Content | |---|---| +| `webui_locks` | the migration row and one row per zone written by the application | | `webui_schema` | the schema version | | `webui_users` | `id`, `username`, `role`, `password_hash`, `created_at`, `updated_at`, `last_login_at`, `deleted_at` | | `webui_sessions` | SHA-256 of the session token, user, creation, last seen and expiry times, origin, user agent | @@ -163,7 +165,7 @@ Validation happens before any other work. The first problem is reported as `core The database connection is built with `mysql.Config` from `github.com/go-sql-driver/mysql` (`ParseTime`, UTC, charset `utf8mb4` via `SET NAMES`, connect timeout 5 s, read and write timeouts 30 s, no multi statements, no client-side interpolation). The pool holds at most 10 open and 10 idle connections with a connection lifetime of 1 minute. The DSN and the password are never logged. -Use a database with the `utf8mb4` character set and InnoDB. The database may use any `utf8mb4` collation. Usernames and delegation keys use exact matching, and zone names are normalized before DNS comparisons. Existing application tables keep their collations and data. On new databases the audit tables store JSON payloads as text; existing native JSON columns still work. CI tests MySQL 5.7, MySQL 8.4 and MariaDB 10.11. +Use a database with the `utf8mb4` character set and InnoDB. The database may use any `utf8mb4` collation. Usernames and delegation keys use exact matching, and zone names are normalized before DNS comparisons. Existing application tables keep their collations and data. On new databases the audit tables store JSON payloads as text; existing native JSON columns still work. CI tests MySQL 5.7, MySQL 8.4, MariaDB 10.11 standalone and MariaDB 10.11 Galera. `TRUSTED_PROXIES` controls the client origin stored in sessions and audit rows. By default it is the TCP peer address. When the peer is inside a trusted CIDR, it is the rightmost `X-Forwarded-For` entry that is not itself trusted; forwarding headers from other peers are ignored. @@ -174,7 +176,7 @@ Use a database with the `utf8mb4` character set and InnoDB. The database may use 1. Loads and validates the configuration and initializes the logger. 2. Opens the pool and pings MySQL, retrying with backoff for up to 30 seconds. 3. Verifies the records table contract. -4. Applies the migrations under the named lock. +4. Bootstraps the lock table and applies migrations under its migration row lock. 5. Starts a background task that deletes expired sessions every 10 minutes. 6. Listens on `${HTTP_ADDR}:${HTTP_PORT}` with `ReadHeaderTimeout` 10 s, `ReadTimeout` 30 s, `WriteTimeout` 60 s, `IdleTimeout` 120 s and `MaxHeaderBytes` 64 KiB. 7. On `SIGINT` or `SIGTERM`, stops accepting connections, waits up to 25 seconds for running requests, stops the background task and closes the pool. @@ -419,7 +421,7 @@ docker run --rm -v "$PWD":/src -w /src -v coredns-web-ui-gomod:/go/pkg/mod -e GO ### Integration tests -`scripts/integration.sh` builds the dockerfile's `integration` stage and runs the tests with the build tag `integration` against a disposable MySQL or MariaDB container (`MYSQL_IMAGE`, default `mysql:8.4`) on an internal Docker network with random credentials. Nothing is published on the host. It covers the records table contract, migrations (including two processes migrating at the same time), the least-privilege grants, the foreign keys, the stores and transactions, the zone lock and the races between role, delegation and user changes and writes. Run with `MYSQL_IMAGE=mysql:5.7` or `MYSQL_IMAGE=mariadb:10.11` to use the other databases in CI. It needs only Docker. Containers, network, volume and image are named `cdwu-it-` (`IT_ID`, default the shell's process id) and are removed at exit, also after failures. +`scripts/integration.sh` builds the dockerfile's `integration` stage and runs the tests with the build tag `integration` against a disposable MySQL or MariaDB container (`MYSQL_IMAGE`, default `mysql:8.4`) on an internal Docker network with random credentials. Nothing is published on the host. It covers the records table contract, migrations (including two processes migrating at the same time), the least-privilege grants, the foreign keys, the stores and transactions, the zone lock and the races between role, delegation and user changes and writes. Run with `MYSQL_IMAGE=mysql:5.7` or `MYSQL_IMAGE=mariadb:10.11` to use the other standalone databases in CI. Run `IT_GALERA=1 MYSQL_IMAGE=mariadb:10.11.3 scripts/integration.sh` for the single-node Galera suite with a loaded wsrep provider. It needs only Docker. Containers, network, volume and image are named `cdwu-it-` (`IT_ID`, default the shell's process id) and are removed at exit, also after failures. ### Image tests diff --git a/apimatrix_backend_test.go b/apimatrix_backend_test.go index 4f3e1e0..bbde7f5 100644 --- a/apimatrix_backend_test.go +++ b/apimatrix_backend_test.go @@ -174,8 +174,8 @@ func (m *matrixSQL) userValues(u userRow) []driver.Value { func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse { has := func(v string) bool { return strings.Contains(query, v) } switch { - case has("GET_LOCK"), has("RELEASE_LOCK"): - return fdbResponse{rows: fdbRow(int64(1))} + case has("webui_locks"): + return fdbResponse{rowsAffected: 1} case has("FROM `coredns_webui_users` u WHERE u.`id` = ?"): id := args[0].(int64) for _, u := range w.state.users { diff --git a/apimatrix_cases_test.go b/apimatrix_cases_test.go index 844c93e..1cec5c2 100644 --- a/apimatrix_cases_test.go +++ b/apimatrix_cases_test.go @@ -19,7 +19,7 @@ func mxStoreFail(method string, err error) func(*matrixEnv) { } func mxBusy(env *matrixEnv) { - env.sql.answer(fdbResponse{rows: fdbRow(int64(0))}, "GET_LOCK") + env.sql.answer(fdbResponse{err: errLockTimeout}, "webui_locks") } func mxCommitFails(env *matrixEnv) { diff --git a/database.go b/database.go index d85bd59..be5c1ad 100644 --- a/database.go +++ b/database.go @@ -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 { diff --git a/database_test.go b/database_test.go index adfc0a9..c8d4dc9 100644 --- a/database_test.go +++ b/database_test.go @@ -34,12 +34,13 @@ func TestNewTableNames(t *testing.T) { sessions: "`dns_webui_sessions`", delegations: "`dns_webui_zone_delegations`", audit: "`dns_webui_audit`", + locks: "`dns_webui_locks`", } if tn != want { t.Fatalf("got %+v", tn) } - got := tn.sql("{records} {schema} {users} {sessions} {delegations} {audit} {other}") - if got != "`dns_records` `dns_webui_schema` `dns_webui_users` `dns_webui_sessions` `dns_webui_zone_delegations` `dns_webui_audit` {other}" { + got := tn.sql("{records} {schema} {users} {sessions} {delegations} {audit} {locks} {other}") + if got != "`dns_records` `dns_webui_schema` `dns_webui_users` `dns_webui_sessions` `dns_webui_zone_delegations` `dns_webui_audit` `dns_webui_locks` {other}" { t.Fatalf("sql %s", got) } if _, err := newTableNames("bad`prefix"); err == nil { @@ -324,157 +325,40 @@ func TestVerifyRecordsContract(t *testing.T) { } } -func lockHandler(get, release driver.Value, getErr error) fdbHandler { - return func(q string, args []any) fdbResponse { - switch { - case strings.HasPrefix(q, "SELECT GET_LOCK"): - if getErr != nil { - return fdbResponse{err: getErr} - } - return fdbResponse{rows: fdbRow(get)} - case strings.HasPrefix(q, "SELECT RELEASE_LOCK"): - return fdbResponse{rows: fdbRow(release)} - } - return fdbResponse{} - } -} - -func TestAcquireNamedLock(t *testing.T) { - ctx := context.Background() - cases := []struct { - get driver.Value - getErr error - want error - }{ - {int64(1), nil, nil}, - {int64(0), nil, errLockTimeout}, - {nil, nil, errors.New("NULL")}, - {nil, errors.New("down"), errors.New("down")}, - } - for _, c := range cases { - db, st := newFakeDB(t, lockHandler(c.get, int64(1), c.getErr)) - conn, err := db.Conn(ctx) - if err != nil { - t.Fatal(err) - } - lock, err := acquireNamedLock(ctx, conn, "coredns_webui:abc", 1500*time.Millisecond) - switch { - case c.want == nil: - if err != nil { - t.Fatal(err) - } - if args := st.Calls()[0].args; args[0] != "coredns_webui:abc" || args[1] != int64(2) { - t.Fatalf("args %v", args) - } - if err := lock.release(ctx); err != nil { - t.Fatal(err) - } - case errors.Is(c.want, errLockTimeout): - if !errors.Is(err, errLockTimeout) { - t.Fatalf("got %v", err) - } - default: - if err == nil || errors.Is(err, errLockTimeout) || !strings.Contains(err.Error(), c.want.Error()) { - t.Fatalf("got %v", err) - } - } - conn.Close() - } -} - -func TestReleaseNamedLockErrors(t *testing.T) { - ctx := context.Background() - for _, rel := range []driver.Value{int64(0), nil} { - db, _ := newFakeDB(t, lockHandler(int64(1), rel, nil)) - conn, _ := db.Conn(ctx) - lock, err := acquireNamedLock(ctx, conn, "n", time.Second) - if err != nil { - t.Fatal(err) - } - if err := lock.release(ctx); err == nil { - t.Fatalf("%v: release succeeded", rel) - } - conn.Close() - } - db, _ := newFakeDB(t, func(q string, _ []any) fdbResponse { - if strings.Contains(q, "RELEASE") { - return fdbResponse{err: errors.New("gone")} - } - return fdbResponse{rows: fdbRow(int64(1))} - }) - conn, _ := db.Conn(ctx) - defer conn.Close() - lock, _ := acquireNamedLock(ctx, conn, "n", time.Second) - if err := lock.release(ctx); err == nil || !strings.Contains(err.Error(), "gone") { - t.Fatalf("got %v", err) - } -} - -func TestWithNamedLock(t *testing.T) { - ctx := context.Background() - db, st := newFakeDB(t, lockHandler(int64(1), int64(1), nil)) +func TestRunZoneTx(t *testing.T) { + ctx := t.Context() + tables := fdbTables(t) + db, state := newFakeDB(t, fdbRules(fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}})) called := false - err := withZoneLock(ctx, db, fdbTables(t), "example.org.", discardLogger(), func(conn *sql.Conn) error { + err := runZoneTx(ctx, db, tables, "example.org.", discardLogger(), func(*sql.Tx) error { called = true return nil }) - if err != nil || !called { - t.Fatalf("%v %v", err, called) + if err != nil || !called || state.commits != 1 || state.rollbacks != 0 { + t.Fatalf("callback=%t commits=%d rollbacks=%d error=%v", called, state.commits, state.rollbacks, err) } - q := st.Queries() - if len(q) != 2 || !strings.HasPrefix(q[0], "SELECT GET_LOCK") || !strings.HasPrefix(q[1], "SELECT RELEASE_LOCK") { - t.Fatalf("queries %v", q) - } - if st.Calls()[0].args[1] != int64(10) || st.Calls()[0].args[0] != fdbTables(t).zoneLockName("example.org.") { - t.Fatalf("args %v", st.Calls()[0].args) + calls := state.Calls() + if len(calls) != 1 || calls[0].query != tables.sql(zoneLockSQL) || calls[0].args[0] != tables.zoneLockName("example.org.") { + t.Fatalf("lock calls: %v", calls) } - fnErr := errors.New("fn failed") - db, st = newFakeDB(t, lockHandler(int64(1), int64(1), nil)) - if err := withNamedLock(ctx, db, "n", time.Second, discardLogger(), func(*sql.Conn) error { return fnErr }); !errors.Is(err, fnErr) { - t.Fatalf("got %v", err) - } - if len(st.Queries()) != 2 { - t.Fatal("lock not released after failure") - } - - var buf bytes.Buffer - db, _ = newFakeDB(t, lockHandler(int64(0), int64(1), nil)) - err = withNamedLock(ctx, db, "busy", time.Second, newLogger(&buf, slog.LevelDebug), func(*sql.Conn) error { - t.Fatal("fn called without lock") - return nil - }) - if !errors.Is(err, errLockTimeout) || !strings.Contains(buf.String(), "level=WARN") { - t.Fatalf("%v %s", err, buf.String()) - } - - for _, release := range []fdbHandler{lockHandler(int64(1), int64(0), nil), lockHandler(int64(1), nil, nil), func(q string, args []any) fdbResponse { - if strings.HasPrefix(q, "SELECT RELEASE_LOCK") { - return fdbResponse{err: errors.New("connection lost")} - } - return lockHandler(int64(1), int64(1), nil)(q, args) - }} { - var logs bytes.Buffer - db, _ = newFakeDB(t, release) - if err := withNamedLock(ctx, db, "n", time.Second, newLogger(&logs, slog.LevelDebug), func(*sql.Conn) error { return nil }); err != nil { - t.Fatalf("release failure replaced the committed outcome: %v", err) - } - if db.Stats().OpenConnections != 0 || !strings.Contains(logs.String(), "named lock release failed, discarding the connection") { - t.Fatalf("connection kept after a failed release: %d %s", db.Stats().OpenConnections, logs.String()) + for _, number := range []uint16{mysqlErrLockWait, mysqlErrDeadlock} { + busy := &mysql.MySQLError{Number: number} + db, state := newFakeDB(t, fdbRules(fdbRule{"webui_locks", fdbResponse{err: busy}})) + err := runZoneTx(ctx, db, tables, "example.org.", discardLogger(), func(*sql.Tx) error { + t.Fatal("callback called without lock") + return nil + }) + if !errors.Is(err, errLockTimeout) || state.rollbacks != 1 { + t.Fatalf("error %v, rollbacks %d", err, state.rollbacks) } } - db, _ = newFakeDB(t, lockHandler(int64(1), int64(1), nil)) - if err := withNamedLock(ctx, db, "n", time.Second, discardLogger(), func(*sql.Conn) error { return nil }); err != nil || db.Stats().OpenConnections != 1 { - t.Fatalf("healthy connection discarded: %v %d", err, db.Stats().OpenConnections) - } - db, _ = newFakeDB(t, lockHandler(int64(1), int64(0), nil)) - if err := withNamedLock(ctx, db, "n", time.Second, discardLogger(), func(*sql.Conn) error { return fnErr }); !errors.Is(err, fnErr) { - t.Fatalf("first error not kept: %v", err) - } - db.Close() - if err := withNamedLock(ctx, db, "n", time.Second, discardLogger(), func(*sql.Conn) error { return nil }); err == nil { - t.Fatal("closed pool accepted") + db, state = newFakeDB(t, fdbRules(fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}})) + state.commitErr = &mysql.MySQLError{Number: mysqlErrDeadlock} + err = runZoneTx(ctx, db, tables, "example.org.", discardLogger(), func(*sql.Tx) error { return nil }) + if !errors.Is(err, errLockTimeout) || state.commits != 0 { + t.Fatalf("certification failure: commits=%d error=%v", state.commits, err) } } diff --git a/dev/mysql-init.sql b/dev/mysql-init.sql index 97a7148..4c1a71f 100644 --- a/dev/mysql-init.sql +++ b/dev/mysql-init.sql @@ -20,6 +20,7 @@ GRANT SELECT ON `coredns`.`coredns_records` TO 'coredns'@'%'; CREATE USER 'coredns_webui'@'%' IDENTIFIED BY 'coredns_webui_dev'; GRANT SELECT, INSERT, UPDATE, DELETE ON `coredns`.`coredns_records` TO 'coredns_webui'@'%'; +GRANT SELECT, INSERT, UPDATE, CREATE ON `coredns`.`coredns_webui_locks` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_schema` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` TO 'coredns_webui'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_sessions` TO 'coredns_webui'@'%'; diff --git a/e2e/stack/mysql-init.sql b/e2e/stack/mysql-init.sql index 954d7ee..c2cdbdd 100644 --- a/e2e/stack/mysql-init.sql +++ b/e2e/stack/mysql-init.sql @@ -18,6 +18,7 @@ GRANT SELECT ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{DNS_USER}}'@'%'; CREATE USER '{{APP_USER}}'@'%' IDENTIFIED BY '{{APP_PASSWORD}}'; GRANT SELECT, INSERT, UPDATE, DELETE ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{APP_USER}}'@'%'; +GRANT SELECT, INSERT, UPDATE, CREATE ON `{{DATABASE}}`.`{{PREFIX}}webui_locks` TO '{{APP_USER}}'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_schema` TO '{{APP_USER}}'@'%'; GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_users` TO '{{APP_USER}}'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_sessions` TO '{{APP_USER}}'@'%'; diff --git a/handlers_api.go b/handlers_api.go index 0777eea..b55530b 100644 --- a/handlers_api.go +++ b/handlers_api.go @@ -849,49 +849,44 @@ type zoneAPIWrite struct { func (h zoneHandlers) writeZone(ctx context.Context, c *apiContext, creating bool, change func(zoneAPIWrite) (apiResponse, error)) (apiResponse, error) { var response apiResponse - var committed bool - err := withZoneLock(ctx, h.server.db, h.server.tables, c.Zone, h.server.log, func(conn *sql.Conn) error { - err := runInTx(ctx, conn, func(tx *sql.Tx) error { - w := zoneAPIWrite{ctx: ctx, api: c, records: newRecordStore(tx, h.server.tables), delegations: newDelegationStore(tx, h.server.tables)} - actor, err := newUserStore(tx, h.server.tables).UserByIDForShare(ctx, c.Principal.User.ID) - if err != nil && !errors.Is(err, errRowNotFound) { - return err - } - if err != nil || actor.DeletedAt.Valid || actor.Role != c.Principal.User.Role { - return errZoneNotFound() - } - if actor.Role == "user" { - allowed, err := w.delegations.HasDelegationForShare(ctx, c.Zone, actor.ID) - if err != nil { - return err - } - if !allowed { - return errZoneNotFound() - } - } - w.rows, err = w.records.ZoneRowsForUpdate(ctx, c.Zone) + err := runZoneTx(ctx, h.server.db, h.server.tables, c.Zone, h.server.log, func(tx *sql.Tx) error { + w := zoneAPIWrite{ctx: ctx, api: c, records: newRecordStore(tx, h.server.tables), delegations: newDelegationStore(tx, h.server.tables)} + actor, err := newUserStore(tx, h.server.tables).UserByIDForShare(ctx, c.Principal.User.ID) + if err != nil && !errors.Is(err, errRowNotFound) { + return err + } + if err != nil || actor.DeletedAt.Valid || actor.Role != c.Principal.User.Role { + return errZoneNotFound() + } + if actor.Role == "user" { + allowed, err := w.delegations.HasDelegationForShare(ctx, c.Zone, actor.ID) if err != nil { return err } - if creating && len(w.rows) != 0 { - return &apiError{Status: http.StatusConflict, Message: "zone already exists"} - } - if !creating && len(w.rows) == 0 { + if !allowed { return errZoneNotFound() } - response, err = change(w) - if err != nil { - return err - } - if c.Entry.Before != nil || c.Entry.After != nil { - return c.writeChangeAudit(ctx, tx, response.Status) - } - return nil - }) - committed = err == nil - return err + } + w.rows, err = w.records.ZoneRowsForUpdate(ctx, c.Zone) + if err != nil { + return err + } + if creating && len(w.rows) != 0 { + return &apiError{Status: http.StatusConflict, Message: "zone already exists"} + } + if !creating && len(w.rows) == 0 { + return errZoneNotFound() + } + response, err = change(w) + if err != nil { + return err + } + if c.Entry.Before != nil || c.Entry.After != nil { + return c.writeChangeAudit(ctx, tx, response.Status) + } + return nil }) - if !committed { + if err != nil { c.auditDone = false c.Entry.Before, c.Entry.After = nil, nil if errors.Is(err, errLockTimeout) { diff --git a/handlers_api_test.go b/handlers_api_test.go index 9d32481..3444a9b 100644 --- a/handlers_api_test.go +++ b/handlers_api_test.go @@ -1058,13 +1058,11 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse { } } switch { - case has("GET_LOCK"): + case has("webui_locks"): if f.locked { - return fdbResponse{rows: fdbRow(int64(0))} + return fdbResponse{err: errLockTimeout} } - return fdbResponse{rows: fdbRow(int64(1))} - case has("RELEASE_LOCK"): - return fdbResponse{rows: fdbRow(int64(1))} + return fdbResponse{rowsAffected: 1} case has("SELECT u.") && has("LOCK IN SHARE MODE"): if !f.hasActor { return fdbResponse{} @@ -1147,6 +1145,18 @@ func zoneAPITestKey(zone string) string { return zone } +func zoneAPIHasDataWrites(state *fdbState) bool { + for _, query := range state.Queries() { + if strings.Contains(query, "webui_locks") { + continue + } + if strings.HasPrefix(query, "INSERT INTO") || strings.HasPrefix(query, "UPDATE ") || strings.HasPrefix(query, "DELETE FROM") { + return true + } + } + return false +} + func zoneAPITestingSQL(state *fdbState, contains string) []fdbCall { var result []fdbCall for _, call := range state.Calls() { @@ -1194,7 +1204,7 @@ func TestZoneAPIReadHandlers(t *testing.T) { } }) } - if len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 { + if zoneAPIHasDataWrites(state) { t.Fatal("read wrote to the database") } user := userRow{ID: 17, Role: "user", Username: "alice"} @@ -1291,9 +1301,8 @@ func TestZoneAPIWriteHandlers(t *testing.T) { t.Fatalf("delegations in the after snapshot: %s", c.Entry.After) } calls := state.Queries() - if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "LOCK IN SHARE MODE") || - !strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-2], "INSERT INTO `coredns_webui_audit`") || - !strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") { + if !strings.Contains(calls[0], "webui_locks") || !strings.HasSuffix(calls[1], "LOCK IN SHARE MODE") || + !strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-1], "INSERT INTO `coredns_webui_audit`") { t.Fatalf("write query order: %v", calls) } }) @@ -1416,7 +1425,7 @@ func TestZoneAPIWriteRefusals(t *testing.T) { t.Fatalf("busy error = %q", apiErr.Message) } if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || - len(zoneAPITestingSQL(state, "INSERT INTO"))+len(zoneAPITestingSQL(state, "UPDATE `"))+len(zoneAPITestingSQL(state, "DELETE FROM")) != 0 { + zoneAPIHasDataWrites(state) { t.Fatalf("refusal wrote data: %+v, queries %v", c.Entry, state.Queries()) } }) @@ -1477,7 +1486,7 @@ func TestZoneAPISOAFieldNames(t *testing.T) { if !errors.As(err, &invalid) || invalid.Status != 422 || len(invalid.Fields) != 1 || invalid.Fields[field] == "" { t.Fatalf("field %q: error %+v", field, err) } - if c.auditDone || len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 || len(zoneAPITestingSQL(state, "UPDATE `")) != 0 { + if c.auditDone || zoneAPIHasDataWrites(state) { t.Fatalf("invalid field wrote data: %v", state.Queries()) } }) @@ -1502,8 +1511,7 @@ func TestZoneAPIRollback(t *testing.T) { c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord) resp, err := zoneAPITestCall(t.Context(), c) if !errors.Is(err, failure) || resp.Status != 0 || c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || - state.commits != 0 || (failAt != "commit" && state.rollbacks != 1) || - !strings.Contains(state.Queries()[len(state.Queries())-1], "RELEASE_LOCK") { + state.commits != 0 || (failAt != "commit" && state.rollbacks != 1) { t.Fatalf("response %+v, err %v, audit %+v, SQL %v", resp, err, c.Entry, state.Queries()) } }) diff --git a/handlers_zone_api_test.go b/handlers_zone_api_test.go index 0e829a2..9608c05 100644 --- a/handlers_zone_api_test.go +++ b/handlers_zone_api_test.go @@ -129,7 +129,7 @@ func TestZoneAPIFailurePaths(t *testing.T) { if tc.ran != "" && len(zoneAPITestingSQL(state, tc.ran)) == 0 { t.Fatalf("%q did not run before the failure: %v", tc.ran, state.Queries()) } - if tc.status == 0 && len(zoneAPITestingSQL(state, "GET_LOCK")) != 0 && state.rollbacks != 1 { + if tc.status == 0 && len(zoneAPITestingSQL(state, "webui_locks")) != 0 && state.rollbacks != 1 { t.Fatalf("rollbacks = %d, SQL %v", state.rollbacks, state.Queries()) } }) @@ -219,7 +219,7 @@ func TestZoneAPIUpdateSOAAmbiguous(t *testing.T) { server, state := f.server() c := zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", tc.etag, strings.Replace(zoneAPITestSOA, `"retry":600`, `"retry":700`, 1)) zoneAPITestStatus(t, t.Context(), c, tc.status) - if len(zoneAPITestingSQL(state, "UPDATE `")) != 0 || !slices.Equal(f.rows, rows) { + if zoneAPIHasDataWrites(state) || !slices.Equal(f.rows, rows) { t.Fatalf("ambiguous SOA update wrote data: %v", state.Queries()) } if tc.status == 422 { @@ -343,7 +343,7 @@ func TestZoneAPIImportInvalidFinalZone(t *testing.T) { if !errors.As(err, &apiErr) || apiErr.Status != 422 || !strings.Contains(zoneAPITestJSON(t, apiErr.Extra["errors"]), tc.fragment) { t.Fatalf("error %#v, want %q", err, tc.fragment) } - if len(zoneAPITestingSQL(state, "INSERT INTO"))+len(zoneAPITestingSQL(state, "UPDATE `"))+len(zoneAPITestingSQL(state, "DELETE FROM")) != 0 { + if zoneAPIHasDataWrites(state) { t.Fatalf("invalid import wrote data: %v", state.Queries()) } }) @@ -359,7 +359,7 @@ func TestZoneAPIRepairBlockedByBrokenSOA(t *testing.T) { _, err := zoneAPITestCall(t.Context(), c) var apiErr *apiError if !errors.As(err, &apiErr) || apiErr.Status != 422 || apiErr.Fields["type"] != "repair the SOA before changing other records" || - len(zoneAPITestingSQL(state, "INSERT INTO")) != 0 { + zoneAPIHasDataWrites(state) { t.Fatalf("error %#v, SQL %v", err, state.Queries()) } c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA) diff --git a/integration_db_test.go b/integration_db_test.go index 12c1587..ba2aded 100644 --- a/integration_db_test.go +++ b/integration_db_test.go @@ -10,6 +10,7 @@ import ( "database/sql" "errors" "fmt" + "os" "strconv" "strings" "sync" @@ -17,6 +18,33 @@ import ( "time" ) +func TestIntegrationGaleraProvider(t *testing.T) { + if os.Getenv("IT_GALERA") != "1" { + t.Skip("standalone database") + } + server := itServerFromEnv(t) + db := server.open(t, "root", server.rootPassword, "") + var enabled bool + var provider, version string + if err := db.QueryRow("SELECT @@SESSION.wsrep_on, @@GLOBAL.wsrep_provider, VERSION()").Scan(&enabled, &provider, &version); err != nil { + t.Fatal(err) + } + var status, ready string + if err := db.QueryRow("SHOW STATUS LIKE 'wsrep_ready'").Scan(&status, &ready); err != nil { + t.Fatal(err) + } + if !enabled || !strings.HasSuffix(provider, "libgalera_smm.so") || ready != "ON" { + t.Fatalf("Galera inactive: wsrep_on=%t provider=%q ready=%q", enabled, provider, ready) + } + if strings.HasPrefix(version, "10.11.3-") { + var acquired int + err := db.QueryRow("SELECT GET_LOCK('cdwu_old_lock_probe', 0)").Scan(&acquired) + if !mysqlErrorIs(err, 1235) { + t.Fatalf("expected legacy lock to fail with 1235, got %v", err) + } + } +} + func TestIntegrationContractCheck(t *testing.T) { t.Parallel() ctx := context.Background() @@ -496,70 +524,61 @@ func TestIntegrationAuditUTF8MB4(t *testing.T) { func TestIntegrationZoneLock(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() d := newITDatabase(t, itOptions{prefix: "coredns_"}) db, tn := d.migrated(t) held := make(chan struct{}) release := make(chan struct{}) + var releaseOnce sync.Once + unlock := func() { releaseOnce.Do(func() { close(release) }) } + defer unlock() holderDone := make(chan error, 1) go func() { - holderDone <- withZoneLock(ctx, db, tn, "example.org.", discardLogger(), func(*sql.Conn) error { + holderDone <- runZoneTx(ctx, db, tn, "example.org.", discardLogger(), func(*sql.Tx) error { close(held) <-release return nil }) }() - <-held - conn, err := db.Conn(ctx) - if err != nil { - t.Fatal(err) + select { + case <-held: + case err := <-holderDone: + t.Fatalf("holder failed: %v", err) + case <-ctx.Done(): + t.Fatal(ctx.Err()) } - defer conn.Close() - startWait := time.Now() - if _, err := acquireNamedLock(ctx, conn, tn.zoneLockName("example.org."), time.Second); !errors.Is(err, errLockTimeout) { - t.Fatalf("expected timeout: %v", err) - } - if waited := time.Since(startWait); waited < 900*time.Millisecond { - t.Fatalf("returned after %v", waited) - } - other, err := acquireNamedLock(ctx, conn, tn.zoneLockName("other.org."), time.Second) - if err != nil { + if err := runZoneTx(ctx, db, tn, "other.org.", discardLogger(), func(*sql.Tx) error { return nil }); err != nil { t.Fatalf("other zone blocked: %v", err) } - if err := other.release(ctx); err != nil { - t.Fatal(err) - } - var order []string - var mu sync.Mutex waiterDone := make(chan error, 1) go func() { - waiterDone <- withZoneLock(ctx, db, tn, "example.org.", discardLogger(), func(*sql.Conn) error { - mu.Lock() - order = append(order, "waiter") - mu.Unlock() - return nil - }) + waiterDone <- runZoneTx(ctx, db, tn, "example.org.", discardLogger(), func(*sql.Tx) error { return nil }) }() - time.Sleep(300 * time.Millisecond) - mu.Lock() - order = append(order, "holder releases") - mu.Unlock() - close(release) + poll := time.NewTicker(itLockPollInterval) + defer poll.Stop() + deadline := time.NewTimer(5 * time.Second) + defer deadline.Stop() + for { + waiting, err := d.rowLockWaiting(ctx, "webui_locks") + if err != nil { + t.Fatal(err) + } + if waiting { + break + } + select { + case err := <-waiterDone: + t.Fatalf("waiter did not wait: %v", err) + case <-deadline.C: + t.Fatal("waiter did not reach lock") + case <-poll.C: + } + } + unlock() if err := <-holderDone; err != nil { t.Fatal(err) } if err := <-waiterDone; err != nil { t.Fatal(err) } - if strings.Join(order, ",") != "holder releases,waiter" { - t.Fatalf("order %v", order) - } - lock, err := acquireNamedLock(ctx, conn, tn.zoneLockName("example.org."), time.Second) - if err != nil { - t.Fatalf("lock not released: %v", err) - } - _ = lock.release(ctx) - if err := lock.release(ctx); err == nil { - t.Fatal("double release succeeded") - } } diff --git a/integration_helpers_test.go b/integration_helpers_test.go index d26f8ef..8dff703 100644 --- a/integration_helpers_test.go +++ b/integration_helpers_test.go @@ -38,6 +38,7 @@ var itAppGrants = []struct { create bool }{ {"records", "SELECT, INSERT, UPDATE, DELETE", false}, + {"webui_locks", "SELECT, INSERT, UPDATE, CREATE", true}, {"webui_schema", "SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES", true}, {"webui_users", "SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES", true}, {"webui_sessions", "SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES", true}, diff --git a/integration_http_race_test.go b/integration_http_race_test.go index dd1fd9e..27b021c 100644 --- a/integration_http_race_test.go +++ b/integration_http_race_test.go @@ -377,13 +377,8 @@ func TestIntegrationZoneCreationDelegationRace(t *testing.T) { go func() { a <- it.do(ctx, first) }() it.waitForUserLock(t, ctx, a) go func() { b <- it.do(ctx, second) }() - it.waitForLock(t, ctx, b, "zone named lock", func() (bool, error) { - var waiting bool - // Each fixture has a separate database account. The only named - // lock wait for that account here is on this zone. - err := it.database.root.QueryRowContext(ctx, "SELECT EXISTS (SELECT 1 FROM information_schema.PROCESSLIST "+ - "WHERE USER = ? AND LOWER(STATE) = 'user lock')", it.database.appUser).Scan(&waiting) - return waiting, err + it.waitForLock(t, ctx, b, "zone row lock", func() (bool, error) { + return it.database.rowLockWaiting(ctx, "webui_locks") }) if err := gate.Commit(); err != nil { t.Fatal(err) diff --git a/integration_zone_api_test.go b/integration_zone_api_test.go index c270514..34b2174 100644 --- a/integration_zone_api_test.go +++ b/integration_zone_api_test.go @@ -344,28 +344,28 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) { func TestIntegrationZoneAPILockTimeout(t *testing.T) { it := newITZoneAPI(t) it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201) - conn, err := it.db.root.Conn(t.Context()) + ctx := t.Context() + tx, err := it.db.root.BeginTx(ctx, nil) if err != nil { t.Fatal(err) } - defer conn.Close() - lock, err := acquireNamedLock(t.Context(), conn, it.server.tables.zoneLockName(zoneAPITestName), 0) - if err != nil { + defer tx.Rollback() + tables := it.server.tables + if _, err := tx.ExecContext(ctx, tables.sql(zoneLockSQL), tables.zoneLockName(zoneAPITestName)); err != nil { t.Fatal(err) } - defer func() { - if err := lock.release(t.Context()); err != nil { - t.Error(err) - } - }() - ctx, cancel := context.WithTimeout(t.Context(), zoneLockTimeout+5*time.Second) + ctx, cancel := context.WithTimeout(ctx, zoneLockTimeout+5*time.Second) defer cancel() + start := time.Now() c := it.request(it.admin, "record_create", "", "", zoneAPITestRecord) _, err = zoneAPITestCall(ctx, c) var apiErr *apiError if !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable || apiErr.Message != "zone busy" { t.Fatalf("contended write error = %v", err) } + if waited := time.Since(start); waited < zoneLockTimeout-time.Second || waited > zoneLockTimeout+3*time.Second { + t.Fatalf("contended write waited %v", waited) + } it.audit(t, "record_create", 0) it.serial(t, newSOASerial(modelNow)) } @@ -690,7 +690,7 @@ func TestIntegrationDelegationZoneLock(t *testing.T) { c := it.request(it.admin, operation, "", "", "") c.Vars["username"] = it.user.Username result := make(chan error, 1) - err := withZoneLock(t.Context(), it.server.db, it.server.tables, zoneAPITestName, it.server.log, func(conn *sql.Conn) error { + err := runZoneTx(t.Context(), it.server.db, it.server.tables, zoneAPITestName, it.server.log, func(tx *sql.Tx) error { go func() { var err error if operation == opDelegationGrant { @@ -705,13 +705,11 @@ func TestIntegrationDelegationZoneLock(t *testing.T) { return fmt.Errorf("delegation did not wait for zone lock: %v", err) case <-time.After(200 * time.Millisecond): } - return runInTx(t.Context(), conn, func(tx *sql.Tx) error { - if _, err := newDelegationStore(tx, it.server.tables).DeleteZoneDelegations(t.Context(), zoneAPITestName); err != nil { - return err - } - _, err := newRecordStore(tx, it.server.tables).DeleteZoneRecords(t.Context(), zoneAPITestName) + if _, err := newDelegationStore(tx, it.server.tables).DeleteZoneDelegations(t.Context(), zoneAPITestName); err != nil { return err - }) + } + _, err := newRecordStore(tx, it.server.tables).DeleteZoneRecords(t.Context(), zoneAPITestName) + return err }) if err != nil { t.Fatal(err) diff --git a/middleware.go b/middleware.go index f0024bc..03a16a0 100644 --- a/middleware.go +++ b/middleware.go @@ -173,10 +173,8 @@ func (s *sqlWebStore) InTx(ctx context.Context, fn func(tx webTx) error) error { } func (s *sqlWebStore) InZoneTx(ctx context.Context, zone string, log *slog.Logger, fn func(tx webTx) error) error { - return withZoneLock(ctx, s.db, s.tables, zone, log, func(conn *sql.Conn) error { - return runInTx(ctx, conn, func(tx *sql.Tx) error { - return fn(newSQLWebTx(tx, s.tables)) - }) + return runZoneTx(ctx, s.db, s.tables, zone, log, func(tx *sql.Tx) error { + return fn(newSQLWebTx(tx, s.tables)) }) } diff --git a/middleware_test.go b/middleware_test.go index c0ee9ce..b336b8a 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -845,7 +845,7 @@ func TestPagePathCleaning(t *testing.T) { } } -func TestZoneTxLockReleaseFailureKeepsTheCommittedChange(t *testing.T) { +func TestDelegationGrantCommitsWithZoneLock(t *testing.T) { token, tokenHash, err := newSessionToken(strings.NewReader(strings.Repeat("k", 32))) if err != nil { t.Fatal(err) @@ -855,8 +855,7 @@ func TestZoneTxLockReleaseFailureKeepsTheCommittedChange(t *testing.T) { } session := append(userValues(1, "admin", roleAdmin), tokenHash, int64(1), webNow, webNow, webNow.Add(time.Hour), "192.0.2.1", "test") db, st := newFakeDB(t, fdbRules( - fdbRule{"SELECT GET_LOCK", fdbResponse{rows: fdbRow(int64(1))}}, - fdbRule{"SELECT RELEASE_LOCK", fdbResponse{err: errors.New("connection lost")}}, + fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}}, fdbRule{"x.`token_hash` = ?", fdbResponse{rows: [][]driver.Value{session}}}, fdbRule{"ORDER BY u.`id` FOR UPDATE", fdbResponse{rows: [][]driver.Value{userValues(1, "admin", roleAdmin)}}}, fdbRule{"SELECT 1 FROM `coredns_records`", fdbResponse{rows: fdbRow(int64(1))}}, @@ -888,7 +887,7 @@ func TestZoneTxLockReleaseFailureKeepsTheCommittedChange(t *testing.T) { if audits != 1 || grants != 1 || st.commits != 1 || st.rollbacks != 0 { t.Fatalf("audits %d grants %d commits %d rollbacks %d", audits, grants, st.commits, st.rollbacks) } - if !strings.Contains(logs.String(), "named lock release failed, discarding the connection") || !strings.Contains(logs.String(), `msg="change committed" operation=delegation_grant`) { + if !strings.Contains(logs.String(), "zone lock acquired") || !strings.Contains(logs.String(), `msg="change committed" operation=delegation_grant`) { t.Fatal(logs.String()) } } diff --git a/migrations.go b/migrations.go index e6b063c..84fb344 100644 --- a/migrations.go +++ b/migrations.go @@ -15,6 +15,7 @@ import ( "sort" "strconv" "strings" + "time" ) //go:embed migrations/*.sql @@ -104,12 +105,58 @@ func splitSQLStatements(content string) []string { return statements } -func migrateDatabase(ctx context.Context, db connSource, t tableNames, log *slog.Logger) error { +const createLockTableSQL = "CREATE TABLE IF NOT EXISTS {locks} (" + + "`name` VARBINARY(64) NOT NULL PRIMARY KEY, `generation` TINYINT NOT NULL) ENGINE = InnoDB" + +func migrateDatabase(ctx context.Context, db *sql.DB, t tableNames, log *slog.Logger) error { migrations, err := loadMigrations(migrationFiles, t.prefix) if err != nil { return err } - return withNamedLock(ctx, db, t.migrateLockName(), migrateLockTimeout, log, func(conn *sql.Conn) error { + + waitCtx, cancel := context.WithTimeout(ctx, migrateLockTimeout) + defer cancel() + for { + err := migrateWithLock(ctx, waitCtx, db, t, migrations, log) + if !mysqlErrorIs(err, mysqlErrDeadlock) { + return err + } + // Bootstrap DDL and a concurrent seed can conflict on Galera. + // Reacquire the guard and re-read the durable schema version. + select { + case <-waitCtx.Done(): + return fmt.Errorf("retry migrations: %w", lockError(ctx, waitCtx, err)) + case <-time.After(50 * time.Millisecond): + } + } +} + +func migrateWithLock(ctx, waitCtx context.Context, db *sql.DB, t tableNames, migrations []migration, log *slog.Logger) error { + name := t.migrateLockName() + seed := t.sql("INSERT IGNORE INTO {locks} (`name`, `generation`) VALUES (?, 0)") + _, err := db.ExecContext(waitCtx, seed, name) + if mysqlErrorIs(err, 1146) { + if _, err = db.ExecContext(waitCtx, t.sql(createLockTableSQL)); err != nil { + return fmt.Errorf("create lock table: %w", lockError(ctx, waitCtx, err)) + } + _, err = db.ExecContext(waitCtx, seed, name) + } + if err != nil { + return fmt.Errorf("seed migration lock: %w", lockError(ctx, waitCtx, err)) + } + + return runInTx(ctx, db, func(tx *sql.Tx) error { + var key string + if err := tx.QueryRowContext(waitCtx, t.sql("SELECT `name` FROM {locks} WHERE `name` = ? FOR UPDATE"), name).Scan(&key); err != nil { + return fmt.Errorf("acquire migration lock: %w", lockError(ctx, waitCtx, err)) + } + // DDL implicitly commits its session. Keep the guard transaction + // open on its own connection while the other session runs migrations. + conn, err := db.Conn(ctx) + if err != nil { + return fmt.Errorf("open migration connection: %w", err) + } + defer conn.Close() if err := applyMigrations(ctx, conn, t, migrations, log); err != nil { return err } diff --git a/migrations_test.go b/migrations_test.go index 5e4a596..0fad0a1 100644 --- a/migrations_test.go +++ b/migrations_test.go @@ -11,6 +11,8 @@ import ( "strings" "testing" "testing/fstest" + + "github.com/go-sql-driver/mysql" ) func TestLoadEmbeddedMigrations(t *testing.T) { @@ -121,8 +123,10 @@ func (m *migrationDB) handler(q string, args []any) fdbResponse { return fdbResponse{err: m.failErr} } switch { - case strings.HasPrefix(q, "SELECT GET_LOCK"), strings.HasPrefix(q, "SELECT RELEASE_LOCK"): - return fdbResponse{rows: fdbRow(int64(1))} + case strings.HasPrefix(q, "INSERT IGNORE INTO `coredns_webui_locks`"): + return fdbResponse{rowsAffected: 1} + case strings.HasPrefix(q, "SELECT `name` FROM `coredns_webui_locks`"): + return fdbResponse{rows: fdbRow(args[0])} case strings.Contains(q, "information_schema.TABLES"): return fdbResponse{rows: fdbRow(m.tableCount)} case strings.HasPrefix(q, "SELECT `version`"): @@ -265,11 +269,11 @@ func TestMigrateDatabase(t *testing.T) { t.Fatal(err) } calls := st.Calls() - if !strings.HasPrefix(calls[0].query, "SELECT GET_LOCK") || calls[0].args[0] != "coredns_webui_migrate" || calls[0].args[1] != int64(30) { - t.Fatalf("first call %+v", calls[0]) + if !strings.HasPrefix(calls[0].query, "INSERT IGNORE INTO `coredns_webui_locks`") || calls[0].args[0] != "coredns_webui_migrate" { + t.Fatalf("initial call %+v", calls[0]) } - if !strings.HasPrefix(calls[len(calls)-1].query, "SELECT RELEASE_LOCK") { - t.Fatalf("last call %+v", calls[len(calls)-1]) + if !strings.HasSuffix(calls[1].query, "FOR UPDATE") || calls[1].args[0] != "coredns_webui_migrate" || st.commits != 1 { + t.Fatalf("guard call %+v, commits %d", calls[1], st.commits) } bad := tableNames{prefix: "bad-prefix"} if err := migrateDatabase(ctx, db, bad, discardLogger()); err == nil { @@ -277,6 +281,29 @@ func TestMigrateDatabase(t *testing.T) { } } +func TestMigrationBootstrapRetriesDeadlock(t *testing.T) { + m := &migrationDB{tableCount: 0} + seeds := 0 + db, state := newFakeDB(t, func(q string, args []any) fdbResponse { + if strings.HasPrefix(q, "INSERT IGNORE INTO `coredns_webui_locks`") { + seeds++ + switch seeds { + case 1: + return fdbResponse{err: &mysql.MySQLError{Number: 1146}} + case 2: + return fdbResponse{err: &mysql.MySQLError{Number: mysqlErrDeadlock}} + } + } + return m.handler(q, args) + }) + if err := migrateDatabase(t.Context(), db, fdbTables(t), discardLogger()); err != nil { + t.Fatal(err) + } + if seeds != 3 || state.commits != 1 || m.executedDDL[0] != fdbTables(t).sql(createLockTableSQL) { + t.Fatalf("seeds=%d commits=%d ddl=%v", seeds, state.commits, m.executedDDL) + } +} + func TestVerifyAppSchema(t *testing.T) { ctx := context.Background() m := &migrationDB{tableCount: 0} diff --git a/scripts/integration.sh b/scripts/integration.sh index 537fd30..3c672f5 100755 --- a/scripts/integration.sh +++ b/scripts/integration.sh @@ -8,6 +8,7 @@ cd "$(dirname "$0")/.." IT_ID=${IT_ID:-$$} IT_NAME=${IT_NAME:-cdwu-it-${IT_ID}} MYSQL_IMAGE=${MYSQL_IMAGE:-mysql:8.4} +IT_GALERA=${IT_GALERA:-0} network="$IT_NAME" mysql="${IT_NAME}-mysql" mysql_data="${IT_NAME}-data" @@ -64,9 +65,14 @@ fi network_id=$(docker network create --internal "$network") require_free_docker_name image "$image" docker build --target integration --file dockerfile --tag "$image" --iidfile "$tmp/image-id" . +set -- +if [ "$IT_GALERA" = 1 ]; then + set -- --wsrep-on=ON --wsrep-provider=/usr/lib/galera/libgalera_smm.so \ + --wsrep-cluster-address=gcomm:// --wsrep-new-cluster --binlog-format=ROW --innodb-autoinc-lock-mode=2 +fi mysql_id=$(docker create --name "$mysql" --network "$network_id" --network-alias mysql \ --volume "$volume:/var/lib/mysql" \ - --env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE") + --env MYSQL_ROOT_PASSWORD="$root_password" "$MYSQL_IMAGE" "$@") docker start "$mysql_id" >/dev/null attempt=0 until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" sh -c ' @@ -81,6 +87,6 @@ until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" sh -c ' sleep 1 done tests_id=$(docker create --name "$tests" --network "$network_id" \ - --env IT_MYSQL_HOST=mysql --env IT_MYSQL_PORT=3306 --env IT_MYSQL_ROOT_PASSWORD="$root_password" \ + --env IT_GALERA="$IT_GALERA" --env IT_MYSQL_HOST=mysql --env IT_MYSQL_PORT=3306 --env IT_MYSQL_ROOT_PASSWORD="$root_password" \ "$(cat "$tmp/image-id")") docker start --attach "$tests_id"