IT Japan

MariaDB 인스톨 본문

카테고리 없음

MariaDB 인스톨

swhwang 2016. 3. 21. 17:04
반응형

1. MariaDB 구성 가이드
MariaDB 5.5 구성의 모든 과정은 MySQL 5.5와 동일하다. 따라서 본 문서에서 설명된 모든 구성안들은 MySQL 5.5에서도 동일하게 사용될 수 있으며, 일부 내용은 MySQL 기준으로 설명되고 있다.

MariaDB의 구성은 크게 서버 당 단일(single) 인스턴스 환경과 복수(multi) 인스턴스 환경으로 나눌 수 있다.

1)     단일 인스턴스 환경 : 서버 당 하나의 MariaDB 인스턴스를 구성, MariaDB 설정 파일 my.cnf 에 하나의 인스턴스 설정만 사용된다.

2)     복수 인스턴스 환경 : 서버 당 여러 개의 MariaDB 인스턴스를 구성, MariaDB 설정 파일 my.cnf 에 여러 개의 인스턴스 설정이 사용된다.

보통 단일 또는 복수 인스턴스 구성에 따라서 디렉토리 구성 및 MariaDB 엔진 설정 파일(my.cnf)의 내용이 달라지지만, 표준 아키텍처는 단일 인스턴스 환경을 기본으로 한다.

1.1  인스턴스 설치
1.1.1  파일 시스템 구성
파일시스템은 운영상의 효율성과 안정성 확보를 위해 DBMS 엔진 영역과 데이터/로그 영역 및 백업 영역를 나누어 구성한다. 상세 구성은 다음과 같다.
1) DBMS 엔진 영역 표준 파티션
파티션 구분     영역     사이즈(GB)
Primary     /MARIA     20GB
2) DATA 영역 표준 파티션
파티션 구분     영역     사이즈(GB)
Primary     /MARIA_DATA     필요 크기에 따라 설정
3) LOG 영역 표준 파티션
파티션 구분     영역     사이즈(GB)     비고
Primary     /MARIA_LOG     30GB ~ 100GB    
※     데이터 변경량이 작은 시스템은 30GB 설정하고, 큰 시스템은 100GB로 설정한다.

1.1.2  설치 디렉토리 및 권한
MariaDB 설정에 필요한 주요 디렉토리 설정은 다음과 같다.
파티션 구분     디렉토리     설명
/MARIA     /MARIA/mariadb     Mariadb 엔진 디렉토리
/MARIA_DATA     /MARIA_DATA/DATA     Mariadb DATA 디렉토리
     /MARIA_DATA/tmpdir     Mariadb 임시파일 디렉토리
/MARIA_LOG     /MARIA_LOG/error
/MARIA_LOG/general
/MARIA_LOG/binary
/MARIA_LOG/slow
/MARIA_LOG/relay     Mariadb error로그
Mariadb general 로그
Mariadb binary로그
Mariadb slow 로그
Mariadb relay 로그

각 디렉토리의 권한 설정은 다음과 같다.
구분     소유     그룹
/MARIA     mysql     dba
/MARIA_DATA/DATA     mysql     dba
/MARIA_LOG     mysql     dba

1.1.3  MariaDB 설치
MariaDB Binary source 파일로 설치한다.
1.1.3.1  user 및 group 생성
1)     groupadd 로 dba 그룹생성 한다.
2)     useradd 로 mysql 계정생성  -g 옵션으로 group 을 dba로 설정 한다. 
3)     mysql user의 HOME은 시스템 기본 설정을 따른다.(/home/mysql)
4)     MySQL DBMS 관리 계정은 mysql:dba 하나를 기본으로 한다.

[mysql@adb1 ~]# groupadd dba
[mysql@adb1 ~]# useradd -g dba mysql
[mysql@adb1 ~]#
[mysql@adb1 ~]# cat /etc/group |grep dba
dba:x:505:mysql
[mysql@adb1 ~]# cat /etc/passwd |grep mysql
mysql:x:503:505::/home/mysql:/bin/bash

1.1.3.2  MariaDB 엔진 디렉토리 생성 및 압축 풀기
mkdir 을 사용하여 MariaDB 엔진 디렉토리를 생성한다. 그리고 MariaDB package를 MariaDB 디렉토리로 옮겨서 tar 를 사용하여 압축을 풀어 준 후 /MARIA/디렉토리로 mv 해주고, 이를 /MARIA/mariadb로 링크한다.
[mysql@adb1 ~]# tar zxvf mariadb-5.5.31-linux-x86_64.tar.gz
[mysql@adb1 ~]# mv mariadb-5.5.31-linux-x86_64 /MARIA/mariadb_5.5.31
[mysql@adb1 ~]# ln ?s /MARIA/mariadb_5.5.31 /MARIA/mariadb
               
1.1.3.3  디렉토리 권한 설정
chown 을 사용하여 MariaDB engine 디렉토리를 mysql계정 dba 그룹으로 설정한다.
# chown -R mysql.dba /MARIA/mariadb
[mysql@adb1 ~]# chown -R mysql.dba /MARIA/mariadb_5.5.31/
[mysql@adb1 ~]# chown -R mysql.dba /MARIA/mariadb
[root@adb1 mariadb_5.5.31]# ll /MARIA/mariadb
total 188
drwxr-xr-x  2 mysql dba   4096 Apr 13 22:14 bin
-rw-r--r--  1 mysql dba  17987 Mar  9 07:11 COPYING
drwxr-xr-x  4 mysql dba   4096 Apr 13 22:15 data
drwxr-xr-x  2 mysql dba   4096 Apr 13 22:15 docs
drwxr-xr-x  3 mysql dba   4096 Apr 13 22:14 include
-rw-r--r--  1 mysql dba   7370 Mar  9 07:11 INSTALL-BINARY
drwxr-xr-x  3 mysql dba   4096 Apr 13 22:15 lib
drwxr-xr-x  4 mysql dba   4096 Apr 13 22:14 man
drwxr-xr-x 10 mysql dba   4096 Apr 13 22:15 mysql-test
-rw-r--r--  1 mysql dba 114014 Mar  9 07:11 README
drwxr-xr-x  2 mysql dba   4096 Apr 13 22:15 scripts
drwxr-xr-x 27 mysql dba   4096 Apr 13 22:15 share
drwxr-xr-x  4 mysql dba   4096 Apr 13 22:15 sql-bench
drwxr-xr-x  2 mysql dba   4096 Apr 13 22:15 support-files

