[DB기술노트82회] PostgreSQL 9.6 (Backup & Recovery)


1.   문서 개요


요즘 Mysql, Maria, PostgreSQL등 오픈소스DB들이 큰 인기를 얻고 있습니다. 이전부터 오픈소스DB는 존재하였지만, 속도가 느릴 것이다, 안정적이지 못할 것이다, 신뢰할 수 없다 라는 생각에 많이 사용하지 않았습니다. 하지만 요즘 오픈소스 DB의 문제점들에 대하여 많은 발전과 개선이 되었으며, 손쉬운 관리가 가능하고, 비용 또한 절감할 수 있기 때문에 더더욱 관심을 받고 있습니다.

이번 화에서는 오픈소스DB PostgreSQL의 간단한 아키텍쳐 설명과 백업 복구 방법에 대해 전달하고자 합니다.

 

2.     PostgreSQL?


 

PostgreSQL은 북미와 일본 사이에서 인기있는 객체-관계형 데이터베이스 입니다. 최초 1985년 버클리 대학 마이클 스톤브레이커 교수가 주도한 POSTGRES 프로젝트(lngres 기반)부터 파생되었으며, 1994Postgresql95 (SQL 지원)이라는 이름으로 릴리즈 되었고, 1996PostgreSQL으로 출시하였습니다. 최초에는 일반적으로 Postgre라고 불렀지만, SQL을 지원하기 시작하면서 Postgre 뒤에 SQL을 덧붙여 PostgreSQL이라고 부르기 시작하였습니다. PostgreSQL은 오픈소스 프로젝트이며, 커뮤니티 (https://www.postgresql.org/, http://www.postgresdba.com )에서 각자의 지식들을 자발적으로 공유하기를 권장하고 있으며, 각종 자료 및 설치파일을 다운로드 할 수 있습니다.


 

2.1.  PostgreSQL 아키텍쳐

 


PostgresSQLInstance – Server Process

 

2.1.1. Postmaster

Postmaster Supervisor 데몬으로서 서버를 기동, 중지 하기 위한 필수 프로세스 입니다. Client로부터 Connect요청에 대한 인증 및 허가를 수행하고, postgre 프로세스와 1:1로 할당합니다. 서버를 기동하게 되면 Postmaster 프로세스는 $PGDATA 경로의 Postmaster.pid 을 생성하게 되는데, 이 파일은 Postmaster 프로세스가 역할 수행을 위한 필요한 정보들을 저장하고, Postmaster는 이 파일을 참조하여 전체적으로 DATABASE를 관리합니다. (postmaster pid, 기동시간, listen_address, shared memory segment id ) 이 파일은600권한으로 생성되며, pg_ctl 명령 사용 시 해당 파일의 유무로 서버 기동 여부를 판단합니다.

 

2.1.2. Postgres

데이터베이스 파일을 관리하고, 데이터베이스를 사용할 수 있도록 기반 작업들을 준비하는 프로세스 입니다. 클라이언트로부터 받은 SQL을 전달 및 결과 데이터를 추출하는 역할을 하며, Storage ManagerUtility 프로세스에게 수행 호출 하는 역할을 하는 프로세스입니다. Dedicate 방식으로 User1:1Connect 합니다.

 

PostgreSQL Instance – System Memory

 

2.1.3. Shared Buffer

Disk의 데이터와 데이터의 변경 사항을 캐싱하는 메모리 공간입니다.

1G 이상인 경우 1/4 을 권장하고 있으며(Windows는 비효율 발생으로 64MB ~ 512MB 권장), $PGDATA/postgresql.conf 파일의 shared_buffers 파라미터 값에 의해 적용됩니다.

 

2.1.4. WAL Buffer

Write ahead log의 약자이며, 세션들이 수행하는 트랜젝션에 대한 변경 로그를 케싱하는 메모리 공간입니다.(복구를 위한 영역) 트렌젝션이 Commit 시에 $PDATA/pg_xlog, $PGDATA/pg_clog에 기록되며, 보통 shared pool1/32 을 권장합니다. $PGDATA/postgresql.confWAL_SIZE 파라미터로 설정할 수 있습니다

 

2.1.5. CLOG Buffer

Commit log의 약자이며, 트렌젝션 상태 정보를 캐싱하는 메모리 공간입니다. Commit log는 모든 트렌젝션의 commit 상태를 가지고(XID Mapping Table) 트렌젝션이 commit되었는지 여부를 나타냅니다.

해당 영역은 사이즈를 설정할 수 있는 매개변수는 없으며, 데이터베이스 엔진에 의해 자동 관리 됩니다.

2.1.6. Lock Space

PostgreSQL 인스턴스가 사용 하는 모든 Lock 정보를 저장합니다. 이 영역은 Background 서버 및 user 프로세스에서 공유됩니다.

 

 

Postgresql Instance – Utility Process

 

2.1.7. BG Writer

OracleDBWR 프로세스와 유사하며, Shared_buffer에 변경된 버퍼(dirty Buffer)를 디스크에 기록하는 역할을 합니다(Log ahead 기법에 의거하여 check point 발생 시). Disk에 기록된 Buffer들은 LRU 알고리즘을 통해 관리됩니다.

 

2.1.8. WAL Writer

WAL Buffer의 내용을 WAL Files에 저장하는 프로세스입니다. 모든 트렌젝션 Commit 데이터는 WAL Writer 프로세스에 의해 저장됩니다.

 

2.1.9. Archiver

디스크의 트랜젝션 로그를 아카이빙 하는 프로세스 입니다. 로그스위칭 시 발생하여 설정된 경로에 archive 파일을 생성합니다.

 

2.1.10.         Autovacuum Lancher

선택적 프로세스이며(autovacuum 파라미터 값에 의하여) 다수의 Autovacumm worker Process를 생성하며 Unsued Memory 해소, 통계정보 갱신, 데이터 손실을 예방하기 위한 Object Vacuum 수행합니다.

 

2.1.11.         SYS Logger

모든 프로세스의 정보를 $PGDATA/pg_log 디텍토리에 기록합니다.(Utility process, User Backends process, Postmaster Deamon)

 

3.     Backup & Recovery

 

3.1.  파일시스템 백업 & 복구

PostgreSQL DATA 디렉토리에 모든 데이터를 저장하고 관리합니다. 용량이 많지 않는 데이터들은 SQL DUMP로 받아 손쉽게 백업받아 복구할 수 있지만, 대용량 데이터인 경우에는 SQL DUMP보다 파일 시스템을 통째로 백업 받는 것이 복구시에 속도가 더 빠를 수 있습니다. 하지만, 제약사항이 존재합니다. 첫째, 반드시 데이터베이스가 종료 된 상태에서 백업을 수행해야 하며, 둘째, 특정 데이터베이스만 백업되지 않고, 전체 백업을 해야 합니다. 마지막으로, 이기종간은 불가능 합니다(Unix-Windwows).

 

3.1.1. 실습 환경

OS Version

RHEL 7.4 64 Bit

DB Version

PostgreSQL 9.6.10

CPU

4

Memory

4GB

 

3.1.2. PostgreSQL Shutdown

[goodus@postgresql96 ~]$ pg_ctl -D $PGDATA -mf stop

waiting for server to shut down.... done

server stopped

 

 

3.1.3. Data 디렉터리 백업

[goodus@postgresql96 ~]$ cd $PG_HOME

[goodus@postgresql96 pgsql]$ ls -dl data

drwx------. 20 goodus dba 4096 Sep  2 13:54 data

[goodus@postgresql96 pgsql]$ tar -zcvf data.tar data/

n  Data 디렉토리를 전체 백업

 

3.1.4. 기존 DATA 디렉토리 삭제

[goodus@postgresql96 pgsql]$ rm -rf data/

 

[goodus@postgresql96 pgsql]$ pg_ctl -D $PGDATA -mf start

pg_ctl: directory "/home/goodus/pgsql/data" does not exist

n  Data 디렉토리가 없어 기동되지 않음.

 

3.1.5. Tar 복구

[goodus@postgresql96 pgsql]$ ls –al data*

-rw-r--r--.  1 goodus dba 155021005 Sep  2 13:53 data.tar

 

[goodus@postgresql96 pgsql]$ tar -xvf data.tar

data/

data/pg_xlog/

data/pg_xlog/archive_status/

data/pg_xlog/000000010000000000000001

data/global/

data/global/pg_control

data/global/1262

이하 생략

 

[goodus@postgresql96 pgsql]$ ls -dl data

drwx------. 20 goodus dba 4096 Sep  2 13:54 data

n  동일 경로에 data 디렉토리 원복

 

3.1.6. PostgreSQL Start

 

[goodus@postgresql96 pgsql]$ pg_ctl -D $PGDATA -mf start

server starting

[goodus@postgresql96 pgsql]$ 2018-09-02 13:54:56 KSTLOG:  redirecting log output to logging collector process

2018-09-02 13:54:56 KSTHINT:  Future log output will appear in directory "pg_log".

n  정상 기동 확인

 

3.1.7. 데이터 확인

[goodus@postgresql96 pgsql]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

 

goodus=# \dt

            List of relations

 Schema |     Name      | Type  | Owner

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

 public | backup_1      | table | goodus

 public | backup_t      | table | goodus

 public | backup_test   | table | goodus

 public | imsi_backup_t | table | goodus

 public | t             | table | goodus

 public | test          | table | goodus

 public | test1         | table | goodus

 public | test2         | table | goodus

 public | tt            | table | goodus

 public | ttt           | table | goodus

(10 rows)

 

goodus=# select * from tt;

 

 idx  |          random_string              |      test_date

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

    1 | 193c1fc6a20acdf735f092637e61332c   | 2018-06-01 00:00:00

    2 | 9b09eba64b5fd62b272c1124227b58ea   | 2018-06-01 01:00:00

    3 | 344de96ac29f990cf2f6fc27608bdc08   | 2018-06-01 02:00:00

    4 | da77ce9b2598eeda6d5cd3c1102eda67   | 2018-06-01 03:00:00

 

n  데이터 정상 출력

 

 

3.2.  SQL Dump 백업 & 복구

해당 방법은 SQL을 이용하여 파일을 생성하는 것이며, 덤프 수행 시점의 동인한 데이터베이스로 복구가 가능합니다. PostgreSQL에서는 PG_DUMP 유틸리티를 지원하며 스크립트 파일이나, 아카이브 파일로 추출할 수 있습니다. 특정 데이터베이스를 선택하여 백업 및 복구 할 수 있다는 장점이 있고, 백업하려는 테이블의 읽기 엑세스 권한이 있어야 합니다. 만약, 데이터베이스 전체를 백업받는 경우에는 슈퍼유저(postgres)로 사용해야 합니다. 또한, DUMPSQL, File형태로 백업 받을 수 있으며, PG_RESTORE 유틸리티를 이용하여 복원이 가능합니다.

 

3.2.1. PG_DUMP & PG_RESTORE 옵션

 

1) PG_DUMP / pg_dump [connection-option...] [option...] [dbname]

