Monday, November 19, 2018

▷ PostgreSQL 스트리밍 복제 구성

[ PostgreSQL Streaming 복제 구성 ]


https://www.postgresql.org/download/

■ 개요
- postgresql log streaming replication
82.버젼부터 제공되던 log shipping 방식보다는 보안성이 강화되고 replication delay가 감소됨
(replication delay는 말 그대로 마스터노드에서 standby노드로 replay될 로그레코드가 전달되기 까지의 지연이고,
apply delay는 전달받은 WAL 레코드를 replay해서 디스크에 writing 하기까지의 발생되는 시간쯤으로 개념을 잡으면 될듯합니다.)
두개이상의 standby 구성이 가능하지만 standby 노드끼리의 replication 은 불가.

■ 구성정보
1) 버젼 : postgresql 9.x.x
2) 노드 : master 192.168.16.128 / standby 192.168.16.129

■ 순서
1) Master / standby 에서 installation
2) Master노드 initdb
3) Master postgresql.conf 설정
4) Master pg_hba.conf 설정
5) Master repluser 생성
6) master base-backup 및 standby노드와 $PGDATA 동기화(pg_xlog 는 제외)
7) standby 노드 recovery,conf 파일 생성
8) replication test / failover test / replication 모니터링

■ 단계별 세부사항
1. (master/standby) PostgreSQL 설치

1) yum 을 이용한 다운로드 및 설치
# yum -y install postgresql-server --downloadonly --downloaddir=./

Loaded plugins: product-id, search-disabled-repos, security, subscription-manager
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package postgresql-server.x86_64 0:8.4.20-7.el6 will be installed
--> Processing Dependency: postgresql-libs(x86-64) = 8.4.20-7.el6 for package: postgresql-server-8.4.20-7.el6.x86_64
--> Processing Dependency: postgresql(x86-64) = 8.4.20-7.el6 for package: postgresql-server-8.4.20-7.el6.x86_64
--> Processing Dependency: libpq.so.5()(64bit) for package: postgresql-server-8.4.20-7.el6.x86_64
--> Running transaction check
---> Package postgresql.x86_64 0:8.4.20-7.el6 will be installed
---> Package postgresql-libs.x86_64 0:8.4.20-7.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================================
 Package                              Arch         Version               Repository         Size
====================================================================================================
Installing:
 postgresql-server                    x86_64       8.4.20-7.el6          base               3.4 M
Installing for dependencies:
 postgresql                           x86_64       8.4.20-7.el6          base               2.6 M
 postgresql-libs                      x86_64       8.4.20-7.el6          base               202 k

Transaction Summary
====================================================================================================
Install       3 Package(s)

Total download size: 6.2 M
Installed size: 29 M
Downloading Packages:
(1/3): postgresql-8.4.20-7.el6.x86_64.rpm                                | 2.6 MB     00:00   
(2/3): postgresql-libs-8.4.20-7.el6.x86_64.rpm                           | 202 kB     00:00   
(3/3): postgresql-server-8.4.20-7.el6.x86_64.rpm                         | 3.4 MB     00:00   
------------------------------------------------------------------------------------------------------
Total                                                                     7.1 MB/s | 6.2 MB     00:00   
exiting because --downloadonly specified

2) 계정 확인
postgrepsql rpm 설치하면 "postgres" 계정을 생성한다.

# cat /etc/passwd | grep postgres

(*) 이후 모든 작업은 "postgres" 계정으로 실행한다.

3) 데이터베이스 생성 경로 지정
# vi ~postgres/.bash_profile
PGDATA=/var/lib/pgsql/data
export PGDATA

2. (master) initdb 실행
postgres 기본 DB를 생성하는 명령어. 기본 DB 생성한다. (master only)
# initdb

3. (master) postgresql 서버 실행
# pg_ctl start
# ps -ef | grep postgres

4. (master) 사용자 DB 생성
# psql -> create database mydb; select * from pg_database;

5. (master) 복제 사용자 생성
# psql -> CREATE ROLE repluser WITH REPLICATION PASSWORD 'password' LOGIN

6. (master) postgresql.conf 설정
# vi PGDATA/postgresql.conf
==>
listen_addresses = '*'
wal_level = 'hot_standby'
max_wal_senders = 3
wal_keep_segments = 64
hot_standby = on

- max_wal_senders: 운영서버를 바라보는 대기서버의 개수보다 조금 많게 지정
- wal_keep_segments: 마스터 서버 디렉토리에 보관할 최근 WAL 파일의 수,
   archive_mode 값이 off 되어 있다면, 서버가 재 시작되고 난 다음부터 대기서버를 구축 할 때까지 쌓일 트랜잭션 로그 조각 파일의 개수보다 많아야 합니다.
  일단, checkpoint_segments 값의 서너배 정도로 넉넉하게 지정. 이럴 만한 공간이 $PGDATA/pg_xlog 쪽에 없다면, archive_mode 값을 on 해서 버릴 트랜잭션 로그 조각들을 따로 보관해 두어야 합니다. 이 값에 대해서는 관리자가 잘 성해야 대기서버를 구축 할 때 좀 더 편해집니다.

7. (master) pg_hba.conf : 복제 DB 유저가 대기서버에서 운영 서버로 접속 가능하도록 접근 권한을 부여하는 일.
# vi $PGDATA/pg_hba.conf
==>
# repluser not allow to connect to database
local   all             repluser                                reject
host    all             repluser        0.0.0.0/0               reject
# localhost replication test
local   replication     repluser                                trust
# Master IP
host    replication     repluser         192.168.16.128/32        trust
# Standby IP
host    replication     repluser         192.168.16.129/32        trust