1.1.3.4  MariaDB install_db 실행
mysql_install_db 실행하여 데이터베이스를 생성한다.
[mysql@adb1 mariadb]# ./scripts/mysql_install_db --defaults-file=/etc/my.cnf --datadir=/MARIA_DATA/ --user=mysql
Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

./bin/mysqladmin -u root password 'new-password'
./bin/mysqladmin -u root -h accountdb password 'new-password'

Alternatively you can run:
./bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:
cd . ; ./bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd ./mysql-test ; perl mysql-test-run.pl

Please report any problems with the ./bin/mysqlbug script!

/MARIA_DATA 디렉토리에서 db 생성 파일을 확인한다. ( mysql , test )
[mysql@adb1 ~]# ll /MARIA_DATA/
합계 12
drwx------. 2 mysql dba 4096 2013-09-09 14:43 mysql
drwx------. 2 mysql dba 4096 2013-09-09 14:49 performance_schema
drwx------. 2 mysql dba 4096 2013-09-09 14:43 test

1.1.3.5  mysql_secure_installation실행 (보안스크립트)
mysql_secure_installation에 socket 경로를 수정 후 적용한다.

1) mysql_secure_installation 파일의 26, 27, 207, 379번째 라인 수정
[root@adb1 mariadb]#vi bin/mysql_secure_installation
basedir=/MARIA/mariadb
bindir=/MARIA/mariadb/bin

do_query() {
    echo "$1" >$command
    #sed 's,^,> ,' < $command  # Debugging
    $bindir/mysql --defaults-file=$config --socket=/MARIA_DATA/mysql.sock <$command
    return $?
}

prepare
#find_mysql_client
set_echo_compa

2) mysql_secure_installation실행하여 기본적인 보안 설정을 한다.
[root@adb1 mariadb]#./bin/mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user.  If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] Y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
... Success!

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
... Success!

By default, MySQL comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MySQL
installation should now be secure.

Thanks for using MySQL!

1.1.3.6  MariaDB 실행
1) MariaDB 엔진 디렉토리에서 support-files/mysql.server 스크립트 파일을 /etc/init.d/maria 로 copy한다
[mysql@adb1 ~]# cp -p /MARIA/mariadb /support-files/mysql.server /etc/init.d/maria

2) mysql.server로부터 복사된 maria 스크립트를 수정한다.
# 빨간 부문만 수정
...
basedir=/MARIA/mariadb
bindir=/MARIA/mariadb/bin
...


1.1.4  추가 보안 적용
1) /etc/my.cnf  권한은 640, 사용자 및 그룹은  mysql.dba 로 설정
chmod 와 chown 을 사용하여 권한 및 사용자 그룹을 변경한다.
[mysql@adb1 ~]# chown mysql.dba /etc/my.cnf
[mysql@adb1 ~]# ll /etc/my.cnf
-rw-r-----. 1 mysql dba 3465 2013-09-09 15:01 /etc/my.cnf

2) mysqld_safe 와 maria의 권한은 750으로 설정
chmod 를 사용하여 권한을 750으로 변경한다.
[root@adb1 ~]# chmod 750 /MARIA/mariadb/bin/mysqld_safe /MARIA/mariadb/bin/mysqld /etc/init.d/maria
[root@adb1 ~]# ll /etc/init.d/maria
-rwxr-x---. 1 mysql dba 1353 2013-09-09 15:23 /etc/init.d/maria


1.1.5  Log Rotate 설정
1) mysql-log-rotate 파일 설정
/MARIA/mariadb/support-files/mysql-log-rotate 파일을 /etc/logrotate.d/ 아래로 복사 한 후 파일 내용을 아래와 같이 수정한다.
[mysql@adb1 mariadb]$ vi /etc/logrotate.d/mysql-log-rotate
#slow query log
/MARIA_LOG/slow/mysql-slow-query.log {
        create 600 mysql dba
        notifempty
        daily
        rotate 30
        missingok
        copytruncate
    postrotate
        # just if mysqld is really running
        if test -x /MARIA/mariadb/bin/mysqladmin && \
           /MARIA/mariadb/bin/mysqladmin --socket=/MARIA_DATA/mysql.sock ping &>/dev/null
        then
           /MARIA/mariadb/bin/mysqladmin --socket=/MARIA_DATA/mysql.sock flush-logs
        fi
    endscript
}

#general log

/MARIA_LOG/general/mysql_general.log{
        create 600 mysql dba
        notifempty
        daily
        rotate 7
        missingok
        copytruncate
    postrotate
        # just if mysqld is really running
        if test -x /MARIA/mariadb/bin/mysqladmin && \
           /MARIA/mariadb/bin/mysqladmin --socket=/MARIA_DATA/mysql.sock ping &>/dev/null
        then
         /MARIA/mariadb/bin/mysqladmin --socket=/MARIA_DATA/mysql.sock flush-logs
        fi
    endscript
}

2) /etc/my.cnf 파일 수정
다음 내용을 추가한다.
[mysqladmin]
password = root
user= root


3) mysql-log-rotate 테스트
[mysql@adb1 mariadb]$ logrotate -f /etc/logrotate.d/mysql-log-rotate
[mysql@adb1 mariadb]$ ll /MARIA_LOG/general
-rw------- 1 mysql dba  2475 Jul 16 10:00 mysql_general.log
-rw------- 1 mysql dba   187 Jul 13 15:34 mysql_general.log.1


