달력

3

« 2013/3 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

'2013/03'에 해당되는 글 3

  1. 2013.03.15 Backup & Restore
  2. 2013.03.13 Postgresql 9.2 Install 및 pg_hint_plan 적용
  3. 2013.03.13 PostgreSQL Streaming Replication
2013. 3. 15. 13:49

Backup & Restore Work/PostgreSQL2013. 3. 15. 13:49

대부분 데이터베이스가 그렇듯이... Postgresql도 백업과 복구가 존재한다.

백업은 크게 논리백업과 물리백업으로 나누어지고... 물리백업은 pg_basebackup 툴을 이용한 백업과 저수준 API를 이용한 백업으로 나누어진다.

 

논리 백업은 os 상에서 pg_dump 라는 uitl 로 하면 된다. 여러가지 옵션이 있어서 다르지만, 복구에 필요한 script가 파일로 생성되는 형태이다.

물리백업은 오라클의 hot backup 과 유사하다. pg_basebackup 을 이용한 간단한 방법이 있다. 검색하면 내용이 많이 나오는 듯.... 저수준 API를 이용한 방법은 psql 상에서 select pg_start_backup (...), select pg_stop_backup (...) 을 이용하게 된다. 마찬가지로 자세한 것은 google에...

 

이외에... PostgreSQL 8.3 이상 버전이면 BARMAN 이라는 백업복구툴을 이용할 수 있을 듯 하다.

