Chuyển đến nội dung chính

レッスン 23: Patroni 構成管理

動的な構成変更、DCS ベースの構成では、patronictl edit-config を使用し、ダウンタイムなしで構成を更新します。

🔒 DevSecOps — レッスン 23 レッスン 23: Patroni 構成管理

Patroni と PostgreSQL の高可用性etcd

パート 5: セキュリティと上級_

xdev.asia_

目標

このレッスンを終えると、次のことができるようになります:

  • Patroni 構成を動的に管理する
  • patronictl edit-config を使用する
  • DCS ストアを理解する構成_
  • ダウンタイムゼロの構成変更の実行
  • 構成の検証とロールバック_

1。構成レイヤー_

1.1。構成階層

Priority (highest to lowest):

  1. PostgreSQL parameters in postgresql.conf (overrides all)
  2. DCS configuration (patronictl edit-config)
  3. Patroni YAML file (/etc/patroni/patroni.yml)
  4. PostgreSQL defaults

Typical workflow:

  • Bootstrap config → patroni.yml
  • Runtime changes → DCS (patronictl edit-config)
  • Local overrides → postgresql.conf (rare, not recommended)

1.2。構成範囲_

# Bootstrap config (patroni.yml) - initial setup only
bootstrap:
dcs:
ttl: 30
loop_wait: 10
postgresql:
parameters:
max_connections: 100
shared_buffers: 256MB

Runtime config (DCS) - can be changed anytime

Stored in etcd/consul/k8s and applied to all nodes

2。現在の構成を表示

2.1。 DCS 構成を表示

patronictl -c /etc/patroni/patroni.yml show-config

Output:

loop_wait: 10

maximum_lag_on_failover: 1048576

postgresql:

parameters:

archive_command: 'test ! -f /var/lib/postgresql/wal_archive/%f && cp %p /var/lib/postgresql/wal_archive/%f'

archive_mode: 'on'

hot_standby: 'on'

max_connections: 100

max_replication_slots: 10

max_wal_senders: 10

shared_buffers: 256MB

wal_level: replica

use_pg_rewind: true

use_slots: true

retry_timeout: 10

ttl: 30

2.2。特定のパラメータ

# Query etcd directly
export ETCDCTL_API=3
etcdctl get /service/postgres-cluster/config --print-value-only | jq .

Or use patronictl

patronictl -c /etc/patroni/patroni.yml show-config | grep max_connections

2.3を取得します。ローカル構成

# Show differences
diff <(patronictl -c /etc/patroni/patroni.yml show-config) 
<(grep -A 100 "^bootstrap:" /etc/patroni/patroni.yml)

3 と比較します。動的な構成の変更

3.1。構成を対話的に編集

# Open editor with current config
patronictl -c /etc/patroni/patroni.yml edit-config

This opens in $EDITOR (vim/nano)

Example changes:

# Before:
postgresql:
parameters:
max_connections: 100
shared_buffers: 256MB

After:

postgresql: parameters: max_connections: 200 # Changed shared_buffers: 512MB # Changed work_mem: 8MB # Added

# Save and exit

Patroni will prompt:

Apply these changes? [y/N]: y

---

+++

@@ -5,7 +5,8 @@

postgresql:

parameters:

- max_connections: 100

- shared_buffers: 256MB

+ max_connections: 200

+ shared_buffers: 512MB

+ work_mem: 8MB

Configuration changed

3.2。自動再起動と手動再起動

PostgreSQL parameters fall into 3 categories:

  1. Dynamic (no restart):

    • work_mem, maintenance_work_mem
    • effective_cache_size
    • random_page_cost
    • Apply immediately with pg_reload_conf()
  2. Reload required (SIGHUP):

    • max_connections (if increasing)
    • shared_buffers
    • Patroni will reload automatically
  3. Restart required:

    • max_connections (if decreasing)
    • shared_buffers (decreasing)
    • wal_level, max_wal_senders
    • Patroni will restart replicas, then switchover and restart leader

3.3。保留中の再起動を確認

patronictl -c /etc/patroni/patroni.yml list



+ Cluster: postgres-cluster (7329123456789012345) ---+----+-----------+

| Member | Host | Role | State | TL | Lag in MB | Pending restart |

+--------+------------+---------+---------+----+-----------+-----------------+

| node1 | 10.0.1.11 | Leader | running | 5 | | * |

| node2 | 10.0.1.12 | Replica | running | 5 | 0 | * |

| node3 | 10.0.1.13 | Replica | running | 5 | 0 | * |

+--------+------------+---------+---------+----+-----------+-----------------+

* = Pending restart required

3.4。再起動をトリガー

# Restart specific node
patronictl -c /etc/patroni/patroni.yml restart postgres-cluster node2

Restart all nodes (one by one)

patronictl -c /etc/patroni/patroni.yml restart postgres-cluster

Force restart (even if no pending changes)

patronictl -c /etc/patroni/patroni.yml restart postgres-cluster node1 --force

4。構成テンプレート_

4.1。コマンドライン_

# Patch configuration
patronictl -c /etc/patroni/patroni.yml edit-config --apply - <<EOF
postgresql:
parameters:
max_connections: 300
shared_buffers: 1GB
EOF

