fix: replace named locks with Galera-compatible row locks
Test / test (push) Successful in 25m39s
Build and publish image / image (push) Successful in 16m16s

This commit is contained in:
bryanpedini committed 2026-11-20 16:27:15 +01:00
1 parent ee07866d1c
commit 65d16c2fc6
22 files changed
+314 -365

No files matched your search

+2
View File
@@ -33,6 +33,8 @@ jobs:
echo "Running integration tests against $database" echo "Running integration tests against $database"
MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh
done 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 - name: Build and test image
id: build id: build
env: env:
+2
View File
@@ -29,6 +29,8 @@ jobs:
echo "Running integration tests against $database" echo "Running integration tests against $database"
MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh MYSQL_IMAGE="$database" IT_ID="${GITHUB_RUN_ID}" scripts/integration.sh
done 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 - name: Image and end-to-end tests
run: | run: |
set -eu set -eu
+3 -2
View File
@@ -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. 2. Initialize the logger and log version and commit.
3. Open the pool and ping MySQL, retrying with backoff for up to 30 seconds. 3. Open the pool and ping MySQL, retrying with backoff for up to 30 seconds.
4. Verify the records table contract (section 3). 4. Verify the records table contract (section 3).
5. Apply the application's migrations (section 6) while holding the MySQL named lock `<prefix>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. 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. 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. 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 ```sql
CREATE USER 'coredns_webui'@'%' IDENTIFIED BY '<password>'; CREATE USER 'coredns_webui'@'%' IDENTIFIED BY '<password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON `coredns`.`coredns_records` TO 'coredns_webui'@'%'; 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_schema` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` 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'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_sessions` TO 'coredns_webui'@'%';
@@ -351,7 +352,7 @@ Warnings:
### Concurrency ### Concurrency
Every write runs on a dedicated connection: take the named lock `<prefix>webui:<first 16 hex chars of sha256(zone)>` 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 `<prefix>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. 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.
+7 -5
View File
@@ -94,7 +94,7 @@ Rows with errors are shown in the UI with their raw content and problems; editin
### Writes, locking and ETags ### Writes, locking and ETags
Every write takes a MySQL named lock per zone (`<prefix>webui:<first 16 hex characters of sha256(zone)>`, 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 `<prefix>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 ### Zone files
@@ -107,6 +107,7 @@ The application user needs `SELECT`, `INSERT`, `UPDATE` and `DELETE` on the reco
```sql ```sql
CREATE USER 'coredns_webui'@'%' IDENTIFIED BY '<password>'; CREATE USER 'coredns_webui'@'%' IDENTIFIED BY '<password>';
GRANT SELECT, INSERT, UPDATE, DELETE ON `coredns`.`coredns_records` TO 'coredns_webui'@'%'; 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_schema` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` 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'@'%'; 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 ### Application schema and migrations
Migrations are embedded SQL files (`migrations/001_initial.sql`, ...) applied in order. The current version is the single row of `<prefix>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 `<prefix>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 `<prefix>webui_schema`. The table prefix is substituted into the SQL after validation; it is the only value ever interpolated into SQL. Startup creates `<prefix>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 | | Table | Content |
|---|---| |---|---|
| `<prefix>webui_locks` | the migration row and one row per zone written by the application |
| `<prefix>webui_schema` | the schema version | | `<prefix>webui_schema` | the schema version |
| `<prefix>webui_users` | `id`, `username`, `role`, `password_hash`, `created_at`, `updated_at`, `last_login_at`, `deleted_at` | | `<prefix>webui_users` | `id`, `username`, `role`, `password_hash`, `created_at`, `updated_at`, `last_login_at`, `deleted_at` |
| `<prefix>webui_sessions` | SHA-256 of the session token, user, creation, last seen and expiry times, origin, user agent | | `<prefix>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. 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. `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. 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. 2. Opens the pool and pings MySQL, retrying with backoff for up to 30 seconds.
3. Verifies the records table contract. 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. 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. 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. 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 ### 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-<id>` (`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-<id>` (`IT_ID`, default the shell's process id) and are removed at exit, also after failures.
### Image tests ### Image tests
+2 -2
View File
@@ -174,8 +174,8 @@ func (m *matrixSQL) userValues(u userRow) []driver.Value {
func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse { func (m *matrixSQL) exec(w *matrixWorld, query string, args []any) fdbResponse {
has := func(v string) bool { return strings.Contains(query, v) } has := func(v string) bool { return strings.Contains(query, v) }
switch { switch {
case has("GET_LOCK"), has("RELEASE_LOCK"): case has("webui_locks"):
return fdbResponse{rows: fdbRow(int64(1))} return fdbResponse{rowsAffected: 1}
case has("FROM `coredns_webui_users` u WHERE u.`id` = ?"): case has("FROM `coredns_webui_users` u WHERE u.`id` = ?"):
id := args[0].(int64) id := args[0].(int64)
for _, u := range w.state.users { for _, u := range w.state.users {
+1 -1
View File
@@ -19,7 +19,7 @@ func mxStoreFail(method string, err error) func(*matrixEnv) {
} }
func mxBusy(env *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) { func mxCommitFails(env *matrixEnv) {
+36 -73
View File
@@ -12,7 +12,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"log/slog" "log/slog"
"math"
"regexp" "regexp"
"runtime" "runtime"
"strings" "strings"
@@ -35,10 +34,12 @@ const (
zoneLockTimeout = 10 * time.Second zoneLockTimeout = 10 * time.Second
migrateLockTimeout = 30 * time.Second migrateLockTimeout = 30 * time.Second
mysqlErrDupEntry = 1062 mysqlErrDupEntry = 1062
mysqlErrLockWait = 1205
mysqlErrDeadlock = 1213
) )
var ( var (
errLockTimeout = errors.New("named lock timeout") errLockTimeout = errors.New("database lock busy")
errRowNotFound = errors.New("row not found") errRowNotFound = errors.New("row not found")
errUsernameTaken = errors.New("username already used") errUsernameTaken = errors.New("username already used")
errContract = errors.New("records table contract violated") errContract = errors.New("records table contract violated")
@@ -67,6 +68,7 @@ type tableNames struct {
sessions string sessions string
delegations string delegations string
audit string audit string
locks string
} }
func newTableNames(prefix string) (tableNames, error) { func newTableNames(prefix string) (tableNames, error) {
@@ -81,6 +83,7 @@ func newTableNames(prefix string) (tableNames, error) {
sessions: quoteIdent(prefix + "webui_sessions"), sessions: quoteIdent(prefix + "webui_sessions"),
delegations: quoteIdent(prefix + "webui_zone_delegations"), delegations: quoteIdent(prefix + "webui_zone_delegations"),
audit: quoteIdent(prefix + "webui_audit"), audit: quoteIdent(prefix + "webui_audit"),
locks: quoteIdent(prefix + "webui_locks"),
}, nil }, nil
} }
@@ -96,6 +99,7 @@ func (t tableNames) sql(query string) string {
"{sessions}", t.sessions, "{sessions}", t.sessions,
"{delegations}", t.delegations, "{delegations}", t.delegations,
"{audit}", t.audit, "{audit}", t.audit,
"{locks}", t.locks,
).Replace(query) ).Replace(query)
} }
@@ -289,83 +293,38 @@ func checkRecordsColumns(table string, columns map[string]columnInfo) error {
return nil return nil
} }
type namedLock struct { // An upsert locks the zone until the transaction ends. Changing the row
conn *sql.Conn // also gives Galera a certification key when different writers use the zone.
name string 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) { func lockError(ctx, waitCtx context.Context, err error) error {
seconds := int64(math.Ceil(timeout.Seconds())) if lockBusy(err) || (ctx.Err() == nil && errors.Is(waitCtx.Err(), context.DeadlineExceeded)) {
var result sql.NullInt64 return fmt.Errorf("%w: %w", errLockTimeout, err)
if err := conn.QueryRowContext(ctx, "SELECT GET_LOCK(?, ?)", name, seconds).Scan(&result); err != nil {
return nil, fmt.Errorf("acquire lock: %w", err)
} }
if !result.Valid { return err
return nil, errors.New("acquire lock: GET_LOCK returned NULL")
}
if result.Int64 != 1 {
return nil, errLockTimeout
}
return &namedLock{conn: conn, name: name}, nil
} }
func (l *namedLock) release(ctx context.Context) error { func runZoneTx(ctx context.Context, db txBeginner, t tableNames, zone string, log *slog.Logger, fn func(*sql.Tx) error) error {
var result sql.NullInt64 name := t.zoneLockName(zone)
if err := l.conn.QueryRowContext(ctx, "SELECT RELEASE_LOCK(?)", l.name).Scan(&result); err != nil { err := runInTx(ctx, db, func(tx *sql.Tx) error {
return fmt.Errorf("release lock: %w", err) waitCtx, cancel := context.WithTimeout(ctx, zoneLockTimeout)
}
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)
defer cancel() defer cancel()
if rerr := lock.release(releaseCtx); rerr != nil { if _, err := tx.ExecContext(waitCtx, t.sql(zoneLockSQL), name); err != nil {
log.ErrorContext(ctx, "named lock release failed, discarding the connection", "lock", name, "error", rerr) return fmt.Errorf("acquire zone lock: %w", lockError(ctx, waitCtx, err))
discard = true
return
} }
log.DebugContext(ctx, "named lock released", "lock", name) log.DebugContext(ctx, "zone lock acquired", "lock", name)
}() return fn(tx)
return fn(conn) })
} // A Galera certification failure can first surface at commit.
if lockBusy(err) && !errors.Is(err, errLockTimeout) {
func withZoneLock(ctx context.Context, db connSource, t tableNames, zone string, log *slog.Logger, fn func(conn *sql.Conn) error) error { return fmt.Errorf("%w: %w", errLockTimeout, err)
return withNamedLock(ctx, db, t.zoneLockName(zone), zoneLockTimeout, log, fn) }
return err
} }
func runInTx(ctx context.Context, b txBeginner, fn func(tx *sql.Tx) error) (err error) { 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 { func isDuplicateKey(err error) bool {
return mysqlErrorIs(err, mysqlErrDupEntry)
}
func mysqlErrorIs(err error, number uint16) bool {
var me *mysql.MySQLError 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 { func dbTime(t time.Time) time.Time {
+27 -143
View File
@@ -34,12 +34,13 @@ func TestNewTableNames(t *testing.T) {
sessions: "`dns_webui_sessions`", sessions: "`dns_webui_sessions`",
delegations: "`dns_webui_zone_delegations`", delegations: "`dns_webui_zone_delegations`",
audit: "`dns_webui_audit`", audit: "`dns_webui_audit`",
locks: "`dns_webui_locks`",
} }
if tn != want { if tn != want {
t.Fatalf("got %+v", tn) t.Fatalf("got %+v", tn)
} }
got := tn.sql("{records} {schema} {users} {sessions} {delegations} {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` {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) t.Fatalf("sql %s", got)
} }
if _, err := newTableNames("bad`prefix"); err == nil { 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 { func TestRunZoneTx(t *testing.T) {
return func(q string, args []any) fdbResponse { ctx := t.Context()
switch { tables := fdbTables(t)
case strings.HasPrefix(q, "SELECT GET_LOCK"): db, state := newFakeDB(t, fdbRules(fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}}))
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))
called := false 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 called = true
return nil return nil
}) })
if err != nil || !called { if err != nil || !called || state.commits != 1 || state.rollbacks != 0 {
t.Fatalf("%v %v", err, called) t.Fatalf("callback=%t commits=%d rollbacks=%d error=%v", called, state.commits, state.rollbacks, err)
} }
q := st.Queries() calls := state.Calls()
if len(q) != 2 || !strings.HasPrefix(q[0], "SELECT GET_LOCK") || !strings.HasPrefix(q[1], "SELECT RELEASE_LOCK") { if len(calls) != 1 || calls[0].query != tables.sql(zoneLockSQL) || calls[0].args[0] != tables.zoneLockName("example.org.") {
t.Fatalf("queries %v", q) t.Fatalf("lock calls: %v", calls)
}
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)
} }
fnErr := errors.New("fn failed") for _, number := range []uint16{mysqlErrLockWait, mysqlErrDeadlock} {
db, st = newFakeDB(t, lockHandler(int64(1), int64(1), nil)) busy := &mysql.MySQLError{Number: number}
if err := withNamedLock(ctx, db, "n", time.Second, discardLogger(), func(*sql.Conn) error { return fnErr }); !errors.Is(err, fnErr) { db, state := newFakeDB(t, fdbRules(fdbRule{"webui_locks", fdbResponse{err: busy}}))
t.Fatalf("got %v", err) err := runZoneTx(ctx, db, tables, "example.org.", discardLogger(), func(*sql.Tx) error {
} t.Fatal("callback called without lock")
if len(st.Queries()) != 2 { return nil
t.Fatal("lock not released after failure") })
} if !errors.Is(err, errLockTimeout) || state.rollbacks != 1 {
t.Fatalf("error %v, rollbacks %d", err, state.rollbacks)
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())
} }
} }
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() db, state = newFakeDB(t, fdbRules(fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}}))
if err := withNamedLock(ctx, db, "n", time.Second, discardLogger(), func(*sql.Conn) error { return nil }); err == nil { state.commitErr = &mysql.MySQLError{Number: mysqlErrDeadlock}
t.Fatal("closed pool accepted") 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)
} }
} }
+1
View File
@@ -20,6 +20,7 @@ GRANT SELECT ON `coredns`.`coredns_records` TO 'coredns'@'%';
CREATE USER 'coredns_webui'@'%' IDENTIFIED BY 'coredns_webui_dev'; 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, 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_schema` TO 'coredns_webui'@'%';
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_users` 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'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `coredns`.`coredns_webui_sessions` TO 'coredns_webui'@'%';
+1
View File
@@ -18,6 +18,7 @@ GRANT SELECT ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{DNS_USER}}'@'%';
CREATE USER '{{APP_USER}}'@'%' IDENTIFIED BY '{{APP_PASSWORD}}'; CREATE USER '{{APP_USER}}'@'%' IDENTIFIED BY '{{APP_PASSWORD}}';
GRANT SELECT, INSERT, UPDATE, DELETE ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{APP_USER}}'@'%'; 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_schema` TO '{{APP_USER}}'@'%';
GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_users` 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}}'@'%'; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_sessions` TO '{{APP_USER}}'@'%';
+32 -37
View File
@@ -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) { func (h zoneHandlers) writeZone(ctx context.Context, c *apiContext, creating bool, change func(zoneAPIWrite) (apiResponse, error)) (apiResponse, error) {
var response apiResponse var response apiResponse
var committed bool err := runZoneTx(ctx, h.server.db, h.server.tables, c.Zone, h.server.log, func(tx *sql.Tx) error {
err := withZoneLock(ctx, h.server.db, h.server.tables, c.Zone, h.server.log, func(conn *sql.Conn) error { w := zoneAPIWrite{ctx: ctx, api: c, records: newRecordStore(tx, h.server.tables), delegations: newDelegationStore(tx, h.server.tables)}
err := runInTx(ctx, conn, func(tx *sql.Tx) error { actor, err := newUserStore(tx, h.server.tables).UserByIDForShare(ctx, c.Principal.User.ID)
w := zoneAPIWrite{ctx: ctx, api: c, records: newRecordStore(tx, h.server.tables), delegations: newDelegationStore(tx, h.server.tables)} if err != nil && !errors.Is(err, errRowNotFound) {
actor, err := newUserStore(tx, h.server.tables).UserByIDForShare(ctx, c.Principal.User.ID) return err
if err != nil && !errors.Is(err, errRowNotFound) { }
return err if err != nil || actor.DeletedAt.Valid || actor.Role != c.Principal.User.Role {
} return errZoneNotFound()
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 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)
if err != nil { if err != nil {
return err return err
} }
if creating && len(w.rows) != 0 { if !allowed {
return &apiError{Status: http.StatusConflict, Message: "zone already exists"}
}
if !creating && len(w.rows) == 0 {
return errZoneNotFound() return errZoneNotFound()
} }
response, err = change(w) }
if err != nil { w.rows, err = w.records.ZoneRowsForUpdate(ctx, c.Zone)
return err if err != nil {
} return err
if c.Entry.Before != nil || c.Entry.After != nil { }
return c.writeChangeAudit(ctx, tx, response.Status) if creating && len(w.rows) != 0 {
} return &apiError{Status: http.StatusConflict, Message: "zone already exists"}
return nil }
}) if !creating && len(w.rows) == 0 {
committed = err == nil return errZoneNotFound()
return err }
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.auditDone = false
c.Entry.Before, c.Entry.After = nil, nil c.Entry.Before, c.Entry.After = nil, nil
if errors.Is(err, errLockTimeout) { if errors.Is(err, errLockTimeout) {
+21 -13
View File
@@ -1058,13 +1058,11 @@ func (f *zoneAPITestDB) query(query string, args []any) fdbResponse {
} }
} }
switch { switch {
case has("GET_LOCK"): case has("webui_locks"):
if f.locked { if f.locked {
return fdbResponse{rows: fdbRow(int64(0))} return fdbResponse{err: errLockTimeout}
} }
return fdbResponse{rows: fdbRow(int64(1))} return fdbResponse{rowsAffected: 1}
case has("RELEASE_LOCK"):
return fdbResponse{rows: fdbRow(int64(1))}
case has("SELECT u.") && has("LOCK IN SHARE MODE"): case has("SELECT u.") && has("LOCK IN SHARE MODE"):
if !f.hasActor { if !f.hasActor {
return fdbResponse{} return fdbResponse{}
@@ -1147,6 +1145,18 @@ func zoneAPITestKey(zone string) string {
return zone 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 { func zoneAPITestingSQL(state *fdbState, contains string) []fdbCall {
var result []fdbCall var result []fdbCall
for _, call := range state.Calls() { 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") t.Fatal("read wrote to the database")
} }
user := userRow{ID: 17, Role: "user", Username: "alice"} 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) t.Fatalf("delegations in the after snapshot: %s", c.Entry.After)
} }
calls := state.Queries() calls := state.Queries()
if !strings.Contains(calls[0], "GET_LOCK") || !strings.HasSuffix(calls[1], "LOCK IN SHARE MODE") || 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)-2], "INSERT INTO `coredns_webui_audit`") || !strings.HasSuffix(calls[2], "FOR UPDATE") || !strings.Contains(calls[len(calls)-1], "INSERT INTO `coredns_webui_audit`") {
!strings.Contains(calls[len(calls)-1], "RELEASE_LOCK") {
t.Fatalf("write query order: %v", calls) t.Fatalf("write query order: %v", calls)
} }
}) })
@@ -1416,7 +1425,7 @@ func TestZoneAPIWriteRefusals(t *testing.T) {
t.Fatalf("busy error = %q", apiErr.Message) t.Fatalf("busy error = %q", apiErr.Message)
} }
if c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || 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()) 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] == "" { if !errors.As(err, &invalid) || invalid.Status != 422 || len(invalid.Fields) != 1 || invalid.Fields[field] == "" {
t.Fatalf("field %q: error %+v", field, err) 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()) 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) c := zoneAPITestRequest(server, f.actor, "record_create", zoneAPITestName, "", "", zoneAPITestRecord)
resp, err := zoneAPITestCall(t.Context(), c) resp, err := zoneAPITestCall(t.Context(), c)
if !errors.Is(err, failure) || resp.Status != 0 || c.auditDone || c.Entry.Before != nil || c.Entry.After != nil || 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) || state.commits != 0 || (failAt != "commit" && state.rollbacks != 1) {
!strings.Contains(state.Queries()[len(state.Queries())-1], "RELEASE_LOCK") {
t.Fatalf("response %+v, err %v, audit %+v, SQL %v", resp, err, c.Entry, state.Queries()) t.Fatalf("response %+v, err %v, audit %+v, SQL %v", resp, err, c.Entry, state.Queries())
} }
}) })
+4 -4
View File
@@ -129,7 +129,7 @@ func TestZoneAPIFailurePaths(t *testing.T) {
if tc.ran != "" && len(zoneAPITestingSQL(state, tc.ran)) == 0 { if tc.ran != "" && len(zoneAPITestingSQL(state, tc.ran)) == 0 {
t.Fatalf("%q did not run before the failure: %v", tc.ran, state.Queries()) 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()) t.Fatalf("rollbacks = %d, SQL %v", state.rollbacks, state.Queries())
} }
}) })
@@ -219,7 +219,7 @@ func TestZoneAPIUpdateSOAAmbiguous(t *testing.T) {
server, state := f.server() server, state := f.server()
c := zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", tc.etag, strings.Replace(zoneAPITestSOA, `"retry":600`, `"retry":700`, 1)) 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) 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()) t.Fatalf("ambiguous SOA update wrote data: %v", state.Queries())
} }
if tc.status == 422 { 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) { 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) 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()) t.Fatalf("invalid import wrote data: %v", state.Queries())
} }
}) })
@@ -359,7 +359,7 @@ func TestZoneAPIRepairBlockedByBrokenSOA(t *testing.T) {
_, err := zoneAPITestCall(t.Context(), c) _, err := zoneAPITestCall(t.Context(), c)
var apiErr *apiError var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.Status != 422 || apiErr.Fields["type"] != "repair the SOA before changing other records" || 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()) t.Fatalf("error %#v, SQL %v", err, state.Queries())
} }
c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA) c = zoneAPITestRequest(server, f.actor, "soa_update", zoneAPITestName, "", recordETag(rows[0]), zoneAPITestSOA)
+62 -43
View File
@@ -10,6 +10,7 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"os"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@@ -17,6 +18,33 @@ import (
"time" "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) { func TestIntegrationContractCheck(t *testing.T) {
t.Parallel() t.Parallel()
ctx := context.Background() ctx := context.Background()
@@ -496,70 +524,61 @@ func TestIntegrationAuditUTF8MB4(t *testing.T) {
func TestIntegrationZoneLock(t *testing.T) { func TestIntegrationZoneLock(t *testing.T) {
t.Parallel() t.Parallel()
ctx := context.Background() ctx := t.Context()
d := newITDatabase(t, itOptions{prefix: "coredns_"}) d := newITDatabase(t, itOptions{prefix: "coredns_"})
db, tn := d.migrated(t) db, tn := d.migrated(t)
held := make(chan struct{}) held := make(chan struct{})
release := 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) holderDone := make(chan error, 1)
go func() { 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) close(held)
<-release <-release
return nil return nil
}) })
}() }()
<-held select {
conn, err := db.Conn(ctx) case <-held:
if err != nil { case err := <-holderDone:
t.Fatal(err) t.Fatalf("holder failed: %v", err)
case <-ctx.Done():
t.Fatal(ctx.Err())
} }
defer conn.Close() if err := runZoneTx(ctx, db, tn, "other.org.", discardLogger(), func(*sql.Tx) error { return nil }); err != nil {
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 {
t.Fatalf("other zone blocked: %v", err) 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) waiterDone := make(chan error, 1)
go func() { go func() {
waiterDone <- withZoneLock(ctx, db, tn, "example.org.", discardLogger(), func(*sql.Conn) error { waiterDone <- runZoneTx(ctx, db, tn, "example.org.", discardLogger(), func(*sql.Tx) error { return nil })
mu.Lock()
order = append(order, "waiter")
mu.Unlock()
return nil
})
}() }()
time.Sleep(300 * time.Millisecond) poll := time.NewTicker(itLockPollInterval)
mu.Lock() defer poll.Stop()
order = append(order, "holder releases") deadline := time.NewTimer(5 * time.Second)
mu.Unlock() defer deadline.Stop()
close(release) 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 { if err := <-holderDone; err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := <-waiterDone; err != nil { if err := <-waiterDone; err != nil {
t.Fatal(err) 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")
}
} }
+1
View File
@@ -38,6 +38,7 @@ var itAppGrants = []struct {
create bool create bool
}{ }{
{"records", "SELECT, INSERT, UPDATE, DELETE", false}, {"records", "SELECT, INSERT, UPDATE, DELETE", false},
{"webui_locks", "SELECT, INSERT, UPDATE, CREATE", true},
{"webui_schema", "SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES", true}, {"webui_schema", "SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES", true},
{"webui_users", "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}, {"webui_sessions", "SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES", true},
+2 -7
View File
@@ -377,13 +377,8 @@ func TestIntegrationZoneCreationDelegationRace(t *testing.T) {
go func() { a <- it.do(ctx, first) }() go func() { a <- it.do(ctx, first) }()
it.waitForUserLock(t, ctx, a) it.waitForUserLock(t, ctx, a)
go func() { b <- it.do(ctx, second) }() go func() { b <- it.do(ctx, second) }()
it.waitForLock(t, ctx, b, "zone named lock", func() (bool, error) { it.waitForLock(t, ctx, b, "zone row lock", func() (bool, error) {
var waiting bool return it.database.rowLockWaiting(ctx, "webui_locks")
// 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
}) })
if err := gate.Commit(); err != nil { if err := gate.Commit(); err != nil {
t.Fatal(err) t.Fatal(err)
+15 -17
View File
@@ -344,28 +344,28 @@ func TestIntegrationZoneAPIHandlers(t *testing.T) {
func TestIntegrationZoneAPILockTimeout(t *testing.T) { func TestIntegrationZoneAPILockTimeout(t *testing.T) {
it := newITZoneAPI(t) it := newITZoneAPI(t)
it.call(t, it.admin, "zone_create", "", "", zoneAPITestCreate, 201) 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer conn.Close() defer tx.Rollback()
lock, err := acquireNamedLock(t.Context(), conn, it.server.tables.zoneLockName(zoneAPITestName), 0) tables := it.server.tables
if err != nil { if _, err := tx.ExecContext(ctx, tables.sql(zoneLockSQL), tables.zoneLockName(zoneAPITestName)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer func() { ctx, cancel := context.WithTimeout(ctx, zoneLockTimeout+5*time.Second)
if err := lock.release(t.Context()); err != nil {
t.Error(err)
}
}()
ctx, cancel := context.WithTimeout(t.Context(), zoneLockTimeout+5*time.Second)
defer cancel() defer cancel()
start := time.Now()
c := it.request(it.admin, "record_create", "", "", zoneAPITestRecord) c := it.request(it.admin, "record_create", "", "", zoneAPITestRecord)
_, err = zoneAPITestCall(ctx, c) _, err = zoneAPITestCall(ctx, c)
var apiErr *apiError var apiErr *apiError
if !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable || apiErr.Message != "zone busy" { if !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable || apiErr.Message != "zone busy" {
t.Fatalf("contended write error = %v", err) 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.audit(t, "record_create", 0)
it.serial(t, newSOASerial(modelNow)) it.serial(t, newSOASerial(modelNow))
} }
@@ -690,7 +690,7 @@ func TestIntegrationDelegationZoneLock(t *testing.T) {
c := it.request(it.admin, operation, "", "", "") c := it.request(it.admin, operation, "", "", "")
c.Vars["username"] = it.user.Username c.Vars["username"] = it.user.Username
result := make(chan error, 1) 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() { go func() {
var err error var err error
if operation == opDelegationGrant { if operation == opDelegationGrant {
@@ -705,13 +705,11 @@ func TestIntegrationDelegationZoneLock(t *testing.T) {
return fmt.Errorf("delegation did not wait for zone lock: %v", err) return fmt.Errorf("delegation did not wait for zone lock: %v", err)
case <-time.After(200 * time.Millisecond): 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 {
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 return err
}) }
_, err := newRecordStore(tx, it.server.tables).DeleteZoneRecords(t.Context(), zoneAPITestName)
return err
}) })
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
+2 -4
View File
@@ -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 { 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 runZoneTx(ctx, s.db, s.tables, zone, log, func(tx *sql.Tx) error {
return runInTx(ctx, conn, func(tx *sql.Tx) error { return fn(newSQLWebTx(tx, s.tables))
return fn(newSQLWebTx(tx, s.tables))
})
}) })
} }
+3 -4
View File
@@ -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))) token, tokenHash, err := newSessionToken(strings.NewReader(strings.Repeat("k", 32)))
if err != nil { if err != nil {
t.Fatal(err) 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") 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( db, st := newFakeDB(t, fdbRules(
fdbRule{"SELECT GET_LOCK", fdbResponse{rows: fdbRow(int64(1))}}, fdbRule{"webui_locks", fdbResponse{rowsAffected: 1}},
fdbRule{"SELECT RELEASE_LOCK", fdbResponse{err: errors.New("connection lost")}},
fdbRule{"x.`token_hash` = ?", fdbResponse{rows: [][]driver.Value{session}}}, 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{"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))}}, 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 { 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) 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()) t.Fatal(logs.String())
} }
} }
+49 -2
View File
@@ -15,6 +15,7 @@ import (
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"time"
) )
//go:embed migrations/*.sql //go:embed migrations/*.sql
@@ -104,12 +105,58 @@ func splitSQLStatements(content string) []string {
return statements 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) migrations, err := loadMigrations(migrationFiles, t.prefix)
if err != nil { if err != nil {
return err 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 { if err := applyMigrations(ctx, conn, t, migrations, log); err != nil {
return err return err
} }
+33 -6
View File
@@ -11,6 +11,8 @@ import (
"strings" "strings"
"testing" "testing"
"testing/fstest" "testing/fstest"
"github.com/go-sql-driver/mysql"
) )
func TestLoadEmbeddedMigrations(t *testing.T) { func TestLoadEmbeddedMigrations(t *testing.T) {
@@ -121,8 +123,10 @@ func (m *migrationDB) handler(q string, args []any) fdbResponse {
return fdbResponse{err: m.failErr} return fdbResponse{err: m.failErr}
} }
switch { switch {
case strings.HasPrefix(q, "SELECT GET_LOCK"), strings.HasPrefix(q, "SELECT RELEASE_LOCK"): case strings.HasPrefix(q, "INSERT IGNORE INTO `coredns_webui_locks`"):
return fdbResponse{rows: fdbRow(int64(1))} 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"): case strings.Contains(q, "information_schema.TABLES"):
return fdbResponse{rows: fdbRow(m.tableCount)} return fdbResponse{rows: fdbRow(m.tableCount)}
case strings.HasPrefix(q, "SELECT `version`"): case strings.HasPrefix(q, "SELECT `version`"):
@@ -265,11 +269,11 @@ func TestMigrateDatabase(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
calls := st.Calls() 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) { if !strings.HasPrefix(calls[0].query, "INSERT IGNORE INTO `coredns_webui_locks`") || calls[0].args[0] != "coredns_webui_migrate" {
t.Fatalf("first call %+v", calls[0]) t.Fatalf("initial call %+v", calls[0])
} }
if !strings.HasPrefix(calls[len(calls)-1].query, "SELECT RELEASE_LOCK") { if !strings.HasSuffix(calls[1].query, "FOR UPDATE") || calls[1].args[0] != "coredns_webui_migrate" || st.commits != 1 {
t.Fatalf("last call %+v", calls[len(calls)-1]) t.Fatalf("guard call %+v, commits %d", calls[1], st.commits)
} }
bad := tableNames{prefix: "bad-prefix"} bad := tableNames{prefix: "bad-prefix"}
if err := migrateDatabase(ctx, db, bad, discardLogger()); err == nil { 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) { func TestVerifyAppSchema(t *testing.T) {
ctx := context.Background() ctx := context.Background()
m := &migrationDB{tableCount: 0} m := &migrationDB{tableCount: 0}
+8 -2
View File
@@ -8,6 +8,7 @@ cd "$(dirname "$0")/.."
IT_ID=${IT_ID:-$$} IT_ID=${IT_ID:-$$}
IT_NAME=${IT_NAME:-cdwu-it-${IT_ID}} IT_NAME=${IT_NAME:-cdwu-it-${IT_ID}}
MYSQL_IMAGE=${MYSQL_IMAGE:-mysql:8.4} MYSQL_IMAGE=${MYSQL_IMAGE:-mysql:8.4}
IT_GALERA=${IT_GALERA:-0}
network="$IT_NAME" network="$IT_NAME"
mysql="${IT_NAME}-mysql" mysql="${IT_NAME}-mysql"
mysql_data="${IT_NAME}-data" mysql_data="${IT_NAME}-data"
@@ -64,9 +65,14 @@ fi
network_id=$(docker network create --internal "$network") network_id=$(docker network create --internal "$network")
require_free_docker_name image "$image" require_free_docker_name image "$image"
docker build --target integration --file dockerfile --tag "$image" --iidfile "$tmp/image-id" . 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 \ mysql_id=$(docker create --name "$mysql" --network "$network_id" --network-alias mysql \
--volume "$volume:/var/lib/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 docker start "$mysql_id" >/dev/null
attempt=0 attempt=0
until docker exec --env MYSQL_PWD="$root_password" "$mysql_id" sh -c ' 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 sleep 1
done done
tests_id=$(docker create --name "$tests" --network "$network_id" \ 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")") "$(cat "$tmp/image-id")")
docker start --attach "$tests_id" docker start --attach "$tests_id"