Transcript

1 http://phpschool.com

Advanced MySQLReplicate & Optimize !

Advanced MySQLReplicate & Optimize !

PHPSCHOOL 정진호

loveme@phpschool.com

PHPSCHOOL 정진호

loveme@phpschool.com

2 http://phpschool.com

ContentsContents Quick Survey What is MySQL? MySQL Architecture MySQL Tables Replication Replication process Replication situation Replication Layout L4 Load Balancing Replication setup Troubleshooting MySQL monitoring PHPSCHOOL System Layout

Quick Survey What is MySQL? MySQL Architecture MySQL Tables Replication Replication process Replication situation Replication Layout L4 Load Balancing Replication setup Troubleshooting MySQL monitoring PHPSCHOOL System Layout

3 http://phpschool.com

About meAbout me

http://phpschool.com administrator Using MySQL : Since 1998 Yahoo! Korea Communications team In charge of Kr.club.yahoo.com

http://phpschool.com administrator Using MySQL : Since 1998 Yahoo! Korea Communications team In charge of Kr.club.yahoo.com

4 http://phpschool.com

Quick SurveyQuick Survey

MySQL 사용기간 MySQL 버전

– 3.23 vs. 4.0 개발 언어

– PHP, C/C++, Perl ,Java Replication 사용 여부

MySQL 사용기간 MySQL 버전

– 3.23 vs. 4.0 개발 언어

– PHP, C/C++, Perl ,Java Replication 사용 여부

5 http://phpschool.com

What is MySQL?What is MySQL? RDBMS(Relational Database

Server)– SQL 을 통하여 데이터베이스의 생성 , 수정 ,

검색 – 테이블에 구조적 데이터가 저장 됨– local 또는 remote 클라이언트 처리

Very Fast Reliable Scalable Inexpensive 경우에 따라 Oracle 대용으로 사용

RDBMS(Relational Database Server)– SQL 을 통하여 데이터베이스의 생성 , 수정 ,

검색 – 테이블에 구조적 데이터가 저장 됨– local 또는 remote 클라이언트 처리

Very Fast Reliable Scalable Inexpensive 경우에 따라 Oracle 대용으로 사용

6 http://phpschool.com

What is MySQL?What is MySQL?

Full-text Search Indexing– 아직 2byte 문자 지원 못함

Replication Query Cache UNIONs SSL (Encrypted connections) Multi-Table Deletes

Full-text Search Indexing– 아직 2byte 문자 지원 못함

Replication Query Cache UNIONs SSL (Encrypted connections) Multi-Table Deletes

7 http://phpschool.com

Why MySQL?Why MySQL?

Speed– MySQL 디스크 기반 관계형 DB 중에서 가장

빠르다 Features

– 최적화가 용이– 웹 어플리케이션 개발에 필요한 다양한 기능 제공– Limit, full-text 검색 , 빠른 연결

API– C, C++, C#, Java, Perl, PHP, Python, Ruby, 등등…

Speed– MySQL 디스크 기반 관계형 DB 중에서 가장

빠르다 Features

– 최적화가 용이– 웹 어플리케이션 개발에 필요한 다양한 기능 제공– Limit, full-text 검색 , 빠른 연결

API– C, C++, C#, Java, Perl, PHP, Python, Ruby, 등등…

8 http://phpschool.com

Why MySQL?Why MySQL?

Simplicity– 간단한 인스톨 (10 분 이내 )– 전문적인 DBA 가 필요 없음

Cost– 저 사양 H/W 에서도 뛰어난 성능– 저렴한 라이센스 비용

Scale– Replication 을 이용한 확장

Simplicity– 간단한 인스톨 (10 분 이내 )– 전문적인 DBA 가 필요 없음

Cost– 저 사양 H/W 에서도 뛰어난 성능– 저렴한 라이센스 비용

Scale– Replication 을 이용한 확장

9 http://phpschool.com

TODO listTODO list

Replication over SSL (4.1) Multiple Character Sets (4.1) Sub-queries (4.1) Views (5.x) Stored Procedures (5.x) XML Output/Query (?)