Or use --set flag (if supported)

patronictl edit-config --set postgresql.parameters.max_connections=300

4.2を使用して構成を設定します。構成を保存して復元_

# Export current config
patronictl -c /etc/patroni/patroni.yml show-config > config-backup-$(date +%Y%m%d).yml

Restore config

patronictl -c /etc/patroni/patroni.yml edit-config --apply config-backup-20241125.yml

4.3。バージョン管理

# Track config changes in git
mkdir -p /opt/patroni/configs
cd /opt/patroni/configs
git init

Save config

patronictl -c /etc/patroni/patroni.yml show-config > current-config.yml git add current-config.yml git commit -m "Increased max_connections to 300"

View history

git log --oneline

abc123 Increased max_connections to 300

def456 Added work_mem parameter

ghi789 Initial configuration

5。一般的な構成タスク

5.1。 max_connections_

patronictl -c /etc/patroni/patroni.yml edit-config
postgresql:
parameters:
max_connections: 200  # Change from 100

# May also need to increase:
shared_buffers: 512MB  # ~25% of RAM
max_wal_senders: 15    # max_connections / 10
max_replication_slots: 15

注: 制限内で増加する場合は再起動が必要です。

5.2。クエリ ログを有効にする

patronictl -c /etc/patroni/patroni.yml edit-config
postgresql:
parameters:
log_statement: 'all'  # or 'ddl', 'mod', 'none'
log_duration: 'on'
log_min_duration_statement: 1000  # Log queries > 1s

注: 再起動は必要ありません (動的パラメーター)。

5.3。メモリ設定を調整

patronictl -c /etc/patroni/patroni.yml edit-config
postgresql:
parameters:
shared_buffers: 512MB          # Requires restart
effective_cache_size: 2GB      # Dynamic
work_mem: 8MB                  # Dynamic
maintenance_work_mem: 128MB    # Dynamic

5.4。チェックポイントの動作を調整します

patronictl -c /etc/patroni/patroni.yml edit-config
postgresql:
parameters:
checkpoint_timeout: 15min
checkpoint_completion_target: 0.9
max_wal_size: 4GB
min_wal_size: 1GB

注: 動的またはリロード、再起動は必要ありません。

5.5。 pg_stat_statements_

patronictl -c /etc/patroni/patroni.yml edit-config
postgresql:
parameters:
shared_preload_libraries: 'pg_stat_statements'  # Requires restart!
pg_stat_statements.track: 'all'
pg_stat_statements.max: 10000
# After restart, create extension
sudo -u postgres psql -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;"

6 を有効にします。検証とテスト

6.1。パラメータ値_

-- Current settings
SELECT name, setting, unit, context, source
FROM pg_settings
WHERE name IN ('max_connections', 'shared_buffers', 'work_mem');

-- Pending reload SELECT name, setting, pending_restart FROM pg_settings WHERE pending_restart = true;

6.2 を確認します。構成

# PostgreSQL validation
sudo -u postgres /usr/lib/postgresql/18/bin/postgres 
-D /var/lib/postgresql/18/data
-C max_connections

Check for errors

sudo journalctl -u patroni -n 100 --no-pager

6.3を検証します。構成の変更

# 1. Change config
patronictl -c /etc/patroni/patroni.yml edit-config --apply test-config.yml

2. Monitor logs

tail -f /var/lib/postgresql/18/data/log/postgresql-*.log

3. Check cluster status

watch -n 1 'patronictl -c /etc/patroni/patroni.yml list'

4. Verify parameter

psql -h 10.0.1.11 -U postgres -c "SHOW max_connections;"

7をテストします。ロールバック手順_

7.1。即時ロールバック

# Restore from backup
patronictl -c /etc/patroni/patroni.yml edit-config --apply config-backup-20241125.yml

Verify

patronictl -c /etc/patroni/patroni.yml show-config

Restart if needed

patronictl -c /etc/patroni/patroni.yml restart postgres-cluster

7.2。緊急復旧_

# If DCS is corrupted, reset from local config

1. Stop Patroni on all nodes

sudo systemctl stop patroni

2. Edit patroni.yml directly

sudo vi /etc/patroni/patroni.yml

3. Reinitialize DCS config (on leader only)

patronictl -c /etc/patroni/patroni.yml reinit postgres-cluster node1 --force

4. Start Patroni on all nodes

sudo systemctl start patroni

8。詳細構成

8.1。データベースごとのパラメータ_

-- Set parameter for specific database
ALTER DATABASE myapp SET work_mem = '16MB';

-- Per-user settings ALTER USER app_user SET statement_timeout = '30s';

注: これらはクラスタ全体の設定をオーバーライドします。

8.2。条件付き構成_

# In patroni.yml (local config)
postgresql:
parameters:
# Leader-only settings
synchronous_standby_names: 'node2,node3'

pg_hba.conf can differ per node

pg_hba: - host replication replicator 10.0.1.0/24 scram-sha-256 - host all all 10.0.1.0/24 scram-sha-256