([출처] PostgresDBA - http://www.postgresdba.com/bbs/board.php?bo_table=B13&wr_id=5)

 

 

 

 

:
Posted by Elick

Overview

 

Installation

USER
Commad
Description
root  
 yum updateOS Update
 rpm -Uvh http://yum.postgresql.org/9.2/redhat/rhel-6-x86_64/pgdg-centos92-9.2-6.noarch.rpmPostgresql 9.2 repository 등록
 yum install postgresql92 postgresql92-server postgresql92-contribPostgresql 9.2 install
 service postgresql-9.2 initdbPostgresql 데이터베이스 초기화
postgres  
 postgresql.conf, pg_hba.conf 수정기본 설정
root  
 service postgresql-9.2 startPostgresql Servcie 실행
 wget "http://en.sourceforge.jp/frs/redir.php?m=iij&f=%2Fpghintplan%2F57713%2Fpg_hint_plan92-1.0.0-1.el6.x86_64.rpm"pg_hint_plan download
 yum localinstall pg_hint_plan92-1.0.0-1.el6.x86_64.rpmpg_hint_plan install
postgres  
 postgresql.conf 수정 : shared_preload_libraries = 'pg_hint_plan' 추가pg_hint_plan 환경 설정 변경
root  
 service postgresql-9.2 restartPostgresql 재시작
postgres  
 psqlpsql 실행
 

CREATE TABLE tbl (i int, j int);
INSERT INTO tbl SELECT x, x * 2 FROM generate_series (1, 10) x;
CREATE INDEX idx ON tbl (i);
VACUUM ANALYZE tbl;
EXPLAIN SELECT * FROM tbl WHERE i = 7;
/*+ IndexScan (tbl) */ EXPLAIN SELECT * FROM tbl WHERE i = 7;

실행계획 비교.

 

실행계획 확인

실행계획 확인
-bash-4.1$ psql
psql (9.2.3)
Type "help" for help.
postgres=# EXPLAIN SELECT * FROM tbl WHERE i = 7;
                    QUERY PLAN                    
---------------------------------------------------
 Seq Scan on tbl  (cost=0.00..1.12 rows=1 width=8)
   Filter: (i = 7)
(2 rows)
postgres=# /*+ IndexScan (tbl) */ EXPLAIN SELECT * FROM tbl WHERE i = 7;
                          QUERY PLAN                          
---------------------------------------------------------------
 Index Scan using idx on tbl  (cost=0.00..8.27 rows=1 width=8)
   Index Cond: (i = 7)
(2 rows)
postgres=# \q
-bash-4.1$


개인적 감상 : 이제 postgresql에서도 hint를 사용할 수 있다!!!


Hint List

  • 스캔 방식
    • SeqScan (table) 
      • 지정된 table에 대해 Seq Scan을 선택합니다.
    • TidScan (table) 
      • 지정된 table에 대해 Tid Scan을 선택합니다. 검색 조건에 ctid을 지정한 경우에만 유효합니다.
    • IndexScan (table index ...) 
      • 지정된 table에 대한 Index Scan을 선택합니다. index를 지정하면, 지정한 index에 비용이 최소가되는 Index Scan을 선택합니다. 
        그러나 index가 존재하지 않거나 지정된 index가 WHERE 절이나 JOIN 조건 등에 관련 않으면 Seq Scan을 선택합니다.
    • IndexOnlyScan (table index ...) 
      • 지정된 table에 대한 Index Onl??y Scan과 Index Scan 중 비용이 최소가되는 스캔 방식을 선택합니다.
         index를 지정하면, 지정한 index에서 Index Onl??y Scan과 Index Scan 중 비용이 최소가되는 스캔 방식을 선택합니다. 
        그러나 index가 존재하지 않거나 지정된 index가 WHERE 절이나 JOIN 조건 등에 관련 않으면 Seq Scan을 선택합니다. 
        또한 이러한 경우 외에도 index가 가지는 값뿐만 아니라 table의 값이 필요한 경우는 Index Scan을 선택합니다. PostgreSQL 9.2 이상이 필요합니다.
    • BitmapScan (table index ...) 
      • 지정된 table에 대해 Bitmap Scan을 선택합니다. 
        index를 지정하면, 지정한 index에 비용이 최소가되는 index를 선택합니다. 
        그러나 index가 존재하지 않거나 지정된 index가 WHERE 절이나 JOIN 조건 등에 관련 않으면 Seq Scan을 선택합니다.
    • NoSeqScan (table) 
      • 지정된 table에 대해 Seq Scan 이외 비용을 최소화하는 스캔 방식을 선택합니다. 
        그러나 다른 검색 방식을 선택할 수없는 경우는 Seq Scan을 선택합니다.
    • NoTidScan (table) 
      • 지정된 table에 대해 Tid Scan 이외 비용을 최소화하는 스캔 방식을 선택합니다.
    • NoIndexScan (table) 
      • 지정된 table에 대한 Index Scan 및 Index Onl??y Scan을 제외한 스캔 방식에서 비용을 최소화하는 스캔 방식을 선택합니다.
    • NoIndexOnlyScan (table) 
      • 지정된 table에 대한 Index Onl??y Scan 이외 비용을 최소화하는 스캔 방식을 선택합니다. (PostgreSQL 9.2 이상)
    • NoBitmapScan (table) 
      • 지정된 table에 대해 Bitmap Scan 이외 비용을 최소화하는 스캔 방식을 선택합니다.
  • 결합 방식
    • NestLoop (table table table ...) 지정된 table 간의 조인에 Nested Loop을 선택합니다.
    • HashJoin (table table table ...) 지정된 table 간의 조인에 Hash Join을 선택합니다.
    • MergeJoin (table table table ...) 지정된 table 간의 조인에 Merge Join을 선택합니다.
    • NoNestLoop (table table table ...) 지정된 table 간의 조인에 Nested Loop 이외의 결합 방식을 선택합니다.
    • NoHashJoin (table table table ...) 지정된 table 간의 조인에 Hash Join 이외의 결합 방식을 선택합니다.
    • NoMergeJoin (table table table ...) 지정된 table 간의 조인에 Merge Join 이외의 결합 방식을 선택합니다.
  • 조인 순서
    • Leading (table table table ...) 지정된 table을 지정한 순서대로 결합합니다.
  • GUC 매개 변수
    • Set (GUC 매개 변수 값) 쿼리 실행 계획을 작성하고있는 동안 만 지정된 GUC 매개 변수 값으로 변경합니다.


:
Posted by Elick
2013. 3. 13. 10:04

PostgreSQL Streaming Replication Work/PostgreSQL2013. 3. 13. 10:04

PostgreSQL Streaming Replication

Overview
  • 스트리밍 복제 (Streaming Replication)은 PostgreSQL 9.0 이상에서 사용 가능한 복제 기능.
  • Insert/Update/Delete, Create/Drop 가능한 1 개의 Master DB에 SELECT만 할 수 있는 여러 Standby DB에 복제하는 것
  • Standby DB의 변경 결과가 반영되기까지 약간의 지연이 있지만 비교적 지연은 적게, 마스터 DB에 영향 작은 복제 방식.
Purpose
  • 많은 SELECT Query의 Server 간 분산
  • Master DB 이상시 신속한 Fail over
  • Master DB의 Disk 장애에 대비한 실시간 Backup
9.0 에 비해 강화된 9.1의 기능
  • 동기화 복제 (변경 결과 도착 보장)
  • 기반 Backup의 간소화 (초기 Data 복제 도구)
  • 복제 상태를 확인하기위한 System view
  • Fail Over 지원 강화 (전용 명령 다른 Master Server에 다시 연결)
구성
  • Master 1EA(192.168.83.146), Slave 1EA(192.168.83.147)
구축 절차
  • Master
    • Postgresql 9.1 설치 (생략)
    • 복제용 사용자 생성

      -bash-4.1$ psql
      psql (9.1.7)
      Type "help" for help.
       
      postgres=# CREATE ROLE repl_user LOGIN REPLICATION PASSWORD 'xxxxxxxx';
      CREATE ROLE
      postgres=# \q
      -bash-4.1$
    • pg_hba.conf 수정

      vi $PGDATA/pg_hba.conf
      host all         all       127.0.0.1/32 trust
      host replication repl_user 127.0.0.1/32 md5
      host all         all       ::1/128      trust
      host replication repl_user ::1/128      md5
    • postgresql.conf 수정

      vi $PGDATA/postgresql.conf
      wal_level = hot_standby
      max_wal_sender = 2 # 대기 DB의 수 + 1
      # Archive 사용시
      archive_mode = on
      archive_command = 'cp "%p" /mnt/pgbackup/archive/"%f"'
      # Archive 미사용시
      archive_mode = off
      wal_keep_segments = 8 # 8-32가 기준
    • pg_basebackup 으로 Master를 Backup

      Base Backup
      -bash-4.1$
      -bash-4.1$ /usr/pgsql-9.1/bin/pg_basebackup -h localhost -U repl_user -D /mnt/pgbackup/cluster/ -xlog -c fast -P
      Password:
      35430/35430 kB (100%), 1/1 tablespace
      -bash-4.1$
  • Slave
    • Postgresql 9.1 설치 (생략)
    • Master의 Backup을 restore

      Master
      -bash-4.1$ rsync -ra /mnt/pgbackup/cluster/* root@192.168.83.147:/mnt/pgbackup/cluster/
      root@192.168.83.147's password:
      -bash-4.1$
      Slave
      -bash-4.1$ cd /mnt/pgbackup/cluster
      -bash-4.1$ cp -rf ./* /$PGDATA/
      -bash-4.1$
    • postgresql.conf 수정

      vi $PGDATA/postgresql.conf
      wal_level = minimal
      max_wal_sender = 0
      archive_command = 'cp "%p" /mnt/pgbackup/archive/"%f"'
      hot_standby = on
    • recovery.conf 생성

      vi $PGDATA/recovery.conf
      standby_mode = 'on'
      primary_conninfo = 'host=192.168.83.146 port=5432 user=repl_user password=xxxxxxxx'
  • Postgresql start
    • Master Start

      [root@localhost mnt]# service postgresql-9.1 start
      Starting postgresql-9.1 service:                           [  OK  ]
      [root@localhost mnt]#
    • Slave Start

      [root@localhost mnt]# service postgresql-9.1 start
      Starting postgresql-9.1 service:                           [  OK  ]
      [root@localhost mnt]#
복제상태 확인
  • Process
    • Master

      wal sender process 있는지 확인
      -bash-4.1$ ps -ef | grep postgres
      postgres  2927     1  0 Jan03 ?        00:00:00 /usr/pgsql-9.1/bin/postmaster -p 5432 -D /var/lib/pgsql/9.1/data
      postgres  2930  2927  0 Jan03 ?        00:00:00 postgres: logger process                                       
      postgres  2933  2927  0 Jan03 ?        00:00:01 postgres: writer process                                       
      postgres  2934  2927  0 Jan03 ?        00:00:01 postgres: wal writer process                                   
      postgres  2935  2927  0 Jan03 ?        00:00:00 postgres: autovacuum launcher process                          
      postgres  2936  2927  0 Jan03 ?        00:00:00 postgres: archiver process   last was 000000010000000000000006.00000020.backup
      postgres  2937  2927  0 Jan03 ?        00:00:00 postgres: stats collector process                              
      postgres  3194  2927  0 Jan03 ?        00:00:00 postgres: wal sender process repl_user 192.168.83.147(44356) streaming 0/7028558
      root      3227  2982  0 Jan03 pts/0    00:00:00 su - postgres
      postgres  3228  3227  0 Jan03 pts/0    00:00:00 -bash
      postgres  3695  3228  0 00:11 pts/0    00:00:00 ps -ef
      postgres  3696  3228  0 00:11 pts/0    00:00:00 grep postgres
      -bash-4.1$
    • Slave

      wal receiver process, startup process 있는지 확인.
      -bash-4.1$ ps -ef | grep postgres
      postgres  4212     1  0 Jan03 ?        00:00:00 /usr/pgsql-9.1/bin/postmaster -p 5432 -D /var/lib/pgsql/9.1/data
      postgres  4214  4212  0 Jan03 ?        00:00:00 postgres: logger process                                       
      postgres  4215  4212  0 Jan03 ?        00:00:00 postgres: startup process   recovering 000000010000000000000007
      postgres  4216  4212  0 Jan03 ?        00:00:01 postgres: writer process                                       
      postgres  4217  4212  0 Jan03 ?        00:00:00 postgres: stats collector process                              
      postgres  4218  4212  0 Jan03 ?        00:00:02 postgres: wal receiver process   streaming 0/7028558           
      root      4277  2961  0 Jan03 pts/0    00:00:00 su - postgres
      postgres  4278  4277  0 Jan03 pts/0    00:00:00 -bash
      postgres  4565  4278  9 00:12 pts/0    00:00:00 ps -ef
      postgres  4566  4278  0 00:12 pts/0    00:00:00 grep postgres
      -bash-4.1$

Fail Over
  • Master Service 중지

    Maseter Postgresql stop
    -bash-4.1$
    -bash-4.1$ exit
    logout
    [root@localhost mnt]# service postgresql-9.1 stop
    Stopping postgresql-9.1 service:                           [  OK  ]
    [root@localhost mnt]#
  • Slave 에서 DDL 실행 : 실패

    Slave Postgresql 상태 확인 및 DDL 실행
    -bash-4.1$
    -bash-4.1$ exit
    logout
    [root@localhost mnt]# service postgresql-9.1 status
     (pid  4212) is running...
    [root@localhost mnt]# su - postgres
    -bash-4.1$ psql -d db_test_01
    psql (9.1.6)
    Type "help" for help.
    db_test_01=# create table t_test_02 (col1 int);
    ERROR:  cannot execute CREATE TABLE in a read-only transaction
    db_test_01=# \q
    -bash-4.1$
  • pg_ctl promote 실행

    -bash-4.1$
    -bash-4.1$ /usr/pgsql-9.1/bin/pg_ctl promote -D $PGDATA
    server promoting
    -bash-4.1$
  • Slave 에서 DDL 실행 : 성공

    -bash-4.1$
    -bash-4.1$ psql
    psql (9.1.6)
    Type "help" for help.
    postgres=# create table t_test_02 (col1 int);
    CREATE TABLE
    postgres=# \q
    -bash-4.1$


Reference : 
http://lets.postgresql.jp/documents/technical/replication/1/


개인적 소감 : 생각보다 간단한 복제 설정이었음. 극단적인 환경에서 사용해보지 않아 성능적인 부분은 보장할 수 없지만, 평범한 환경에서라면 충분히 쓸만한 듯 함.

:
Posted by Elick