Replication over SSL (4.1) Multiple Character Sets (4.1) Sub-queries (4.1) Views (5.x) Stored Procedures (5.x) XML Output/Query (?)

10 http://phpschool.com

MySQL ArchitectureMySQL Architecture

Connection Management/Security

MyISAM(default)

NDB(clustered)

HEAP(in-memory)

InnoDB(transactions)

Storage Engines

SQL Parsing/Execution/Caching

11 http://phpschool.com

MyISAM TablesMyISAM Tables

기본 테이블 타입 가볍고 부하가 적다 Table Locking

– 동시 읽기 / 쓰기가 매우 많은 경우 성능 저하– 대부분의 일반적인 경우에 적합

주요 사용처– 실시간 데이터– Logging applications

기본 테이블 타입 가볍고 부하가 적다 Table Locking

– 동시 읽기 / 쓰기가 매우 많은 경우 성능 저하– 대부분의 일반적인 경우에 적합

주요 사용처– 실시간 데이터– Logging applications

12 http://phpschool.com

MyISAM TablesMyISAM Tables

저장방식– 각각의 DB 하나의 디렉토리

• /usr/local/mysql/data/PHPSCHOOL• 각 테이블은 3 개의 파일로 구성•mytable.frm – 테이블 구조 정의•mytable.MYI – 색인 데이터•mytable.MYD – 실제 데이터

– 캐싱 내용• 테이블 구조• 색인 데이터• 개별 Rows 는 아님 !

저장방식– 각각의 DB 하나의 디렉토리

• /usr/local/mysql/data/PHPSCHOOL• 각 테이블은 3 개의 파일로 구성•mytable.frm – 테이블 구조 정의•mytable.MYI – 색인 데이터•mytable.MYD – 실제 데이터

– 캐싱 내용• 테이블 구조• 색인 데이터• 개별 Rows 는 아님 !

13 http://phpschool.com

InnoDB TablesInnoDB Tables

Oracle 과 유사 row-level locks

– 뛰어난 동시 읽기 / 쓰기 성능– Non-locking SELECT

유연한 transaction 지원 Foreign key 지원 주요 사용처

– Transaction 필요한 곳– 금융관련 주요 데이터

Oracle 과 유사 row-level locks

– 뛰어난 동시 읽기 / 쓰기 성능– Non-locking SELECT

유연한 transaction 지원 Foreign key 지원 주요 사용처

– Transaction 필요한 곳– 금융관련 주요 데이터

14 http://phpschool.com

InnoDB TablesInnoDB Tables

저장방식– 모든 데이터는 하나의 “ tablespace” 에 저장

• 하나 이상의 파일로 구성 • Row 데이터와 색인이 함께 저장• Redo/Undo 로그

– Transaction 로그• transaction 내역을 복수의 로그파일에 기록

– 캐싱 내용• 색인• 개별 Rows• 통합 buffer pool

저장방식– 모든 데이터는 하나의 “ tablespace” 에 저장

• 하나 이상의 파일로 구성 • Row 데이터와 색인이 함께 저장• Redo/Undo 로그

– Transaction 로그• transaction 내역을 복수의 로그파일에 기록

– 캐싱 내용• 색인• 개별 Rows• 통합 buffer pool

15 http://phpschool.com

HEAP TablesHEAP Tables

완전히 memory 만 이용 최대 용량에 제한 적합한 곳

– 고정적 읽기 테이블 임시 테이블은 HEAP 사용

– CREATE TEMPORARY TABLE …

완전히 memory 만 이용 최대 용량에 제한 적합한 곳

– 고정적 읽기 테이블 임시 테이블은 HEAP 사용

– CREATE TEMPORARY TABLE …

16 http://phpschool.com

NDB TablesNDB Tables

Alzato NDB 클러스터링 기술 이용– 데이터가 복수의 클러스터 노드에 존재– 입증된 고가용성 / 확장성 기술

• http://www.mysql.com/press/release_2003_30.html “MySQL AB Acquires Alzato”

Alzato NDB 클러스터링 기술 이용– 데이터가 복수의 클러스터 노드에 존재– 입증된 고가용성 / 확장성 기술

