Pular para conteúdo

Usuários do banco

O Tenax faz backup de cada banco com um único usuário, tenax, cuja senha fica em um Secret chamado tenax-* ao lado do banco. Ele nunca usa uma conta de administrador. Criar o usuário leva dois comandos, mais uma linha de configuração do servidor para restaurar qualquer segundo.

NS=team-a                         # the database's namespace
PASSWORD=$(openssl rand -hex 24)  # hex: no quoting surprises

# 1. The Secret Tenax reads
kubectl -n $NS create secret generic tenax-postgres \
  --from-literal=username=tenax --from-file=password=<(printf %s "$PASSWORD")

# 2. The user, as a superuser, through the database's pod (deploy/…, sts/… or a pod)
kubectl -n $NS exec -i deploy/postgres -- psql -U postgres -v ON_ERROR_STOP=1 <<SQL
\set tenax_password '$PASSWORD'
SELECT 'CREATE ROLE tenax LOGIN REPLICATION' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'tenax') \gexec
ALTER ROLE tenax WITH LOGIN REPLICATION PASSWORD :'tenax_password';
GRANT pg_read_all_data, pg_monitor TO tenax;
ALTER SYSTEM SET max_slot_wal_keep_size = '2GB';
SELECT pg_reload_conf();
SQL

3. Para restaurar qualquer segundo, permita que o usuário faça replicação: adicione esta linha ao pg_hba.conf e recarregue (sem reiniciar).

host  replication  tenax  all  scram-sha-256

Se um operator ou chart do Helm gerencia o Postgres, adicione a linha onde ele configura o pg_hba (por exemplo spec.postgresql.pg_hba no CloudNativePG, ou o valor pgHbaConfiguration do chart).

O mesmo SQL como arquivo, com comentários (docs/sql/postgres-users.sql)
docs/sql/postgres-users.sql
-- Tenax's database user for PostgreSQL 15/16/17 (run once as a superuser, e.g. with psql):
--
--   psql -v tenax_password="$TENAX_PASSWORD" -f postgres-users.sql
--
-- One user, `tenax`, does everything (ADR 0016): inventory queries, logical dumps (pg_dump), exports and checks
-- with pg_read_all_data + pg_monitor; physical base backups (pg_basebackup) and the WAL stream with REPLICATION.
--
-- For physical backups and point-in-time restore pg_hba.conf must also allow it to replicate, then reload:
--     host replication tenax all scram-sha-256
-- Without that rule Tenax still works: it takes logical backups and tells you the rule to add.
-- Also needed: wal_level = replica (the default) and max_wal_senders >= 2 (default 10).
\set ON_ERROR_STOP on

SELECT format('CREATE ROLE tenax LOGIN REPLICATION PASSWORD %L', :'tenax_password')
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'tenax') \gexec
ALTER ROLE tenax WITH LOGIN REPLICATION NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD :'tenax_password';
GRANT pg_read_all_data, pg_monitor TO tenax;
-- Keep backup sessions bounded.
ALTER ROLE tenax SET idle_in_transaction_session_timeout = '10min';

-- A stopped streamer must never fill the database disk: cap WAL retained by replication slots (no restart needed).
ALTER SYSTEM SET max_slot_wal_keep_size = '2GB';
SELECT pg_reload_conf();
NS=team-a
PASSWORD=$(openssl rand -hex 24)

# 1. The Secret Tenax reads
kubectl -n $NS create secret generic tenax-mysql \
  --from-literal=username=tenax --from-file=password=<(printf %s "$PASSWORD")

# 2. The user, as root (the official image has the root password in MYSQL_ROOT_PASSWORD)
kubectl -n $NS exec -i deploy/mysql -- sh -c 'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysql -uroot' <<SQL
CREATE USER IF NOT EXISTS 'tenax'@'%' IDENTIFIED BY '$PASSWORD';
GRANT SELECT, SHOW VIEW, TRIGGER, EVENT, LOCK TABLES, PROCESS, RELOAD, SHOW_ROUTINE,
      REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'tenax'@'%';
SQL

3. Restaurar qualquer segundo exige o binlog ativado, em formato de linha: ambos são padrões do MySQL 8. select @@log_bin, @@binlog_format mostra 1, ROW.

O mesmo SQL como arquivo, com comentários (docs/sql/mysql-users.sql)
docs/sql/mysql-users.sql
-- Tenax's database user for MySQL 8.4 (run once as root, replace the password):
--
--   mysql -uroot -p < mysql-users.sql
--
-- One user, `tenax`, does everything (ADR 0016): consistent logical dumps (mysqldump --single-transaction
-- --source-data=2), inventory and checks, and the binlog stream (mysqlbinlog --read-from-remote-server).
-- Without REPLICATION SLAVE / REPLICATION CLIENT Tenax still takes dumps, but without point-in-time restore.
--
-- Server settings (all MySQL 8 defaults except GTIDs): log_bin=ON, binlog_format=ROW, a unique server_id;
-- gtid_mode=ON with enforce_gtid_consistency=ON is recommended; binlog_expire_logs_seconds long enough for the
-- streamer to catch up after an outage (default 30 days).
CREATE USER IF NOT EXISTS 'tenax'@'%' IDENTIFIED BY 'CHANGE_ME_PASSWORD';
GRANT SELECT, SHOW VIEW, TRIGGER, EVENT, LOCK TABLES, PROCESS, RELOAD, SHOW_ROUTINE,
      REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'tenax'@'%';
FLUSH PRIVILEGES;

Pronto. Aponte o alvo para o Secret:

spec:
  credentials:
    secretRef: { name: tenax-postgres }

Sem o passo 3

Nada falha. O Tenax tenta fazer replicação com o usuário e, se o banco recusar:

  • os backups completos são lógicos, no agendamento da política;
  • a condição Replication do alvo, o console e os avisos de cada backup dizem exatamente o que adicionar;
  • o Tenax verifica de novo a cada poucos minutos e começa o streaming sozinho assim que você fizer a adição.
O usuário pode O que você ganha Privilégios
Ler tudo backups lógicos, inventários, exportações, checagens Postgres pg_read_all_data + pg_monitor; MySQL SELECT, SHOW VIEW, TRIGGER, EVENT, LOCK TABLES, PROCESS, RELOAD, SHOW_ROUTINE
Replicar backups físicos (Postgres) e o fluxo de alterações: restaurar qualquer segundo Postgres REPLICATION mais a regra no pg_hba.conf; MySQL REPLICATION SLAVE, REPLICATION CLIENT

Slots de replicação

O stream do Postgres mantém o WAL em um slot de replicação até o Tenax armazená-lo. O SQL limita a 2 GB o que um streamer parado pode reter (max_slot_wal_keep_size), o Tenax alerta com TenaxSlotWALRetentionHigh bem antes disso e remove o slot quando o alvo é excluído ou a restauração point-in-time é desativada.

Avançado: mantenha o usuário sincronizado automaticamente, para ambientes GitOps em que as senhas são rotacionadas e os bancos são recriados.