1.2  인스턴스 설정
경험상 MariaDB의 엔진 파라메터 설정은, default 값으로도 적정한 성능/안정성 수준을 가질 수 있으므로, 서버 물리 메모리 크기에 직접적으로 관계된 buffer pool size (innodb_buffer_pool_size, Oracle의 SGA size에 해당)만 조정한 후 아래 권고 값들을 그대로 사용을 권장한다.
즉, 일반적인 경우, 단일 및 다중 인스턴스 환경 모두에서 아래의 파라메터 설정 중 DB 인스턴스 구성에 따른 포트번호, 데이터/로그 파일 경로, 메모리 버퍼 풀 크기만 조정 후  적용하도록 한다. 간혹 비즈니스 특성에 따라서 특정 대형 쿼리 등를 위해 메모리 옵션 등을 변경할 수 있겠지만, 이는 일부 예외적인 경우이며 경험상 큰 차이는 발생하지 않는다.

다음은 중요 파라메터들에 대한 설명 권고 값 및 이에 대한 설명이다.

1) 전체 Connection 수 연관 파라메터
MariaDB에 접속하는 WAS들의 전체 connection 수 관련 파라메터 이다.
DBMS 엔진 파라미터     설정 권고 값     Default값
back_log     1024     50
> 한번에 처리될 수 있는 요청 수. 충분히 크게 설정 후 사용한다.
max_connections     2000     151
> 최대 커넥션 수. 접속 WAS 들의 총 connection pool 수 보다 크게 잡도록 한다. 권고된 DB인스턴스 당 2000 정도면 대부분의 시스템에서 적용 가능하다.
table_open_cache     10240     400
> 전체 Thread가 열수 있는 테이블 수. 충분히 크게 잡고 사용하며 이 값을 조정 시 O/S의 file descriptors 수도 같이 조정하여야 한다.

2) 접속 세션 당 메모리 설정
각 세션 Thread가 사용하는 메모리 설정이다. 각각의 running thread 는 이 설정 값만큼 메모리를 할당 받아 사용하므로, 너무 크지 않은 값을 설정하도록 한다.
DBMS 엔진 파라미터     설정 권고 값     Default값
join_buffer_size     2M     131072
> Join Buffer의 최소 할당 크기. Index 없이 full table scan을 하는 Join에 사용되며, 여러 개의 Join이 발생하는 복잡 쿼리의 경우에는 여러 개의 Join Buffer가 할당된다.

sort_buffer_size     1M     2097144
> 각 세션이 Sort시 사용되는 버퍼 크기

read_buffer_size     2M     131072
> 기본적으로 MyISAM 테이블의 sequential scan시 사용되는 버퍼 크기이지만, 다른 모든 스토리지 엔진에서 정렬을 위한 임시 테이블 사용, 대량 insert, 쿼리 결과 caching 등에도 사용된다.

read_rnd_buffer_size     8M     262144
> MyISAM 테이블을 정렬된 순서로 read시 disk seek를 줄이기 위해 사용되는 버퍼 크기.

binlog_cache_size     1M     32768
> 한 트랜잭션 동안 binary log 에 쓸 변경분 캐쉬 크기

3) 트랜잭션 및 로그 처리 관련 (Redo, Binary, Sync 옵션)
각 트랜잭션 처리마다 동반되는 log 처리에 대한 옵션이다. 이 값들을 조정 시 일부 성능 향상을 위할 수도 있지만 시스템 장애 시 그 만큼의 안정성 trade-off가 있으므로 모든 값들은 안정성을 우선 고려하여 다음과 같이 설정하도록 한다.
DBMS 엔진 파라미터     설정 권고 값     Default값
transaction-isolation     READ-COMMITTED     REPEATABLE-READ
데이터베이스 isolation level 값이다. 가장 일반적인 READ-COMMITTED를 사용한다.

sync_binlog     1     0
설정된 값 만큼의 트랜잭션 마다 Binary log를 디스크에 write한다. 권고된 1은 매번 트랜잭션 커밋마다 디스크에 쓰는 방식으로 시스템 장애 대비 가장 안정적이지만 성능 저하를 유발할 수 있으므로, 이를 보완하기 위해 디스크 캐쉬와 함께 사용토록 한다.

binlog_format     MIXED     STATEMENT
Binary log 기록 형태이다. 권고된 MIXED는 이전 버전에서 지원하던 ROW 및 STATEMENT 행태를 장점들을 취합한 혼합 방식이다.

relay_log_purge     0     0
Relay log의 자동 purge 설정이다. Replicatoin 구성 시 장애/복구에 relay log들이 사용될 수 있으므로 0으로 설정하여 자동 purge하지 않도록 하고, crontab에 purge job을 등록하여 매일 1회 ~ 수회 정도 별도로 purge하도록 한다. 참고로, 권고되는 가용성 솔루션인 MHA에 이를 purge하는 스크립트가 제공된다.

general-log     0     1
> 제너럴 로그파일에는 시간단위로 실행했던 쿼리의 내용이 모두 기록된다.
  로그파일이 과다 생성되어 성능 및 디스크용량 관계로 loging기능을 off한다.

expire_logs_days     7     7
> binlog파일 보관 주기이며, 필요에 따라 보관주기를 조정할 수 있음.

long_query_time     1     1
> 어떤 쿼리가 느린지 확인하기 위해설정, 정의한 시간(long_query_time 파라미터에 초단위로 설정)이상의 시간이 소요된 쿼리가 모두 기록된다.