• http://www.mysql.com/press/release_2003_30.html “MySQL AB Acquires Alzato”

17 http://phpschool.com

ReplicationReplication

MySQL 은 LOG 기반 Replication 이용– Master 는 모든 쿼리를 로그로 남김

• binary log ( = binlog = replication log )

– Slaves 는 binlog 를 참고해 쿼리 실행• IO (relay) thread 와 SQL thread

다양한 Replication 구조 가능– Master/slave– Master/Master (dual-master)– Master/slave/slave (chained slaves)– 이상의 것들의 조합

http://www.mysql.com/doc/en/Replication.html

MySQL 은 LOG 기반 Replication 이용– Master 는 모든 쿼리를 로그로 남김

• binary log ( = binlog = replication log )

– Slaves 는 binlog 를 참고해 쿼리 실행• IO (relay) thread 와 SQL thread

다양한 Replication 구조 가능– Master/slave– Master/Master (dual-master)– Master/slave/slave (chained slaves)– 이상의 것들의 조합

http://www.mysql.com/doc/en/Replication.html

18 http://phpschool.com

Replication processReplication process

ClientClient

MasterMaster

1.Insert2.Update3.Delete…4…..

InsertUpdateDelete…

InsertUpdateDelete…

BINLOGBINLOG

DB/TablesDB/Tables

InsertUpdateDelete…

InsertUpdateDelete…

LoggingLogging

SlaveSlave

InsertUpdateDelete…

InsertUpdateDelete…

IO ThreadIO Thread

SQL ThreadSQL Thread

DB/TablesDB/Tables

19 http://phpschool.com

Replication situationReplication situation

mysql> show master status ;+------------+----------+--------------+------------------+| File | Position | Binlog_do_db | Binlog_ignore_db |+------------+----------+--------------+------------------+| db-bin.023 | 112198 | | |+------------+----------+--------------+------------------+1 row in set (0.00 sec)

mysql>

mysql> show slave status \G *************************** 1. row *************************** Master_Host: 210.118.169.50 Master_User: repl Master_Port: 3306 Connect_retry: 60 Master_Log_File: db-bin.023 Read_Master_Log_Pos: 111148 Relay_Log_File: www1-relay-bin.009 Relay_Log_Pos: 778804537Relay_Master_Log_File: db-bin.023 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_do_db: PHPSCHOOL,LOVESERA Replicate_ignore_db: mysql.user Last_errno: 0 Last_error: Skip_counter: 0 Exec_master_log_pos: 111148 Relay_log_space: 7788045371 row in set (0.00 sec)

mysql>

[root@www1 data]# ls *relay* master*master.info www1-relay-bin.009relay-log.info www1-relay-bin.index[root@www1 data]#

[root@db data]# ls db*db-bin.001 db-bin.010 db-bin.019db-bin.002 db-bin.011 db-bin.020db-bin.003 db-bin.012 db-bin.021db-bin.004 db-bin.013 db-bin.022db-bin.005 db-bin.014 db-bin.023db-bin.006 db-bin.015 db-bin.indexdb-bin.007 db-bin.016 db-slow.logdb-bin.008 db-bin.017 db.phpschool.com.errdb-bin.009 db-bin.018 db.phpschool.com.pid

[Master][Master] [Slave][Slave]

20 http://phpschool.com

Replication LayoutReplication Layout

Master/Slave Replication Master/Slave Replication

Slave

Master

Slave Slave

21 http://phpschool.com

Replication LayoutReplication Layout

Dual-Master Replication• 상당한 주의를 요망• Auto-Increment 필드 문제• primary 키를 별도 생성해 주어야 함

Dual-Master Replication• 상당한 주의를 요망• Auto-Increment 필드 문제• primary 키를 별도 생성해 주어야 함

Master Master

22 http://phpschool.com

Replication LayoutReplication Layout

Complex Replication Complex Replication

Master Master

Slave Slave Slave

SlaveSlave

23 http://phpschool.com

Replication LayoutReplication Layout

Two Data 센터 Two Data 센터

Master Local Master

Slave SlaveSlave Slave

24 http://phpschool.com

L4 Load BalancingL4 Load Balancing

L4 Switch