8.3。カスタム コールバック__HTMLTAG_162___
# In patroni.yml
postgresql:
callbacks:
on_reload: /usr/local/bin/patroni-reload-hook.sh
on_restart: /usr/local/bin/patroni-restart-hook.sh
on_role_change: /usr/local/bin/patroni-role-change-hook.sh
#!/bin/bash

/usr/local/bin/patroni-reload-hook.sh

echo "$(date): PostgreSQL reloaded" >> /var/log/patroni-hooks.log

Send notification

curl -X POST https://hooks.slack.com/...
-d '{"text": "PostgreSQL config reloaded on '$(hostname)'"}'

9。構成のベスト プラクティス_

✅ DO

  1. ランタイム変更に DCS を使用 - クラスター全体で一貫性
  2. バージョン管理configs - git の変更を追跡_
  3. 最初にステージングでテスト - 運用前に検証
  4. ドキュメントの変更 -なぜ、何を、いつ_
  5. 変更前のバックアップ - 簡単なロールバック
  6. 変更後の監視 -問題_
  7. 再起動のスケジュール - メンテナンス期間中
  8. patronictl edit-config を使用 - 手動ではありません etcd変更
  9. パラメータを検証 - pg_settings を確認
  10. 定期的に確認 - 四半期ごとの構成監査_

❌ 禁止

  1. postgresql.conf を編集しないでください - patronictl を使用してください代わりに_
  2. etcd を直接変更しない - Patroni ツールを使用
  3. バックアップをスキップしない - 必ず保存する前に変更_
  4. 未テストの変更を適用しない - まずテスト
  5. 保留中の再起動を無視しない - 適用されない場合があります正しく
  6. wal_level をわずかに変更しないでください - 完全な再起動が必要
  7. レプリカを忘れないでください - 変更が適用されますクラスター全体_

10。構成の監視_

10.1。構成ドリフト_

# Check if all nodes have same config
for node in node1 node2 node3; do
echo "=== $node ==="
ssh $node "sudo -u postgres psql -Atc "SELECT name, setting FROM pg_settings WHERE name = 'max_connections'""
done

10.2を追跡します。構成変更に関するアラート

# Prometheus alert
groups:

  • name: patroni-config rules:
    • alert: PatroniConfigChanged expr: changes(patroni_config_last_modified[5m]) > 0 labels: severity: info annotations: summary: "Patroni configuration changed"

    • alert: PostgreSQLPendingRestart expr: patroni_pending_restart == 1 for: 1h labels: severity: warning annotations: summary: "PostgreSQL pending restart for {{ $labels.instance }}"

10.3。構成変更の監査ログ

# Enable auditd for /etc/patroni/
sudo auditctl -w /etc/patroni/ -p wa -k patroni-config

View audit logs

sudo ausearch -k patroni-config

Or use journalctl for Patroni service

sudo journalctl -u patroni --since "1 hour ago" | grep "config"

11。ラボ演習

ラボ 1: 動的な構成変更

タスク:

  1. 現在の構成を表示_
  2. 構成を編集して増やすmax_connections_
  3. 再起動せずに変更を適用
  4. 新しい設定を確認
  5. 構成のバックアップを保存

実習 2: 構成が必要再起動_

タスク:

  1. shared_buffers パラメータの変更_
  2. 保留中の再起動フラグを確認
  3. ローリングを実行する再起動_
  4. 適用された変更を確認
  5. pg_settings クエリでテスト_

ラボ 3: ロールバック構成

タスク:

  1. 現在の構成をバックアップ
  2. 意図的に悪い変更を加える
  3. クラスターを観察する動作_
  4. バックアップへのロールバック
  5. ドキュメントの回復手順

ラボ 4: 構成自動化

タスク:

  1. 構成を適用するシェルスクリプトの作成
  2. 検証チェックの実装
  3. 追加バックアップ/ロールバック ロジック_
  4. クラスター上のテスト スクリプト_
  5. スケジュールされた変更のために cron に追加_

12。概要_

構成管理フロー

1. Backup current config
↓
2. Edit configuration (patronictl edit-config)
↓
3. Validate changes
↓
4. Apply to DCS
↓
5. Patroni propagates to all nodes
↓
6. Reload or restart as needed
↓
7. Verify changes applied
↓
8. Monitor cluster health

主要コマンド_

# View config
patronictl show-config

Edit config

patronictl edit-config

Backup config

patronictl show-config > backup.yml

Restore config

patronictl edit-config --apply backup.yml

Check pending restart

patronictl list

Restart node

patronictl restart postgres-cluster node1

パラメータのタイプ

タイプアクション例__HTMLTAG_340______ HTMLTAG_341___
動的即時work_mem、 effect_cache_size_
ReloadSIGHUPmax_connections (up)、 log_statement_
再起動完全再起動__shared_buffers (down)、wal_level
_

_次のステップ___HTMLTAG_372__HTMLTAG_373___レッスン 24 ではアップグレード戦略:

  • PostgreSQL メジャー バージョン アップグレード
  • Patroni について説明します。バージョンアップグレード
  • ゼロダウンタイムアップグレード手順
  • ロールバック戦略
  • テストと検証