8. (master) postgresql 서버 재실행
# pg_ctl restart
# ps -ef | grep postgres

9. (standby)
2-1) 운영 서버를 그대로 백업해서 대기 서버에 운영에 필요한 파일들을 해당 호스트에 가져오는 것입니다. 가장 손 쉬운 방법은 pg_basebackup 명령을 이용하는 것입니다.
(The directory /var/lib/pgsql/data should be empty)
# (예) pg_basebackup -h MASTER -D /var/lib/pgsql/9.x/data -U repluser -v -P --xlog-method=stream
# pg_basebackup -h 192.168.16.128 -U repluser -D /var/lib/pgsql/data


10. (standby) recovery.conf 설정
# vi $PGDATA/recovery.conf
=>
standby_mode = 'on'
primary_conninfo = 'host=192.168.16.128 user=repluser password=password'
trigger_file = '/tmp/postgresql.trigger.5432' ## failover trigger
recovery_target_timeline = 'latest'

- 이 recovery.conf 파일을 운영서버 쪽 어느 한 곳에 두고 primary_conninfo 설정값에 있는 마스터 서버 주소를 바꾸어줍니다.
(나중에 운영 서버를 대기 서버로 재구축 없이 바로 사용하려고 할 때 이 파일이 미리 있으면 편합니다.)

11. (standby) postgresql 서버 실행
# pg_ctl start
# ps -ef | grep postgres

12. (master/standby) 모니터링
# ps -ef | grep sender   (master)
# ps -ef | grep receiver (standby)

13. replication test / failover test / replication 모니터링
# psql
select * from pg_stat_replication;

1) (standby) failover test (recovery.conf -> recovery.done 으로 변경됨)
# touch /tmp/postgresql.trigger.5432

# ls -l recovery.*

-rw-r--r-- 1 postgres dba   136  8월 27 02:33 recovery.done


(*) Log-Shipping 복제 구성 (참조)
- postgres 계정 작업

1. (standby) WAL 파일을 쌓아둘 디렉토리 설정
# mkdir /var/lib/pgsql/archives
# chown postgres:postgres /var/lib/pgsql/archives
# chmod 700 /var/lib/pgsql/archives

2. (standby) recovery.conf 파일에 다음 라인 추가
# vi /var/lib/pgsql/data/recovery.conf
==>
restore_command = 'cp /var/lib/pgsql/archives/%f %p'
archive_cleanup_command = 'pg_archivecleanup /var/lib/pgsql/archives %r'

3. (master) 비밀번호 입력 없이 scp가 동작하도록 설정
# ssh-keygen
# ssh-copy-id -i /var/lib/pgsql/.ssh/id_rsa.pub postgres@STANDBY
  - ssh-copy-id 명령은 대상 계정의 authorized_keys 파일에 원하는 키를 등록한다.

4. (master) WAL 파일 전송 설정
# vi /var/lib/pgsql/data/postgresql.conf
==>
archive_command = 'scp -i /var/lib/pgsql/.ssh/id_rsa %p postgres@STANDBY:/var/lib/pgsql/archives/%f'
archive_timeout = 30

- %p는 archive(WAL) 파일의 full path이고 %f는 파일의 이름이다.
- 마스터 서버를 재시작 하면, 스탠바이 서버의 지정된 디렉토리에 파일이 쌓이는 것을 확인할 수 있다.

5. Failover / Failback
- 마스터 서버에 스키마 혹은 row를 추가한다면, 곧바로 스탠바이 서버에 같은 내용이 적용된 것을 확인할 수 있을 것이다.
- 마스터 서버에 장애가 발생했을 때 어떻게 스탠바이 서버를 써먹을 수 있는지 (Failover)
- 마스터 서버에 발생했던 장애가 복구된 이후 어떻게 최초의 상황으로 돌아갈 수 있는지 (Failback)

1) Failover
- 스탠바이 서버를 운영 서버로 전환하는 방법은 두 가지가 있는데 하나는 pg_ctl promote 명령어를 사용하는 방법이고,
또 하나는 recovery.conf 파일에 trigger_file 옵션을 이용하는 방법이다.
trigger_file에 경로를 등록해 놓으면 해당 경로에 파일이 생성되었을 때(touch 등으로), 스탠바이 서버가 새로운 마스터 서버로 승격된다.

- trigger_file = '/path/of/triggerfile'
- 스탠바이 서버를 승격시킬때는 기존 마스터 서버가 확실하게 다운된 상태인지 확인해야 한다.
만약 마스터 서버가 살아있는 상태에서 스탠바이 서버를 승격시킬 경우, 데이터 손실 등의 예상치 못한 문제가 발생할 수 있으니 주의가 필요하다.

- Auto Failover: 위의 방법은 모두 수동으로 진행해야 하는 방법이고, 만약 자동으로 Failover를 하고 싶다면 다른 도구나 방법을 강구해야 한다.

2) Failback
- 기본적으로는 Failback을 위해서 특별한 기능이 제공되지 않는다. 따라서 다음과 같이 번거로운 단계를 거쳐야 한다. (?)

- 마스터 서버의 장애가 복구 되면 이 서버를 스탠바이 서버로 구축한다.
- 새 마스터 서버(기존 스탠바이 서버)를 강제로 다운시킨다.
- 새로 구축된 스탠바이 서버를 다시 마스터 서버로 승격 시킨다.
- 스탠바이 서버를 새로 구축한다.

No comments:

Post a Comment

◈ Recent Post

▷ UITest demo with TestOne (Mobile, Keypad and Drag until found tip)

[ UITest Demo Environment ] 1. UITest Solution: TestOne 2. Description 데모 설명    How to use keypad, and to drag until found.     키패드를...

◈ Popular Posts