4) innoDB 설정
InnoDB의 주요 설정이다. 아래 값들 중 서버 물리 메모리 크기에 맞게 innodb_buffer_pool_size (Oracle SGA 해당) 값을 조정해야 하며, 앞서 설명된 세션당 사용되는 메모리 (Oralce의 PGA 해당)를 고려하여 전체 서버 물리 메모리 크기의 50%~70% 정도로 설정하여 사용토록 한다. 다중 인스턴스 환경의 경우 모든 인스턴스의 innodb_buffer_pool_size 합이 서버 물리 메모리의 50%~70%로 결정토록 한다.
DBMS 엔진 파라미터     설정 권고 값     Default값
innodb_flush_method     ALL_O_DIRECT     Fdatasync
> innoDB 데이터 파일 I/O를 async 방식 direct I/O로 설정한다. 참고로 다른 모든 파라메터 값들은 MySQL 5.5와 그대로 호환되지만 ALL_O_DIRECT 하나만 MariaDB에만 있는 옵션 값이므로 MySQL 5.5에는 O_Direct로 설정하여 사용하도록 한다.
O_DIRECT는 InnoDB 데이터 파일만 asyc I/O가 적용되며, ALL_O_DIRECT는 데이터 파일에 추가로 redo log에도 async I/O가 적용된다.

innodb_log_file_size     500M     5242880
> innodb의 redo log 파일 크기이다. innodb_log_files_in_group과 함께 사용된다.

innodb_log_files_in_group     8     2
> innodb relo log 파일 개수이다. 500MB x 8개 총 4GB의 redo log 파일을 설정하도록 한다. 참고로 MySQL 5.5은 relo log 전체 크기가 최대 4GB 로 제한이 있으며, MariaDB 5.5의 경우는 제한이 없지만, 전체 4GB 정도면 대부문의 경우에서 무난한 설정이다.

innodb_autoinc_lock_mode     1     1
> auto_increment가 정의된 테이블의 locking mode 이다. 0 (traditional), 1 (consecutive), 2 (interleaved)의 세 가지 설정이 가능하며 값이 올라갈수록 경량화된 lock 메커니즘을 사용하여 성능 향상이 꾀할 수 있다. 하지만 가장 성능이 좋은 2 (interleaved) 방식은 시스템 장애 시 binlog_format을 ROW 방식으로 설정해야 한다.

innodb_buffer_pool_size     물리 메모리 50 ~ 70%     134217728
> innodb가 사용하는 공유 버퍼 풀 크기이다.

innodb_buffer_pool_instances     4     1
> 수십 GB 이상의 대형 메모리 사용 시 버퍼 풀 locking 메커니즘에 따른 성능 저하를 막기 이해 이 옵션을 사용하여 여러 개의 버퍼풀 인스턴스로 분리해서 사용한다. 보통 4 정도로 설정하면 다양한 시스템 환경에도 문제없이 적용 가능하다. 참고로 innodb_buffer_pool_size의 설정된 버퍼 풀 크기 내에서 해쉬 알고리즘에 의해 버퍼 풀을 쪼개서 사용하는 개념이므로 innodb_buffer_pool_size 값과는 상관없이 적용하도록 한다.

이러한 구성을 요약하면, 대부분의 시스템에서는 앞서 설명된 권고 값들을 그대로 사용하며, 설정 파일(my.cnf)에 다음과 같이 수정하여 적용토록 한다.
?     MariaDB 엔진 base 디렉토리 설정 (예: /MARIA/mariadb)
?     인스턴스 포트 번호 설정 (포트는 33XX를 사용한다. 예: 3301 )
?     인스턴스 데이터 디렉토리 설정(예: /MARIA_DATA)
?     인스턴스 로그 디렉토리 설정 (예: /MARIA_LOG 밑의 binary, error, slow 등)

?     인스턴스 innoDB 버퍼 풀 크기 설정 (예: 물리 메모리의 50%~70%)
?     Server-id  설정 ( 예: 1로 설정 )

최종적으로, 아래의 예를 따라서 /etc/my.cnf 를 설정하도록 한다.
(맨 마지막 파란색으로 표기된 내용을 환경에 맞게 수정한다)

############################################
#STEP 01. 클라이언트 설정
[client]
socket=/MARIA_DATA/mysql.sock
############################################
#STEP 02. 인스턴스 설정
[mysqld]
user=root
# Character set Config
character-set-client-handshake=FALSE
character-set-server=utf8
init_connect=SET collation_connection = utf8_general_ci
init_connect=SET NAMES utf8

# Common Config
back_log=1024
binlog_cache_size=1M
ft_min_word_len=4
interactive_timeout=600
join_buffer_size=2M
max_allowed_packet=128M
max_heap_table_size=2048M
max_connections=1024
performance_schema
read_buffer_size=2M
read_rnd_buffer_size=8M
skip-external-locking
skip-name-resolve=1
sort_buffer_size=1M
max_length_for_sort_data=1024
tmp_table_size=2048M
table_open_cache=10240
transaction-isolation=REPEATABLE-READ 
open_files_limit = 8192

# Query Cache Disable
query_cache_type=0
query_cache_size=0

# Log Config
log-bin=/MARIA_LOG/binary/mysql-bin
relay-log=/MARIA_LOG/relay/relay-log
expire_logs_days=7        
max_binlog_size=1G
sync_binlog=1
binlog_format=mixed
relay_log_purge=0

log-error=/MARIA_LOG/error/mysql.err
slow_query_log_file=/MARIA_LOG/slow/mysql-slow-query.log
slow_query_log=1
long_query_time=2

# Innodb config
innodb_data_file_path=ibdata1:1024M;ibdata2:1024M;ibdata3:10M:autoextend
innodb_file_per_table=1
innodb_flush_method=ALL_O_DIRECT
innodb_lock_wait_timeout=15
innodb_log_buffer_size=128M
innodb_log_file_size= 512M
innodb_log_files_in_group=8
innodb_thread_sleep_delay=0
innodb_fast_shutdown
innodb_autoinc_lock_mode=1
innodb_thread_concurrency = 0
innodb_read_io_threads = 4
innodb_write_io_threads = 8
innodb_additional_mem_pool_size = 32M
innodb_open_files = 8192

#Thread Pool
thread_handling=pool-of-threads
thread_pool_stall_limit = 8092
thread_pool_idle_timeout = 120