options

 

-a
--data-only

-b
--blobs

-c
--clean

-C
--create

-E encoding
--encoding=encoding

-f file
--file=file

-F format
--format=format

p
plain

c
custom

d
directory

t
tar

-j njobs
--jobs=njobs

-n schema
--schema=schema

-N schema
--exclude-schema=schema

-o
--oids

-O
--no-owner

-R
--no-reconnect

-s
--schema-only

-S username
--superuser=username

-t table
--table=table

-T table
--exclude-table=table

-v
--verbose

-V
--version

-x
--no-privileges
--no-acl

-Z 0..9
--compress=0..9

--binary-upgrade

--column-inserts
--attribute-inserts

--disable-dollar-quoting

--disable-triggers

--enable-row-security

--exclude-table-data=table

--if-exists

--inserts

--lock-wait-timeout=timeout

--no-security-labels

--no-synchronized-snapshots

--no-tablespaces

--no-unlogged-table-data

--quote-all-identifiers

--section=sectionname

--serializable-deferrable

--snapshot=snapshotname

--strict-names

--use-set-session-authorization

-?
--help

-d dbname
--dbname=dbname

-h host
--host=host

-p port
--port=port

-U username
--username=username

-w
--no-password

-W
--password

--role=rolename

l  자세한 설명은 https://www.postgresql.org/docs/9.6/static/app-pgdump.html 참조

 

