34.8. Operating MariaDB
MariaDB covers the same ground as PostgreSQL with different machinery
and different defaults - unix-socket authentication for root,
per-user network patterns instead of pg_hba.conf, binary logs
instead of WAL files, and GTID domains that let several sources feed
one replica. This section runs the whole arc in one pass on a second
small application: the server is installed and locked to its client
network, application and replication accounts are granted least
privilege over TLS, logical and physical backups are taken and
restored, binary logs roll the database forward to a chosen position,
replication is built with GTIDs and exercised through a controlled
promotion, and the diagnostics section closes with the slow-query log.
34.8.1. Installing the Server, Selecting Authentication, and Restricting Listeners
MariaDB gets the same treatment PostgreSQL received, in one pass,
using a second small application so nothing inherits by accident:
a shop database served by db3 and replicated to client1. Install on
both hosts:
$ sudo apt install mariadb-server mariadb-client mariadb-backup
Answer the prompts normally; the package creates the data directory,
starts the service, and - the part that shapes every administrative
step after this - configures root@localhost to authenticate with
the unix_socket plugin. That plugin is peer authentication: the
server checks the operating system user of the connecting process,
so sudo mariadb connects as the database superuser with no
password, and nothing else can. Every administrative command in this
section uses that channel; network access is reserved for the
application and replication accounts that get their own passwords
in section 34.8.2.
One package note for rebuilds: the chapter's replication exercise
later reinitializes both data directories with
mariadb-install-db, which - unlike the packaged install - creates
anonymous localhost accounts; they were removed with DELETE FROM
mysql.user WHERE LENGTH(User)=0; FLUSH PRIVILEGES; before anything
else was allowed on those instances. Check for them the same way
after any datadir you build yourself.
The listener and the replication substrate are configuration. Save
on db3 as /etc/mysql/mariadb.conf.d/99-handbook.cnf:
[mysqld]
bind-address = 192.168.236.13
server_id = 13
log_bin = /var/log/mysql/mariadb-bin
log_bin_index = /var/log/mysql/mariadb-bin.index
binlog_format = ROW
gtid_strict_mode = ON
gtid_domain_id = 1
ssl_ca = /etc/mysql/certs/ca.crt
ssl_cert = /etc/mysql/certs/server.crt
ssl_key = /etc/mysql/certs/server.key
require_secure_transport = ON
Line by line, because each one is a decision. bind-address
restricts the listener to the client network's address - the
loopback listener stays available for local administration, and
nothing else is exposed. server_id must differ on every member of
a replication topology. log_bin turns on the binary log - the
record of committed changes that both replication and point-in-time
recovery consume - and puts it in /var/log/mysql, which must
exist owned by mysql before the restart:
$ sudo install -d -o mysql -g mysql -m 750 /var/log/mysql
The command prints nothing. binlog_format = ROW records row images
rather than statement text, which is the safe default for
replication (identical row changes on the replica, no
nondeterministic-statement surprises). gtid_strict_mode = ON
rejects out-of-order or duplicate GTID application - the replica
side of the consistency discipline. gtid_domain_id names this
server's transaction stream; section 34.8.5 explains why the
replica gets a different domain. The TLS lines serve the
certificates installed in a moment, and require_secure_transport
refuses every connection that is not TLS.
The certificate files come from the lab CA of section 34.6.4 (the
mdb-db3 and mdb-client1 pairs). On db3:
$ sudo install -d -m 755 /etc/mysql/certs && sudo install -m 644 /etc/ssl/handbook/ca.crt /etc/mysql/certs/ca.crt && sudo install -m 644 /etc/ssl/handbook/mdb-db3.crt /etc/mysql/certs/server.crt && sudo install -m 600 /etc/ssl/handbook/mdb-db3.key /etc/mysql/certs/server.key && sudo chown mysql:mysql /etc/mysql/certs/server.key
Each install is silent; together they give MariaDB a CA to verify
clients with, a server certificate whose SAN carries db3's name
and address, and a key only the mysql user can read. Restart the
server to apply everything, on db3:
$ sudo systemctl restart mariadb
Silent on success. Then verify the server's own opinion of its configuration, on db3:
$ sudo mariadb -NBe "SELECT @@server_id, @@bind_address, @@gtid_domain_id, @@read_only, @@require_secure_transport;"
13 192.168.236.13 1 0 1
Server ID 13, listening on 192.168.236.13 only, domain 1, writable
(@@read_only 0), TLS required (1). The replica gets the same file
with its own identity - on client1, /etc/mysql/mariadb.conf.d/99-handbook.cnf:
[mysqld]
bind-address = 192.168.236.14
server_id = 14
log_bin = /var/log/mysql/mariadb-bin
log_bin_index = /var/log/mysql/mariadb-bin.index
binlog_format = ROW
gtid_strict_mode = ON
gtid_domain_id = 2
ssl_ca = /etc/mysql/certs/ca.crt
ssl_cert = /etc/mysql/certs/server.crt
ssl_key = /etc/mysql/certs/server.key
require_secure_transport = ON
read_only = ON
Three differences, all deliberate: server_id 14, gtid_domain_id
2 - its own stream, so its eventual promotion in section 34.8.5
produces distinguishable GTIDs - and read_only = ON, which makes
the machine refuse writes at the SQL layer from the moment it boots.
Install the mdb-client1 certificate pair into
/etc/mysql/certs exactly as db3's, create the log directory,
restart, and verify, on client1:
$ sudo install -d -o mysql -g mysql -m 750 /var/log/mysql && sudo systemctl restart mariadb
Both stages - the directory creation and the restart - print nothing on success. Then verify, on client1:
$ sudo mariadb -NBe "SELECT @@server_id, @@bind_address, @@gtid_domain_id, @@read_only;"
14 192.168.236.14 2 1
Server 14 on its own address, domain 2, read-only. The -N (no
column names) and -B (batch) options give the one-line form used
throughout this section; -e supplies the SQL.
34.8.2. Users, Grants, Databases, and TLS Connections
The application gets the same least-privilege treatment as PostgreSQL's: a network account restricted to its own database, and a separate replication account that can do nothing but replicate. On db3, as root over the local socket:
$ sudo mariadb <<'SQL'
CREATE DATABASE shop CHARACTER SET utf8mb4;
CREATE USER 'shop_app'@'192.168.236.%' IDENTIFIED BY 'shop-secret';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON shop.* TO 'shop_app'@'192.168.236.%';
CREATE USER 'repl'@'192.168.236.%' IDENTIFIED BY 'repl-secret';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.236.%';
SQL
The here-document feeds the statements to the client in order; it
prints nothing on success. Both accounts are network accounts whose
host pattern admits only the client network, and the grant lines
draw the boundary precisely: shop_app holds table-level privileges
inside shop only, while repl holds the single global privilege
REPLICATION SLAVE - the one a replica needs and nothing more.
Create the application's table, on db3:
$ sudo mariadb shop <<'SQL'
CREATE TABLE orders (id bigint AUTO_INCREMENT PRIMARY KEY, customer varchar(80) NOT NULL, total_cents integer NOT NULL, created_at timestamp NOT NULL DEFAULT current_timestamp);
INSERT INTO orders (customer, total_cents) VALUES ('alice', 1250), ('bob', 4800);
SQL
Also silent. Verify both layers - data and accounts, on db3:
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop.orders; SELECT user, host FROM mysql.user WHERE user IN ('shop_app','repl');"
2
repl 192.168.236.%
shop_app 192.168.236.%
Two rows in the orders table, and exactly the two expected network
accounts with the client-network host pattern. Now the network
test from the other host, as john on client1:
$ MYSQL_PWD=shop-secret mariadb --host=db3 --user=shop_app --ssl-ca=/etc/mysql/certs/ca.crt --ssl-verify-server-cert -e "SHOW STATUS LIKE 'Ssl_cipher'; SELECT COUNT(*) FROM shop.orders;"
Variable_name Value
Ssl_cipher TLS_AES_256_GCM_SHA384
Count(*) 2
MYSQL_PWD carries the password without a prompt, as PGPASSWORD
did for psql. The client verifies the server: --ssl-ca names the
trust anchor and --ssl-verify-server-cert requires the
certificate to belong to the host named db3. The server verifies
the session's policy: the negotiated cipher is
TLS_AES_256_GCM_SHA384, reported by the server itself through
SHOW STATUS, and the query result crossed the same protected
session. The negative test, still on client1:
$ MYSQL_PWD=shop-secret mariadb --host=db3 --user=shop_app --skip-ssl -e "SELECT 1;"
ERROR 3159 (08004): Connections using insecure transport are prohibited while --require_secure_transport=ON.
The server refuses the connection with error 3159 before any
authentication happens - require_secure_transport is a gate in
front of the gate, and the error says so.
34.8.3. Logical Dumps and Consistent Physical Backups
MariaDB's two backup families mirror PostgreSQL's. The logical dump
is mariadb-dump; the physical copy is mariadb-backup, which
copies the data files while the server runs and then prepares them
into a consistent restore image. The exercise uses both, on db3,
into john's workspace:
$ cd ~/debian-handbook/databases && sudo mariadb-dump --single-transaction --master-data=2 --routines --triggers shop > shop-before.sql && ls -lh shop-before.sql
-rw-rw-r-- 1 john john 3.0K Nov 26 11:20 shop-before.sql
The redirection happens in john's shell, so the 3 KB dump is
john-owned while the read ran as root. The options carry the
consistency guarantees:
| Option | Description |
|---|---|
--single-transaction |
Read the whole dump from one InnoDB snapshot; no table locks, consistent even while writes continue |
--master-data=2 |
Record the dump's binary-log coordinates as a commented CHANGE MASTER line - the anchor section 34.8.4 replays from |
--routines / --triggers |
Include stored procedures, functions, and triggers, which the default omits |
Restore the logical dump into a scratch database and count, on db3:
$ sudo mariadb -e "DROP DATABASE IF EXISTS shop_restore; CREATE DATABASE shop_restore;"
$ sudo mariadb shop_restore < shop-before.sql
Both commands are silent on success - the drop-and-create prepares an empty target, and the dump replays into it. Verify, on db3:
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop_restore.orders;"
2
Both rows arrived. The physical backup is the one that scales to large data:
$ sudo rm -rf /var/backups/mariadb/full && sudo mkdir -p /var/backups/mariadb/full && sudo mariadb-backup --backup --target-dir=/var/backups/mariadb/full --user=root > /tmp/mdb-backup.log 2>&1
The redirection sends the tool's progress output to a log file rather than the terminal - the backup itself writes a steady stream of status lines. Then prepare the copy, on db3:
$ sudo mariadb-backup --prepare --target-dir=/var/backups/mariadb/full >> /tmp/mdb-backup.log 2>&1
--backup produces a file-for-file copy of the data directory plus
a record of the log activity that happened during the copy;
--prepare applies that log, bringing the copy to a consistent
point-in-time. Its checkpoints file summarizes the result, on db3:
$ sudo cat /var/backups/mariadb/full/mariadb_backup_checkpoints
backup_type = log-applied
from_lsn = 0
to_lsn = 45418
last_lsn = 53203
recover_binlog_info = 0
backup_type = log-applied is the flag that the prepare finished;
the LSN range shows what the backup covers. Restoring a physical
backup means replacing the data directory, so the next sequence
stops the server and moves its current data aside - on a server
with data you want, that decision is a recovery exercise, not a
step in a demo. On db3:
$ sudo systemctl stop mariadb && sudo mv /var/lib/mysql /var/lib/mysql.before-physical && sudo install -d -o mysql -g mysql -m 750 /var/lib/mysql
Silent; the old directory survives at /var/lib/mysql.before-physical.
Copy the backup in, fix ownership, and start, on db3:
$ sudo mariadb-backup --copy-back --target-dir=/var/backups/mariadb/full >> /tmp/mdb-backup.log 2>&1 && sudo chown -R mysql:mysql /var/lib/mysql && sudo systemctl start mariadb
Also silent. The moment of truth, on db3:
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop.orders;"
2
The server came up from the restored physical copy with both rows
intact. Once the count satisfies, remove the moved-aside directory
(sudo rm -rf /var/lib/mysql.before-physical) - it is the
pre-restore state, kept only until the restore proves itself.
34.8.4. Binary Logs, Point-in-Time Recovery, and Restore Verification
The binary log is MariaDB's WAL-equivalent for recovery: a record
of committed changes that can be replayed from any starting point.
The dump from the previous section already carries its anchor - the
--master-data=2 line. Take a fresh one at the moment the exercise
begins, on db3:
$ cd ~/debian-handbook/databases && sudo mariadb-dump --single-transaction --master-data=2 --routines --triggers shop > shop-pitr.sql && grep -m1 "CHANGE MASTER" shop-pitr.sql
-- CHANGE MASTER TO MASTER_LOG_FILE='mariadb-bin.000003', MASTER_LOG_POS=344;
The dump is silent as before; the grep extracts the anchor line:
everything in the dump is consistent as of binlog file
mariadb-bin.000003, position 344. Now commit two rows that must
survive, and note where the log stands, on db3:
$ sudo mariadb shop -e "INSERT INTO orders (customer,total_cents) VALUES ('before_target_1',111), ('before_target_2',222);"
$ sudo mariadb -NBe "SHOW MASTER STATUS; SELECT COUNT(*) FROM shop.orders;"
mariadb-bin.000003 693
4
Four rows, and the binary log's current position is
mariadb-bin.000003, 693 - the target: everything between 344 and
693 is the work that happened after the dump. Now commit the damage
the recovery must avoid - the classic accident, applied deliberately
to the disposable demo table, on db3:
$ sudo mariadb -e "DROP TABLE shop.orders;"
$ sudo mariadb -NBe "SHOW TABLES FROM shop;"
The SHOW TABLES prints nothing: the table is gone, and with it the
application's data. The recovery is dump-plus-replay. Recreate the
database and load the dump, on db3:
$ sudo mariadb -e "DROP DATABASE IF EXISTS shop; CREATE DATABASE shop;"
$ sudo mariadb shop < ~/debian-handbook/databases/shop-pitr.sql
Both silent. The replay needs one accommodation: the binary log's
events carry their original GTIDs, and gtid_strict_mode -
correctly - refuses to re-apply transactions the server believes it
has already recorded. Relax it for the replay only, on db3:
$ sudo mariadb -e "SET GLOBAL gtid_strict_mode=OFF;"
Replay exactly the window between the dump and the target, on db3:
$ sudo mariadb-binlog --start-position=344 --stop-position=693 /var/log/mysql/mariadb-bin.000003 | sudo mariadb shop
The pipeline is one logical operation: mariadb-binlog decodes the
log range into SQL statements, and the client applies them to the
restored database. It prints nothing on success.
| Option | Description |
|---|---|
--start-position |
Begin at this byte offset in the first named log file |
--stop-position |
Stop before this offset in the same file |
| (files) | Multiple files are replayed in the order given |
Restore the guard, on db3:
$ sudo mariadb -e "SET GLOBAL gtid_strict_mode=ON;"
And verify - count, then names, on db3:
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop.orders; SELECT GROUP_CONCAT(customer ORDER BY customer) FROM shop.orders;"
4
alice,before_target_1,before_target_2,bob
Four rows: the dump's two (alice, bob), plus the two committed
before the target (before_target_1, before_target_2) - and
nothing that happened after position 693, because the replay never
touched it. GROUP_CONCAT makes the row identity legible, which is
the verification that matters: a count alone cannot distinguish
"the right four" from "four of something". The integrity check
completes the verification, on db3:
$ sudo mariadb-check --databases shop
mariadb-check walks the restored tables verifying indexes and row
formats; it prints one OK line per table when everything is
sound, and anything else is a restore to repeat before the
application ever sees the data.
34.8.5. GTID Replication, Controlled Promotion, and Replica Recovery
Global transaction identifiers give each committed transaction a
coordinate of the form domain-server-sequence, so a replica can
state exactly which transactions it has applied and request exactly
the ones it has not - no binlog file names or offsets in the
replication configuration, and no ambiguity about what a re-pointed
replica needs. The exercise builds the shop replication from a clean slate so the
GTID history is legible. The next command empties the data
directory - the MariaDB instances hold only this section's demo
data, but never apply the pattern to a server with anything you
want. On both db3 and client1, stop the server and rebuild the
data directory, then restart:
$ sudo systemctl stop mariadb && sudo rm -rf /var/lib/mysql/* && sudo mariadb-install-db --user=mysql --datadir=/var/lib/mysql > /tmp/mdb-init.log 2>&1 && sudo systemctl start mariadb
Silent on success (the installer's output goes to the log file). As noted in section 34.8.1, an install-db-built datadir carries anonymous accounts - remove them before proceeding, on both hosts:
$ sudo mariadb -e "DELETE FROM mysql.user WHERE LENGTH(User)=0; FLUSH PRIVILEGES;"
The command prints nothing on success. It matters more than it looks:
MariaDB matches incoming connections against the grant tables with the
most specific host first, so the exact-host anonymous account that
mariadb-install-db creates on client1 - ''@'client1' - shadows the
pattern-host shop_app@'192.168.236.% for any connection arriving
from client1 itself, and the application's login fails with a denial
that looks like a wrong password. The seed, the replication, and the
promotion below all connect to or from this machine, so the removal
comes first.
Now seed the source. On db3, reset the binary log so the topology's history starts here, then recreate the users and data:
$ sudo mariadb -e "RESET MASTER;"
RESET MASTER empties the binary log and the GTID history - on a
server with replicas or archives this is destructive; on the
exercise's fresh datadir it is the deliberate start of a new
history. Then the seed, on db3:
$ sudo mariadb <<'SQL'
CREATE DATABASE shop CHARACTER SET utf8mb4;
CREATE USER 'shop_app'@'192.168.236.%' IDENTIFIED BY 'shop-secret';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON shop.* TO 'shop_app'@'192.168.236.%';
CREATE USER 'repl'@'192.168.236.%' IDENTIFIED BY 'repl-secret';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.236.%';
SQL
$ sudo mariadb shop <<'SQL'
CREATE TABLE orders (id bigint AUTO_INCREMENT PRIMARY KEY, customer varchar(80) NOT NULL, total_cents integer NOT NULL, created_at timestamp NOT NULL DEFAULT current_timestamp);
INSERT INTO orders (customer, total_cents) VALUES ('alice', 1250), ('bob', 4800), ('carol', 990);
SQL
Both scripts are silent. Confirm the source's state and position, on db3:
$ sudo mariadb -NBe "SHOW MASTER STATUS; SELECT COUNT(*) FROM shop.orders;"
mariadb-bin.000001 1887
3
Three rows; the log stands at mariadb-bin.000001, position 1887.
Seed the replica with a dump that records both coordinate systems,
on db3:
$ cd ~/debian-handbook/databases && sudo mariadb-dump --single-transaction --master-data=2 --routines --triggers shop > replica-seed.sql && grep -E "CHANGE MASTER|gtid_slave_pos" replica-seed.sql
-- CHANGE MASTER TO MASTER_LOG_FILE='mariadb-bin.000001', MASTER_LOG_POS=1887;
-- SET GLOBAL gtid_slave_pos='1-13-7';
The two comment lines are the same moment in two vocabularies: the
binlog coordinate (mariadb-bin.000001, 1887) and the GTID
position (1-13-7 - domain 1, server 13, transaction 7). Copy
replica-seed.sql to client1, load it there, and start replication
by GTID, on client1:
$ sudo mariadb -e "DROP DATABASE IF EXISTS shop; CREATE DATABASE shop;"
$ sudo mariadb shop < ~/debian-handbook/databases/replica-seed.sql
$ sudo mariadb <<'SQL'
SET GLOBAL gtid_slave_pos=CONCAT('1-13-7', ',', SUBSTRING_INDEX(@@gtid_binlog_pos, ',', -1));
CHANGE MASTER TO
MASTER_HOST='db3',
MASTER_USER='repl',
MASTER_PASSWORD='repl-secret',
MASTER_USE_GTID=slave_pos,
MASTER_SSL=1,
MASTER_SSL_CA='/etc/mysql/certs/ca.crt',
MASTER_SSL_VERIFY_SERVER_CERT=1;
START SLAVE;
SQL
The heredoc is silent on success. The gtid_slave_pos line deserves
the pause: the seed's domain-1 position says "I have the source's
transactions through 1-13-7", but loading the seed also wrote
local events into the replica's own binlog under its own domain 2
- so the starting position combines the dump's domain-1 component
with the replica's own current domain-2 component, and neither
history is lost. MASTER_USE_GTID=slave_pos then tells the replica
to request from the source exactly what follows that position, over
TLS with the certificate verified against the hostname db3.
Watch it work, on client1:
$ sudo mariadb -e "SHOW SLAVE STATUS\G" | grep -E "Slave_IO_Running|Slave_SQL_Running|Seconds_Behind_Master|Using_Gtid|Last_IO_Error|Last_SQL_Error"
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
Using_Gtid: Slave_Pos
Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
Both threads running - Slave_IO_Running fetches from the source,
Slave_SQL_Running applies locally - zero seconds behind, and the
mode is Slave_Pos (GTID-based). Prove it end to end: write on the
source, on db3:
$ sudo mariadb -e "INSERT INTO shop.orders (customer,total_cents) VALUES ('dave',1500);"
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop.orders;"
4
And read it on the replica, on client1:
$ sudo mariadb -e "SHOW SLAVE STATUS\G" | grep -E "Seconds_Behind_Master|Slave_SQL_Running_State"
Seconds_Behind_Master: 0
Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop.orders;"
4
The row crossed as GTID 1-13-something and applied; both servers
agree. Seconds_Behind_Master is the lag metric to monitor - it is
the RPO of an asynchronous replica at any instant.
Controlled promotion. Stop the source, on db3:
$ sudo systemctl stop mariadb
$ systemctl is-active mariadb
inactive
Promote the replica deliberately, on client1:
$ sudo mariadb <<'SQL'
STOP SLAVE;
RESET SLAVE ALL;
SET GLOBAL read_only = OFF;
SQL
STOP SLAVE halts both threads; RESET SLAVE ALL forgets the
source entirely (connection parameters and relay logs); and
read_only = OFF opens the machine for writes. Note what is
temporary and what is persistent: the SET GLOBAL change lasts
until the next restart, when the configuration file's
read_only = ON reasserts itself - a promotion you mean to keep
belongs in /etc/mysql/mariadb.conf.d/99-handbook.cnf too. Confirm
the new reality, on client1:
$ sudo mariadb -NBe "SELECT @@read_only;"
0
$ sudo mariadb -NBe "INSERT INTO shop.orders (customer,total_cents) VALUES ('eve',2300); SELECT COUNT(*) FROM shop.orders; SHOW MASTER STATUS;"
5
mariadb-bin.000013 2226
The batch output answers in statement order: 5 rows after the
write, and SHOW MASTER STATUS reporting the promoted server's own
log - on domain 2 now, file mariadb-bin.000013. The promoted server also needs its own
copies of the network accounts - it is a full server now, and its
mysql.user came from the seed's replication, not from db3's grant
tables. On client1:
$ sudo mariadb <<'SQL'
CREATE USER IF NOT EXISTS 'repl'@'192.168.236.%' IDENTIFIED BY 'repl-secret';
GRANT REPLICATION SLAVE ON *.* TO 'repl'@'192.168.236.%';
CREATE USER IF NOT EXISTS 'shop_app'@'192.168.236.%' IDENTIFIED BY 'shop-secret';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER ON shop.* TO 'shop_app'@'192.168.236.%';
SQL
The script prints nothing. Confirm the accounts exist with the same query used on db3, on client1:
$ sudo mariadb -NBe "SELECT user, host FROM mysql.user WHERE user IN ('shop_app','repl');"
repl 192.168.236.%
shop_app 192.168.236.%
Replica recovery - bring db3 back as the replica of client1. Start it, seed it from a dump of the promoted server, and point it forward. First the seed, on client1:
$ cd ~/debian-handbook/databases && sudo mariadb-dump --single-transaction --master-data=2 --routines --triggers shop > promoted-seed.sql && grep -E "CHANGE MASTER|gtid_slave_pos" promoted-seed.sql
-- CHANGE MASTER TO MASTER_LOG_FILE='mariadb-bin.000013', MASTER_LOG_POS=2994;
-- SET GLOBAL gtid_slave_pos='1-13-8,2-14-57';
The GTID line now carries two domains - 1-13-8 inherited from
the replication of db3's stream, and 2-14-57 from the promoted
server's own writes - which is exactly what a topology that has
changed direction once looks like, and why each server got its own
domain ID at the start. Copy promoted-seed.sql to db3. Then start
db3's server, prepare its role, and start replication, on db3:
$ sudo systemctl start mariadb
$ sudo mariadb -e "DROP DATABASE IF EXISTS shop; CREATE DATABASE shop;"
$ sudo mariadb shop < ~/debian-handbook/databases/promoted-seed.sql
$ sudo mariadb -e "SET GLOBAL read_only=ON;"
Then the reset of its history and the new source, on db3 - with the
same warning as before, RESET MASTER discards db3's old binlog
and GTID history, which is exactly what rejoining as a fresh replica
of a new source requires:
$ sudo mariadb -e "RESET MASTER;"
$ sudo mariadb <<'SQL'
SET GLOBAL gtid_slave_pos='1-13-8,2-14-57';
CHANGE MASTER TO
MASTER_HOST='client1',
MASTER_USER='repl',
MASTER_PASSWORD='repl-secret',
MASTER_USE_GTID=slave_pos,
MASTER_SSL=1,
MASTER_SSL_CA='/etc/mysql/certs/ca.crt',
MASTER_SSL_VERIFY_SERVER_CERT=1;
START SLAVE;
SQL
The promoted dump recorded the full two-domain position, so no
CONCAT is needed this time - the seed comment is the position.
Confirm, on db3:
$ sudo mariadb -e "SHOW SLAVE STATUS\G" | grep -E "Slave_IO_Running|Slave_SQL_Running|Seconds_Behind_Master|Last_IO_Error|Last_SQL_Error"
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Seconds_Behind_Master: 0
Last_IO_Error:
Last_SQL_Error:
$ sudo mariadb -NBe "SELECT COUNT(*) FROM shop.orders;"
5
db3 streams from client1 with both threads running, no errors, and
sees all five rows including the post-promotion write. The roles
have fully swapped - the same transition PostgreSQL's section 34.5.4
made with timelines and pg_rewind, expressed here with GTID
domains and a seed dump, and subject to the same rule: the old
source was stopped before the promotion and reset before the
rejoin, so there was never a moment when two servers accepted
writes.
34.8.6. Upgrades, Slow Queries, Locks, and Operational Diagnostics
The slow query log is the first diagnostic to turn on when "the database feels slow" - it records every query that exceeds a threshold, with the numbers that explain it. Turn it on at runtime and lower the threshold to catch everything for a bounded window, on client1:
$ sudo mariadb -e "SET GLOBAL slow_query_log=ON; SET GLOBAL long_query_time=0;"
The command prints nothing. Generate one deliberately slow query, on client1:
$ sudo mariadb -e "SELECT SLEEP(1);"
SLEEP(1)
0
The query reports its result (0 after sleeping one second). It is
now in the log - read the tail of it, on client1:
$ sudo tail -8 /var/lib/mysql/client1-slow.log
Time Id Command Argument
# Time: 261126 11:24:29
# User@Host: root[root] @ localhost []
# Thread_id: 23 Schema: QC_hit: No
# Query_time: 1.000278 Lock_time: 0.000000 Rows_sent: 1 Rows_examined: 0
# Rows_affected: 0 Bytes_sent: 65
SET timestamp=1795692269;
SELECT SLEEP(1);
The excerpt is the slow log's format: who ran it, which schema,
Query_time 1.000278 seconds, and - often the real story -
Lock_time and Rows_examined. A slow query with Lock_time near
its Query_time was waiting for someone else; a slow query with
Rows_examined in the millions is missing an index. In production
long_query_time goes back to a sane threshold (fractions of a
second) once the hunting window closes, and the log feeds whatever
monitoring pipeline Chapter 28
built.
Locks are the other half of "slow": a query waiting on a row lock
looks identical to a slow query from the outside. The two
inspection commands to pair are SHOW PROCESSLIST - every
connection, its state (Waiting for table metadata lock, Locked,
and friends are the telltales) - and the InnoDB transaction view:
SELECT trx_state, trx_query FROM information_schema.INNODB_TRX;
A LOCK WAIT transaction whose trx_query names the same table as
the processlist's waiting query is the blocker chain; the response
is the same decision as PostgreSQL's - let it finish, or KILL
<id> the session holding it. Lock diagnosis is command-for-command
the section 34.3.1 method with MariaDB's vocabulary.
Upgrades close the section with the same discipline PostgreSQL's
had. Minor releases arrive through the normal
Chapter 6 workflow (sudo apt update,
sudo apt full-upgrade) and restart the server; the binary log and
replication make such restarts cheap. After any upgrade that
changes the server version, run the compatibility check before
trusting the datadir to the new binaries, on each server:
$ sudo mariadb-upgrade --check-if-upgrade-is-needed
The command examines system tables and reports whether anything
needs fixing; run mariadb-upgrade itself (without the check flag)
when it says so - it updates system-table formats and rechecks all
databases. And the replication constraint is PostgreSQL's again:
source and replica must run the same major version while
replication is active, so MariaDB major upgrades move the topology
together - dump or mariadb-backup onto the new version, repoint,
verify - never one side at a time. mariadb-check --databases shop
from section 34.8.4 is the integrity check to run after any of
these transitions; a database that just changed hands should prove
its tables before applications return to it.