# MyISAM Config
bulk_insert_buffer_size =       64M
key_buffer_size =      128M
myisam_max_sort_file_size       =       10G
myisam_recover
myisam_repair_threads   =       1
myisam_sort_buffer_size =       64M

# Replication related settings
log_bin_trust_function_creators = 1

basedir=/MARIA/mariadb
port=3301  #접속 포트 번호
socket=/MARIA_DATA/mysql.sock
pid-file=/MARIA_DATA/mysql.pid
datadir=/MARIA_DATA/DATA
tmpdir=/MARIA_DATA/tmpdir
innodb_data_home_dir=/MARIA_DATA/DATA
innodb_log_group_home_dir=/MARIA_DATA/DATA
#general_log=1                                           #general_log 설정 시 적용
#general_log_file=/MARIA_LOG/general/mysql_general.log  #general_log 설정 시 적용
innodb_buffer_pool_size = 12G  #인스턴스 별 innoDB  버퍼 풀 메모리 설정
innodb_buffer_pool_instances = 4
server-id=1  #인스턴스 번호

[mysqldump]
quick
max_allowed_packet=512M

[mysqladmin]
user = root
password = root

1.3  인스턴스 구동/종료
1.3.1  인스턴스 구동
1) /etc/my.cnf 설정 후 인스턴스 구동은service maria명령어를 사용하여 다음과 같이 진행한다.
# 인스턴스 구동
[mysql@adb1 ~]# service maria start


2) 인스턴스 구동 시에는 다음의 로그 내용을 보면서 정상 작동을 확인하도록 한다.
MariaDB의 기본 에러 로그 확인 (/MARIA_LOG/error/mysql.err)
[mysql@adb1 ~]# tail -100f /MARIA_LOG/error/mysql.err

… 중략
131030 16:03:28 [Note] /MARIA/mariadb-5.5.31-linux-x86_64/bin/mysqld: ready for connections.
Version: '5.5.31-MariaDB-log'  socket: '/MARIA_DATA/data/db01/mysql.sock'  port: 3301  MariaDB Server
>> 인스턴스 정상 기동 상황

1.3.2  인스턴스 종료
1) 인스턴스 종료는service maria 명령어를 사용하여 진행한다.
# 인스턴스 종료
[mysql@adb1 ~]# service maria stop

2) 인스턴스 종료 시에는 다음의 로그 내용을 보면서 정상 종료를 확인하도록 한다.
MariaDB의 기본 에러 로그 확인 (/MARIA_LOG/error/mysql.err)
[mysql@adb1 ~]# tail -100f /MARIA_LOG/error/mysql.err

… 중략
131030 15:43:59 [Note] /MARIA/mariadb-5.5.31-linux-x86_64/bin/mysqld: Shutdown complete
131030 15:43:59 mysqld_safe mysqld from pid file /MARIA_DATA/data/db01/mysql.pid ended
2. MariaDB 리플리케이션 구성 가이드
2.1  환경 준비
2.1.1  슬레이브노드 MariaDB 설치
MariaDB 엔진 설치과정의 앞의 인스턴스 설치 내용과 동일하다.

2.1.2  데이터 파일 복사 (백업/복구)
슬레이브노드 구성 시 마스터노드 인스턴스 DOWN이 가능 여부에 따라 다음의 절차를 따르도록 한다.

1) 마스터노드 인스턴스 DOWN이 가능한 경우
?     마스터노드 인스턴스 shutdown을 수행한다. 그리고 shutdown 후 마지막 Binary log 파일명 및 LSN(Log Sequence Number)를 기록해 놓는다. 이 정보는 슬레이브노드 구성 후 replication 설정 시 시작지점 정보로 사용된다.
?     아래 예에서는 mysql-마지막 binary log 파일명은 mysql-bin.000032 이며, DB shutdown 시의 마지막 LSN 번호는 215868624639이다.
# 마지막 binary 파일명 확인
[mysql@adb1 ~]# ls -lrt /MARIA_LOG/binary
… 중략
-rw-rw---- 1 mysql dba       1248 Oct 30 15:50 mysql-bin.index
-rw-rw---- 1 mysql dba        264 Oct 30 15:51 mysql-bin.000032 

# 마지막 LSN(Log Sequence Number) 확인
[mysql@adb1 ~]# tail -100f /MARIA_LOG/error/mysql.err
… 중략
31030 15:43:57 [Note] Event Scheduler: Purging the queue. 0 events
131030 15:43:57 [Note] unregister_replicator OK
131030 15:43:57  InnoDB: Starting shutdown...
131030 15:43:59  InnoDB: Shutdown completed; log sequence number 215868624639
131030 15:43:59 [Note] /MARIA/mariadb-5.5.31-linux-x86_64/bin/mysqld: Shutdown complete

131030 15:43:59 mysqld_safe mysqld from pid file /MARIA_DATA/mysql.pid ended
?     이제 마스터노드 데이터 파일을 슬레이브노드로 복사하고, 로그 파일 디렉토리를 만들어 준다. 아래 예는 슬레이브노드(adb2)를 구성하는 예이다. 데이터파일 복사가 끝난 후에는 마스터노드 인스턴스를 기동해도 무방하다.
# 마스터노드 데이터파일 슬레이브로 복사
[mysql@adb2 ~]$  scp -r mysql@adb1:/MARIA_DATA /MARIA_DATA

# 로그파일 디렉토리 생성
[mysql@adb2 ~]$  mkdir /MARIA_LOG/binary
[mysql@adb2 ~]$  mkdir /MARIA_LOG/error
[mysql@adb2 ~]$  mkdir /MARIA_LOG/general
[mysql@adb2 ~]$  mkdir /MARIA_LOG/slow
[mysql@adb2 ~]$  mkdir /MARIA_LOG/relay