2) PG_STORE / pg_restore [connection-option...] [option...] [filename]

Options

filename

-a
--data-only

-c
--clean

-C
--create

-d dbname
--dbname=dbname

-e
--exit-on-error

-f filename
--file=filename

-F format
--format=format

c
custom

d
directory

t
tar

-I index
--index=index

-j number-of-jobs
--jobs=number-of-jobs

-l
--list

-L list-file
--use-list=list-file

-n namespace
--schema=schema

-O
--no-owner

-P function-name(argtype [, ...])
--function=function-name(argtype [, ...])

-R
--no-reconnect.

-s
--schema-only

-S username
--superuser=username

-t table
--table=table

-T trigger
--trigger=trigger

-v
--verbose

-V
--version

-x
--no-privileges
--no-acl

-1
--single-transaction

--disable-triggers

--enable-row-security

--if-exists

--no-data-for-failed-tables

--no-security-labels

--no-tablespaces

--section=sectionname

--strict-names

--use-set-session-authorization

-?
--help

-h host
--host=host

-p port
--port=port

-U username
--username=username

-w
--no-password

-W
--password

--role=rolename

 

 

l  자세한 설명은 https://www.postgresql.org/docs/9.6/static/app-pgdump.html 참조

 

3.2.2. 실습 환경