Slave SlaveSlave

Master

Read ConnectionRead Connection

Write ConnectionWrite Connection

25 http://phpschool.com

Replication setup Replication setup

1. 최신 버전의 MySQL 설치 1. 최신 버전의 MySQL 설치 # groupadd mysql# useradd -g mysql mysql# cd /usr/local# gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf -# ln -s full-path-to-mysql-VERSION-OS mysql# cd mysql# scripts/mysql_install_db# chown -R root .# chown -R mysql data# chgrp -R mysql .# bin/safe_mysqld --user=mysql &

26 http://phpschool.com

Replication setup Replication setup

2. Master 에 repl 유저 등록

※ LOAD TABLE FROM MASTER 또는 LOAD DATA FROM MASTER 명령을 사용하려면 다음 권한을 추가 .

2. Master 에 repl 유저 등록

※ LOAD TABLE FROM MASTER 또는 LOAD DATA FROM MASTER 명령을 사용하려면 다음 권한을 추가 .

mysql> GRANT REPLICATION SLAVE ON *.* TO repl@'%' IDENTIFIED BY 'replpasswd';Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SUPER , RELOAD ON *.* TO repl@'%' IDENTIFIED BY 'replpasswd';

27 http://phpschool.com

Replication setup Replication setup

3. master 의 snap-shot 만들기– 3.1 쓰기 쿼리를 막기 위해 READ LOCK 을

건다 .

– 3.2 데이타를 묶기

※ master.info ,relay-log.info 등의 로그 파일은 포함할 필요 없음 , replication 이 시작 되면 slave 에 자동으로 생성됨

3. master 의 snap-shot 만들기– 3.1 쓰기 쿼리를 막기 위해 READ LOCK 을

건다 .

– 3.2 데이타를 묶기

※ master.info ,relay-log.info 등의 로그 파일은 포함할 필요 없음 , replication 이 시작 되면 slave 에 자동으로 생성됨

mysql> FLUSH TABLES WITH READ LOCK;

# tar cvfpz ./master_snap.tgz . # tar cvfpz ./master_snap.tgz ./PHPSCHOOL ( 특정 DB 만 repl.)

28 http://phpschool.com

Replication setup Replication setup – 3.3 binlog 를 확인

– 3.4 Lock 을 푼다 .

– 3.5 스냅샷을 Slave 로 옮겨 압축을 푼다 .

– 3.3 binlog 를 확인

– 3.4 Lock 을 푼다 .

– 3.5 스냅샷을 Slave 로 옮겨 압축을 푼다 .

mysql> SHOW MASTER STATUS;+------------+----------+--------------+------------------+| File | Position | Binlog_do_db | Binlog_ignore_db |+------------+----------+--------------+------------------+| db-bin.004 | 7138| | |+------------+----------+--------------+------------------+1 row in set (0.00 sec)

mysql> UNLOCK TABLES;

29 http://phpschool.com

Replication setup Replication setup 4. Master 의 binlog 를 확인 한다 .

– /etc/my.cnf 에 아래 내용이 있는 지 확인 한다 .

– 없다면 추가하고 mysql.server restart 를 한다 . 5. slave 의 my.cnf 설정

• : master 와 다른 고유한 값 . 모든 slave 는 서로 다른 값을 가져야 한다 . 생략되면 디폴트 1.

4. Master 의 binlog 를 확인 한다 .– /etc/my.cnf 에 아래 내용이 있는 지 확인 한다 .

– 없다면 추가하고 mysql.server restart 를 한다 . 5. slave 의 my.cnf 설정

• : master 와 다른 고유한 값 . 모든 slave 는 서로 다른 값을 가져야 한다 . 생략되면 디폴트 1.

…[mysqld]log-binserver-id=1

…[mysqld]server-id=2

30 http://phpschool.com

Replication setup Replication setup

6. master 의 데이터 디렉토리를 복사 했다면 slave 를 start 하기 전에 data 디렉토리에 복사해 둔다 . 파일과 디렉토리 퍼미션 확인한다 .

7. slave 서버 start 1) repl 을 처음 실행하는 경우

※ data/master.info 가 만들어 진다 .c