2) 마스터노드 인스턴스 DOWN이 어려운 경우
운영 중 시스템이라면 replication 구성을 위해 마스터노드 인스턴스 DOWN이 어려울 수 있다. 이 경우는 백업/복구 솔루션의 Full 백업본을 사용하여 슬레이브노드에 복구한다.
복구 후 replication 설정을 위해 백업/복구 솔루션 로그를 보고 적용 백업본의 마지막 binary 로그 파일명 및 LSN 번호를 확인해야 한다.


2.2  인스턴스 설정
2.2.1  기본 Replication 설정
마스터노드로부터 my.cnf 파일을 슬레이브노드로 복사하여 다음 사항만 변경한다.

1) Server-id 설정
인스턴스 번호를 설정한다. Replication이 구성되는 마스터/슬레이브 노드들은 서로 다른 인스턴스 번호를 가져야 하므로 다음의 번호 규칙을 적용한다.
마스터노드 인스턴스번호 뒤에 두자리수 슬레이브 인스턴스 번호 추가
예) 마스터 인스턴스 번호 1 => 첫번째 슬레이브 인스턴스 번호 101
                           => 두번째 슬레이브 인스턴스 번호 102
    마스터 인스턴스 번호 12 => 첫번째 슬레이브 인스턴스 번호 1201
                           => 두번째 슬레이브 인스턴스 번호 1202
2) DB 파라메터에 read_only 추가
슬레이브 노드의 my.cnf 파일에 read_only 옵션을 추가한다. 마스터/슬레이브 replication 중에 슬레이브노드에 데이터가 write되면 해당 DB는 정합성이 깨질 수 있으므로 슬레이브는 반드시 read_only로 구성되어야 한다.

모든 마스터/슬레이브 노드들의 설정은 위의 server-id 및 read_only 옵션만 다르고, 엔진 위치, 데이터 파일 위치, 포트 번호 등의 중요 구성을 동일하게 맞추어 설정하도록 한다.

다음은 슬레이브 구성 시 /etc/my.cnf 파일에 이러한 설정을 적용하는 예이다. 파란색 부문만 변경하도록 한다.
############################################
...
[mysqld]
...
basedir=/MARIA/mariadb
port=3301  #접속 포트 번호
socket=/MARIA_DATA/mysql.sock
pid-file=/MARIA_DATA/mysql.pid
datadir=/MARIA_DATA
tmpdir=/MARIA_DATA/tmpdir
innodb_data_home_dir=/MARIA_DATA
innodb_log_group_home_dir=/MARIA_DATA
log-bin=/MARIA_LOG/binary/mysql-bin
log-error=/MARIA_LOG/error/mysql.err
relay-log=/MARIA_LOG/relay/relay-log
slow_query_log_file=/MARIA_LOG/slow/mysql-slow-query.log
innodb_buffer_pool_size = 12G  #인스턴스 별 innoDB  버퍼 풀 메모리 설정
innodb_buffer_pool_instances = 4
#rpl_semi_sync_master_enabled=1   #semi-sync 설정 시 적용
#rpl_semi_sync_slave_enabled=1    #semi-sync 설정 시 적용
server-id=101  #슬레이브 인스턴스 번호 변경
read_only      #슬레이브 read_only 설정 추가
...
마스터노드 및 슬레이브 노드 기동 후 리플리케이션 유저를 등록한다.
//Master node
//repliaction용 계정생성 및 MHA manager용 계정생성
[mysql@adb1 mariadb]# ./bin/mysql -uroot -p
MariaDB [(none)]> grant replication slave on *.* to 'repl'@'10.1.1.%' identified by 'repl';
Query OK, 0 rows affected (0.02 sec)
MariaDB [(none)]> grant all on *.* to 'root'@'10.1.1.%' identified by 'root';
Query OK, 0 rows affected (0.02 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.01 sec)

//포지션정보 확인 (업무 부하 시에는 계속 증가하므로 미리 찾아놔야 한다.)
MariaDB [(none)]> show master status;
+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000037 |     1932 |              |                  |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)

//Slave node
// MHA의 특성상 Slave 가 Master 의 role 을 받아 오므로 Slave Node 에도 replication 권한 설정 및 MHA manager용 계정생성
[mysql@adb2 mariadb]# ./bin/mysql -uroot -p
MariaDB [(none)]> grant replication slave on *.* to 'repl'@'10.1.1.%' identified by 'repl';
Query OK, 0 rows affected (0.02 sec)
MariaDB [(none)]> grant all on *.* to 'root'@'10.1.1.%' identified by 'root';
Query OK, 0 rows affected (0.02 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.01 sec)

앞서서 슬레이브노드 데이터 복사 시 기록해 놨던 마스터노드의 binlog 파일명 및 마지막 Position번호를 사용하여 슬레이브노드의 리플리케이션을 설정한다.
슬레이브 기동 후 “show slave status” 명령어로 슬레이브의 리플리케이션의 상태를 확인할 수 있다. 여기서 I/O 쓰레드 및 SQL 쓰레드의 Running 상태 및 마스터/슬레이브간의 time gab도 확인하도록 한다.
//Slave node 접속
[mysql@adb2 mariadb]# ./bin/mysql -uroot -p --socket=/MARIA_DATA/data/db01/mysql.sock

//replication 설정
MariaDB [(none)]> change master to
master_host='10.1.1.157',  //마스터 IP주소 또는 호스트명
master_user='repl',  
master_password='repl',
master_port=3301,
master_log_file='mysql-bin.000037',   //기록해 놨던 마스터의 마지막 binlog 파일명
master_log_pos=1932;            //기록해 놨던 마스터의 마지막 binlog LSN
Query OK, 0 rows affected (0.02 sec)

//리플리케이션 구동
MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.02 sec)