OS Version

RHEL 7.4 64 Bit

DB Version

PostgreSQL 9.6.10

CPU

4

Memory

4GB

 

3.2.3. 대상 Database 확인

[goodus@postgresql96 pgsql]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

goodus=# \l+

                                                                    List of databases

   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   |  Size   | Tablespace |                Description

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

 goodus    | goodus   | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 485 MB  | pg_default |

 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 7343 kB | pg_default | default administrative connection database

 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7233 kB | pg_default | unmodifiable empty database

           |          |          |             |             | postgres=CTc/postgres |         |            |

 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7233 kB | pg_default | default template for new databases

           |          |          |             |             | postgres=CTc/postgres |         |            |

(4 rows)

 

à goodus database 대상 선정

 

3.2.4. PG_DUMP 수행

[goodus@postgresql96 pgsql]$ pg_dump -h 172.40.40.197 -p 5432 -U goodus -d goodus -w -Fc -v -f goodus.dump

 

n   h : host , p : port, U : user name, d : database name, w : password 생략, Fc : Custem 형식(Dump),  v : 상세정보 출력 f : 파일 이름

 

pg_dump: last built-in OID is 16383

pg_dump: reading extensions

pg_dump: identifying extension members

pg_dump: reading schemas

pg_dump: reading user-defined tables

pg_dump: reading user-defined functions

pg_dump: reading user-defined types

pg_dump: reading procedural languages

pg_dump: reading user-defined aggregate functions

pg_dump: reading user-defined operators

pg_dump: reading user-defined access methods

pg_dump: reading user-defined operator classes

..이하 생략

 

[goodus@postgresql96 pgsql]$ vi goodus.dump

 

PGDMP^A^M^@^D^H^A^A^A^@^@^@^@^L^@^@^@^@^K^@^@^@^@^N^@^@^@^@^B^@^@^@^@^H^@^@^@^@v^@^@^@^@^@^@^@^@^@^F^@^@^@goodus^@^F^@^@^@9.6.10^@^F^@^@^@9.6.10^@^\^@^@^@^@^S^L^@^@^@^@^@^@^@^@^A^@^@^@0^@^A^@^@^@0^@^H^@^@^@ENCODING^@^H^@^@^@ENCODING^@^B^@^@^@^@^^^@^@^@SET client_encoding = 'UTF8';