6. master 의 데이터 디렉토리를 복사 했다면 slave 를 start 하기 전에 data 디렉토리에 복사해 둔다 . 파일과 디렉토리 퍼미션 확인한다 .

7. slave 서버 start 1) repl 을 처음 실행하는 경우

※ data/master.info 가 만들어 진다 .c

mysql> CHANGE MASTER TOMASTER_HOST='210.118.169.99',MASTER_USER='repl',MASTER_PASSWORD='replpasswd',MASTER_LOG_FILE='db-bin.004',MASTER_LOG_POS=7138 ;

mysql> start slave;

31 http://phpschool.com

Replication setup Replication setup – 2) /etc/my.cnf 를 수정 후 mysql.server start 하는

방법 (master.info 가 이미 존재하는 경우 )

* http://www.mysql.com/doc/en/Replication_Options.html

– 2) /etc/my.cnf 를 수정 후 mysql.server start 하는 방법 (master.info 가 이미 존재하는 경우 )

* http://www.mysql.com/doc/en/Replication_Options.html

#vi my.cnf....server-id = 2master-host = 210.118.169.50master-user = replmaster-password = replmaster-port = 3306slave-skip-errors=allreplicate-ignore-db = mysql.userreplicate-do-db = PHPSCHOOLreplicate-ignore-table = PHPSCHOOL.adviews....# mysql.server start

32 http://phpschool.com

Replication setupReplication setup

8. Master/Slave Status 확인– [master]

8. Master/Slave Status 확인– [master]

mysql> show master status;+------------+----------+--------------+------------------+| File | Position | Binlog_do_db | Binlog_ignore_db |+------------+----------+--------------+------------------+| db-bin.004 | 7032623 | | |+------------+----------+--------------+------------------+1 row in set (0.00 sec)

33 http://phpschool.com

Replication setupReplication setup– [slave]– [slave]

mysql> show slave status \G*************************** 1. row *************************** Master_Host: 210.118.169.** Master_User: repl Master_Port: 3306 Connect_retry: 60 Master_Log_File: db-bin.004 Read_Master_Log_Pos: 11595623 Relay_Log_File: www1-relay-bin.002 Relay_Log_Pos: 427515Relay_Master_Log_File: db-bin.004 Slave_IO_Running: Yes Slave_SQL_Running: Yes Replicate_do_db: PHPSCHOOL Replicate_ignore_db: mysql.user Last_errno: 0 Last_error: Skip_counter: 0 Exec_master_log_pos: 11595623 Relay_log_space: 4275151 row in set (0.00 sec)

34 http://phpschool.com

Replication setup Replication setup

9. process list 확인– [master]

– [slave]

9. process list 확인– [master]

– [slave]

mysql> SHOW PROCESSLIST ;+-------+--------+-----------+--------+-------------+------+----------------------------------+--------+| Id | User | Host | db | Command | Time | State | Info |+-------+--------+-----------+--------+-------------+------+----------------------------------+--------+| 44980 | repl | p2:36630 | NULL | Binlog Dump | 283 | Slave: waiting for binlog update | NULL |....

mysql> SHOW PROCESSLIST \G*************************** 1. row *************************** Id: 1 User: system user Host: db: NULLCommand: Connect Time: 3028861 State: Waiting for master to send event Info: NULL*************************** 2. row *************************** Id: 2 User: system user Host: db: NULLCommand: Connect Time: 4294967272 State: Has read all relay log; waiting for the I/O slave thread to update it Info: NULL

35 http://phpschool.com

TroubleshootingTroubleshooting

일반적인 문제– 데이터 손실 , 시스템 충돌

• 대부분 보고된 버그– 업그레이드 확인

•잘못된 설정 값– 과다한 메모리 사용

– Replication•Slave 싱크가 맞지 않을 경우

– Slave 를 직접 업데이트 하지 않는지 확인– http://www.mysql.com/doc/en/Replication_Features.html

•Slave 의 싱크가 늦을 경우– 대부분 시스템 병목이 원인

일반적인 문제– 데이터 손실 , 시스템 충돌

• 대부분 보고된 버그– 업그레이드 확인