//리플리케이션 상태 확인
MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.1.1.157
                  Master_User: repl
                  Master_Port: 3301
                Connect_Retry: 60
              Master_Log_File: mysql-bin.000037
          Read_Master_Log_Pos: 2084
               Relay_Log_File: mysql-relay-bin.000052
                Relay_Log_Pos: 2230
        Relay_Master_Log_File: mysql-bin.000037
             Slave_IO_Running: Yes     // I/O쓰레드가 마스터에서 binlog를 relaylog로 받아온다
            Slave_SQL_Running: Yes    // SQL쓰레드가 relaylog를 DB에 반영한다.
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table:
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 2084
              Relay_Log_Space: 48057666
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: 0           //마스터 슬레이브간의 리플리케이션 time gab(초)
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
1 row in set (0.00 sec)

//위의 결과값에서 Slave_IO_Running , Slave_SQL_Running이 yes이면 replication 설정성공


하나의 마스터에 여러 슬레이브들을 설정 시, 다른 슬레이브들도 이와 같이 설정하도록 한다.
3. 추가 프로그램 설치가이드
3.1  innotop
innotop은 터미널 상에서 실시간으로 현재 MariaDB의 상태를 확인할 수 있는 모니터 도구이며, Query ID를 통해서 해당 쿼리에 대한 실행계획 및 kill 할 수있는 기능을 제공한다.

3.1.1  innotop 설치
사전 설치 파일
perl-DBD-MySQL-4.013-3.el6.x86_64
perl-DBI-1.609-4.el6.x86_64
perl-TermReadKey-2.30-13.el6.x86_64

설치 방법
[root@pacetest1 innotop]# pwd
/root/DBA/innotop
[root@pacetest1 innotop]# ls
innotop-1.8.1  innotop-1.8.1.tar.gz
[root@pacetest1 innotop]# tar zxvf innotop-1.8.1.tar.gz
innotop-1.8.1/
innotop-1.8.1/COPYING
innotop-1.8.1/t/
innotop-1.8.1/t/innodb-status-005
innotop-1.8.1/t/innodb-status-002
innotop-1.8.1/t/InnoDBParser.t
innotop-1.8.1/t/innodb-status-006
innotop-1.8.1/t/innodb-status-001
innotop-1.8.1/t/innodb-status-004
innotop-1.8.1/t/innodb-status-003
innotop-1.8.1/Makefile.PL
innotop-1.8.1/innotop
innotop-1.8.1/innotop.spec
innotop-1.8.1/MANIFEST
innotop-1.8.1/Changelog
innotop-1.8.1/INSTALL
[root@pacetest1 innotop]# cd innotop-1.8.1
[root@pacetest1 innotop-1.8.1]# ls
blib  Changelog  COPYING  innotop  innotop.spec  INSTALL  Makefile  Makefile.PL  MANIFEST  pm_to_blib  t
[root@pacetest1 innotop-1.8.1]# perl Makefile.PL && make && make install

3.1.2   innotop 실행
[root@pacetest1 innotop-1.8.1]# innotop

[RO] Query List (? for help)                                            localhost, 13+02:42:17.003, 0.31 QPS, 2/2/0 con/run/cac thds, 5.5.34-MariaDB-log

When   Load  QPS   Slow  Se/In/Up/De%  QCacheHit  KCacheHit  BpsIn   BpsOut
Total  0.00  0.31    63  98/ 0/ 0/ 0       0.00%     99.16%  191.29  316.12

Cmd    ID      State  User   Host           DB      Time   Query

3.1.3  innotop 사용방법
help 또는 ? 버튼을 누르면 보고 싶은 내용에 대한 단축키가 표출된다.

Switch to a different mode:
   B  InnoDB Buffers    L  Locks               R  InnoDB Row Ops
   C  Command Summary   M  Replication Status  S  Variables & Status
   D  InnoDB Deadlocks  O  Open Tables         T  InnoDB Txns
   F  InnoDB FK Err     Q  Query List          U  User Statistics
   I  InnoDB I/O Info                         

Actions:
   a  Toggle the innotop process    k  Kill a query's connection
   c  Choose visible columns        n  Switch to the next connection
   d  Change refresh interval       p  Pause innotop
   e  Explain a thread's query      q  Quit innotop
   f  Show a thread's full query    r  Reverse sort order
   h  Toggle the header on and off  s  Change the display's sort column
   i  Toggle idle processes         x  Kill a query

Other:
TAB  Switch to the next server group   /  Quickly filter what you see
   !  Show license and warranty         =  Toggle aggregation
   #  Select/create server groups       @  Select/create server connections
   $  Edit configuration settings       \  Clear quick-filters
Press any key to continue

3.2  percona-xtrabackup
MariaDB는 mysqldump 외에 백업/복구 유틸리티가 제공되지 않으며 innodb에 대한 hotbackup을 위해서는 percona에서 제공하는 오픈소스 백업 유틸리티인 xtrabackup 을 설치한다.
LGU+에서는 MHA for MariaDB에 대한 백업 솔루션으로 Zmanda를 사용하는 데 Zmanda로 xtrabackup을 이용해 DB Data를 백업 /복구한다.

3.2.1  다운로드 경로
http://www.percona.com/software/percona-xtrabackup
위 URL에서 새롭게 릴리즈되는 파일을 다운받을 수 있으며, 오픈소스로 무료로 제공하고 있다.

3.2.2  percona-xtrabackup 설치
사전 설치 파일 (RHEL6 기준)
perl-DBD-MySQL-4.013-3.el6.x86_64
perl-DBI-1.609-4.el6.x86_64
perl-Time-HiRes-1.9721-136.el6.x86_64

설치 방법
[root@pacetest1 DBA]# rpm -ivh percona-xtrabackup-2.1.8-733.rhel6.x86_64.rpm
Preparing...                ########################################### [100%]
   1:percona-xtrabackup     ########################################### [100%]

3.2.3  percona-xtrabackup 설치 경로
[root@pacetest1 DBA]# rpm -ql percona-xtrabackup-2.1.8-733.rhel6.x86_64
/usr/bin/innobackupex
/usr/bin/innobackupex-1.5.1
/usr/bin/xbcrypt
/usr/bin/xbstream
/usr/bin/xtrabackup
/usr/bin/xtrabackup_55
/usr/bin/xtrabackup_56
/usr/share/doc/percona-xtrabackup-2.1.8
/usr/share/doc/percona-xtrabackup-2.1.8/COPYING