^@^@^@^@^@^A^A^@^@^@^A^A^@^@^@^A^A^@^@^@^@^@^@^@^@^@^E^@^@^@false^A^A^@^@^@^C^@^@^@^@^@^@^@^@^@^T^L^@^@^@^@^@^@^@^@^A^@^@^@0^@^A^@^@^@0^@

^@^@^@STDSTRINGS^@

^@^@^@STDSTRINGS^@^B^@^@^@^@(^@^@^@SET standard_conforming_strings = 'on';

^@^@^@^@^@^A^A^@^@^@^A^A^@^@^@^A^A^@^@^@^@^@^@^@^@^@^E^@^@^@false^A^A^@^@^@^C^@^@^@^@^@^@^@^@^@^U^L^@^@^@^@^@^@^@^@^A^@^@^@0^@^A^@^@^@0^@

^@^@^@SEARCHPATH^@

^@^@^@SEARCHPATH^@^B^@^@^@^@8^@^@^@SELECT pg_catalog.set_config('search_path', '', false);

.. 이하 생략

n  바이너리 형식으로 저장되어 있음

 

[goodus@postgresql96 pgsql]$ ls -al goodus.dump

-rw-r--r--. 1 goodus dba 126410693 Sep  2 14:29 goodus.dump

n  Dump파일 생성 확인

 

3.2.5. Database Drop

[goodus@postgresql96 pgsql]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

goodus=# drop database goodus;

ERROR:  cannot drop the currently open database

현재 사용중인 Database임으로 Postgres User, Postgres DB 접속 후 수행

goodus=# \c postgres postgres   -- \c Database_name User_name

Password for user postgres:

You are now connected to database "postgres" as user "postgres".

postgres=# drop database goodus;

DROP DATABASE

 

goodus=# \l+

                                                                    List of databases

   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   |  Size   | Tablespace |                Description

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

postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 7343 kB | pg_default | default administrative connection database

 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7233 kB | pg_default | unmodifiable empty database

           |          |          |             |             | postgres=CTc/postgres |         |            |

 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7233 kB | pg_default | default template for new databases

           |          |          |             |             | postgres=CTc/postgres |         |            |

(4 rows)

 

n  Goodus database 삭제 확인

 

 

3.2.6. PG_RESTORE 수행

[goodus@postgresql96 pgsql]$ ls -al goodus.dump

-rw-r--r--. 1 goodus dba 126410693 Sep  2 14:29 goodus.dump

 

[goodus@postgresql96 pgsql]$ psql -U postgres -d postgres

Password for user postgres:

psql.bin (9.6.10)

Type "help" for help.

postgres=# create database goodus;

CREATE DATABASE

postgres=# \q

n  깡통 goodus Database 생성

 

[goodus@postgresql96 pgsql]$ pg_restore -h 172.40.40.197 -p 5432 -U goodus -d goodus -w goodus.dump

n  PG_RESTORE 수행

 

3.2.7. 데이터 확인

[goodus@postgresql96 pgsql]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

 

goodus=# \dt

            List of relations

 Schema |     Name      | Type  | Owner

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

public | backup_1      | table | goodus

public | backup_t      | table | goodus

public | backup_test   | table | goodus

public | imsi_backup_t | table | goodus

public | t             | table | goodus

public | test          | table | goodus

public | test1         | table | goodus

public | test2         | table | goodus

public | tt            | table | goodus

public | ttt           | table | goodus

(10 rows)--

 

goodus=# \l+

                                                                    List of databases

   Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   |  Size   | Tablespace |                Description

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

 goodus    | goodus   | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 485 MB  | pg_default |

 postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |                       | 7343 kB | pg_default | default administrative connection database

 template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7233 kB | pg_default | unmodifiable empty database

           |          |          |             |             | postgres=CTc/postgres |         |            |

 template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +| 7233 kB | pg_default | default template for new databases

           |          |          |             |             | postgres=CTc/postgres |         |            |

(4 rows)

 

n  데이터 복구 확인

 

 

3.3.  연속 아카이빙 및 PITR

 

Postgresql $PGDATA/pg_xlog/ 경로에 WAL 파일을 항상 관리합니다. 이 로그에는 데이터베이스의 데이터 파일에서 일어난 모든 변경 내용이 기록됩니다. 이 로그는 본래 충돌 안전을 보장하기 위한 목적으로 만들었지만(시스템 충돌 시 마지막 체크포인트 이후에 만들어진 로그 항목을 “리플레이” 하여 일관된 상태로 복구), BASE 데이터 파일 + WAL log를 통해 Recovery를 수행하여 PITR을 가능하게 합니다. 하지만, 이 방법은 아카이브용 용량 및 BASE 파일 관리 등 다소 관리가 다소 필요한 점이 있지만, 고 신뢰도가 요구되는 다수의 상황에서 많이 사용되는 기법입니다.

 

3.3.1. WAL 모드 확인 및 Archive 경로 생성

[goodus@postgresql96 data]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

 

goodus=# SELECT name, setting FROM pg_settings WHERE name IN ('archive_mode', 'archive_command', 'archive_timeout', 'wal_level', 'max_wal_senders');

 

     name        |  setting

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

archive_command  | (disabled)

archive_mode     | off

archive_timeout  | 0

max_wal_senders  | 0

wal_level        | minimal

(5 rows)

n  현재 설정되어 있지 않음

 

[goodus@postgresql96 data]$ mkdir /home/goodus/archive

n  아카이브를 저장할 디렉토리 생성

 

3.3.2. WAL 활성화

[goodus@postgresql96 data]$ cd $PGDATA

[goodus@postgresql96 data]$ pwd

/home/goodus/pgsql/data

[goodus@postgresql96 data]$ vi postgresql.conf

 

wal_level = replica          -- 9.6 이전에는 archive

archive_mode = on

archive_command = 'cp %p /home/goodus/archive/%f' 

max_wal_senders = 2

 

 

3.3.3. Replication connect 허용

[goodus@postgresql96 data]$ vi pg_hba.conf

 

host     replication     postgres        0.0.0.0/0               md5

 

n  PG_BASEBACKUP을 수행하기 위해서는 replication 을 설정해야 합니다.

n  Postgres의 계정에 대하여 모든 IP를 허용함

 

3.3.4. Postgresql 재기동

[goodus@postgresql96 data]$ pg_ctl -D $PGDATA -mf restart

waiting for server to shut down.... done

server stopped

server starting

[goodus@postgresql96 data]$ 2018-09-02 17:17:44 KSTLOG:  redirecting log output to logging collector process

2018-09-02 17:17:44 KSTHINT:  Future log output will appear in directory "pg_log".

n  재기동을 하여 수정한 postgresql.con 내용을 apply 합니다

 

3.3.5. WAL 반영 확인

postgres=# SELECT name, setting FROM pg_settings WHERE name IN ('archive_mode', 'archive_command', 'archive_timeout', 'wal_level', 'max_wal_senders');

     name        |            setting

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

archive_command  | cp %p /home/goodus/archive/%f

archive_mode     | on

archive_timeout  | 0

max_wal_senders  | 2

wal_level        | replica

(5 rows)

n  재기동 이후 WAL archive 적용됨

 

 

3.3.6. WAL 파일 확인

[goodus@postgresql96 data]$ cd /home/goodus/archive/

[goodus@postgresql96 archive]$ ls -al

total 16388

drwxr-xr-x. 2 goodus dba       38 Sep  2 17:21 .

drwx------. 7 goodus dba     4096 Sep  2 17:21 ..

-rw-------. 1 goodus dba 16777216 Sep  2 17:21 000000010000000000000034

 

3.3.7. Base Backup 생성

[goodus@postgresql96 basebackup]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

 

goodus=# select * from pitr_test order by 1 desc limit 3;

     create_date

---------------------

2018/09/02 17:42:01

2018/09/02 17:41:01

2018/09/02 17:40:01

n  1분에 1 rowinsert 하는 Table을 사전에 구성함

 

[goodus@postgresql96 ~]$ mkdir /home/goodus/basebackup

[goodus@postgresql96 ~]$ pg_basebackup -h 172.40.40.197 -p 5432 -U postgres -D /home/goodus/basebackup

Password:

NOTICE:  pg_stop_backup complete, all required WAL segments have been archived

n  17:42분경 BASE BACKUP 수행

 

[goodus@postgresql96 ~]$ cd /home/goodus/basebackup/

[goodus@postgresql96 basebackup]$ ls -al

total 64

drwxr-xr-x. 20 goodus dba  4096 Sep  2 17:42 .

drwx------.  8 goodus dba  4096 Sep  2 17:41 ..

-rw-------.  1 goodus dba   208 Sep  2 17:42 backup_label

drwx------.  6 goodus dba    54 Sep  2 17:42 base

drwx------.  2 goodus dba  4096 Sep  2 17:42 global

drwx------.  2 goodus dba    18 Sep  2 17:42 pg_clog

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_commit_ts

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_dynshmem

-rw-------.  1 goodus dba  4300 Sep  2 17:42 pg_hba.conf

-rw-------.  1 goodus dba  1636 Sep  2 17:42 pg_ident.conf

drwx------.  2 goodus dba  4096 Sep  2 17:42 pg_log

drwx------.  4 goodus dba    39 Sep  2 17:42 pg_logical

drwx------.  4 goodus dba    36 Sep  2 17:42 pg_multixact

drwx------.  2 goodus dba    18 Sep  2 17:42 pg_notify

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_replslot

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_serial

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_snapshots

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_stat

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_stat_tmp

drwx------.  2 goodus dba    18 Sep  2 17:42 pg_subtrans

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_tblspc

drwx------.  2 goodus dba     6 Sep  2 17:42 pg_twophase

-rw-------.  1 goodus dba     4 Sep  2 17:42 PG_VERSION

drwx------.  3 goodus dba    28 Sep  2 17:42 pg_xlog

-rw-------.  1 goodus dba    88 Sep  2 17:42 postgresql.auto.conf

-rw-------.  1 goodus dba 22308 Sep  2 17:42 postgresql.conf

n  PG_BASEBACKUP 명령 시점(17:42)PGDATA 전체가 Backup .

 

[goodus@postgresql96 basebackup]$ cd /home/goodus/archive/

[goodus@postgresql96 archive]$ ls -al

total 49160

drwxr-xr-x. 2 goodus dba      150 Sep  2 17:42 .

drwx------. 8 goodus dba     4096 Sep  2 17:41 ..

-rw-------. 1 goodus dba 16777216 Sep  2 17:39 000000010000000000000034

-rw-------. 1 goodus dba 16777216 Sep  2 17:42 000000010000000000000035

-rw-------. 1 goodus dba 16777216 Sep  2 17:42 000000010000000000000036

-rw-------. 1 goodus dba      305 Sep  2 17:42 000000010000000000000036.00000028.backup

n  xxxx.backup 파일은 base backup 수행 시점을 나타내주는 파일임

n  이 후의 archive 파일들은 PITR하기 위해 필수로 필요함

 

 

 

 

3.3.8. 복구시점 설정

 

goodus=# select now();

              now

-------------------------------

2018-09-02 17:50:51.872766+09

(1 row)

 

goodus=# select * from pitr_test order by 1 desc limit 5;

     create_date

---------------------

 2018/09/02 17:50:02

 2018/09/02 17:49:01

 2018/09/02 17:48:01

 2018/09/02 17:47:01

 2018/09/02 17:46:01

(5 rows)

 

2018-09-02 17:50:51.872766+09 시점으로 복구 계획 수립

 

3.3.9. Database crush

[goodus@postgresql96 ~]$ ps -ef |grep postgres

goodus   22603     1  0 17:39 pts/0    00:00:00 /home/goodus/pgsql/bin/postgres -D /home/goodus/pgsql/data

goodus   22604 22603  0 17:39 ?        00:00:00 postgres: logger process

goodus   22606 22603  0 17:39 ?        00:00:00 postgres: checkpointer process

goodus   22607 22603  0 17:39 ?        00:00:00 postgres: writer process

goodus   22608 22603  0 17:39 ?        00:00:00 postgres: wal writer process

goodus   22609 22603  0 17:39 ?        00:00:00 postgres: autovacuum launcher process

goodus   22610 22603  0 17:39 ?        00:00:00 postgres: archiver process   last was 000000010000000000000036

goodus   22611 22603  0 17:39 ?        00:00:00 postgres: stats collector process

goodus   23400  8201  0 17:53 pts/0    00:00:00 grep --color=auto postgres

[goodus@postgresql96 ~]$ kill -9 22603

[goodus@postgresql96 ~]$ ps -ef |grep postgres

goodus   23448  8201  0 17:54 pts/0    00:00:00 grep --color=auto postgres

n  필수 프로세스가 Kill 되면서 memory crush 상황 가정

 

3.3.10.         BASE BACKUP 받은 파일을 기존의 PGDATA 파일과 변경

[goodus@postgresql96 pgsql]$ cd $PGDATA

[goodus@postgresql96 pgsql]$ mv data data.bak

[goodus@postgresql96 pgsql]$ mkdir data

[goodus@postgresql96 pgsql]$ chmod 700 data

n  기존 PGDATA 영역 파일을 Rename

n  Data 디렉토리는 700 필수

 

[goodus@postgresql96 pgsql]$ cd /home/goodus/basebackup/

[goodus@postgresql96 basebackup]$ cp -ar ./* $PG_HOME/data

n  BASE BACKUP데이터를 PGDATA로 복사

 

[goodus@postgresql96 ~]$ cd $PG_HOME/data.bak/pg_xlog/

[goodus@postgresql96 pg_xlog]$ cp -p /home/goodus/pgsql/data.bak/pg_xlog/0* /home/goodus/pgsql/data/pg_xlog/

n  기존 PGDATA/pg_xlog 파일을 새로 구성한 pg_xlog로 복사

 

3.3.11.         Recovery.conf 생성

[goodus@postgresql96 pg_xlog]$ cd $PGDATA

 

[goodus@postgresql96 data]$ vi recovery.conf

restore_command = 'cp /home/goodus/archive/%f %p'

recovery_target_time = '2018-09-02 17:50:51 KST'

n  Recovery.conf 파일을 새로 생성하여 restore_command, recovery_target_time을 설정한다

n  복구 시점 설정 가능

 

3.3.12.         DB 기동

[goodus@postgresql96 pgsql]$ pg_ctl -D $PGDATA -mf start

server starting

You have new mail in /var/spool/mail/goodus

[goodus@postgresql96 pgsql]$ 2018-09-02 18:16:49 KSTLOG:  redirecting log output to logging collector process

2018-09-02 18:16:49 KSTHINT:  Future log output will appear in directory "pg_log".

 

[goodus@postgresql96 data]$ psql -U goodus -d goodus

Password for user goodus:

psql.bin (9.6.10)

Type "help" for help.

 

goodus=# select * from pitr_test order by 1 desc limit 5;

     create_date

---------------------

2018/09/02 17:50:02

2018/09/02 17:49:01

2018/09/02 17:48:01

2018/09/02 17:47:01

2018/09/02 17:46:01

(5 rows)

 

2018-09-02 17:50:51 시간으로 복구 됨.

 

[goodus@postgresql96 data]$ ls -al re*

-rw-r--r--. 1 goodus dba 101 Sep  2 18:10 recovery.done

 

복구 완료 후에 Recovery.conf 파일이 recovery.done 으로 이름이 변경되었다.

 

4.     참고자료

 

https://www.postgresql.org/docs/9.6

https://d2.naver.com/helloworld/227936

http://ktdsoss.tistory.com/162

 DATA기술팀  박성현 엔지니어

 

< 끝 >




#굿어스데이터 #GoodusData #DB기술노트 #Oralce #오라클 #PostgreSQL 9.6


"People make a better world with Data"

[Written by GoodusData / 굿어스데이터]



이 글을 공유하기

댓글

Designed by JB FACTORY