•잘못된 설정 값– 과다한 메모리 사용

– Replication•Slave 싱크가 맞지 않을 경우

– Slave 를 직접 업데이트 하지 않는지 확인– http://www.mysql.com/doc/en/Replication_Features.html

•Slave 의 싱크가 늦을 경우– 대부분 시스템 병목이 원인

36 http://phpschool.com

TroubleshootingTroubleshooting

성능•CPU 를 100% 가까이 사용 중

– 색인을 이용하지 않는 쿼리– DNS 문제

•느린 쿼리– 추가적인 색인의 필요성 확인– 디스크 I/O 병목현상

» 복수의 디스크에 데이터 분산» RAID»심볼릭 링크

성능•CPU 를 100% 가까이 사용 중

– 색인을 이용하지 않는 쿼리– DNS 문제

•느린 쿼리– 추가적인 색인의 필요성 확인– 디스크 I/O 병목현상

» 복수의 디스크에 데이터 분산» RAID»심볼릭 링크

37 http://phpschool.com

MonitoringMonitoring

OS 모니터링– Disk 공간– CPU / Memory 사용량

MySQL 모니터링– Performance (queries/sec)– Cache 효율– 사용중인 Connections

OS 모니터링– Disk 공간– CPU / Memory 사용량

MySQL 모니터링– Performance (queries/sec)– Cache 효율– 사용중인 Connections

38 http://phpschool.com

MySQL monitoringMySQL monitoring SHOW FULL PROCESSLIST

– 접속중인 clients 목록– 실행중인 쿼리– 기타 유용한 정보

SHOW STATUS– MySQL 내부 상태 출력– 효율성 , 병목 현상 파악 시 유용

SHOW VARIABLES– 설정 값 출력 ( 튜닝 )

mytop– MySQL 상황 요약 출력

SHOW FULL PROCESSLIST– 접속중인 clients 목록– 실행중인 쿼리– 기타 유용한 정보

SHOW STATUS– MySQL 내부 상태 출력– 효율성 , 병목 현상 파악 시 유용

SHOW VARIABLES– 설정 값 출력 ( 튜닝 )

mytop– MySQL 상황 요약 출력

39 http://phpschool.com

MySQL monitoringMySQL monitoring

Mytop : http://jeremy.zawodny.com/mysql/mytop/ Mytop : http://jeremy.zawodny.com/mysql/mytop/

40 http://phpschool.com

MySQL monitoringMySQL monitoring

Mytop : Command stats Mytop : Command stats

41 http://phpschool.com

MySQL monitoringMySQL monitoring

mysqlrrd mysqlrrd

42 http://phpschool.com

MySQL monitoringMySQL monitoring

– #mysqladmin -uroot -plove -i3 status– #mysqladmin -uroot -plove -i3 status

43 http://phpschool.com

MySQL monitoringMySQL monitoring

class of mysql status - http://linuxchannel.net/ class of mysql status - http://linuxchannel.net/

44 http://phpschool.com

PHPSCHOOL System Layout PHPSCHOOL System Layout

www1 / www2P4 CPU 1.8 GHz512 M / 40 GRed Hat 8.0

www1 / www2P4 CPU 1.8 GHz512 M / 40 GRed Hat 8.0

DNS / backupP4 1.3GHz256 M / 40 GRed Hat 8.0

DNS / backupP4 1.3GHz256 M / 40 GRed Hat 8.0

DBMSAMD Opteron™ 1.4G RAM 2 GByteSCSI 40GRed Hat 8.0 x86_64

DBMSAMD Opteron™ 1.4G RAM 2 GByteSCSI 40GRed Hat 8.0 x86_64

DNS / backupDNS / backup MySQL DBMSMySQL DBMS

WWW2WWW2WWW1WWW1

TCP/IP SocketsTCP/IP Sockets

MySQL

Cool Backup

MySQL

Cool Backup

MySQL

Replication

MySQL

Replication

HTML Data RSYNCHTML Data RSYNC

45 http://phpschool.com

Q & AQ & A

46 http://phpschool.com

감사합니다 !감사합니다 !

loveme@phpschool.comloveme@phpschool.com

top related