percona-xtrabackup 에 대한 사용자 메뉴얼은 http://www.percona.com/software/percona-xtrabackup 에서 확인 가능하며, 본 프로젝트에서는 ZMANDA를 사용하여 백업/복구를 진행하기 때문에 xtrabackup에 대한 운용가이드는 제공하지 않는다.

3.3  percona-toolkit
MariaDB의 관리를 효율적으로 하기 위해 Percona에서는 관리도구를 오픈소스로 배포하고 있다.
Percona-tookit은 Oracle에서 제공하는 MySQL-Utilities 와 비슷한 도구이며, 더 다양한 기능을 제공하는 펄 프로그램이며 DBA의 운용능력을 향상시켜 줄 수 있는 도구이다.

3.3.1  다운로드 경로
http://www.percona.com/software/percona-toolkit
위 URL에서 새롭게 릴리즈되는 파일을 다운받을 수 있으며, 오픈소스로 무료로 제공하고 있다.

3.3.2  percona-toolkit설치
사전 설치 파일 (RHEL6 기준)
perl-DBD-MySQL-4.013-3.el6.x86_64
perl-DBI-1.609-4.el6.x86_64
perl-IO-Socket-SSL-1.31-2.el6.noarch

설치 방법은 두가지로 나눌 수 있다. rpm 설치방법과 tar 압축해제 및 컴파일을 통해서 설치가 가능하다. 아래는 rpm파일로 설치하는 방법을 보여준다.
[root@pacetest1 DBA]# rpm -ivh percona-toolkit-2.2.7-1.noarch.rpm
Preparing...                ########################################### [100%]
   1:percona-toolkit     ########################################### [100%]

3.3.3  percona-toolkit 설치 경로
[root@bdb1 ~]# rpm -ql percona-toolkit-2.2.7-1.noarch
/usr/bin/pt-agent
/usr/bin/pt-align
/usr/bin/pt-archiver
/usr/bin/pt-config-diff
/usr/bin/pt-deadlock-logger
/usr/bin/pt-diskstats
/usr/bin/pt-duplicate-key-checker
/usr/bin/pt-fifo-split
/usr/bin/pt-find
/usr/bin/pt-fingerprint
/usr/bin/pt-fk-error-logger
/usr/bin/pt-heartbeat
/usr/bin/pt-index-usage
/usr/bin/pt-ioprofile
/usr/bin/pt-kill
/usr/bin/pt-mext
/usr/bin/pt-mysql-summary
/usr/bin/pt-online-schema-change
/usr/bin/pt-pmp
/usr/bin/pt-query-digest
/usr/bin/pt-show-grants
/usr/bin/pt-sift
/usr/bin/pt-slave-delay
/usr/bin/pt-slave-find
/usr/bin/pt-slave-restart
/usr/bin/pt-stalk
/usr/bin/pt-summary
/usr/bin/pt-table-checksum
/usr/bin/pt-table-sync
/usr/bin/pt-table-usage
/usr/bin/pt-upgrade
/usr/bin/pt-variable-advisor
/usr/bin/pt-visual-explain
/usr/share/doc/percona-toolkit-2.2.7
/usr/share/doc/percona-toolkit-2.2.7/COPYING
/usr/share/doc/percona-toolkit-2.2.7/Changelog
/usr/share/doc/percona-toolkit-2.2.7/INSTALL
/usr/share/doc/percona-toolkit-2.2.7/README
/usr/share/man/man1/percona-toolkit.1p.gz
/usr/share/man/man1/pt-agent.1p.gz
/usr/share/man/man1/pt-align.1p.gz
/usr/share/man/man1/pt-archiver.1p.gz
/usr/share/man/man1/pt-config-diff.1p.gz
/usr/share/man/man1/pt-deadlock-logger.1p.gz
/usr/share/man/man1/pt-diskstats.1p.gz
/usr/share/man/man1/pt-duplicate-key-checker.1p.gz
/usr/share/man/man1/pt-fifo-split.1p.gz
/usr/share/man/man1/pt-find.1p.gz
/usr/share/man/man1/pt-fingerprint.1p.gz
/usr/share/man/man1/pt-fk-error-logger.1p.gz
/usr/share/man/man1/pt-heartbeat.1p.gz
/usr/share/man/man1/pt-index-usage.1p.gz
/usr/share/man/man1/pt-ioprofile.1p.gz
/usr/share/man/man1/pt-kill.1p.gz
/usr/share/man/man1/pt-mext.1p.gz
/usr/share/man/man1/pt-mysql-summary.1p.gz
/usr/share/man/man1/pt-online-schema-change.1p.gz
/usr/share/man/man1/pt-pmp.1p.gz
/usr/share/man/man1/pt-query-digest.1p.gz
/usr/share/man/man1/pt-show-grants.1p.gz
/usr/share/man/man1/pt-sift.1p.gz
/usr/share/man/man1/pt-slave-delay.1p.gz
/usr/share/man/man1/pt-slave-find.1p.gz
/usr/share/man/man1/pt-slave-restart.1p.gz
/usr/share/man/man1/pt-stalk.1p.gz
/usr/share/man/man1/pt-summary.1p.gz
/usr/share/man/man1/pt-table-checksum.1p.gz
/usr/share/man/man1/pt-table-sync.1p.gz
/usr/share/man/man1/pt-table-usage.1p.gz
/usr/share/man/man1/pt-upgrade.1p.gz
/usr/share/man/man1/pt-variable-advisor.1p.gz
/usr/share/man/man1/pt-visual-explain.1p.gz

percona-toolkit 에 대한 사용자 메뉴얼은 http://www.percona.com/software/percona-toolkit 에서 확인 가능하며, MHA 운영가이드를 통해서 실제 운영에 필요한 도구를 소개하고 있다.

반응형
Comments