SlideShare une entreprise Scribd logo
1  sur  238
Télécharger pour lire hors ligne
MySQL Administrator
네오클로바
▶ 2021. 06
2
목차
구분 내용
Basic
- MySQL 개요
- MySQL 설치 / 설정
- MySQL 아키텍처
- MySQL 스토리지 엔진
- MySQL 관리
- MySQL 백업 / 복구
- MySQL 모니터링
Advanced
- MySQL Optimization
- MariaDB / Percona
- MySQL HA (High Availability)
- MySQL troubleshooting
Next Opensource Cloud Value
MySQL 개요
4
MySQL 개요
• Open Source Relational Database
• 사용이 편리하고, 확장성이 좋으며, 우수한 성능
• 타 DB 대비 상대적으로 작은 크기
• MySQL AB -> Sun (2008) -> Oracle (2010)
• Initial release : 23 May 1995
5
MySQL 개요
 참고 사이트
• https://dev.mysql.com/
• https://github.com/mysql
• https://mariadb.org/
• https://www.percona.com/
 한국 사용자 그룹
• https://www.facebook.com/groups/623067261102382/
• https://www.facebook.com/groups/mariadbkorea
6
MySQL 개요
• Scale Up / Scale Out
• 상용 RDBMS 들은 일반적으로 Scale Up 을 지향
• MySQL은 Scale Out 에 기반을 두고 DB Architecture 설계 시 고성능 발휘
Scale Up 분류 Scale Out
• 높은 안정성
• 고성능
장점
• 저비용
• 장애시 서비스 Impact 적음
• 부분적 증설이 가능
• 지속적인 시스템 확장 가능
• 고비용
• 장애시 대형 장애로 연결
• 한대의 고성능 서버로 감당이 어려
운 경우 문제 발생
단점
• 많은 서버로 인한 관리 부담
• 각 서버의 장애 발생 가능성이 높음
7
MySQL 개요
 MySQL 편리성
• 다중 사용자, 다중 Thread 지원
• 다양한 응용프로그램 API제공
(C, C++, Java, Perl, PHP, Python, .Net, Ruby 등)
• ANSI SQL 표준 준수
• 다양한 스토리지 엔진 제공
8
MySQL 개요
 MySQL 확장성
• Table Partitioning
• Replication을 통한 읽기 확장
• Table 수준에서 다양한 특성의 Storage Engine 지원
• 보다 유연한 시스템 확장을 위해 전용 Router 지원
• Cloud 기반의 환경 지원 (AWS, Azure, GCP, OCI, SkySQL, Docker)
9
MySQL 개요
 MySQL 이식성
• 다양한 OS 환경 지원 (Linux, Window 32/64)
• 쉬운 Migration (MySQL, MariaDB, Percona)
• MySQL client 지원 (mysqldump, mysqladmin 등)
• 쉬운 Minor Upgrade
• OpenSource Ecosystem
10
MySQL 개요
 MySQL 보안
• MySQL Minor Patch include CVE
• SSL 지원
• user & host 기반의 Object별 Privileges
(user & host별 비밀번호, User Role)
• Data-at-Rest Encryption (MySQL TDE)
• Password Validation Plugin 지원
11
MySQL 개요
 MySQL 성능
• Table Partitioning
• Thread Pooling
• Replication
• Storage engine
• my.cnf configuration
• Database Proxy (ProxySQL, MaxScale, MySQL Router)
12
MySQL History
https://github.com/dveeden/mysql-history-graph
13
MySQL History
MySQL 1.0
1995
GPL MySQL
2000
MySQL 5.1
Percona
SUN MySQL
2008
MariaDB 5.1
Oracle MySQL
2009
MySQL 5.5
Percona 5.5 (2011)
MariaDB 5.5 (2012)
2010
MySQL 5.6 GA (2013)
MariaDB 10.0 GA (2013)
MariaDB 10.1 GA (2014)
MySQL 5.7 GA (2015)
MariaDB 10.2 GA (2016)
MariaDB 10.3 GA (2017)
2013
MySQL 8.0
MariaDB 10.4
Percona 8.0
2018
MariaDB 10.5 GA
Oracle MySQL cloud
MariaDB SkySQL
MariaDB 10.6 (2021)
2020
14
MySQL History
 History of MySQL
• https://dev.mysql.com/doc/refman/8.0/en/history.html
• We started out with the intention of using the mSQL database system to connect to our
tables using our own fast low-level (ISAM) routines. However, after some testing, we
came to the conclusion that mSQL was not fast enough or flexible enough for our needs.
This resulted in a new SQL interface to our database but with almost the same API
interface as mSQL. This API was designed to enable third-party code that was written for
use with mSQL to be ported easily for use with MySQL.
15
MySQL History
 History of MySQL
• MySQL is named after co-founder Monty Widenius's daughter, My.
• The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen from a huge list
of names suggested by users in our “Name the Dolphin” contest. The winning name was
submitted by Ambrose Twebaze, an Open Source software developer from Eswatini (formerly
Swaziland), Africa. According to Ambrose, the feminine name Sakila has its roots in
SiSwati, the local language of Eswatini. Sakila is also the name of a town in Arusha,
Tanzania, near Ambrose's country of origin, Uganda.
16
MySQL History
 Michael "Monty" Widenius
• https://en.wikipedia.org/wiki/Michael_Widenius
Ulf Michael Widenius (often called Monty; born 3 March 1962, in Helsinki,
Finland) is the main author of the original version of the open source MySQL
database, a founding member of the MySQL AB company and CTO of the MariaDB
Corporation AB
• https://monty-says.blogspot.com
• https://www.informatik-aktuell.de/betrieb/datenbanken/mariadb-
und-mysql-vergleich-der-features.html
• https://www.slideshare.net/Codemotion/my-sql-
mariadbstorycodemotion
Next Opensource Cloud Value
MySQL Install
18
MySQL 설치
source Package binary
• 서버 환경에 맞는 옵션을
지정하여 사용 가능
• configure 명령으로 옵션
지정
• OS 버전에 상관 없이 설치
가능
• 각 OS 별 최적화된 설치
파일
• 지정된 repository 에서
compile 된 binary 파일
및 환경설정을 모두
가져와 설치
• 설치가 간편함
• 각 OS 별 최적화된
compile 된 binary 제공
• core 의 옵션을 제외한
환경변수 설정 가능
• 원하는 환경변수를
이용하여 설치 가능
19
MySQL 설치
https://www.slideshare.net/neoclova
20
MySQL binary installation
1. MySQL binary file 다운로드
• 설치 경로 : /usr/local/mysql
• https://dev.mysql.com/downloads/ 사이트를 이용하여 다운로드
Directory Contents of Directory
bin mysqld server, client and utility programs
docs MySQL manual in Info format
man Unix manual pages
include Include (header) files
lib Libraries
share Error messages, dictionary, and SQL for database installation
support-files Miscellaneous support files
MySQL Installation Layout for Generic Unix/Linux Binary Package
21
MySQL binary installation
2. 사용자 그룹 및 사용자 생성
3. 파일의 압축 해제 및 디렉토리 생성
22
MySQL binary installation
4. my.cnf 설정
23
MySQL binary installation
5. MySQL initialize
• 설치 로그 확인 : error.log
• 데이터 디렉토리 확인
24
MySQL binary installation
 추가 작업
.bash_profile 설정
Secure installation 실행
25
MySQL binary installation
 추가 작업
Linux limit 설정
26
MySQL binary installation
 추가 작업
Linux systemd 설정
27
MySQL binary installation
 추가 작업
Linux systemd 설정
28
MySQL 실행 및 접속
 MySQL 실행
 MySQL 접속
29
MySQL Data File
 MySQL 기본 DataFile 구성
• Database directories
• Table format files (*.frm)
• Data and index files ( *.ibd – InnoDB )
• Own tablespace and log files (for InnoDB engine)
• Server logs and status files
30
MySQL Example Data
https://dev.mysql.com/doc/index-other.html
Next Opensource Cloud Value
MySQL Trend
32
MySQL Trend
2022 년 까지
70% 이상의 신규 개발 애플리케이션은
오픈소스 DB 를 이용할 것이며
“
50% 이상의 기존 업무가 상용 DB 에서
이관될 전망이다 .
Gartner | State of the Open-Source DBMS Market, 2018
33
MySQL Trend
 Dzone Trend Report : SQL or NoSQL in the Age of Big Data
https://dzone.com/trendreports/database-evolution
2020년 7월 보고서에 의하면 NoSQL보다 SQL을 더 많이 사용합니다. 그 이유는 시장의 예측보다 비정형 데이터
의 양이 지나치게 많아 지고 있으며 SQL 데이터베이스의 더 많은 경험자와 공급자들이 NoSQL 업체들과 경쟁할
수 있는 SQL의 새롭고 혁신적인 기능들을 개발하여 NoSQL 보다 좀 더 단순한 수준으로 제공을 하고 있습니다
34
MySQL Trend
https://db-engines.com/en/ranking
35
MySQL Trend
 DB-Engines 비교 : MySQL / MariaDB / Percona / PostgreSQL
PostgreSQL MariaDB MySQL Percona Server for MySQL
Primary database model Relational DBMS Relational DBMS Relational DBMS Relational DBMS
DB-Engines Ranking
#4 Overall
#4 RDBMS
#12 Overall
#8 RDBMS
#2 Overall
#2 RDBMS
#112 Overall
#55 RDBMS
Website www.postgresql.org mariadb.org www.mysql.com www.percona.com
Developer
PostgreSQL Global
Development Group
MariaDB Foundation Oracle Percona
Initial release 1989 2009 1995 2008
Current release 13.3 , May 2021 10.5.10, May 2021 8.0.25, May 2021 8.0.21-12, 2020
License Open Source Open Source Open Source Open Source
Replication methods Source-replica
Multi-source
Source-replica
Multi-source
Source-replica
Multi-source
Source-replica
In-memory capabilities no yes yes Yes
cluster Galera Cluster
Galera Cluster
NDB / InnoDB Cluster
XtraDB Cluster
36
MySQL Trend
PostgreSQL
EDB Postgres MySQL
Percona
MariaDB
Standard Enterprise community Enterprise community Enterprise
License OpenSource OpenSource Commercial OpenSource Commercial OpenSource OpenSource OpenSource
기술 지원
Subscription
(CPU core)
Subscription
(CPU core)
Subscription
(node)
Subscription
(node)
Subscription
(node)
DB Link O O O X X X Δ Δ
오라클 호환성 70% 75% 90% 70% 70%
Monitoring O O O O O
Hot Backup O O O O O O
SQL 관리 툴 O O O O O O
Replication O O O O O O O O
Cluster Galera Cluster InnoDB Cluster XtraDB Cluster Galera Cluster Galera Cluster
DB Proxy Pgpool Pgpool EFM ProxySQL MySQL Router ProxySQL MaxScale(BSL) MaxScale(BSL)
마이그레이션 툴 O O O O Δ Δ
 오픈소스 RDBMS (PostgreSQL, MySQL, Percona, MariaDB) 비교
37
MySQL Trend
MySQL Percona MariaDB
Community Enterprise Community Community Enterprise
모니터링 Enterprise Monitor PMM Monyog
백업 (Hot backup) Enterprise Backup Xtrabackup MariaBakcup MariaBakcup
SQL management MySQL Workbench MySQL Workbench Tadpole DB Hub SQLyog
Load Balancing & Routing MySQL Router MySQL Router ProxySQL MaxScale(BSL) MaxScale(BSL)
Firewall Enterprise Firewall ProxySQL MaxScale(BSL) MaxScale(BSL)
GTID MySQL GTID MySQL GTID MySQL GTID MariaDB GTID MariaDB GTID
Data Masking Enterprise Data Masking Plugin MaxScale(BSL) MaxScale(BSL)
Encryption Enterprise Encryption community community community
Audit Enterprise Audit community community community
Thread pool Enterprise Thread Pool community community community
 MariaDB / MySQL / Percona DBMS들의 community / Enterprise 버전 기능/특징 비교
Q&A
Next Opensource Cloud Value
MySQL Architecture
40
MySQL Architecture
41
MySQL Architecture
• 1’st Layer: Connectors
– MySQL client
– MySQL에 접근하기 위해 Application에서 설치하여 사용
– C, API, JDBC 등 언어에 따라 여러 가지 connector를 사용
• 2’nd Layer: MySQL Instance
– SQL 구문 분석
– 옵티마이저 최적화로 실행계획 작성
– 필요하면 메모리에 캐쉬
• 3’rd Layer: Storage Engine
– 데이터를 저장하고 추출
– 각각의 storage engine은 서로 다른 데이터 저장 및 추출 방법을 가짐
– InnoDB, Federated, MyISAM, MyRocks, …
42
MySQL Connectors
• Developed by MySQL
– ADO.NET Driver for MySQL (Connector/NET)
– ODBC Driver for MySQL (Connector/ODBC)
– JDBC Driver for MySQL (Connector/J)
– Python Driver for MySQL (Connector/Python)
– C++ Driver for MySQL (Connector/C++)
– C Driver for MySQL (Connector/C)
– C API for MySQL (mysqlclient)
• Developed by MySQL Community
– PHP Drivers for MySQL (mysqli, ext/mysqli, PDO_MYSQL, PHP_MYSQLND)
– Perl Driver for MySQL (DBD::mysql)
– Ruby Driver for MySQL (ruby-mysql)
– C++ Wrapper for MySQL C API (MySQL++)
43
MySQL Connectors
• Supported communication protocol
– Unix socket (Only Unix/Linux Local)
– TCP/IP (All OS)
– Shared memory (Only Window Local)
– Named pipes (Only Window Local/Remote)
• Port
– 3306 (default)
44
MySQL Server
 MySQL Engine (instance) + Storage Engine (Handler API)
• MySQL Engine
• 요청된 SQL 문장을 분석 & 최적화 하는 등의 일을 처리
• Connection Handler, SQL Parser, Precompiler, Optimizer, Cache, Buffer
• Storage Engine
• 실제 데이터를 disk 스토리지에 저장
• disk 스토리지로부터 데이터를 추출
MySQL Engine Storage Engine
45
MySQL Server
 MySQL Process
• mysqld
- 필수 main process
- connection 처리
- SQL 처리
- Data Storage 핸들링
• mysqld_safe
- mysqld를 background로 실행
- mysqld 모니터링
- optional process
46
MySQL Server
 MySQL Thread
• server process (mysqld) can create a number of threads
• Connection Manager Thread가 각 User Connection Thread 제어
• 각 User Connection Thread가 인증 및 Query 수행
• Signal Thread가 timeout 및 long idle 알림/제어
• Data / Record / Key / Table / Host / Privileges Cache 사용
• DBMS 관리를 위한 Background Threads (read/write, concurrency control, replication, and so on)
47
MySQL Server Process Flow
Application
Handler API
InnoDB MyISAM Federated MyRocks ....
SQL
Logging
Thread Cache
Connection
Manager
User
Authentication
Command
Diaspatcher
Query Cache
Module
Optimizer
(select)
Access Control
Table Manager
Parser
Table Open Cache
Table Definition Cache
Table
Modification
(Update)
Table
Maintenance
(Repairs)
Replication
(Primary, Replica)
Status
Report
(status)
48
MySQL Server Process Flow
• Connection Manager
– MySQL 내부에서 Connection을 관리하는 Manager
– 새로운 user connection thread를 DB에 할당
– Connection 생성과 함께 SQL 작업을 위한 메모리를 자동 할당
• User Authentication, Command Dispatcher
– 해당 세션의 자격증명이 확인되면 Command Dispatcher에게 요청 전달
– Query or Command 확인 후, Command는 Dispatcher가 단순 수행
복잡한 Command는 타 모듈에 Redirection 처리
– Query(DML)는 로그 기록 요청
– Query Cache 전달
49
MySQL Server Process Flow
• Cache & Buffer
– 자주 사용되는 데이터/인덱스를 빠르게 사용 하기 위한 메모리 저장 영역
– Query Cache 는 Select문 결과를 캐시 하여 매우 빠른 응답을 지원
– 데이터베이스 Metadata 메모리 캐시를 제공
– 스토리지 엔진에 따라 기능의 차이가 존재함
– 서버 전체, 엔진 별, 유저 별 캐시 존재
• Parser / Optimizer 모듈들
– 유저의 오브젝트 접근 권한 확인
– SQL문 실행을 위한 준비 작업
– SQL 문을 Database 내부 언어로 변환, 실행 경로 분석
– 모든 Storage engine에 동일하게 적용
50
MySQL Server Process Flow
• Access Control
– 요청된 작업에 대한 Objects(DB, Table, Column, …) 수행 권한 확인
– Table Manager 전달
• Table Manager
– 테이블 정의 파일(.frm) 작성, 수정
– Table Cache 유지보수
– 테이블 레벨 잠금
51
MySQL Server Memory
• Global (shared)
– query cache
– table open cache
– thread cache
– data/index cache
• Session (not shared)
– join buffer
– sort buffer
– temporary table
52
MySQL Server Memory
• InnoDB / XtraDB
– innodb_buffer_pool_size (shared)
– innodb_sort_buffer_size (not shared)
• MyISAM
– key_buffer_size (shared)
– myisam_sort_buffer_size (not shared)
Next Opensource Cloud Value
MySQL
Configuration
54
MySQL Configuration
 설정 파일 경로
• 단 하나의 설정파일(my.cnf)만 사용
• 설정파일을 지정 해서 적용 가능
• my.cnf 가 명시되지 않는 경우 defaults path 중 아래의 순서대로 사용됨
- /etc/my.cnf
- /etc/mysql/my.cnf
- my.cnf in the DEFAULT_SYSCONFDIR specified during the compilation
- the file specified in --defaults-extra-file (if any)
- user-home-dir/.my.cnf
55
MySQL Configuration
 설정 변수
• MySQL 8.0
- https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html
- https://dev.mysql.com/doc/mysqld-version-reference/en/optvar.html
• MariaDB
- https://mariadb.com/kb/en/server-system-variables/
- https://mariadb.com/kb/en/system-variable-differences-between-mariadb-105-and-mysql-80/
56
MySQL Configuration
 Port / Path 설정
57
MySQL Configuration
 Cache / Buffer 설정
58
MySQL Configuration
 InnoDB 설정
59
MySQL Configuration
 Connection, Log, Character Set 설정
60
MySQL Configuration
 Replication 설정
Next Opensource Cloud Value
MySQL
Variables / Status
62
MySQL Variables
 Server System Variables
https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html
• Server 기동 시 사용: command-line 과 option file 이용
• Server 운영 중에 SET 명령어로 바꿀 수 있음
– System variable 이름과 값 보기
 mysqld --verbose –help
– 현재 사용중인 server variable 보기
63
MySQL Variables
 동적 변수와 정적 변수
– 동적 변수 (dynamic)
 기동 중인 상태에서 변경 가능 한 변수
– 정적 변수 (static)
 기동 중인 상태에서 변경 불가능한 변수로 설정파일을 통해 변경 후 서비스를 재시작 해야 함
 세션 변수와 글로벌 변수
– 세션 변수 (session)
 클라이언트가 데이터베이스 서버에 접속해서 사용하는 옵션을 제어하는데 사용하는 변수
– 글로벌 변수 (global)
 하나의 데이터베이스 서버 인스턴스에서 전체적으로 영향을 미치는 시스템 변수
 SHOW GLOBAL VARIABLES로 확인
64
MySQL Variables
 동적 변수 변경 (dynamic)
• GLOBAL VARIABLES 수정
• SESSION VARIABLES 수정
• 서버가 실행되는 동안 설정파일 변경 없이 시스템변수 변경 가능
• 주의) 영구 적용은 my.cnf 수정 필요
• 동적 변수 설정 시 주의사항
- MB, GB와 같은 단위 표기법 사용불가
- 2 * 1024 * 1024 같은 수식 사용 가능
65
MySQL Variables
 Buffer, Cache 변수
• key_buffer_size
- dynamic ( global )
- Index block에서 사용하는 메모리 buffer 크기이며 MyISAM 변수
• innodb_buffer_pool_size
- dynamic ( global )
- InnoDB용 Data/Index Page 버퍼 크기
- 물리메모리의 최대 80%까지, 권고 50~70%
• join_buffer_size
- dynamic ( global / session )
- join 에서 사용하는 버퍼의 크기
66
MySQL Variables
 Buffer, Cache 변수
• read_buffer_size
- dynamic ( global / session)
- 순차적인 검색을 하는 Thread에 할당되는 버퍼의 크기
• sort_buffer_size
- dynamic ( global / session )
- 정렬할때 Thread에 할당하는 버퍼의 크기
- 기본값 2M, 적게 설정하고 필요한 세션만 늘려서 사용
• max_join_size
- dynamic ( global / session )
- 최대 join 되는 크기 (18,446,744,073,709,551,615)
67
MySQL Variables
 Buffer, Cache 변수
• table_open_cache
- dynamic ( global)
- 모든 thread에서 열린 table수의 최대 크기
• query_cache_size
- dynamic ( global )
- 이미 실행된 SQL Query의 결과값을 저장해 놓은 Cache크기
- 동일결과를 반복적으로 수행하는 읽기 위주의 thread가 많으면 효과적
• tmp_table_size
- dynamic ( global / session )
- 임시테이블의 최대 메모리 크기
68
MySQL Variables
 Buffer, Cache 변수
• thread_cache_size
- Dynamic ( global )
- cache에 저장해둔 thread 수
- thread 생성시 cache에 thread가 있으면 생성하지 않고 재사용함
• innodb_thread_concurrenty
- dynamic ( global )
- 동시에 수행 가능한 thread 수
- 너무 많으면 지나친 context switching, 너무 적으면 장비의 비효율
- 0 제한 없음, (cpu core *2 + disk num)
69
MySQL Status
 Server Status Variables
https://dev.mysql.com/doc/refman/8.0/en/server-status-variables.html
 Global Status
• 운영 중인 데이터베이스의 상태 보기
70
MySQL Status
 Connection 상태
• Connections
- 연결시도 횟수 = 사용량
• Max_used_connections
- 최대 동시 접속자수
- 이 값을 확인 후에 MAX_CONNECTIONS의 값을 조정
• Aborted_connects
- 연결을 시도해서 실패한 횟수, Max_used_connections 를 확인
• Aborted_clients
- 연결 후, 클라이언트에서 연결이 적절하게 닫지 못해 취소된 횟수
- 네트워크 연결에 문제 가능성 높음
71
MySQL Status
 InnoDB 상태
• innodb_buffer_pool_pages_total
- InnoDB Buffer Pool의 페이지 수
- Innodb_buffer_pool_pages_free
- innodb_page_size=16K
• innodb_buffer_pool_reads, innodb_buffer_pool_read_requests
- InnoDB Buffer Pool 미 적중으로 디스크에서 읽은 수
- InnoDB Buffer Pool 읽기 요청 수
- InnoDB Buffer Cache Hit Ratio !!
72
MySQL Status
 Query 상태
• Questions, Queries
- server로 보낸 쿼리 횟수
- SP 내부의 queries 수 차이
- QPS (초당 쿼리 수) : Questions와 Uptime 이용
• Table_locks_waited
- table lock을 위해 대기한 수
• Select_full_join
- INDEX를 사용하지 않은 조인 쿼리 실행 횟수
- 이 값이 너무 크면 TABLE의 INDEX 검토
- 쿼리 튜닝 검토
73
MySQL Status
 Open Tables 상태
• open_tables, opened_tables
- 열린, 열었던 table 수
- 이 값이 너무 크면 table_open_cache 값을 증가
Q&A
Next Opensource Cloud Value
MySQL
Storage Engine
76
MySQL Storage Engine
77
MySQL Storage Engine
• 스토리지 엔진은 하나의 모듈로서 작동
• 스토리지 엔진을 별도 컴파일 하여 서버에 적재가 가능
• 지속적으로 새로운 내부 스토리지 엔진을 개발
• 개별적인 스토리지 엔진이 다양하게 개발됨
78
MySQL Storage Engine
스토리지 엔진 MySQL MariaDB 트랜잭션 잠금 주요 응용 프로그램
InnoDB O >= 10.2.x Yes MVCC 트랜잭션 처리
XtraDB Percona
>= 5.1.x
<= 10.1.x
Yes MVCC 트랜잭션 처리
MEMORY O >= 4.0 No 테이블 중간 계산, 통계 참조
ColumnStore >= 10.1.x Yes MVCC 대용량 분석 (OLAP)
FederatedX Federated >= 10.0.x Yes N/A 원격 서버 연결
CONNECT >= 10.0.x Yes N/A 이기종 DB 및 파일 연결
TokuDB Percona >= 5.5.x Yes MVCC 트랜잭션 처리, 로깅
Xpand >= 10.5 Yes MVCC newSQL (Clustrix)
NDB O Yes MVCC 고성능 트랜잭션
79
MySQL Storage Engine
스토리지 엔진 MySQL MariaDB 트랜잭션 잠금 주요 응용 프로그램
MyISAM O > 3.23 No 동시 insert 가능 SELECT, INSERT 대량 적재
Aria >= 5.1 No 동시 insert 가능 MyISAM 활용
Archive O >= 4.1 No row 로깅, 집계 분석
CSV O >= 4.1 No 테이블 로깅, 외부 데이터 대량 적재
BLACKHOLE O >= 4.1 N/A N/A 로깅, 복제 아카이브
MRG_MyISAM Merge >= 3.23 No 동시 삽입 가능 테이블 MyISAM 테이블의 모음
SphinxSE >= 10.0 N/A N/A Full Text Search
Mroonga >= 10.0 No No Groonga기반 FTS
Example O Example code
80
MySQL Storage Engine
스토리지 엔진 MySQL MariaDB 트랜잭션 잠금 주요 응용 프로그램
OQGRAPH >= 10.0 N/A N/A 계층구조, 그래프 처리
Sequence >= 10.0 Yes Read-only 임시테이블용 시퀀스
Spider Tencent >= 10.0 Yes row 샤딩
Cassandra >= 10.0 N/A N/A SQL/NoSQL간 데이터 통합
MyRocks Facebook >= 10.2.x Yes MVCC 트랜잭션 처리
S3 >= 10.5 Read-only archive tables in Amazon S3
MindsDB >= 10.5 Machine Learning
81
MySQL Storage Engine
 show engines
• 현재 사용 가능한 engine 조회
• transactional 지원 여부 조회 가능
82
MySQL Storage Engine
 General Purpose Storage Engines
• Transactional
• InnoDB, TokuDB, MyRocks, NDB, Xpand
• Non-Transactional
• MyISAM
 Analytics and Data Warehousing
• ColumnStore
 Special Purpose Storage Engines
• Connect, Memory, Spider, Archive, Blackhole, CSV,...
 Full Text Search Storage Engines
• SphinxSE, Mroonga
83
MySQL Storage Engine
 MyISAM
• MySQL 3.23.x 이후 버전에서 사용 가능
• Data 저장이 효율적이고 빈번한 Data 사용의 부하를 잘 소화함
• B-tree, R-tree & Full-text Index를 지원
• 특정 Index에 대한 Memory Cache를 지원 ( key_buffer_size )
• Data 압축에 대한 옵션을 제공 ( fixed / dynamic / compressed )
• Table 레벨의 Lock을 지원 & Transaction 미지원
• Backup 및 특정 시점으로의 복구 지원
• .frm / .myd / .myi 파일로 구성 ( Table 구조정보 / data / index )
• engine = myisam 형태로 지정
84
MySQL Storage Engine
 Memory
• Non-transactional Storage Engine
• Memory 에 모든 data 가 저장됨
• 고정길이열의 컬럼만 사용 가능함 (varchar, blob, text 컬럼 사용불가)
• 타 Engine 에 비해 DML 속도가 월등히 빠름 (고정 길이열 기반으로 인함)
• Server 의 재 구동 시 Data는 모두 소실
• 동등 조건( ex) where a=10 ) 검색에 HASH기반 검색을 제공
• 범위 검색 시 Index 를 사용할 수 없음
• temporary table 과 다르게 타 세션에서도 조회가 가능
85
MySQL Storage Engine
 Archive
• 자동적인 Data 압축을 지원
• 다른 Storage Engine 대비 80%의 저장공간 절약
• 실제적인 저장용량의 제한 없음
• Index 미지원
• 빠른 Insert 속도를 위해 특별한 입력 버퍼를 제공
• Insert와 select만을 지원
• row레벨 Lock을 지원
• Backup 및 특정 시점으로의 복구 지원
• 데이터 웨어하우스, 데이터 감사 등에 사용
86
MySQL Storage Engine
 Federated
• MySQL 5.0에 Federated engine 도입
• 원격의 물리적 Data 객체에 대한 논리적 Data 객체를 생성
• 하나의 Data 객체에서 다른 타겟 객체로의 ‘포인터’역할
• 원격 Data 접근을 위한 특별한 미들웨어가 필요하지 않음
• 실행 속도는 네트워크 성능에 따라 좌우됨
• 실제 Data 객체의 Engine 특성에 따라 처리됨
• Table 정의를 통한 SSL 보안 처리
• 모든 SQL 오퍼레이션 지원( as per target object )
• 분산 데이터베이스 환경에서 사용
87
MySQL Storage Engine
 MyROCKS
- A RocksDB storage engine with MySQL
- Benefit from all the features of MySQL while using RocksDB as backend storage
- http://myrocks.io/
- https://www.facebook.com/groups/myrocks/
- open source storage engine : developed by Facebook
- MyRocks, typically, gives greater performance for web scale type applications
- It can be an ideal storage engine solution when you have workloads that require greater
compression and IO efficiency.
- https://mariadb.com/kb/en/library/about-myrocks-for-mariadb/
88
MySQL Storage Engine
 MyROCKS Benefits
- Greater Space Efficiency
2x more compression : MyRocks has 2x better compression compared to compressed InnoDB, 3-4x better
compression compared to uncompressed InnoDB, meaning you use less space.
- Greater Writing Efficiency
2x lower write rates to storage : MyRocks has a 10x less write amplification compared to InnoDB,
giving you better endurance of flash storage and improving overall throughput.
- Faster Data Loading
faster database loads : MyRocks writes data directly onto the bottommost level, which avoids all
compaction overheads when you enable faster data loading for a session.
- Faster Replication
No random reads for updating secondary keys, except for unique indexes. The Read-Free Replication
option does away with random reads when updating primary keys, regardless of uniqueness, with a row-
based binary logging format.
89
MySQL Storage Engine
 MyROCKS using (MariaDB)
Next Opensource Cloud Value
MySQL InnoDB
91
MySQL InnoDB
• Heikki Tuuri 에 의해 개발됨
• Oracle Corp 에서 소유권을 가지고 있음
• XtraDB는 Percona의 open source
• The default engine is InnoDB in MySQL 8.0
• By default, until MariaDB 10.1, MariaDB uses the XtraDB storage engine, a
performance enhanced fork of the InnoDB storage engine. From MariaDB 10.2,
InnoDB is the default
• https://mariadb.com/kb/en/library/why-does-mariadb-102-use-innodb-instead-of-xtradb/
92
MySQL InnoDB
• Transaction-Safe 스토리지 엔진
• Primary Key 에 의한 클러스터링
• 모든 InnoDB 테이블은 기본적으로 PK 를 기준으로 클러스터링 되어 저장
• PK 에 의한 range 스캔에 최적화
• optimizer 가 PK 에 의한 실행계획을 더 선호함
• Oracle 의 IOT 와 동일한 구조
• 읽기 일관성 보장 ( Non-locking consistent read )
• MVCC ( Multi Version Concurrency Control )
• Foreign Key 지원
93
MySQL InnoDB
• 자동 Deadlock 감지
• Deadlock 발생시 Server 에서 바로 감지
• Deadlock 트랜잭션 중 Rollback이 가장 용이한 트랜잭션 강제 종료
• show engine innodb status 명령으로 확인
• 자동 장애 복구
• MySQL 서버의 구동 시 완료되지 못한 트랜잭션 복구
• disk에 일부만 기록된 데이터 페이지 복구
• mysqld_safe 를 이용한 mysqld 의 모니터링 및 장애 시 restart 수행
94
MySQL InnoDB
• 동시접속 퍼포먼스가 뛰어나 대용량 데이터 처리에 적합
• 메인 메모리내 데이터 캐싱 및 인덱싱 위한 버퍼 풀(pool)을 관리
• innodb_buffer_pool_size
• 테이블과 인덱스를 테이블 스페이스에 저장
• 테이블 스페이스를 몇개의 파일이나 disk 파티션으로 구성
cf) MyISAM은 테이블과 인덱스를 각각 분리된 파일로 관리
• InnoDB 테이블은 OS 파일 사이즈에 독립적인 파일 사이즈를 가짐
• 트랜잭션의 동시성 퍼포먼스가 필요한 대용량 사이트에 적합
95
MySQL InnoDB
Connection Manager Thread Signal Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Client
Client
Client
Client
Client
Insert Buffer Thread
InnoDB File I/O Threads
InnoDB
Log Thread
Read Thread
Write Thread
Storage Engine
innodb_read_io_threads
innodb_write_io_threads
96
MySQL InnoDB
97
MySQL InnoDB
Log Buffer
( buffered log records )
Buffer Pool
( buffered data pages )
Additional Mem Pool
Commit
( + checkpoint )
Log File 1
Log File 2
Log File 3
Redo
Log
ibdata1
data file
checkpoint
In Memory On Disk
Log
Files
Tablespace
Undo Log
ibdata2
data file
iblogfile1
innodb_file_per_table=0
innodb_max_purge_log
InnoDB Log / Data Disk Write
98
MySQL InnoDB
Memory
buffer pool
Page level cache for tables and indexes
Insert buffer part of buffer_pool
Adaptive hash search – Speeds up search by secondary
indexes lookups and range scans
Open tables info
Misc internal memory :
Page hash
File system Lock system
Recovery system
Threads
Disk
Table1.ibd
pages
Table2.ibd
pages
Table3.ibd
pages
XtraDB : I_S.INNODB_BUFFER_POOL_PAGES
show content of buffer_pool
InnoDB-std : may tabke ½ of buffer pool
XtraDB : innoDB_ibuf_max_size
Disable : innodb_change_buffering=0
background thread
“merges” buffer with indexes
Query
Query
XtraDB : Check sizes in
SHOW ENGINE INNODB STATUS
InnoDB-std : can grow unlimitedly
XtraDB : innodb_dict_size_limit
XtraDB : Check sizes in
SHOW ENGINE INNODB STATUS
innodb_buffer_pool_size is cretical
parameter Thumb rule : 60-80% of RAM
Table1.ibd
Table2.ibd
Table3.ibd
Primary Key
== data
Secondary
indexes
.ibd are placed separately if
innodb_file_per_table=1
Otherwise in ibdata1
Files are divided by 16K pages
XtraDB : 4K, 8K, 16K
ibdata1 ( system table space )
Data dictionary
Double write buffer
Insert buffer
Changes to secondary non-unique indexes are buffered there
Rollback segments
UNDO space
Undo
slot
Undo
slot
Undo
slot
XtraDB : you can view content in
I_S.INNODB_SYS_TABLES,
I_S.INNODB_SYS_INDEXES
Innodb-std : rollback segment is 1
XtraDB : innodb_extra_segments
1023 slots per segment
Pointers to undo space
UNDO space may grow unlimitedly
XtraDB : innodb_use_purge_thread=1
to use separate threads for cleaning
log file
log file
Log buffer
Usually changes are fixed
In background “log thread”
on disk with fsync() command.
innodb_flush_log_at_trx_commit
controls how to fsync
innodb_log_buffer_size
4M-16M is good value
Changes are fixed in
log file via log buffer
Insert buffer is
written from BP to disk
Pages are written in background
innodb_write_io_threads.
innodb_flush_method=O_DIRECT
To avoid caching in OS cache
Writes are done via
“double write buffer”
to prevent corruptions
REDO LOGS
innodb_lof_file_size
InnoDB-std : max size < 4GB
XtraDB : max size < 2TB
innodb_log_files_in_group ( usually 2-3 )
Reads are done in foreground.
innodb_read_io_threads are for read-ahead
99
MySQL InnoDB
commit – Write to disk
commit
Write & Flush to disk - every 1 Second
Log Files
O/S buffer
Log Buffer
InnoDB
Update table set col1 ....
commit - Write & Flush to disk
Update table set col1 ....
Flush to disk - every 1 Second
Variables
0
1
2
Update table set col1 ....
1s
1s
innodb_flush_method=O_DIRECT
innodb_flush_log_at_trx_commit
InnoDB Redo Log Write
100
MySQL InnoDB
 InnoDB Data Flush
• buffer pool 의 dirty pages에 대해 주기적으로 disk flush
• main thread 에서 checkpoint 를 발생하거나 free page 가 없는 경우
write thread 를 통해 disk 로 flush 함
• undo log 의 flush 는 checkpoint 와 별개로 동작
Buffer Pool
( dirty pages )
ibdata1
data file
checkpoint
Tablespace
Undo Log
ibdata2
data file
innodb_max_purge_log
In Memory On Disk
Write
Thread
Disk Flush
dirty page pagedata
innodb_max_dirty_pages_pct
innodb_io_capacity
pagedata
101
MySQL InnoDB Variables
• INNODB_DATA_HOME_DIR
– 테이블스페이스 파일의 생성 위치 설정
• INNODB_DATA_FILE_PATH
– 테이블스페이스 파일 명 및 크기, 옵션 설정
– ibdata1:100M:autoextend:max:1G
 ibdata1라는 파일명으로 생성
 100MB의 고정크기로 최초 생성
 100MB가 넘을 경우 “autoextend” 라는 옵션으로 자동으로 파일 크기가 확장
 최대 확장되는 크기는 MAX 옵션의 설정 값만큼 확장
• INNODB_AUTOEXTEND_INCREMENT
– autoextend 옵션으로 자동 확장되는 크기 지정
– Default Value: 64 (from MariaDB 10.0) 8 (before MariaDB 10.0)
– Size in MB to increment an auto-extending shared tablespace file when it becomes full
102
MySQL InnoDB Variables
• INNODB_FILE_PER_TABLE
– 공용 테이블스페이스 사용 대신에 테이블 별 테이블스페이스 사용 옵션
– TableName.ibd 파일 생성
• INNODB_BUFFER_POOL_SIZE
– 테이블의 데이터와 인덱스를 캐시하기 위해 사용하는 메모리 버퍼의 크기
– 크게 설정하면 할수록, data의 disk I/O가 적어짐
– 전체 물리메모리의 70~80%로 설정하나, 세션수가 많으면 50%로 설정
– ORACLE DB_BUFFER_CACHE와 유사
• INNODB_BUFFER_POOL_DUMP_AT_SHUTDOWN/STARTUP
– 데이터와 인덱스 캐시를 위한 메모리 버퍼의 재사용을 위해
중지/재시작 시 버퍼정보를 파일에 기록/로딩함
103
MySQL InnoDB Variables
• INNODB_LOG_FILE_SIZE
– Redo 로그 파일의 크기 설정
– 순차적으로 파일이 일정한 크기와 용량으로 순환식으로 생성
– Larger values mean less disk I/O due to less flushing checkpoint activity, but also slower recovery
from a crash
• INNODB_LOG_GROUP_HOME_DIR
– Redo 로그 파일에 대한 디렉토리 경로 설정
• INNODB_LOG_FILES_IN_GROUP
– Redo 로그파일 개수
• INNODB_LOG_BUFFER_SIZE
– Redo 로그 파일을 기록하기 위한 버퍼 사이즈
104
MySQL InnoDB Variables
• INNODB_LOCK_WAIT_TIMEOUT
– 롤백이 진행되기 전에 lock을 대기하는 시간 ( default 50 )
• INNODB_THREAD_CONCURRENCY
– InnoDB 내부에 OS 쓰레드 동시 사용 설정
– 설정된 값과 같거나 적게 유지
– A setting of 0, the default, permits as many threads as necessary
– A suggested setting is twice the number of CPU's plus the number of disks
• INNODB_FLUSH_LOG_AT_TRX_COMMIT
– Commit 동작 시 데이터를 log file 에 기록여부를 설정
 0 : log buffer내용이 1초 간격으로 로그파일에 쓰여지고 flush, commit시 미동작
 1 : log buffer내용이 commit할 때에 로그 파일에 쓰여지고 flush
 2 : log buffer내용이 commit할 때에 로그 파일에 쓰여지고 flush는 1초 간격으로 동작
105
MySQL InnoDB Variables
• INNODB_FLUSH_METHOD
– Flush 명령어 방식 설정, 디폴트는 fdatasync
 fdatasync : fsync()를 사용해서 데이터와 로그 파일을 flush
 O_SYNC : 로그 파일을 열고 flush 하지만, 데이터 파일을 flush하기 위해서는 fsync()를 사용
 O_DIRECT : O_DIRECT를 사용해서 데이터 파일을 열고, 데이터 파일과 로그 파일을 flush
 Windows에서는 flush 방식은 항상 async_unbuffered 사용
106
MySQL InnoDB Variables
• INNODB_STATS_PERSISTENT
– ANALYZE TABLE 명령 수행 후에 통계가 disk에 저장될지 여부
• INNODB_STATS_PERSISTENT_SAMPLE_PAGES
– Indexed column의 통계를 측정할 때 샘플링 할 page 수
– 값이 크면 index통계의 정확도는 올라가나, 통계정보 수집 시 I/O 증가할 수 있음
• INNODB_STATS_TRANSIENT_SAMPLE_PAGES
– INNODB_STATS_PERSISTENT가 off일 때 샘플링 할 page 수
107
MySQL InnoDB Variables
• INNODB_STATS_AUTO_RECALC
– Default는 on, table에서 10% 이상의 row가 변경되면 자동으로 persistent statistics를 재계산 함
• INNODB_STATS_ON_METADATA
– Show table status, Show index 또는 INFORMATION_SCHEMA의 tables/statistics 테이블 접근 시 자동으로 통
계정보 수집
– Default Value: OFF (from MariaDB 10.0), ON (before MariaDB 10.0)
108
MySQL InnoDB Variables
• INNODB_UNDO_LOGS
• INNODB_UNDO_TABLESPACES
• INNODB_UNDO_DIRECTORY
– Path to the directory (relative or absolute) that InnoDB uses to create separate tablespaces for the
undo logs. (the default value before 10.2.2) leaves the undo logs in the same directory as the other
log files. From MariaDB 10.2.2, the default value is NULL, and if no path is specified, undo
tablespaces will be created in the directory defined by datadir. Use together with innodb_undo_logs and
innodb_undo_tablespaces. Undo logs are most usefully placed on a separate storage device.
– Default Value: NULL (>= 10.2.2), . (<= 10.2.1)
– Introduced: MariaDB 10.0.0
https://dev.mysql.com/doc/refman/8.0/en/innodb-undo-tablespaces.html
Q&A
Next Opensource Cloud Value
MySQL
Data Types
111
MySQL Data Types
 String Data Types
– 고정 길이
• CHAR(0~255), BINARY(0~255)
– 가변 길이
• VARCHAR(0~65535), VARBINARY(0~65535)
– LOB, TEXT
• TINYBLOB(2^8-1), BLOB(2^16-1), MEDIUMBLOB(2^22-1), LONGBLOB(2^32-1)
• TINYTEXT(2^8-1), TEXT(2^16-1), MEDIUMTEXT(2^22-1), LONGTEXT(2^32-1)
– ENUM
• MAX 65535 values
주의) MySQL/MariaDB에서 size는 문자열의 길이를 감안해서 이기종 DBMS에서 데이터 이행 시 고려
112
MySQL Data Types
 Numeric Data Types
– BOOLEAN
– BIT(1~64)
– TINYINT SIGNED/UNSIGNED : (-128~127 / 0~2^8)
– SMALLINT SIGNED/UNSIGNED : (-2^15~2^15-1 / 0~2^16)
– MEDIUMINT SIGNED/UNSIGNED : (-2^23~2^23-1 / 0~2^24)
– INT SIGNED/UNSIGNED : (-2^31~2^31-1 / 0~2^32)
– BIGINT SIGNED/UNSIGNED : (-2^31~2^31-1 / 0~2^32)
– DECIMAL(p,s) : 고정소수점, p-65, s-30
– FLOAT(p,s) : 부동소수점,근사치, p-23
– DOUBLE(p,s) : 부동소수점,근사치, p-53
113
MySQL Data Types
 Date/Time Data Types
– DATE
• ‘1000-01-01’ ~ ‘9999-12-31’
• ‘0000-00-00’ 허용가능 (sql_mode 미설정 ‘NO_ZERO_DATE’)
– TIME
• ‘HH:MM:SS.ssssss’
– DATETIME
• ‘1000-01-01 00:00:00.000000’ ~ ‘9999-12-31 23:59:59.999999’
– TIMESTAMP
• ‘1970-01-01 00:00:00’ ~ ‘2038-01-19 03:14:07’
– YEAR(4)
114
MySQL Data Types
 Binary Types
– BINARY / VARBINARY / TINYBLOB / BLOB / MEDIUMBLOB / LONGBLOB
– BINARY and VARBINARY are Case-Sensitive Versions of CHAR and VARCHAR
– No Character Set and Collation for Binary Types - ordered by bytes
– Blobs are Used often to Store Files in a Database
– Files on Disk are often Faster
– Blobs are Included in Transactions, Replication, and Backups
– Blobs 는 mysqld 메모리 사용량을 증가시킵니다
115
MySQL Data Types
 JSON Types
– https://dev.mysql.com/doc/refman/8.0/en/json.html
– MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in
JSON (JavaScript Object Notation) documents.
116
MySQL Data Types
 JSON Types (MariaDB)
– JSON is an alias for LONGTEXT introduced for compatibility reasons with MySQL's JSON data type
– In order to ensure that a valid json document is inserted, the JSON_VALID function can be used as a
CHECK constraint
– This constraint is automatically included for types using the JSON alias from MariaDB 10.4.3
– JSON Functions : https://mariadb.com/kb/en/library/json-functions/
117
MySQL Data Types
 auto_increment
– LAST_INSERT_ID()
– SERIAL is a synonym for "BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE"
118
MySQL Data Types
 Virtual Column
– Two Virtual Column Types:
• PERSISTENT (stored)
• VIRTUAL (generated only)
– All Data Types Supported
– Use PERSISTENT for Indexes – Cannot be Primary Key
– Used with InnoDB, Aria, MyISAM, CONNECT
Next Opensource Cloud Value
MySQL Transaction
120
MySQL Transaction
 Transaction
– 트랜잭션(Transaction) 은 더 이상 나뉠 수 없는 하나의 업무단위
– 데이터베이스 내에서 한꺼번에 수행되어야 할 일련의 연산
– All or Nothing
– Commit 시 모든 작업 결과는 데이터베이스에 반영
– Rollback 시 모든 작업 결과가 데이터베이스에 미반영
121
MySQL Transaction
 은행 입출금
122
MySQL Transaction
 ACID
– 원자성 (Atomicity)
 Transaction 은 더 이상 분류할 수 없는 작업 단위
 모든 데이터 수정 작업이 수행되거나 되지 않아야 함
– 일관성 (Consistency)
 Transaction 전후 도메인의 유효성, 무결성 제약조건등을 만족해야 함
– 고립성 (Isolation)
 동시 Transaction 에 의한 수정은 다른 동시 Transaction 에 의한 수정과 격리
 Transaction 중간의 데이터는 변경을 수행한 Transaction 에서만 확인됨
– 영속성 (Durability)
 Transaction 이 완료되면 영구적으로 시스템에 적용
 시스템 오류와 무관하게 데이터는 보존
123
MySQL Transaction
 Transaction 세가지 형태
Transaction A Transaction B Transaction C
BEGIN BEGIN BEGIN
READ READ READ
WRITE WRITE WRITE
READ READ READ
... ... ...
WRITE ABORT SYSTEM ABORT
COMMIT ROLLBACK SYSTEM ROLLBACK
Transaction 정상 종료 잘못된 입력
일관성 제약 조건 위배
사용자 요청에 의한 철회
타임아웃
교착상태
시스템 crash
124
MySQL Transaction
 Isolation level
– READ UNCOMMITTED
– READ COMMITTED
 InnoDB system tablespace의 undo segment 이용
 Transaction 의 ACID 보장이 필요하면 SELECT 시 명시적 LOCK 사용
 Transaction 도중 SELECT 값이 타 transaction 에 의해 변동 가능
– REPEATABLE READ
 InnoDB 스토리지 엔진에서 기본적으로 사용되는 격리 수준
 Transaction 에서 SELECT 값을 항상 동일하게 보장
 Undo record 에는 잠금을 걸 수 없으므로 PHANTOM READ 발생 가능
a. InnoDB 의 경우 Gap Lock 방식으로 PHANTOM READ 발생하지 않음
– SERIALIZABLE
 읽기 작업 시에도 공유 잠금을 획득 해야 함
Next Opensource Cloud Value
MySQL Locking
126
MySQL Locking
 Lock 이란?
– 데이터베이스에서 동일 자원 사용시 자원의 경합을 최소화 하기 위한 장치
– Transaction 의 순차적 진행을 보장하기 위한 직렬화 장치
– 다중 Transaction 의 일관성과 무결성을 유지하기 위한 장치
– MVCC 를 구현하기 위한 필요 장치
– 사용 의도에 따라 공유, 배타, 갱신, 의도, 스키마 lock 등이 존재
127
MySQL Locking
 Global Lock
– 글로벌 읽기 잠금 (Global Read Lock)
– A세션 자체에서 글로벌하게 READ LOCK 이 필요할 경우 사용
– 다른 세션에서는 READ만 가능
– 논리백업(mysqldump) 수행 시 유용
128
MySQL Locking
 Table Read Lock
– A세션에서 테이블 자원을 사용하기 위하여 데이터를 읽기를 할 때, 다른 세션에서는 테이블
자원에 대한 사용을 제한 하는 lock
– A세션에서 명시적으로 테이블 lock 을 사용하면 해당 세션에서 lock 을 해지하지 않으면 다
른 세션에서는 접근을 할 수 없음
– 테이블 lock을 사용 하려면 테이블 lock 권한을 가지고 있어야 가능
129
MySQL Locking
 Table Write Lock
– lock을 건 thread 에서만 read, write가 가능
– lock을 건 thread를 제외하고 해당테이블에 대해 read/write 불가능
– unlock 은 lock 을 건 thread 에서만 가능
– multiple table lock은 ‘,’로 구분
130
MySQL Locking
 Metadata Lock
– 데이터 이외의 메타데이터 변경시 발생하는 lock
– 주로 table, trigger 등을 drop 또는 alter 할 때 발생
Metalock 발생
131
MySQL Locking
 Dead Lock
– Transactional Database 의 공통 문제
– Application 설계의 문제로 인해 발생
– show engine innodb status 명령으로 최신의 deadlock 정보 확인 가능
– InnoDB Engine 사용시 Deadlock 자동 감지 및 즉시 처리
– InnoDB Engine 에서 Deadlock 발생시 undo 가 작은 transaction rollback
132
MySQL Locking
 Dead Lock 방지
– Application 에서 Deadlock 으로 종료된 Transaction 을 재수행 하도록 작성 필요
– Transaction 의 단위를 작게 나누어서 실행
– 고정 순서로 테이블과 열에 접근하도록 Application 설계
– Index 설계를 통해서 Deadlock 발생을 최소화
133
MySQL Locking
 InnoDB Lock Monitoring
– SHOW ENGINE INNODB STATUS
– Information_schema 의 INNODB_TRX, INNODB_LOCKS, INNODB_LOCK_WAIT
 INNODB_TRX : 트랜잭션이 어떤 프로세스에 의해 기동되고, 어떤 lock을 기다리는지를 관리
 INNODB_LOCKS : 어떤 lock이 존재하는지 관리
 INNODB_LOCK_WAITS : lock에 의한 프로세스 간의 의존 관계를 관리
– Server variables 로 확인
 innodb_status_output=ON (in error.log )
 innodb_status_output_locks=ON … SHOW ENGINE INNODB STATUS;
 일정시간 동안만 사용하세요
Q&A
Next Opensource Cloud Value
MySQL Security
136
MySQL Security
– 데이터베이스는 chroot 환경에서 실행
– mysqld 프로세스는 다른 프로세스가 사용하지 않는 유일한 UID/GID로 실행
– 인가된 계정을 제외한 시스템 계정은 로컬 엑세스만 허용
– root user 계정의 패스워드는 추정하기 어렵도록 설정
– 관리자(root) 어카운트 변경
– history 의 주기적인 삭제 or /dev/null 링크
– 데이터베이스로의 익명 접속(anonymous 계정 사용)을 금지
– test 및 미사용 데이터베이스와 테이블을 모두 삭제
– local-infile 파일 경로 제한
– load_file() 함수의 사용 권한 제한
– DB 관련 directory 의 권한 제한
– mysql user, db, table, column 권한 설정
137
MySQL Security
• Remote Access 제한
– default port 인 3306 을 차단 혹은 타 port 로 변경
– port 를 변경하여도 mysql.sock socket 으로 통신은 가능
– skip-networking 설정 시 3306/tcp 포트로 접근 불가능
– Remote 데이터 백업 등 Remote 작업 수행 시 ssh 사용
• 로컬 보안 개선
– LOAD DATA LOCAL INFILE 제한
– my.cnf 의 [mysqld] 난에 다음을 추가
138
MySQL Security
• 관리자(root) 패스워드 변경
– mysql 클라이언트를 실행하여 패스워드 변경
– 기본적으로 root 계정에 패스워드가 설정되어 있지 않음
– 쉽게 유추할 수 없는 패스워드로 설정
– mysql 접속시 password 가 노출되지 않도록 –p 옵션으로 접속
– mysqladmin 를 이용하여 변경하는 것이 보안에 뛰어남
– ps aux 커맨드 사용시 타 사용자가 password 를 확인할 수 있음
– history 파일(~/.history, ~/.bash_history)을 보면 패스워드가 쉽게 노출
139
MySQL Security
• 기본 제공되는 사용자/데이터베이스 삭제
– MySQL 설치 시 제공하는 anonymous 계정과 test 데이터베이스 삭제
– 사용되지 않는 root 를 제외한 계정을 정리하도록 권고
– 익명 접속으로 데이터베이스를 설정하는 것을 막을 수 있음
– 또는 mysql_secure_installation 수행
140
MySQL Security
• 관리자 (root) 계정 변경
– default 설정인 관리자 계정(root) 를 말함
– 무차별 대입 & 딕셔너리 공격 등으로 추측해 내기 어려운 이름으로 변경
– root 계정을 제외하고 타 계정에 권한만 부여하여 사용
• history 삭제
– client에 의해 실행되는 모든 SQL 커맨드가 저장
– ~/.mysql_history 에 기록됨
– 패스워드 정보도 노출될 수 있음
Next Opensource Cloud Value
MySQL
Management
142
MySQL Management
 MySQL Log
 MySQL DDL
 MySQL Partition
 MySQL Stored Routines / Triggers / Events
 MySQL User
 MySQL Admin Command
143
MySQL Log
 에러 로그 (error log)
– 서버 시작 및 종료 기록을 포함
– 문제가 되는 쿼리에 대한 로그
 느린 쿼리 로그 (slow query log)
– long_query_time 설정 보다 길게 수행 하는 쿼리에 대한 로그
– mysqldumpslow 유틸리티를 이용해서 분석
144
MySQL Log
 일반 쿼리 로그 (general query log)
– 클라이언트의 연결, 클라이언트로부터의 쿼리 등 다양한 이벤트가 기록
– 서버로 수신되는 모든 쿼리를 기록
– 서버의 활동상황(누가 연결하며, 무엇을 하고 있는지)을 감시하는데 유용
145
MySQL Log
 바이너리 로그 (binary log)
– UPDATE, DELETE, INSERT, CREATE TABLE, GRANT 등의 명령문에 의해서 수정이 발생한 명령문을 기록
– 서버가 비정상 종료할 경우, 백업 이후의 데이터를 복원하기 위해 사용
 릴레이 로그 (relay log)
– 서버가 리플리케이션 리플리카(replication replica) 서버로 동작하는 경우, primary 서버로부터 수신
한 데이터 수정 이벤트를 기록
146
MySQL Log
 Log output
– log_output 을 FILE 또는 TABLE 로 설정 할 수 있음
 로그 관리
– 파일이 일정 사이트가 되면 rename 등으로 관리
– https://dev.mysql.com/doc/refman/8.0/en/log-file-maintenance.html
– https://mariadb.com/kb/en/rotating-logs-on-unix-and-linux/
147
MySQL Log
 MariaDB audit log
– Includes Table Event Logging (Triggers, Stored Procedure Calls)
– Optional Field Substitution of Placeholders in Query Log to Improve Security
– Filtering Audit Logs by Role & User Accounts
– Records Privilege Changes
– Password Change Logging
– https://mariadb.com/kb/en/library/mariadb-audit-plugin/
148
MySQL DDL
 Create Database
149
MySQL DDL
 Create Table
– Column : Data Type, Default Value, Character Set, Collation
– Index
– Storage Engine
150
MySQL DDL
 Alter Table
– Add / Drop / Change / Modify Column
– Add / Drop Index
151
MySQL DDL
 Create View
– 어플리케이션에 대한 테이블 스키마 표준화
– 특정 사용자 및 어플리케이션에 대한 데이터 접근 제한
– 복잡한 쿼리의 단순화, 분할
– Views are Not Materialized
152
MySQL Partition
 Table Partitioning
– 데이터와 인덱스 모두 분할
– 유지관리와 성능개선
– 수평 파티션(행을 분배)
– 다중 저장장치에 배포, 파일구성(*.frm, *.par, *#P#파티션명.ext)
– 특정파티션의 백업/분리
153
MySQL Partition
 Partitioning Types
– RANGE
– LIST
– HASH, LINEAR HASH
– KEY, LINEAR KEY
– RANGE COLUMNS, LIST COLUMNS
– SYSTEM_TIME
system-versioned tables ( added MariaDB 10.3)
– SUBPARTITION BY
HASH, LINEAR HASH
KEY, LINEAR KEY
154
MySQL Partition
 Partitioning Limitation
– 최대 8192개 파티션
– Each table can contain a maximum of 8192 partitions (from MariaDB 10.0.4)
– The maximum possible number of partitions for a given table not using the NDB storage engine is 8192
– SQL은 병렬화 안됨
– 지원하는 일부 Storage Engine
– 모든 파티션은 동일 Storage Engine
– query cache는 파티션 프루닝 인식못함
– FK 포함 or 참조 불가능(INNODB)
– binlog_format=ROW 경우 업데이트속도 상대적 느림
– 파티션용 컬럼은 PK/UK에 반드시 포함되어야 함
155
MySQL Partition
 Partitioning Maintenance
– RANGE PARTITION 유용
– 시계열 데이터에 유용
– ALTER TABLE
– DROP PARTITION
– REMOVE PARTITIONING
– ADD PARTITION
– REORGANIZE PARTITION
– EXCHANGE PARTITION
https://dev.mysql.com/doc/refman/8.0/en/partitioning-management.html
https://mariadb.com/kb/en/partition-maintenance/
156
MySQL Stored Routines
 Method and Value of Stored Routines
– Procedures and Functions are Supported
– Database Level Functions — Isolating Certain Functionality
– Databases Used as Namespaces (e.g., CALL db_name.my_proc())
– Routines are Dropped with Database
– Library of Common Functions to make Complex Logic Accessible
 Stored Routines Limitations
– 재귀 호출 제한 (max_sp_recursion_depth)
– PREPARE 에서 미지원 명령어 대부분 지원 안함
– SBR(Statement Based Replication) : Primary / Replica 서버의 수행 결과 다를 수 있음
157
MySQL Stored Routines
 Stored Routines Privileges
– CREATE ROUTINE
– ALTER ROUTINE
– EXECUTE
– Routine 내부 OBJECT 권한과 무관하게 단지 EXECUTE 권한
– DEFINER와 SQL SECURITY의 활용
158
MySQL Stored Routines
 Procedures vs Functions
– Stored Procedures
Called Directly (e.g., CALL show_user())
Can Replace SQL statements, Encapsulate Complex Logic
Can Recurse (see, max_sp_recursion_depth and thread_stack)
Returns One or More Results Sets
– User Defined Functions
Called within other SQL Statements (e.g., SELECT DELTA_PCT(n, n))
Performs Smaller Data Manipulation, Calculations, or Conversion
Cannot Recurse
Returns a Single Scalar Value
https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
https://mariadb.com/kb/en/stored-routines/
159
MySQL Triggers
 Triggers
– 테이블에 이벤트 발생시 각 행마다 수행
– 트리거 시점 : BEFORE / AFTER
– 트리거 이벤트 : INSERT / UPDATE / DELETE
– NEW, OLD
– Limitations
 Routines 제약사항 모두
 FK시 미작동
 DEFINER 계정 미존재 시 trigger의 미작동이 아니라 이벤트가 취소됨
 slave_run_triggers_for_rbr (MariaDB 10.1)
https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html
https://mariadb.com/kb/en/triggers/
160
MySQL Events
 Events
– 정기적으로 실행될 DB OBJECT
– event_scheduler = ON
– Limitations
 Routines 제약사항 모두
 결과셋 반환 안함, 대소문자 구분 안함
 본문내 명령문 실행마다 새 연결 사용
 실행시 서버상태변수에 반영 안함
https://dev.mysql.com/doc/refman/8.0/en/events-configuration.html
https://mariadb.com/kb/en/events/
161
MySQL User
 User Accounts
– Authentication Based on User, Host, and Password
– Empty String is User Wildcard
– Percent Sign (%) is a Host Wildcard
– Host is an IP or Host Name
– localhost is used by Local Socket on Linux Systems
– Privileges are Based on User and Host Combined
162
MySQL User
 Granting Privileges
– Users given Permission with GRANT Statement
– Privilege Levels — Global, Database, Table, Column, or Routine
– Grant / Revoke
163
MySQL User
 User SQL Statements
– RENAME USER : User Names and Hosts can be Changed
– SET PASSWORD : Users Passwords can be Changed
– DROP USER : Users can be Deleted
164
MySQL User
 Limiting User
– User-Host Accounts may be Limited by Resources
– https://dev.mysql.com/doc/refman/8.0/en/user-resources.html
– Usage Related to Limits are kept in mysql Database
– Counters Reset when Server Starts or FLUSH PRIVILEGES Executed
– User Counters may be Reset Specifically — Not MAX_USER_CONNECTIONS
165
MySQL User
 Creating a User Roles
– Use CREATE ROLE to Create Group Privileges
– Use GRANT to Grant Privileges to Role
– Use GRANT to Grant Privileges to Role
166
MySQL User
 Granting a Role to a User
– Use GRANT to Designate Users for Role
– Use WITH ADMIN OPTION so Grantee may Grant Role
– Check mysql.roles_mapping for Roles Granted
167
MySQL User
 Assuming and Relinquishing a Role
– User Assumes a Role for Session with SET ROLE
– User Relinquishes a Role by Setting it to None Or by Ending Session
– User can Set Default Role to NONE or Preferred Role
168
MySQL User
 Revoking a Role
– Check mysql.roles_mapping for a List of Roles Granted
– Use REVOKE to take Role Option from User
169
MySQL User
 Dropping a Role
– Check mysql.user for List of Roles
– Use DROP ROLE to take Eliminate a Role
170
MySQL Admin Command
 Set
옵션 설명 옵션 설명
@사용자정의변수 :=
Set @v := 1
Select 2 into @v;
[global | session]
variable =
전역|세션 서버변수 변경
CHARSET 캐릭터셋 SQL_LOG_BIN 세션 전용
NAMES 캐릭터셋 SQL_SLAVE_SKIP_COUNTER 글로벌 전용
PASSWORD 비밀번호 STATEMENT ~ FOR ~ 쿼리별 세션변수설정
ROLE 권한 TRANSACTION
Isolation level
Read only
171
MySQL Admin Command
 SHOW
옵션 설명 옵션 설명
AUTHORS 저자 목록 ENGINE ~ STATUS 서버 상태
CHARACTER SET 문자셋 ENGINES Storage engine 목록
COLLATION 정렬 ERRORS 최근 세션 오류
COLUMNS ~ 테이블의 컬럼들 EVENTS 이벤트 목록
CONTRIBUTORS 재정적 스폰서 목록 FUNCTION CODE FUNCTION 내용
CREATE ~ 오브젝트 스키마 내용 GRANTS FOR ~ 계정의 권한
DATABASES Database/schema 목록 INDEX FROM ~ 테이블의 인덱스 목록
OPEN TABLES Table open cache 목록 ~ VARIABLES [global, session]
PLUGINS 로딩된 플러그인 목록 BINARY LOGS 바이너리로그 파일목록
PRIVILEGES 권한 목록 BINLOG EVENTS [IN ~] 로그 이벤트 목록
PROCESSLIST 프로세스 목록 EXPLAIN FOR ~ thread_id , 실행계획
~ STATUS [global, session] [master, slave] SLAVE HOSTS Slave 목록
TABLES 테이블 목록 WSREP_MEMBERSHIP
install soname ‘wsrep_info.so’
TRIGGERS 트리거 목록 WSREP_STATUS
172
MySQL Admin Command
 DESC
 EXPLAIN
 USE
 HELP
173
MySQL Admin Command
 RESET
 EXECUTE
 FLUSH
 KILL
174
MySQL Admin Command
 PURGE
 ANALYZE
 OUTFILE
 LOAD DATA
175
MySQL Admin Command
 REPLICATION
옵션 설명 예제
SHOW MASTER STATUS Master’s binlog정보 Primary> show master status;
CHANGE MASTER TO Master에 Slave 연결정보
Replica> CHANGE MASTER TO
MASTER_HOST='192.168.0.1',
MASTER_USER='repl',
MASTER_PASSWORD='repl',
MASTER_PORT=3306,
MASTER_LOG_FILE='mysql-bin.000001',
MASTER_LOG_POS=342;
START SLAVE 복제 시작 Replica> start slave;
STOP SLAVE 복제 중지 Replica> stop slave;
RESET SLAVE Slave 정보 삭제 Replica> reset slave;
SHOW SLAVE STATUS Slave 상태 Replica> show slave status;
SHOW SLAVE HOSTS 등록된 Slave 목록 Primary> show slave hosts;
RESET MASTER 바이너리로그 초기화 Primary> reset master;
Q&A
Next Opensource Cloud Value
MySQL
Backup / Restore
178
MySQL Backup
 백업이란?
– 의미 있는 정보인 데이터에 대해 논리적, 물리적으로 복제하여 관리하는 것
– 동일 장비 혹은 다른 장비의 Disk 장치 혹은 별도의 백업 장치에 관리
 백업의 목적
– 데이터 안정성 유지 및 데이터 소실 방지
– HW 시스템 고장 / Disk 손상 / SW 손상 / 운영데이터 소실
– 사고로 시스템이나 파일이 피해를 입더라도 최근에 백업한 시점의 내용으로 복구를 위함
179
MySQL Backup
bin.
0004
MySQL bin.
0001
bin.
0002
bin.
0003
FULL
백업
사고!!
MySQL
일요일 오전3시
화요일 오후5시
데이터베이스 파손
binlog.0001~0003 기록
binlog.0001~0003 적용
증분
백업
180
MySQL Backup
 백업 정책 수립
– 백업 대상 선정
 Data Files
 Binary Log
 Configuration File (my.cnf)
 Redo / Undo Log
– 백업 주기 선정
 백업의 수행시간에 따른 백업 주기 산정
– 백업 방법 선정
 논리 백업 / 물리 백업
 Cold 백업 / Hot 백업
181
MySQL Backup
 백업 정책 수립
– 백업 용량 산정
 백업 정책에 따른 보관 일자 및 용량 산정
– 백업 전략 선정
 full 백업
 incremental 백업
– 백업 관리방법 선정
 백업 정책에 따른 보관 일자 산정
 incremental 백업에 대해 증분 데이터 보관 결정
182
MySQL Backup
 복구 시나리오
– 가장 인접한 full 백업 선정
– full 백업으로 복구 수행
– 가장 인접한 증분 백업 선정
– 증분 백업을 순차적으로 실행
– full 백업 이후의 binlog에 대해 SQL 산출(Point-In-Time Recovery)
– 추출한 SQL 을 적용
183
MySQL Backup
 Logical Backup
– 특징 및 장점
 SQL 형태의 text 문으로 데이터 백업
 데이터 검토 가능
 복원 작업이 수월
 물리 백업에 비해 복원 시 데이터 손상을 줄여줌
 문제 발생시 원인 파악 및 해결이 수월
– 단점
 수행 시간 동안 WRITE LOCK 발생(mysqldump)
 시스템 리소스를 물리백업에 비해 많이 소모
 부동 소수점 데이터의 정확성을 잃을 수도 있음
– 종류
 mysqldump
 into outfile / load data infile
 mysql execute mode > text file
 Physical Backup
– 특징 및 장점
 MariaDB의 물리적 파일을 백업
 속도가 빠름
 대체적으로 작업이 단순함
– 단점
 논리적 백업에 비해 백업 해야 하는 파일의 크기가 큼
 복구 시 문제가 발생하면 원인 파악 및 해결이 어려움
 필요한 논리 개념의 data 만 백업이 불가능
– 종류
 directory copy ( cold backup )
 mysqlhotcopy ( myisam, archive )
 xtrabackup ( percona, open source )
 mariabackup ( innodb hot backup )
Next Opensource Cloud Value
MySQL
Logical Backup
185
MySQL Logical Backup
 mysqldump
– 논리 백업 방식
– row 기반 데이터 백업
– insert 구문으로 데이터를 추출 및 저장하여 백업
– 데이터베이스, 테이블 단위로 백업 가능
– GRANT
REPLICATION CLIENT
SELECT
SHOW VIEW
RELOAD
EVENT
TRIGGER
LOCK TABLES
186
MySQL Logical Backup
 mysqldump option
-A, --all-databases : 모든 DB를 덤프
--add-drop-table : 데이터베이스 앞에 drop table 명령 추가
-B, --databases : 여러 DB를 동시에 백업 할 때 사용
-T, --tab : 테이블 단위로 백업
-h, --host : 지정한 호스트의 데이터를 덤프
-p : 사용자의 암호를 지정
-P : 포트번호 지정
-u : 사용자명 지정
--default-character-set= : 덤프 시 character-set 설정
-f, --force : 에러를 무시
187
MySQL Logical Backup
 mysqldump option
-t, --no-create-info : data만 덤프
-d, --no-data : 데이터를 제외하고 스키마만 덤프
--single-transaction : Lock 을 사용하지 않는 일관성 있는 읽기 연산 사용
--extended-insert : 확장 형태의 insert 구문으로 출력
--flush-logs : 새로운 바이너리 로그파일 생성
--master-data= 1 / 2
a. dump 파일의 헤더 부분에 CHANGE MASTER TO 구문을 포함
b. 덤프 시작 시점의 Binary log 파일명과 위치 정보 및 호스트 정보를 포함
c. 1 : 수행할 수 있는 형태의 SQL 구문 , 2 : 정보만 출력
--routines : 프로시저 함수 백업
--triggers : 트리거 백업
--events : 이벤트 백업
188
MySQL Logical Backup
 mysqldump 사용
– 스키마 백업
– 데이터 백업
189
MySQL Logical Backup
 Source 명령
– 외부 파일의 SQL 문을 실행
– mysql client의 프롬프트에서 사용 하거나 mysql 의 –e 옵션을 이용하여 사용
– source 명령을 prompt에서 사용시 파일의 경로는 '' 대신 '/' 를 이용
– 복구 시 dump 파일의 character set, collation 확인 필요
– set names <character set>;
190
MySQL Logical Backup
 select ... into outfile
– 논리 데이터의 백업 방식
– Row 기반 데이터 백업
– 인식 가능한 구분자(separator)로 column 을 구분하여 파일로 저장
– 원하는 형태의 SQL 을 구성하여 결과값을 파일로 저장 가능
– file_priv = ‘Y’
– secure-file-priv=‘path’ 에만 export 가능
– 절대경로 혹은 상대경로 위치에 output 저장
– 해당 경로에 대한 OS 계정 user/group 의 쓰기 권한이 있어야 함
191
MySQL Logical Backup
 select ... into outfile
– https://mariadb.com/kb/en/select-into-outfile/
192
MySQL Logical Backup
 Load data infile
– 논리 백업 데이터의 복구 방식
– row 기반 데이터 백업
– 인식 가능한 구분자(separator)로 구분된 파일의 데이터를 읽어 복원
– local / non local
– local-infile = 0
– file_priv = ‘Y’
– 파일의 절대경로 혹은 상대경로의 파일을 읽어서 복원
193
MySQL Logical Backup
 Load data infile
– https://mariadb.com/kb/en/load-data-infile/
Next Opensource Cloud Value
MySQL
Physical Backup
195
MySQL Physical Backup
 Cold Backup
– OS 의 copy 명령을 사용하여 수행
– 물리적인 data file 의 copy 수행 중 disk block 이 변경되면 안됨
– 데이터베이스를 stop한 뒤 data block의 변경이 없는 경우 수행
– down time 이 발생하나 가장 간단하고, 장애 없이 수행 가능
196
MySQL Physical Backup
 Xtrabackup
– Percona 에서 개발한 InnoDB용 backup tool
– Online Hot Backup
– 물리 data file 을 백업하고 apply-log 명령을 이용하여 DML 변경분 attach
– 정상 backup 완료 시 completed OK!
– PERCONA_XTRABACKUP 테이블에 백업 log 저장
– 복구 시 mysqld daemon 은 shutdown 상태로 copy-back 옵션 사용
– full/incremental backup 가능
197
MySQL Physical Backup
 Xtrabackup
– 전체 데이터 백업
– 복구할 DB의 data directory 로 백업 파일 이동
198
MySQL Physical Backup
 mariabackup
– MariaDB 10.1.26 / 10.2.10 부터 제공되는 백업 툴
– Percona Xtrabackup 2.3.8기반
– Linux / Window 지원
– Online Hot Backup
– 암호화(TDE)된 XtraDB / InnoDB 지원 (only)
– 압축된 XtraDB / InnoDB 지원 (only)
– InnoDB, MyRocks, Aria, MyISAM 지원
– Galera Cluster SST 옵션 지원
https://mariadb.com/kb/en/mariabackup-overview/
Next Opensource Cloud Value
MySQL
binary log
200
MySQL binary log
 mysqlbinlog
– binary / relay log 를 직접 읽기 위한 도구
– binary format으로 작성된 binlog를 text format으로 변환하는 도구
– binlog_format = statement / row
 statement-based : event 정보는 SQL문과 실행한 서버ID, 실행된 시간, 걸린 시간, 기타 정보
 row-based : event 정보는 쿼리로 인해 변경된 row 에 대한 정보를 포함
201
MySQL binary log
 mysqlbinlog option
--help, -?
도움말 메시지를 출력하고 종료
--server-id=id
서버 ID 에 해당하는 로그만 출력
--start-datetime=datetime
datetime 인수와 동일하거나 느린 타임 스탬프를 가지고 있는 첫 번째 이벤트에서 바이너리 로그를 읽기 시작
DATETIME 또는 TIMESTAMP 데이터 타입에 적합한 포맷 형태로 대입
mysqlbinlog --start-datetime="2005-12-25 11:25:56" binlog.000003
포인트-인-타입(point-in-time) 복구 시에 유용
--stop-datetime=datetime
datetime 인수와 동일하거나 빠른 타임 스탬프를 가지고 있는 이벤트에서 바이너리 로그를 읽기 종료
포인트-인-타입(point-in-time) 복구 시에 유용
202
MySQL binary log
 mysqlbinlog option
--start-position=N
N 인수와 동일한 위치를 가지고 있는 이벤트가 처음 발생할 때 바이너리 로그를 읽기 시작
명령문 라인에 지명된 첫 번째 로그 파일에 적용
--stop-position=N
N 인수와 동일하거나 보다 큰 위치를 가지고 있는 이벤트 시점에 바이너리 로그를 읽기 종료
명령문 라인에 지명된 마지막 로그 파일에 적용
203
MySQL binary log
 mysqlbinlog 사용
– mysqlbinlog 유틸을 이용하여 sql 형태로 저장 및 실행
– mysqlbinlog 결과를 직접 mysql client로 실행
204
MySQL binary log
 Managing Binary Logs
– Binary log 확인
– Binary log 삭제
205
MySQL binary log
 Managing Binary Logs
– Binary log 상세 정보 확인
Next Opensource Cloud Value
MySQL Replication
207
MySQL Replication
 Replication
- 하나 이상의 서버로부터 데이터를 선택적으로 복제 하는 기능
- binary log에 모든 업데이트를 기록
- Replica는 Primary의 binary log를 읽고 Replica에 relay log를 기록
- relay log를 수행하여 Replica 서버에 반영
Binary
log
Relay
log
I/O thread
SQL thread
Primary Replica
Data changes
Read
Write
Read
Replay
Binary log
dump thread
Write
208
MySQL Replication
 Primary - Replica
The terms master and slave have historically been used in replication, but the terms primary and replica
are now preferred. The old terms are used throughout the documentation, and in MariaDB commands, although
MariaDB 10.5 has begun the process of renaming. The documentation will follow over time. See MDEV-18777 to
follow progress on this effort.
https://mariadb.com/kb/en/standard-replication/
209
MySQL Replication
 Replication Thread : Primary
- Binary Log Dump Thread
Primary의 binlog를 읽어서 Replica의 I/O
Thread에 전달
- ACK Receiver Thread
Semisync Replication의 ACK 수신
 Replication Thread : Replica
- Replica I/O Thread
수신된 binary log를 relay log에 기록
Primary’s binary log file 과 log position 기록
- Replica SQL Thread
relay log 읽어 SQL 수행
Parallel-Replication Off : 데이터에 적용
Parallel-Replication On : Worker Thread 전달
- Worker Thread
병렬 복제 처리
210
MySQL Replication
 GTID
- Global Transaction ID
- MySQL과 MariaDB의 GTID 구조 다름
- Replication 전환 구조의 편리성
- Replication 안정성 (충돌 방지)
 MySQL GTID
- source_id:transaction_id
3E11FA47-71CA-11E1-9E33-C80AA9429562:23
- source_id : the server generates a true UUID
- transaction_id : sequence number
- MySQL 5.6 부터 지원
 MariaDB GTID
- Domain ID – Server ID – Sequence Number
0-1-10
- Domain ID : 32비트 정수
- Server ID : 32비트 정수
- Sequence Number : 64비트 정수
- MariaDB 10.0 부터 지원
211
MySQL Replication
 Replication 구성
- my.cnf 설정
- Replication 계정 생성
212
MySQL Replication
 Replication 구성
- binary log 확인
Replica 설정 할 때 Primary의 File 정보를 MASTER_LOG_FILE에, Position 정보를 MASTER_LOG_POS에 사용
- Primary 백업 – Replica 복원
213
MySQL Replication
 Replication 구성
- Replica 설정
214
MySQL Replication
 Replication 구성
- Replica 상태 확인
215
MySQL Replication
 Replication 구성
- Replica 삭제
Next Opensource Cloud Value
MySQL Monitoring
217
MySQL Monitoring
 서버 과부하
 데이터베이스 shutdown
 데이터베이스 복구
 테이블 메타 정보 불일치
 로그 파일 관리
 테이블 및 레코드의 잠금 해결
 호스트 잠금
218
MySQL Monitoring
 서버 과부하
- CPU : 사용량, idle (top, vmstat)
- MEMORY : used, free, swap (free)
- DISK : read / write (vmstat, iostat, iotop)
- NETWORK : Received / Send / time wait (netstat)
- PROCESS : resource per process (top)
- Log : system log, cron log
219
MySQL Monitoring
 데이터베이스 startup / shutdown
- Startup
 MariaDB 서버가 기동 후 error.log 확인
 Warning, Error 이벤트가 발생했는지 확인
 log_warnings=2 (기본값 10.2이상 2, 미만 1)
- Shutdown
 MariaDB 서버가 자동으로 Shutdown 되는 경우 error.log 확인
 Normal Shutdown 이외의 메시지로 내려가는 경우 서버 재시작
 mysqld_safe 옵션으로 mysqld daemon 이 시작된 경우 자동 복구
 Killed 등의 메시지로 원인확인이 불가능 할 때 OS log 를 통해 원인 분석
220
MySQL Monitoring
 데이터베이스 복구
- Data 복구
 MyISAM 테이블 손상의 경우 repair table 명령으로 복구
 InnoDB 의 손상 시 innodb_force_recovery 옵션을 my.cnf에 추가하여 복구
- Metadata 복구
 Data Dictionary 와 .frm 파일의 정보가 불일치 하는 경우 발생
 Data Dictionary 에서 정상 삭제된 경우 이상 없음
 .frm 데이터가 삭제되고 Data Dictionary 에 남아 있다면 에러 발생
 다른 database 에서 해당 테이블과 동일한 구조의 테이블을 만들고 .frm 파일을 복사하여 복구
221
MySQL Monitoring
 데이터베이스 log
- Error log
 MySQL 서버에 문제가 발생하는 경우 기본적으로 Error Log 에 기록됨
 장애 시 Error Log 의 마지막 부분은 반드시 확인
 MySQL 에러로그파일은 기본적으로 ‘log_error’로 설정한 경로파일에 존재
 log_error 파라메터를 설정함으로써 directory 및 filename 지정 가능
 파일이 너무 큰 경우 tail 명령이나 less 명령을 이용하여 마지막 라인만 확인
 vi로 큰 파일을 열 때는 주의가 필요
222
MySQL Monitoring
 데이터베이스 log
- Slow Query Log
 slow-log 옵션을 활성화하는 경우 기록
 로그파일 혹은 테이블로 기록 ( log_output=‘FILE,TABLE’ )
 지정된 시간 이상 정상 수행 및 종료된 SQL 에 대해 기록
 mysqldumpslow 유틸을 이용하여 slow log 의 통계 집계 가능
 -s 옵션에 count(c) , lock(l) , record(r) 기준으로 출력 가능
 hostname-slow.log 형태로 기록
223
MySQL Monitoring
 데이터베이스 log
- Log 파일 관리
 Error Log 파일의 사이즈가 warning 으로 인해 커지는 경우
 warning 메시지를 error log 에 출력하지 않도록 설정
 error log 나 binary log 의 경우 파일 삭제 후 flush logs 를 통해 새로운 log 생성
 Slow Log 파일 일시적인 사용(slow_query_log=OFF)
 General Log 파일 (general_log=OFF)
 Binary Log 파일 (expire_log_days=0)
 Relay Log 파일 (relay_log_purge=ON)
224
MySQL Monitoring
 데이터베이스 log
- Log 파일 관리
 binary log 의 사이즈가 커지는 경우
 일정기간 이외의 파일을 지우도록 설정 ( expire_logs_days )
 직접적으로 binary log purge 하여 용량 확보
225
MySQL Monitoring
 데이터베이스 Locks
- 테이블 및 레코드 lock 해결
 transaction이 특정 이유로 commit이 되지 않은 상태로 남아있는 경우
 Lock wait timeout exceeded error 발생
 Lock 을 유발하는 transaction 을 종료하여 처리
 processlist 상의 id 항목에 대해 kill query id 로 처리
 innodb_lock_wait_timeout 변수를 통해 대기시간을 줄일 수 있음
226
MySQL Monitoring
 데이터베이스 Locks
- 서버 host 잠금
 client host별 에러count값이 max_connect_errors 값 초과시 발생
 hostname is blocked because of many connection errors 발생
 flush hosts 명령으로 처리 가능
 max_connect_errors 값을 증가시켜서 처리가능
227
MySQL Monitoring
 데이터베이스 status
- Connections
- Thread / Processlist
- QPS (query per second)
- Table Cache
- InnoDB Buffer Pool
- Table Full scan
- Replication status
228
MySQL Monitoring
 데이터베이스 status
- Processlist 확인
 데이터베이스에 접속하거나 mysqladmin utility 를 이용하여 확인
 현재 실행중인 SQL 확인 가능
 show (full) processlist 명령으로 확인 가능
 각 프로세스의 command / state / time 값을 확인하여 현재 상태와 실행시간 확인
State 항목이 Waiting 인 경우 타 프로세스에 의한 잠금 확인 필요
Copy to tmp table 인 경우 해당 SQL 의 튜닝포인트 확인
Command 및 State 항목이 동일 항목이 여러 개 반복해서 나타나는 경우 SQL 튜닝 필요
Command 및 State 항목이 여러 종류가 다양하게 나타난다면 서버 외부 요인 파악
서버의 부하는 높으나 Command 항목이 대부분 Sleep 상태인 경우 network in 확인
229
MySQL Monitoring
 데이터베이스 status
- Max Connection 확인
 평상시보다 많은 Network In 이 발생하는 경우
 서버가 처리할 수 있는 허용량 보다 많은 connection 이 동시에 몰리는 경우 부하
 Session 메모리를 고려한 max connection 설정 필요
 status 항목의 max_used_connection을 모니터링하여 connection 허용값을 증가하여 운영
 max_connections 시스템 변수로 조정 가능
230
MySQL Monitoring
 데이터베이스 status
- SQL 실행 상태 확인
 mysqladmin 의 status항목으로 (Uptime, Threads, Questions, Slow, Open…, QPS) 확인
 mysqladmin 의 extended-status 항목으로 서버 상태 값 출력
 egrep 커맨드로 필요한 항목만 확인
 초당 처리되는 쿼리의 수를 확인하고 평상시보다 과부하가 발생하는지 확인
231
MySQL Monitoring
 mytop (innotop)
https://github.com/jzawodn/mytop
https://github.com/innotop/innotop
232
MySQL Monitoring
 Grafana
https://grafana.com/grafana/dashboards/7362
233
MySQL Monitoring
 PMM (Percona Monitoring and Management)
https://www.percona.com/software/database-tools/percona-monitoring-and-management
Q&A
Next Opensource Cloud Value
NeoClova
236
NeoClova
회사명
임직원
대표이사
설립년도
주소
대표전화
홈페이지
주식회사 네오클로바
19명
이 재 중
2011년 11월
서울시 강서구 양천로 583, 우림블루나인 B동 12층
02-539-4880
www.neoclova.co.kr
기업 개요 주요 파트너쉽
주요사업분야
IT 통합유지보수
Red Hat Enterprise Linux, JBoss, Apache / Tomcat,
MySQL / MariaDB / Percona Technical Support
Red Hat Ready Partner
T2 Partner
Registered Partner
Registered Partner
Registered Partner
237
NeoClova reference
주요 고객사
구축 부분
오픈소스
구축
업무분석
운영지원
컨설팅
- 운영시스템 전반 유지보수
- 장애 및 성능 분석 지원
- U.Key 3.0 U2L PI
- Unix Oracle RAC to Linux구축
- Jboss EWS/EAP 전환 및 성능 측정
- MySQL/MariaDB 컨설팅 서비스
- 통합시스템 내 리눅스 부분
유지보수 및 분석 지원
- 정보시스템 클라우드 전환 컨설팅 (ISP)
- 전체운영시스템 클라우드 전환 ISP
- G-Box플랫폼 구축 관련 오픈소스 지원
- ITO 오픈소스 컴플라이언스 검증
- New Kt.com 구축 관련 오픈소스 지원
- 오픈소스 SW 전사기술지원
- 가족관계 등록정보시스템 구축 사업내 오픈소스 구축
- 온라인 출생신고시스템 전산장비 도입 사업내
오픈소스 구축
- 스마트 산업입지 플랫폼 시범사업 전산장비 구축내 오픈소스 부분
- 빅데이터 기반의 차세대 공장설립온라인지원시스템 구축내 오픈소스 부분
- 차세대 운영정보시스템 구축내 오픈소스 부분
- 운영시스템 오픈소스(Linux부분) 운영지원
- 운영시스템 통합유지보수 지원
238
NeoClova
지원제품 List
1.3 Amazon Web Services
2.1 Red Hat OpenStack Platform
3.1 MySQL
4.1 Red Hat JBoss EAP
2.4 Red Hat Gluster Storage
5.1 Red Hat Enterprise Linux
1.1 Google Cloud Platform
2.2 Red Hat OpenShift Container Platform
2.3 Red Hat Ceph Storage 2.6 Azure Stack
2.5 Red Hat Virtualization
3.2 MariaDB
4.2 Red Hat JBoss Web Server
1.2 Microsoft Azure
4.3 Red Hat OpenShift
4.4 ACCORDION
4.5 Apache / Tomcat / NginX
5.2 CentOS
5.3 Ubuntu
5.4 Oracle Linux
3.4 DBMON-Star(DB 모니터링 자체솔루션)
3.5 DB CHECKER(DataBase 검증 및 자체튜닝 솔루션)
3.3 Percona Server for MySQL

Contenu connexe

Tendances

MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용I Goo Lee
 
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법Ji-Woong Choi
 
MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼NeoClova
 
MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바NeoClova
 
M|18 Architectural Overview: MariaDB MaxScale
M|18 Architectural Overview: MariaDB MaxScaleM|18 Architectural Overview: MariaDB MaxScale
M|18 Architectural Overview: MariaDB MaxScaleMariaDB plc
 
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxKeepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxNeoClova
 
[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기NHN FORWARD
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Mydbops
 
Maxscale switchover, failover, and auto rejoin
Maxscale switchover, failover, and auto rejoinMaxscale switchover, failover, and auto rejoin
Maxscale switchover, failover, and auto rejoinWagner Bianchi
 
ProxySQL for MySQL
ProxySQL for MySQLProxySQL for MySQL
ProxySQL for MySQLMydbops
 
ProxySQL High Avalability and Configuration Management Overview
ProxySQL High Avalability and Configuration Management OverviewProxySQL High Avalability and Configuration Management Overview
ProxySQL High Avalability and Configuration Management OverviewRené Cannaò
 
The Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication TutorialThe Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication TutorialJean-François Gagné
 
MariaDB 10: The Complete Tutorial
MariaDB 10: The Complete TutorialMariaDB 10: The Complete Tutorial
MariaDB 10: The Complete TutorialColin Charles
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBMydbops
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재PgDay.Seoul
 
MaxScale이해와활용-2023.11
MaxScale이해와활용-2023.11MaxScale이해와활용-2023.11
MaxScale이해와활용-2023.11NeoClova
 
ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)Mydbops
 
Intro ProxySQL
Intro ProxySQLIntro ProxySQL
Intro ProxySQLI Goo Lee
 
MariaDB Optimization
MariaDB OptimizationMariaDB Optimization
MariaDB OptimizationJongJin Lee
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability Mydbops
 

Tendances (20)

MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용MySQL 상태 메시지 분석 및 활용
MySQL 상태 메시지 분석 및 활용
 
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
 
MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼
 
MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바
 
M|18 Architectural Overview: MariaDB MaxScale
M|18 Architectural Overview: MariaDB MaxScaleM|18 Architectural Overview: MariaDB MaxScale
M|18 Architectural Overview: MariaDB MaxScale
 
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docxKeepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
 
[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기[2018] MySQL 이중화 진화기
[2018] MySQL 이중화 진화기
 
Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0Redo log improvements MYSQL 8.0
Redo log improvements MYSQL 8.0
 
Maxscale switchover, failover, and auto rejoin
Maxscale switchover, failover, and auto rejoinMaxscale switchover, failover, and auto rejoin
Maxscale switchover, failover, and auto rejoin
 
ProxySQL for MySQL
ProxySQL for MySQLProxySQL for MySQL
ProxySQL for MySQL
 
ProxySQL High Avalability and Configuration Management Overview
ProxySQL High Avalability and Configuration Management OverviewProxySQL High Avalability and Configuration Management Overview
ProxySQL High Avalability and Configuration Management Overview
 
The Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication TutorialThe Full MySQL and MariaDB Parallel Replication Tutorial
The Full MySQL and MariaDB Parallel Replication Tutorial
 
MariaDB 10: The Complete Tutorial
MariaDB 10: The Complete TutorialMariaDB 10: The Complete Tutorial
MariaDB 10: The Complete Tutorial
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
[pgday.Seoul 2022] PostgreSQL구조 - 윤성재
 
MaxScale이해와활용-2023.11
MaxScale이해와활용-2023.11MaxScale이해와활용-2023.11
MaxScale이해와활용-2023.11
 
ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)ProxySQL High Availability (Clustering)
ProxySQL High Availability (Clustering)
 
Intro ProxySQL
Intro ProxySQLIntro ProxySQL
Intro ProxySQL
 
MariaDB Optimization
MariaDB OptimizationMariaDB Optimization
MariaDB Optimization
 
Galera cluster for high availability
Galera cluster for high availability Galera cluster for high availability
Galera cluster for high availability
 

Similaire à MySQL Administrator 2021 - 네오클로바

MariaDB Administrator 교육
MariaDB Administrator 교육 MariaDB Administrator 교육
MariaDB Administrator 교육 Sangmo Kim
 
MariaDB 제품 소개
MariaDB 제품 소개MariaDB 제품 소개
MariaDB 제품 소개NeoClova
 
MySQL Document Store를 활용한 NoSQL 개발
MySQL Document Store를 활용한 NoSQL 개발MySQL Document Store를 활용한 NoSQL 개발
MySQL Document Store를 활용한 NoSQL 개발Oracle Korea
 
Azure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDBAzure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDBrockplace
 
MySQL Deep dive with FusionIO
MySQL Deep dive with FusionIOMySQL Deep dive with FusionIO
MySQL Deep dive with FusionIOI Goo Lee
 
Mysql on windows_kr_20170221
Mysql on windows_kr_20170221Mysql on windows_kr_20170221
Mysql on windows_kr_20170221Sumi Ryu
 
DB Migration to Azure Database for MySQL
DB Migration to Azure Database for MySQLDB Migration to Azure Database for MySQL
DB Migration to Azure Database for MySQLrockplace
 
Azure Database for MySQL
Azure Database for MySQLAzure Database for MySQL
Azure Database for MySQLrockplace
 
MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개rockplace
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20Amazon Web Services Korea
 
Migration to Azure Database for MySQL
Migration to Azure Database for MySQLMigration to Azure Database for MySQL
Migration to Azure Database for MySQLrockplace
 
MySQL operator for_kubernetes
MySQL operator for_kubernetesMySQL operator for_kubernetes
MySQL operator for_kubernetesrockplace
 
MariaDB 기본 소개 20201216.pdf
MariaDB 기본 소개 20201216.pdfMariaDB 기본 소개 20201216.pdf
MariaDB 기본 소개 20201216.pdfssusercbaa33
 
Azure databases for PostgreSQL, MySQL and MariaDB
Azure databases for PostgreSQL, MySQL and MariaDB Azure databases for PostgreSQL, MySQL and MariaDB
Azure databases for PostgreSQL, MySQL and MariaDB rockplace
 
[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly
[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly
[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena DollyJi-Woong Choi
 
Introduction of Mesosphere DCOS
Introduction of Mesosphere DCOSIntroduction of Mesosphere DCOS
Introduction of Mesosphere DCOSDeughyeon Chang
 
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...Cloud-Barista Community
 
1711 azure-live
1711 azure-live1711 azure-live
1711 azure-live세준 김
 
[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례
[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례
[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례OpenStack Korea Community
 

Similaire à MySQL Administrator 2021 - 네오클로바 (20)

MariaDB Administrator 교육
MariaDB Administrator 교육 MariaDB Administrator 교육
MariaDB Administrator 교육
 
MariaDB 제품 소개
MariaDB 제품 소개MariaDB 제품 소개
MariaDB 제품 소개
 
MySQL Document Store를 활용한 NoSQL 개발
MySQL Document Store를 활용한 NoSQL 개발MySQL Document Store를 활용한 NoSQL 개발
MySQL Document Store를 활용한 NoSQL 개발
 
Azure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDBAzure Databases for PostgreSQL MYSQL and MariaDB
Azure Databases for PostgreSQL MYSQL and MariaDB
 
MySQL Deep dive with FusionIO
MySQL Deep dive with FusionIOMySQL Deep dive with FusionIO
MySQL Deep dive with FusionIO
 
Mysql on windows_kr_20170221
Mysql on windows_kr_20170221Mysql on windows_kr_20170221
Mysql on windows_kr_20170221
 
DB innovation conference 2020
DB innovation conference 2020DB innovation conference 2020
DB innovation conference 2020
 
DB Migration to Azure Database for MySQL
DB Migration to Azure Database for MySQLDB Migration to Azure Database for MySQL
DB Migration to Azure Database for MySQL
 
Azure Database for MySQL
Azure Database for MySQLAzure Database for MySQL
Azure Database for MySQL
 
MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개MySQL InnoDB Cluster 소개
MySQL InnoDB Cluster 소개
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
 
Migration to Azure Database for MySQL
Migration to Azure Database for MySQLMigration to Azure Database for MySQL
Migration to Azure Database for MySQL
 
MySQL operator for_kubernetes
MySQL operator for_kubernetesMySQL operator for_kubernetes
MySQL operator for_kubernetes
 
MariaDB 기본 소개 20201216.pdf
MariaDB 기본 소개 20201216.pdfMariaDB 기본 소개 20201216.pdf
MariaDB 기본 소개 20201216.pdf
 
Azure databases for PostgreSQL, MySQL and MariaDB
Azure databases for PostgreSQL, MySQL and MariaDB Azure databases for PostgreSQL, MySQL and MariaDB
Azure databases for PostgreSQL, MySQL and MariaDB
 
[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly
[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly
[오픈소스컨설팅]이기종 WAS 클러스터링 솔루션- Athena Dolly
 
Introduction of Mesosphere DCOS
Introduction of Mesosphere DCOSIntroduction of Mesosphere DCOS
Introduction of Mesosphere DCOS
 
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
 
1711 azure-live
1711 azure-live1711 azure-live
1711 azure-live
 
[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례
[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례
[OpenInfra Days Korea 2018] (Track 3) Software Defined Infrastructure 전략 및 사례
 

MySQL Administrator 2021 - 네오클로바

  • 2. 2 목차 구분 내용 Basic - MySQL 개요 - MySQL 설치 / 설정 - MySQL 아키텍처 - MySQL 스토리지 엔진 - MySQL 관리 - MySQL 백업 / 복구 - MySQL 모니터링 Advanced - MySQL Optimization - MariaDB / Percona - MySQL HA (High Availability) - MySQL troubleshooting
  • 3. Next Opensource Cloud Value MySQL 개요
  • 4. 4 MySQL 개요 • Open Source Relational Database • 사용이 편리하고, 확장성이 좋으며, 우수한 성능 • 타 DB 대비 상대적으로 작은 크기 • MySQL AB -> Sun (2008) -> Oracle (2010) • Initial release : 23 May 1995
  • 5. 5 MySQL 개요  참고 사이트 • https://dev.mysql.com/ • https://github.com/mysql • https://mariadb.org/ • https://www.percona.com/  한국 사용자 그룹 • https://www.facebook.com/groups/623067261102382/ • https://www.facebook.com/groups/mariadbkorea
  • 6. 6 MySQL 개요 • Scale Up / Scale Out • 상용 RDBMS 들은 일반적으로 Scale Up 을 지향 • MySQL은 Scale Out 에 기반을 두고 DB Architecture 설계 시 고성능 발휘 Scale Up 분류 Scale Out • 높은 안정성 • 고성능 장점 • 저비용 • 장애시 서비스 Impact 적음 • 부분적 증설이 가능 • 지속적인 시스템 확장 가능 • 고비용 • 장애시 대형 장애로 연결 • 한대의 고성능 서버로 감당이 어려 운 경우 문제 발생 단점 • 많은 서버로 인한 관리 부담 • 각 서버의 장애 발생 가능성이 높음
  • 7. 7 MySQL 개요  MySQL 편리성 • 다중 사용자, 다중 Thread 지원 • 다양한 응용프로그램 API제공 (C, C++, Java, Perl, PHP, Python, .Net, Ruby 등) • ANSI SQL 표준 준수 • 다양한 스토리지 엔진 제공
  • 8. 8 MySQL 개요  MySQL 확장성 • Table Partitioning • Replication을 통한 읽기 확장 • Table 수준에서 다양한 특성의 Storage Engine 지원 • 보다 유연한 시스템 확장을 위해 전용 Router 지원 • Cloud 기반의 환경 지원 (AWS, Azure, GCP, OCI, SkySQL, Docker)
  • 9. 9 MySQL 개요  MySQL 이식성 • 다양한 OS 환경 지원 (Linux, Window 32/64) • 쉬운 Migration (MySQL, MariaDB, Percona) • MySQL client 지원 (mysqldump, mysqladmin 등) • 쉬운 Minor Upgrade • OpenSource Ecosystem
  • 10. 10 MySQL 개요  MySQL 보안 • MySQL Minor Patch include CVE • SSL 지원 • user & host 기반의 Object별 Privileges (user & host별 비밀번호, User Role) • Data-at-Rest Encryption (MySQL TDE) • Password Validation Plugin 지원
  • 11. 11 MySQL 개요  MySQL 성능 • Table Partitioning • Thread Pooling • Replication • Storage engine • my.cnf configuration • Database Proxy (ProxySQL, MaxScale, MySQL Router)
  • 13. 13 MySQL History MySQL 1.0 1995 GPL MySQL 2000 MySQL 5.1 Percona SUN MySQL 2008 MariaDB 5.1 Oracle MySQL 2009 MySQL 5.5 Percona 5.5 (2011) MariaDB 5.5 (2012) 2010 MySQL 5.6 GA (2013) MariaDB 10.0 GA (2013) MariaDB 10.1 GA (2014) MySQL 5.7 GA (2015) MariaDB 10.2 GA (2016) MariaDB 10.3 GA (2017) 2013 MySQL 8.0 MariaDB 10.4 Percona 8.0 2018 MariaDB 10.5 GA Oracle MySQL cloud MariaDB SkySQL MariaDB 10.6 (2021) 2020
  • 14. 14 MySQL History  History of MySQL • https://dev.mysql.com/doc/refman/8.0/en/history.html • We started out with the intention of using the mSQL database system to connect to our tables using our own fast low-level (ISAM) routines. However, after some testing, we came to the conclusion that mSQL was not fast enough or flexible enough for our needs. This resulted in a new SQL interface to our database but with almost the same API interface as mSQL. This API was designed to enable third-party code that was written for use with mSQL to be ported easily for use with MySQL.
  • 15. 15 MySQL History  History of MySQL • MySQL is named after co-founder Monty Widenius's daughter, My. • The name of the MySQL Dolphin (our logo) is “Sakila,” which was chosen from a huge list of names suggested by users in our “Name the Dolphin” contest. The winning name was submitted by Ambrose Twebaze, an Open Source software developer from Eswatini (formerly Swaziland), Africa. According to Ambrose, the feminine name Sakila has its roots in SiSwati, the local language of Eswatini. Sakila is also the name of a town in Arusha, Tanzania, near Ambrose's country of origin, Uganda.
  • 16. 16 MySQL History  Michael "Monty" Widenius • https://en.wikipedia.org/wiki/Michael_Widenius Ulf Michael Widenius (often called Monty; born 3 March 1962, in Helsinki, Finland) is the main author of the original version of the open source MySQL database, a founding member of the MySQL AB company and CTO of the MariaDB Corporation AB • https://monty-says.blogspot.com • https://www.informatik-aktuell.de/betrieb/datenbanken/mariadb- und-mysql-vergleich-der-features.html • https://www.slideshare.net/Codemotion/my-sql- mariadbstorycodemotion
  • 17. Next Opensource Cloud Value MySQL Install
  • 18. 18 MySQL 설치 source Package binary • 서버 환경에 맞는 옵션을 지정하여 사용 가능 • configure 명령으로 옵션 지정 • OS 버전에 상관 없이 설치 가능 • 각 OS 별 최적화된 설치 파일 • 지정된 repository 에서 compile 된 binary 파일 및 환경설정을 모두 가져와 설치 • 설치가 간편함 • 각 OS 별 최적화된 compile 된 binary 제공 • core 의 옵션을 제외한 환경변수 설정 가능 • 원하는 환경변수를 이용하여 설치 가능
  • 20. 20 MySQL binary installation 1. MySQL binary file 다운로드 • 설치 경로 : /usr/local/mysql • https://dev.mysql.com/downloads/ 사이트를 이용하여 다운로드 Directory Contents of Directory bin mysqld server, client and utility programs docs MySQL manual in Info format man Unix manual pages include Include (header) files lib Libraries share Error messages, dictionary, and SQL for database installation support-files Miscellaneous support files MySQL Installation Layout for Generic Unix/Linux Binary Package
  • 21. 21 MySQL binary installation 2. 사용자 그룹 및 사용자 생성 3. 파일의 압축 해제 및 디렉토리 생성
  • 23. 23 MySQL binary installation 5. MySQL initialize • 설치 로그 확인 : error.log • 데이터 디렉토리 확인
  • 24. 24 MySQL binary installation  추가 작업 .bash_profile 설정 Secure installation 실행
  • 25. 25 MySQL binary installation  추가 작업 Linux limit 설정
  • 26. 26 MySQL binary installation  추가 작업 Linux systemd 설정
  • 27. 27 MySQL binary installation  추가 작업 Linux systemd 설정
  • 28. 28 MySQL 실행 및 접속  MySQL 실행  MySQL 접속
  • 29. 29 MySQL Data File  MySQL 기본 DataFile 구성 • Database directories • Table format files (*.frm) • Data and index files ( *.ibd – InnoDB ) • Own tablespace and log files (for InnoDB engine) • Server logs and status files
  • 31. Next Opensource Cloud Value MySQL Trend
  • 32. 32 MySQL Trend 2022 년 까지 70% 이상의 신규 개발 애플리케이션은 오픈소스 DB 를 이용할 것이며 “ 50% 이상의 기존 업무가 상용 DB 에서 이관될 전망이다 . Gartner | State of the Open-Source DBMS Market, 2018
  • 33. 33 MySQL Trend  Dzone Trend Report : SQL or NoSQL in the Age of Big Data https://dzone.com/trendreports/database-evolution 2020년 7월 보고서에 의하면 NoSQL보다 SQL을 더 많이 사용합니다. 그 이유는 시장의 예측보다 비정형 데이터 의 양이 지나치게 많아 지고 있으며 SQL 데이터베이스의 더 많은 경험자와 공급자들이 NoSQL 업체들과 경쟁할 수 있는 SQL의 새롭고 혁신적인 기능들을 개발하여 NoSQL 보다 좀 더 단순한 수준으로 제공을 하고 있습니다
  • 35. 35 MySQL Trend  DB-Engines 비교 : MySQL / MariaDB / Percona / PostgreSQL PostgreSQL MariaDB MySQL Percona Server for MySQL Primary database model Relational DBMS Relational DBMS Relational DBMS Relational DBMS DB-Engines Ranking #4 Overall #4 RDBMS #12 Overall #8 RDBMS #2 Overall #2 RDBMS #112 Overall #55 RDBMS Website www.postgresql.org mariadb.org www.mysql.com www.percona.com Developer PostgreSQL Global Development Group MariaDB Foundation Oracle Percona Initial release 1989 2009 1995 2008 Current release 13.3 , May 2021 10.5.10, May 2021 8.0.25, May 2021 8.0.21-12, 2020 License Open Source Open Source Open Source Open Source Replication methods Source-replica Multi-source Source-replica Multi-source Source-replica Multi-source Source-replica In-memory capabilities no yes yes Yes cluster Galera Cluster Galera Cluster NDB / InnoDB Cluster XtraDB Cluster
  • 36. 36 MySQL Trend PostgreSQL EDB Postgres MySQL Percona MariaDB Standard Enterprise community Enterprise community Enterprise License OpenSource OpenSource Commercial OpenSource Commercial OpenSource OpenSource OpenSource 기술 지원 Subscription (CPU core) Subscription (CPU core) Subscription (node) Subscription (node) Subscription (node) DB Link O O O X X X Δ Δ 오라클 호환성 70% 75% 90% 70% 70% Monitoring O O O O O Hot Backup O O O O O O SQL 관리 툴 O O O O O O Replication O O O O O O O O Cluster Galera Cluster InnoDB Cluster XtraDB Cluster Galera Cluster Galera Cluster DB Proxy Pgpool Pgpool EFM ProxySQL MySQL Router ProxySQL MaxScale(BSL) MaxScale(BSL) 마이그레이션 툴 O O O O Δ Δ  오픈소스 RDBMS (PostgreSQL, MySQL, Percona, MariaDB) 비교
  • 37. 37 MySQL Trend MySQL Percona MariaDB Community Enterprise Community Community Enterprise 모니터링 Enterprise Monitor PMM Monyog 백업 (Hot backup) Enterprise Backup Xtrabackup MariaBakcup MariaBakcup SQL management MySQL Workbench MySQL Workbench Tadpole DB Hub SQLyog Load Balancing & Routing MySQL Router MySQL Router ProxySQL MaxScale(BSL) MaxScale(BSL) Firewall Enterprise Firewall ProxySQL MaxScale(BSL) MaxScale(BSL) GTID MySQL GTID MySQL GTID MySQL GTID MariaDB GTID MariaDB GTID Data Masking Enterprise Data Masking Plugin MaxScale(BSL) MaxScale(BSL) Encryption Enterprise Encryption community community community Audit Enterprise Audit community community community Thread pool Enterprise Thread Pool community community community  MariaDB / MySQL / Percona DBMS들의 community / Enterprise 버전 기능/특징 비교
  • 38. Q&A
  • 39. Next Opensource Cloud Value MySQL Architecture
  • 41. 41 MySQL Architecture • 1’st Layer: Connectors – MySQL client – MySQL에 접근하기 위해 Application에서 설치하여 사용 – C, API, JDBC 등 언어에 따라 여러 가지 connector를 사용 • 2’nd Layer: MySQL Instance – SQL 구문 분석 – 옵티마이저 최적화로 실행계획 작성 – 필요하면 메모리에 캐쉬 • 3’rd Layer: Storage Engine – 데이터를 저장하고 추출 – 각각의 storage engine은 서로 다른 데이터 저장 및 추출 방법을 가짐 – InnoDB, Federated, MyISAM, MyRocks, …
  • 42. 42 MySQL Connectors • Developed by MySQL – ADO.NET Driver for MySQL (Connector/NET) – ODBC Driver for MySQL (Connector/ODBC) – JDBC Driver for MySQL (Connector/J) – Python Driver for MySQL (Connector/Python) – C++ Driver for MySQL (Connector/C++) – C Driver for MySQL (Connector/C) – C API for MySQL (mysqlclient) • Developed by MySQL Community – PHP Drivers for MySQL (mysqli, ext/mysqli, PDO_MYSQL, PHP_MYSQLND) – Perl Driver for MySQL (DBD::mysql) – Ruby Driver for MySQL (ruby-mysql) – C++ Wrapper for MySQL C API (MySQL++)
  • 43. 43 MySQL Connectors • Supported communication protocol – Unix socket (Only Unix/Linux Local) – TCP/IP (All OS) – Shared memory (Only Window Local) – Named pipes (Only Window Local/Remote) • Port – 3306 (default)
  • 44. 44 MySQL Server  MySQL Engine (instance) + Storage Engine (Handler API) • MySQL Engine • 요청된 SQL 문장을 분석 & 최적화 하는 등의 일을 처리 • Connection Handler, SQL Parser, Precompiler, Optimizer, Cache, Buffer • Storage Engine • 실제 데이터를 disk 스토리지에 저장 • disk 스토리지로부터 데이터를 추출 MySQL Engine Storage Engine
  • 45. 45 MySQL Server  MySQL Process • mysqld - 필수 main process - connection 처리 - SQL 처리 - Data Storage 핸들링 • mysqld_safe - mysqld를 background로 실행 - mysqld 모니터링 - optional process
  • 46. 46 MySQL Server  MySQL Thread • server process (mysqld) can create a number of threads • Connection Manager Thread가 각 User Connection Thread 제어 • 각 User Connection Thread가 인증 및 Query 수행 • Signal Thread가 timeout 및 long idle 알림/제어 • Data / Record / Key / Table / Host / Privileges Cache 사용 • DBMS 관리를 위한 Background Threads (read/write, concurrency control, replication, and so on)
  • 47. 47 MySQL Server Process Flow Application Handler API InnoDB MyISAM Federated MyRocks .... SQL Logging Thread Cache Connection Manager User Authentication Command Diaspatcher Query Cache Module Optimizer (select) Access Control Table Manager Parser Table Open Cache Table Definition Cache Table Modification (Update) Table Maintenance (Repairs) Replication (Primary, Replica) Status Report (status)
  • 48. 48 MySQL Server Process Flow • Connection Manager – MySQL 내부에서 Connection을 관리하는 Manager – 새로운 user connection thread를 DB에 할당 – Connection 생성과 함께 SQL 작업을 위한 메모리를 자동 할당 • User Authentication, Command Dispatcher – 해당 세션의 자격증명이 확인되면 Command Dispatcher에게 요청 전달 – Query or Command 확인 후, Command는 Dispatcher가 단순 수행 복잡한 Command는 타 모듈에 Redirection 처리 – Query(DML)는 로그 기록 요청 – Query Cache 전달
  • 49. 49 MySQL Server Process Flow • Cache & Buffer – 자주 사용되는 데이터/인덱스를 빠르게 사용 하기 위한 메모리 저장 영역 – Query Cache 는 Select문 결과를 캐시 하여 매우 빠른 응답을 지원 – 데이터베이스 Metadata 메모리 캐시를 제공 – 스토리지 엔진에 따라 기능의 차이가 존재함 – 서버 전체, 엔진 별, 유저 별 캐시 존재 • Parser / Optimizer 모듈들 – 유저의 오브젝트 접근 권한 확인 – SQL문 실행을 위한 준비 작업 – SQL 문을 Database 내부 언어로 변환, 실행 경로 분석 – 모든 Storage engine에 동일하게 적용
  • 50. 50 MySQL Server Process Flow • Access Control – 요청된 작업에 대한 Objects(DB, Table, Column, …) 수행 권한 확인 – Table Manager 전달 • Table Manager – 테이블 정의 파일(.frm) 작성, 수정 – Table Cache 유지보수 – 테이블 레벨 잠금
  • 51. 51 MySQL Server Memory • Global (shared) – query cache – table open cache – thread cache – data/index cache • Session (not shared) – join buffer – sort buffer – temporary table
  • 52. 52 MySQL Server Memory • InnoDB / XtraDB – innodb_buffer_pool_size (shared) – innodb_sort_buffer_size (not shared) • MyISAM – key_buffer_size (shared) – myisam_sort_buffer_size (not shared)
  • 53. Next Opensource Cloud Value MySQL Configuration
  • 54. 54 MySQL Configuration  설정 파일 경로 • 단 하나의 설정파일(my.cnf)만 사용 • 설정파일을 지정 해서 적용 가능 • my.cnf 가 명시되지 않는 경우 defaults path 중 아래의 순서대로 사용됨 - /etc/my.cnf - /etc/mysql/my.cnf - my.cnf in the DEFAULT_SYSCONFDIR specified during the compilation - the file specified in --defaults-extra-file (if any) - user-home-dir/.my.cnf
  • 55. 55 MySQL Configuration  설정 변수 • MySQL 8.0 - https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html - https://dev.mysql.com/doc/mysqld-version-reference/en/optvar.html • MariaDB - https://mariadb.com/kb/en/server-system-variables/ - https://mariadb.com/kb/en/system-variable-differences-between-mariadb-105-and-mysql-80/
  • 59. 59 MySQL Configuration  Connection, Log, Character Set 설정
  • 61. Next Opensource Cloud Value MySQL Variables / Status
  • 62. 62 MySQL Variables  Server System Variables https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html • Server 기동 시 사용: command-line 과 option file 이용 • Server 운영 중에 SET 명령어로 바꿀 수 있음 – System variable 이름과 값 보기  mysqld --verbose –help – 현재 사용중인 server variable 보기
  • 63. 63 MySQL Variables  동적 변수와 정적 변수 – 동적 변수 (dynamic)  기동 중인 상태에서 변경 가능 한 변수 – 정적 변수 (static)  기동 중인 상태에서 변경 불가능한 변수로 설정파일을 통해 변경 후 서비스를 재시작 해야 함  세션 변수와 글로벌 변수 – 세션 변수 (session)  클라이언트가 데이터베이스 서버에 접속해서 사용하는 옵션을 제어하는데 사용하는 변수 – 글로벌 변수 (global)  하나의 데이터베이스 서버 인스턴스에서 전체적으로 영향을 미치는 시스템 변수  SHOW GLOBAL VARIABLES로 확인
  • 64. 64 MySQL Variables  동적 변수 변경 (dynamic) • GLOBAL VARIABLES 수정 • SESSION VARIABLES 수정 • 서버가 실행되는 동안 설정파일 변경 없이 시스템변수 변경 가능 • 주의) 영구 적용은 my.cnf 수정 필요 • 동적 변수 설정 시 주의사항 - MB, GB와 같은 단위 표기법 사용불가 - 2 * 1024 * 1024 같은 수식 사용 가능
  • 65. 65 MySQL Variables  Buffer, Cache 변수 • key_buffer_size - dynamic ( global ) - Index block에서 사용하는 메모리 buffer 크기이며 MyISAM 변수 • innodb_buffer_pool_size - dynamic ( global ) - InnoDB용 Data/Index Page 버퍼 크기 - 물리메모리의 최대 80%까지, 권고 50~70% • join_buffer_size - dynamic ( global / session ) - join 에서 사용하는 버퍼의 크기
  • 66. 66 MySQL Variables  Buffer, Cache 변수 • read_buffer_size - dynamic ( global / session) - 순차적인 검색을 하는 Thread에 할당되는 버퍼의 크기 • sort_buffer_size - dynamic ( global / session ) - 정렬할때 Thread에 할당하는 버퍼의 크기 - 기본값 2M, 적게 설정하고 필요한 세션만 늘려서 사용 • max_join_size - dynamic ( global / session ) - 최대 join 되는 크기 (18,446,744,073,709,551,615)
  • 67. 67 MySQL Variables  Buffer, Cache 변수 • table_open_cache - dynamic ( global) - 모든 thread에서 열린 table수의 최대 크기 • query_cache_size - dynamic ( global ) - 이미 실행된 SQL Query의 결과값을 저장해 놓은 Cache크기 - 동일결과를 반복적으로 수행하는 읽기 위주의 thread가 많으면 효과적 • tmp_table_size - dynamic ( global / session ) - 임시테이블의 최대 메모리 크기
  • 68. 68 MySQL Variables  Buffer, Cache 변수 • thread_cache_size - Dynamic ( global ) - cache에 저장해둔 thread 수 - thread 생성시 cache에 thread가 있으면 생성하지 않고 재사용함 • innodb_thread_concurrenty - dynamic ( global ) - 동시에 수행 가능한 thread 수 - 너무 많으면 지나친 context switching, 너무 적으면 장비의 비효율 - 0 제한 없음, (cpu core *2 + disk num)
  • 69. 69 MySQL Status  Server Status Variables https://dev.mysql.com/doc/refman/8.0/en/server-status-variables.html  Global Status • 운영 중인 데이터베이스의 상태 보기
  • 70. 70 MySQL Status  Connection 상태 • Connections - 연결시도 횟수 = 사용량 • Max_used_connections - 최대 동시 접속자수 - 이 값을 확인 후에 MAX_CONNECTIONS의 값을 조정 • Aborted_connects - 연결을 시도해서 실패한 횟수, Max_used_connections 를 확인 • Aborted_clients - 연결 후, 클라이언트에서 연결이 적절하게 닫지 못해 취소된 횟수 - 네트워크 연결에 문제 가능성 높음
  • 71. 71 MySQL Status  InnoDB 상태 • innodb_buffer_pool_pages_total - InnoDB Buffer Pool의 페이지 수 - Innodb_buffer_pool_pages_free - innodb_page_size=16K • innodb_buffer_pool_reads, innodb_buffer_pool_read_requests - InnoDB Buffer Pool 미 적중으로 디스크에서 읽은 수 - InnoDB Buffer Pool 읽기 요청 수 - InnoDB Buffer Cache Hit Ratio !!
  • 72. 72 MySQL Status  Query 상태 • Questions, Queries - server로 보낸 쿼리 횟수 - SP 내부의 queries 수 차이 - QPS (초당 쿼리 수) : Questions와 Uptime 이용 • Table_locks_waited - table lock을 위해 대기한 수 • Select_full_join - INDEX를 사용하지 않은 조인 쿼리 실행 횟수 - 이 값이 너무 크면 TABLE의 INDEX 검토 - 쿼리 튜닝 검토
  • 73. 73 MySQL Status  Open Tables 상태 • open_tables, opened_tables - 열린, 열었던 table 수 - 이 값이 너무 크면 table_open_cache 값을 증가
  • 74. Q&A
  • 75. Next Opensource Cloud Value MySQL Storage Engine
  • 77. 77 MySQL Storage Engine • 스토리지 엔진은 하나의 모듈로서 작동 • 스토리지 엔진을 별도 컴파일 하여 서버에 적재가 가능 • 지속적으로 새로운 내부 스토리지 엔진을 개발 • 개별적인 스토리지 엔진이 다양하게 개발됨
  • 78. 78 MySQL Storage Engine 스토리지 엔진 MySQL MariaDB 트랜잭션 잠금 주요 응용 프로그램 InnoDB O >= 10.2.x Yes MVCC 트랜잭션 처리 XtraDB Percona >= 5.1.x <= 10.1.x Yes MVCC 트랜잭션 처리 MEMORY O >= 4.0 No 테이블 중간 계산, 통계 참조 ColumnStore >= 10.1.x Yes MVCC 대용량 분석 (OLAP) FederatedX Federated >= 10.0.x Yes N/A 원격 서버 연결 CONNECT >= 10.0.x Yes N/A 이기종 DB 및 파일 연결 TokuDB Percona >= 5.5.x Yes MVCC 트랜잭션 처리, 로깅 Xpand >= 10.5 Yes MVCC newSQL (Clustrix) NDB O Yes MVCC 고성능 트랜잭션
  • 79. 79 MySQL Storage Engine 스토리지 엔진 MySQL MariaDB 트랜잭션 잠금 주요 응용 프로그램 MyISAM O > 3.23 No 동시 insert 가능 SELECT, INSERT 대량 적재 Aria >= 5.1 No 동시 insert 가능 MyISAM 활용 Archive O >= 4.1 No row 로깅, 집계 분석 CSV O >= 4.1 No 테이블 로깅, 외부 데이터 대량 적재 BLACKHOLE O >= 4.1 N/A N/A 로깅, 복제 아카이브 MRG_MyISAM Merge >= 3.23 No 동시 삽입 가능 테이블 MyISAM 테이블의 모음 SphinxSE >= 10.0 N/A N/A Full Text Search Mroonga >= 10.0 No No Groonga기반 FTS Example O Example code
  • 80. 80 MySQL Storage Engine 스토리지 엔진 MySQL MariaDB 트랜잭션 잠금 주요 응용 프로그램 OQGRAPH >= 10.0 N/A N/A 계층구조, 그래프 처리 Sequence >= 10.0 Yes Read-only 임시테이블용 시퀀스 Spider Tencent >= 10.0 Yes row 샤딩 Cassandra >= 10.0 N/A N/A SQL/NoSQL간 데이터 통합 MyRocks Facebook >= 10.2.x Yes MVCC 트랜잭션 처리 S3 >= 10.5 Read-only archive tables in Amazon S3 MindsDB >= 10.5 Machine Learning
  • 81. 81 MySQL Storage Engine  show engines • 현재 사용 가능한 engine 조회 • transactional 지원 여부 조회 가능
  • 82. 82 MySQL Storage Engine  General Purpose Storage Engines • Transactional • InnoDB, TokuDB, MyRocks, NDB, Xpand • Non-Transactional • MyISAM  Analytics and Data Warehousing • ColumnStore  Special Purpose Storage Engines • Connect, Memory, Spider, Archive, Blackhole, CSV,...  Full Text Search Storage Engines • SphinxSE, Mroonga
  • 83. 83 MySQL Storage Engine  MyISAM • MySQL 3.23.x 이후 버전에서 사용 가능 • Data 저장이 효율적이고 빈번한 Data 사용의 부하를 잘 소화함 • B-tree, R-tree & Full-text Index를 지원 • 특정 Index에 대한 Memory Cache를 지원 ( key_buffer_size ) • Data 압축에 대한 옵션을 제공 ( fixed / dynamic / compressed ) • Table 레벨의 Lock을 지원 & Transaction 미지원 • Backup 및 특정 시점으로의 복구 지원 • .frm / .myd / .myi 파일로 구성 ( Table 구조정보 / data / index ) • engine = myisam 형태로 지정
  • 84. 84 MySQL Storage Engine  Memory • Non-transactional Storage Engine • Memory 에 모든 data 가 저장됨 • 고정길이열의 컬럼만 사용 가능함 (varchar, blob, text 컬럼 사용불가) • 타 Engine 에 비해 DML 속도가 월등히 빠름 (고정 길이열 기반으로 인함) • Server 의 재 구동 시 Data는 모두 소실 • 동등 조건( ex) where a=10 ) 검색에 HASH기반 검색을 제공 • 범위 검색 시 Index 를 사용할 수 없음 • temporary table 과 다르게 타 세션에서도 조회가 가능
  • 85. 85 MySQL Storage Engine  Archive • 자동적인 Data 압축을 지원 • 다른 Storage Engine 대비 80%의 저장공간 절약 • 실제적인 저장용량의 제한 없음 • Index 미지원 • 빠른 Insert 속도를 위해 특별한 입력 버퍼를 제공 • Insert와 select만을 지원 • row레벨 Lock을 지원 • Backup 및 특정 시점으로의 복구 지원 • 데이터 웨어하우스, 데이터 감사 등에 사용
  • 86. 86 MySQL Storage Engine  Federated • MySQL 5.0에 Federated engine 도입 • 원격의 물리적 Data 객체에 대한 논리적 Data 객체를 생성 • 하나의 Data 객체에서 다른 타겟 객체로의 ‘포인터’역할 • 원격 Data 접근을 위한 특별한 미들웨어가 필요하지 않음 • 실행 속도는 네트워크 성능에 따라 좌우됨 • 실제 Data 객체의 Engine 특성에 따라 처리됨 • Table 정의를 통한 SSL 보안 처리 • 모든 SQL 오퍼레이션 지원( as per target object ) • 분산 데이터베이스 환경에서 사용
  • 87. 87 MySQL Storage Engine  MyROCKS - A RocksDB storage engine with MySQL - Benefit from all the features of MySQL while using RocksDB as backend storage - http://myrocks.io/ - https://www.facebook.com/groups/myrocks/ - open source storage engine : developed by Facebook - MyRocks, typically, gives greater performance for web scale type applications - It can be an ideal storage engine solution when you have workloads that require greater compression and IO efficiency. - https://mariadb.com/kb/en/library/about-myrocks-for-mariadb/
  • 88. 88 MySQL Storage Engine  MyROCKS Benefits - Greater Space Efficiency 2x more compression : MyRocks has 2x better compression compared to compressed InnoDB, 3-4x better compression compared to uncompressed InnoDB, meaning you use less space. - Greater Writing Efficiency 2x lower write rates to storage : MyRocks has a 10x less write amplification compared to InnoDB, giving you better endurance of flash storage and improving overall throughput. - Faster Data Loading faster database loads : MyRocks writes data directly onto the bottommost level, which avoids all compaction overheads when you enable faster data loading for a session. - Faster Replication No random reads for updating secondary keys, except for unique indexes. The Read-Free Replication option does away with random reads when updating primary keys, regardless of uniqueness, with a row- based binary logging format.
  • 89. 89 MySQL Storage Engine  MyROCKS using (MariaDB)
  • 90. Next Opensource Cloud Value MySQL InnoDB
  • 91. 91 MySQL InnoDB • Heikki Tuuri 에 의해 개발됨 • Oracle Corp 에서 소유권을 가지고 있음 • XtraDB는 Percona의 open source • The default engine is InnoDB in MySQL 8.0 • By default, until MariaDB 10.1, MariaDB uses the XtraDB storage engine, a performance enhanced fork of the InnoDB storage engine. From MariaDB 10.2, InnoDB is the default • https://mariadb.com/kb/en/library/why-does-mariadb-102-use-innodb-instead-of-xtradb/
  • 92. 92 MySQL InnoDB • Transaction-Safe 스토리지 엔진 • Primary Key 에 의한 클러스터링 • 모든 InnoDB 테이블은 기본적으로 PK 를 기준으로 클러스터링 되어 저장 • PK 에 의한 range 스캔에 최적화 • optimizer 가 PK 에 의한 실행계획을 더 선호함 • Oracle 의 IOT 와 동일한 구조 • 읽기 일관성 보장 ( Non-locking consistent read ) • MVCC ( Multi Version Concurrency Control ) • Foreign Key 지원
  • 93. 93 MySQL InnoDB • 자동 Deadlock 감지 • Deadlock 발생시 Server 에서 바로 감지 • Deadlock 트랜잭션 중 Rollback이 가장 용이한 트랜잭션 강제 종료 • show engine innodb status 명령으로 확인 • 자동 장애 복구 • MySQL 서버의 구동 시 완료되지 못한 트랜잭션 복구 • disk에 일부만 기록된 데이터 페이지 복구 • mysqld_safe 를 이용한 mysqld 의 모니터링 및 장애 시 restart 수행
  • 94. 94 MySQL InnoDB • 동시접속 퍼포먼스가 뛰어나 대용량 데이터 처리에 적합 • 메인 메모리내 데이터 캐싱 및 인덱싱 위한 버퍼 풀(pool)을 관리 • innodb_buffer_pool_size • 테이블과 인덱스를 테이블 스페이스에 저장 • 테이블 스페이스를 몇개의 파일이나 disk 파티션으로 구성 cf) MyISAM은 테이블과 인덱스를 각각 분리된 파일로 관리 • InnoDB 테이블은 OS 파일 사이즈에 독립적인 파일 사이즈를 가짐 • 트랜잭션의 동시성 퍼포먼스가 필요한 대용량 사이트에 적합
  • 95. 95 MySQL InnoDB Connection Manager Thread Signal Thread Connection Thread Connection Thread Connection Thread Connection Thread Connection Thread Client Client Client Client Client Insert Buffer Thread InnoDB File I/O Threads InnoDB Log Thread Read Thread Write Thread Storage Engine innodb_read_io_threads innodb_write_io_threads
  • 97. 97 MySQL InnoDB Log Buffer ( buffered log records ) Buffer Pool ( buffered data pages ) Additional Mem Pool Commit ( + checkpoint ) Log File 1 Log File 2 Log File 3 Redo Log ibdata1 data file checkpoint In Memory On Disk Log Files Tablespace Undo Log ibdata2 data file iblogfile1 innodb_file_per_table=0 innodb_max_purge_log InnoDB Log / Data Disk Write
  • 98. 98 MySQL InnoDB Memory buffer pool Page level cache for tables and indexes Insert buffer part of buffer_pool Adaptive hash search – Speeds up search by secondary indexes lookups and range scans Open tables info Misc internal memory : Page hash File system Lock system Recovery system Threads Disk Table1.ibd pages Table2.ibd pages Table3.ibd pages XtraDB : I_S.INNODB_BUFFER_POOL_PAGES show content of buffer_pool InnoDB-std : may tabke ½ of buffer pool XtraDB : innoDB_ibuf_max_size Disable : innodb_change_buffering=0 background thread “merges” buffer with indexes Query Query XtraDB : Check sizes in SHOW ENGINE INNODB STATUS InnoDB-std : can grow unlimitedly XtraDB : innodb_dict_size_limit XtraDB : Check sizes in SHOW ENGINE INNODB STATUS innodb_buffer_pool_size is cretical parameter Thumb rule : 60-80% of RAM Table1.ibd Table2.ibd Table3.ibd Primary Key == data Secondary indexes .ibd are placed separately if innodb_file_per_table=1 Otherwise in ibdata1 Files are divided by 16K pages XtraDB : 4K, 8K, 16K ibdata1 ( system table space ) Data dictionary Double write buffer Insert buffer Changes to secondary non-unique indexes are buffered there Rollback segments UNDO space Undo slot Undo slot Undo slot XtraDB : you can view content in I_S.INNODB_SYS_TABLES, I_S.INNODB_SYS_INDEXES Innodb-std : rollback segment is 1 XtraDB : innodb_extra_segments 1023 slots per segment Pointers to undo space UNDO space may grow unlimitedly XtraDB : innodb_use_purge_thread=1 to use separate threads for cleaning log file log file Log buffer Usually changes are fixed In background “log thread” on disk with fsync() command. innodb_flush_log_at_trx_commit controls how to fsync innodb_log_buffer_size 4M-16M is good value Changes are fixed in log file via log buffer Insert buffer is written from BP to disk Pages are written in background innodb_write_io_threads. innodb_flush_method=O_DIRECT To avoid caching in OS cache Writes are done via “double write buffer” to prevent corruptions REDO LOGS innodb_lof_file_size InnoDB-std : max size < 4GB XtraDB : max size < 2TB innodb_log_files_in_group ( usually 2-3 ) Reads are done in foreground. innodb_read_io_threads are for read-ahead
  • 99. 99 MySQL InnoDB commit – Write to disk commit Write & Flush to disk - every 1 Second Log Files O/S buffer Log Buffer InnoDB Update table set col1 .... commit - Write & Flush to disk Update table set col1 .... Flush to disk - every 1 Second Variables 0 1 2 Update table set col1 .... 1s 1s innodb_flush_method=O_DIRECT innodb_flush_log_at_trx_commit InnoDB Redo Log Write
  • 100. 100 MySQL InnoDB  InnoDB Data Flush • buffer pool 의 dirty pages에 대해 주기적으로 disk flush • main thread 에서 checkpoint 를 발생하거나 free page 가 없는 경우 write thread 를 통해 disk 로 flush 함 • undo log 의 flush 는 checkpoint 와 별개로 동작 Buffer Pool ( dirty pages ) ibdata1 data file checkpoint Tablespace Undo Log ibdata2 data file innodb_max_purge_log In Memory On Disk Write Thread Disk Flush dirty page pagedata innodb_max_dirty_pages_pct innodb_io_capacity pagedata
  • 101. 101 MySQL InnoDB Variables • INNODB_DATA_HOME_DIR – 테이블스페이스 파일의 생성 위치 설정 • INNODB_DATA_FILE_PATH – 테이블스페이스 파일 명 및 크기, 옵션 설정 – ibdata1:100M:autoextend:max:1G  ibdata1라는 파일명으로 생성  100MB의 고정크기로 최초 생성  100MB가 넘을 경우 “autoextend” 라는 옵션으로 자동으로 파일 크기가 확장  최대 확장되는 크기는 MAX 옵션의 설정 값만큼 확장 • INNODB_AUTOEXTEND_INCREMENT – autoextend 옵션으로 자동 확장되는 크기 지정 – Default Value: 64 (from MariaDB 10.0) 8 (before MariaDB 10.0) – Size in MB to increment an auto-extending shared tablespace file when it becomes full
  • 102. 102 MySQL InnoDB Variables • INNODB_FILE_PER_TABLE – 공용 테이블스페이스 사용 대신에 테이블 별 테이블스페이스 사용 옵션 – TableName.ibd 파일 생성 • INNODB_BUFFER_POOL_SIZE – 테이블의 데이터와 인덱스를 캐시하기 위해 사용하는 메모리 버퍼의 크기 – 크게 설정하면 할수록, data의 disk I/O가 적어짐 – 전체 물리메모리의 70~80%로 설정하나, 세션수가 많으면 50%로 설정 – ORACLE DB_BUFFER_CACHE와 유사 • INNODB_BUFFER_POOL_DUMP_AT_SHUTDOWN/STARTUP – 데이터와 인덱스 캐시를 위한 메모리 버퍼의 재사용을 위해 중지/재시작 시 버퍼정보를 파일에 기록/로딩함
  • 103. 103 MySQL InnoDB Variables • INNODB_LOG_FILE_SIZE – Redo 로그 파일의 크기 설정 – 순차적으로 파일이 일정한 크기와 용량으로 순환식으로 생성 – Larger values mean less disk I/O due to less flushing checkpoint activity, but also slower recovery from a crash • INNODB_LOG_GROUP_HOME_DIR – Redo 로그 파일에 대한 디렉토리 경로 설정 • INNODB_LOG_FILES_IN_GROUP – Redo 로그파일 개수 • INNODB_LOG_BUFFER_SIZE – Redo 로그 파일을 기록하기 위한 버퍼 사이즈
  • 104. 104 MySQL InnoDB Variables • INNODB_LOCK_WAIT_TIMEOUT – 롤백이 진행되기 전에 lock을 대기하는 시간 ( default 50 ) • INNODB_THREAD_CONCURRENCY – InnoDB 내부에 OS 쓰레드 동시 사용 설정 – 설정된 값과 같거나 적게 유지 – A setting of 0, the default, permits as many threads as necessary – A suggested setting is twice the number of CPU's plus the number of disks • INNODB_FLUSH_LOG_AT_TRX_COMMIT – Commit 동작 시 데이터를 log file 에 기록여부를 설정  0 : log buffer내용이 1초 간격으로 로그파일에 쓰여지고 flush, commit시 미동작  1 : log buffer내용이 commit할 때에 로그 파일에 쓰여지고 flush  2 : log buffer내용이 commit할 때에 로그 파일에 쓰여지고 flush는 1초 간격으로 동작
  • 105. 105 MySQL InnoDB Variables • INNODB_FLUSH_METHOD – Flush 명령어 방식 설정, 디폴트는 fdatasync  fdatasync : fsync()를 사용해서 데이터와 로그 파일을 flush  O_SYNC : 로그 파일을 열고 flush 하지만, 데이터 파일을 flush하기 위해서는 fsync()를 사용  O_DIRECT : O_DIRECT를 사용해서 데이터 파일을 열고, 데이터 파일과 로그 파일을 flush  Windows에서는 flush 방식은 항상 async_unbuffered 사용
  • 106. 106 MySQL InnoDB Variables • INNODB_STATS_PERSISTENT – ANALYZE TABLE 명령 수행 후에 통계가 disk에 저장될지 여부 • INNODB_STATS_PERSISTENT_SAMPLE_PAGES – Indexed column의 통계를 측정할 때 샘플링 할 page 수 – 값이 크면 index통계의 정확도는 올라가나, 통계정보 수집 시 I/O 증가할 수 있음 • INNODB_STATS_TRANSIENT_SAMPLE_PAGES – INNODB_STATS_PERSISTENT가 off일 때 샘플링 할 page 수
  • 107. 107 MySQL InnoDB Variables • INNODB_STATS_AUTO_RECALC – Default는 on, table에서 10% 이상의 row가 변경되면 자동으로 persistent statistics를 재계산 함 • INNODB_STATS_ON_METADATA – Show table status, Show index 또는 INFORMATION_SCHEMA의 tables/statistics 테이블 접근 시 자동으로 통 계정보 수집 – Default Value: OFF (from MariaDB 10.0), ON (before MariaDB 10.0)
  • 108. 108 MySQL InnoDB Variables • INNODB_UNDO_LOGS • INNODB_UNDO_TABLESPACES • INNODB_UNDO_DIRECTORY – Path to the directory (relative or absolute) that InnoDB uses to create separate tablespaces for the undo logs. (the default value before 10.2.2) leaves the undo logs in the same directory as the other log files. From MariaDB 10.2.2, the default value is NULL, and if no path is specified, undo tablespaces will be created in the directory defined by datadir. Use together with innodb_undo_logs and innodb_undo_tablespaces. Undo logs are most usefully placed on a separate storage device. – Default Value: NULL (>= 10.2.2), . (<= 10.2.1) – Introduced: MariaDB 10.0.0 https://dev.mysql.com/doc/refman/8.0/en/innodb-undo-tablespaces.html
  • 109. Q&A
  • 110. Next Opensource Cloud Value MySQL Data Types
  • 111. 111 MySQL Data Types  String Data Types – 고정 길이 • CHAR(0~255), BINARY(0~255) – 가변 길이 • VARCHAR(0~65535), VARBINARY(0~65535) – LOB, TEXT • TINYBLOB(2^8-1), BLOB(2^16-1), MEDIUMBLOB(2^22-1), LONGBLOB(2^32-1) • TINYTEXT(2^8-1), TEXT(2^16-1), MEDIUMTEXT(2^22-1), LONGTEXT(2^32-1) – ENUM • MAX 65535 values 주의) MySQL/MariaDB에서 size는 문자열의 길이를 감안해서 이기종 DBMS에서 데이터 이행 시 고려
  • 112. 112 MySQL Data Types  Numeric Data Types – BOOLEAN – BIT(1~64) – TINYINT SIGNED/UNSIGNED : (-128~127 / 0~2^8) – SMALLINT SIGNED/UNSIGNED : (-2^15~2^15-1 / 0~2^16) – MEDIUMINT SIGNED/UNSIGNED : (-2^23~2^23-1 / 0~2^24) – INT SIGNED/UNSIGNED : (-2^31~2^31-1 / 0~2^32) – BIGINT SIGNED/UNSIGNED : (-2^31~2^31-1 / 0~2^32) – DECIMAL(p,s) : 고정소수점, p-65, s-30 – FLOAT(p,s) : 부동소수점,근사치, p-23 – DOUBLE(p,s) : 부동소수점,근사치, p-53
  • 113. 113 MySQL Data Types  Date/Time Data Types – DATE • ‘1000-01-01’ ~ ‘9999-12-31’ • ‘0000-00-00’ 허용가능 (sql_mode 미설정 ‘NO_ZERO_DATE’) – TIME • ‘HH:MM:SS.ssssss’ – DATETIME • ‘1000-01-01 00:00:00.000000’ ~ ‘9999-12-31 23:59:59.999999’ – TIMESTAMP • ‘1970-01-01 00:00:00’ ~ ‘2038-01-19 03:14:07’ – YEAR(4)
  • 114. 114 MySQL Data Types  Binary Types – BINARY / VARBINARY / TINYBLOB / BLOB / MEDIUMBLOB / LONGBLOB – BINARY and VARBINARY are Case-Sensitive Versions of CHAR and VARCHAR – No Character Set and Collation for Binary Types - ordered by bytes – Blobs are Used often to Store Files in a Database – Files on Disk are often Faster – Blobs are Included in Transactions, Replication, and Backups – Blobs 는 mysqld 메모리 사용량을 증가시킵니다
  • 115. 115 MySQL Data Types  JSON Types – https://dev.mysql.com/doc/refman/8.0/en/json.html – MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents.
  • 116. 116 MySQL Data Types  JSON Types (MariaDB) – JSON is an alias for LONGTEXT introduced for compatibility reasons with MySQL's JSON data type – In order to ensure that a valid json document is inserted, the JSON_VALID function can be used as a CHECK constraint – This constraint is automatically included for types using the JSON alias from MariaDB 10.4.3 – JSON Functions : https://mariadb.com/kb/en/library/json-functions/
  • 117. 117 MySQL Data Types  auto_increment – LAST_INSERT_ID() – SERIAL is a synonym for "BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE"
  • 118. 118 MySQL Data Types  Virtual Column – Two Virtual Column Types: • PERSISTENT (stored) • VIRTUAL (generated only) – All Data Types Supported – Use PERSISTENT for Indexes – Cannot be Primary Key – Used with InnoDB, Aria, MyISAM, CONNECT
  • 119. Next Opensource Cloud Value MySQL Transaction
  • 120. 120 MySQL Transaction  Transaction – 트랜잭션(Transaction) 은 더 이상 나뉠 수 없는 하나의 업무단위 – 데이터베이스 내에서 한꺼번에 수행되어야 할 일련의 연산 – All or Nothing – Commit 시 모든 작업 결과는 데이터베이스에 반영 – Rollback 시 모든 작업 결과가 데이터베이스에 미반영
  • 122. 122 MySQL Transaction  ACID – 원자성 (Atomicity)  Transaction 은 더 이상 분류할 수 없는 작업 단위  모든 데이터 수정 작업이 수행되거나 되지 않아야 함 – 일관성 (Consistency)  Transaction 전후 도메인의 유효성, 무결성 제약조건등을 만족해야 함 – 고립성 (Isolation)  동시 Transaction 에 의한 수정은 다른 동시 Transaction 에 의한 수정과 격리  Transaction 중간의 데이터는 변경을 수행한 Transaction 에서만 확인됨 – 영속성 (Durability)  Transaction 이 완료되면 영구적으로 시스템에 적용  시스템 오류와 무관하게 데이터는 보존
  • 123. 123 MySQL Transaction  Transaction 세가지 형태 Transaction A Transaction B Transaction C BEGIN BEGIN BEGIN READ READ READ WRITE WRITE WRITE READ READ READ ... ... ... WRITE ABORT SYSTEM ABORT COMMIT ROLLBACK SYSTEM ROLLBACK Transaction 정상 종료 잘못된 입력 일관성 제약 조건 위배 사용자 요청에 의한 철회 타임아웃 교착상태 시스템 crash
  • 124. 124 MySQL Transaction  Isolation level – READ UNCOMMITTED – READ COMMITTED  InnoDB system tablespace의 undo segment 이용  Transaction 의 ACID 보장이 필요하면 SELECT 시 명시적 LOCK 사용  Transaction 도중 SELECT 값이 타 transaction 에 의해 변동 가능 – REPEATABLE READ  InnoDB 스토리지 엔진에서 기본적으로 사용되는 격리 수준  Transaction 에서 SELECT 값을 항상 동일하게 보장  Undo record 에는 잠금을 걸 수 없으므로 PHANTOM READ 발생 가능 a. InnoDB 의 경우 Gap Lock 방식으로 PHANTOM READ 발생하지 않음 – SERIALIZABLE  읽기 작업 시에도 공유 잠금을 획득 해야 함
  • 125. Next Opensource Cloud Value MySQL Locking
  • 126. 126 MySQL Locking  Lock 이란? – 데이터베이스에서 동일 자원 사용시 자원의 경합을 최소화 하기 위한 장치 – Transaction 의 순차적 진행을 보장하기 위한 직렬화 장치 – 다중 Transaction 의 일관성과 무결성을 유지하기 위한 장치 – MVCC 를 구현하기 위한 필요 장치 – 사용 의도에 따라 공유, 배타, 갱신, 의도, 스키마 lock 등이 존재
  • 127. 127 MySQL Locking  Global Lock – 글로벌 읽기 잠금 (Global Read Lock) – A세션 자체에서 글로벌하게 READ LOCK 이 필요할 경우 사용 – 다른 세션에서는 READ만 가능 – 논리백업(mysqldump) 수행 시 유용
  • 128. 128 MySQL Locking  Table Read Lock – A세션에서 테이블 자원을 사용하기 위하여 데이터를 읽기를 할 때, 다른 세션에서는 테이블 자원에 대한 사용을 제한 하는 lock – A세션에서 명시적으로 테이블 lock 을 사용하면 해당 세션에서 lock 을 해지하지 않으면 다 른 세션에서는 접근을 할 수 없음 – 테이블 lock을 사용 하려면 테이블 lock 권한을 가지고 있어야 가능
  • 129. 129 MySQL Locking  Table Write Lock – lock을 건 thread 에서만 read, write가 가능 – lock을 건 thread를 제외하고 해당테이블에 대해 read/write 불가능 – unlock 은 lock 을 건 thread 에서만 가능 – multiple table lock은 ‘,’로 구분
  • 130. 130 MySQL Locking  Metadata Lock – 데이터 이외의 메타데이터 변경시 발생하는 lock – 주로 table, trigger 등을 drop 또는 alter 할 때 발생 Metalock 발생
  • 131. 131 MySQL Locking  Dead Lock – Transactional Database 의 공통 문제 – Application 설계의 문제로 인해 발생 – show engine innodb status 명령으로 최신의 deadlock 정보 확인 가능 – InnoDB Engine 사용시 Deadlock 자동 감지 및 즉시 처리 – InnoDB Engine 에서 Deadlock 발생시 undo 가 작은 transaction rollback
  • 132. 132 MySQL Locking  Dead Lock 방지 – Application 에서 Deadlock 으로 종료된 Transaction 을 재수행 하도록 작성 필요 – Transaction 의 단위를 작게 나누어서 실행 – 고정 순서로 테이블과 열에 접근하도록 Application 설계 – Index 설계를 통해서 Deadlock 발생을 최소화
  • 133. 133 MySQL Locking  InnoDB Lock Monitoring – SHOW ENGINE INNODB STATUS – Information_schema 의 INNODB_TRX, INNODB_LOCKS, INNODB_LOCK_WAIT  INNODB_TRX : 트랜잭션이 어떤 프로세스에 의해 기동되고, 어떤 lock을 기다리는지를 관리  INNODB_LOCKS : 어떤 lock이 존재하는지 관리  INNODB_LOCK_WAITS : lock에 의한 프로세스 간의 의존 관계를 관리 – Server variables 로 확인  innodb_status_output=ON (in error.log )  innodb_status_output_locks=ON … SHOW ENGINE INNODB STATUS;  일정시간 동안만 사용하세요
  • 134. Q&A
  • 135. Next Opensource Cloud Value MySQL Security
  • 136. 136 MySQL Security – 데이터베이스는 chroot 환경에서 실행 – mysqld 프로세스는 다른 프로세스가 사용하지 않는 유일한 UID/GID로 실행 – 인가된 계정을 제외한 시스템 계정은 로컬 엑세스만 허용 – root user 계정의 패스워드는 추정하기 어렵도록 설정 – 관리자(root) 어카운트 변경 – history 의 주기적인 삭제 or /dev/null 링크 – 데이터베이스로의 익명 접속(anonymous 계정 사용)을 금지 – test 및 미사용 데이터베이스와 테이블을 모두 삭제 – local-infile 파일 경로 제한 – load_file() 함수의 사용 권한 제한 – DB 관련 directory 의 권한 제한 – mysql user, db, table, column 권한 설정
  • 137. 137 MySQL Security • Remote Access 제한 – default port 인 3306 을 차단 혹은 타 port 로 변경 – port 를 변경하여도 mysql.sock socket 으로 통신은 가능 – skip-networking 설정 시 3306/tcp 포트로 접근 불가능 – Remote 데이터 백업 등 Remote 작업 수행 시 ssh 사용 • 로컬 보안 개선 – LOAD DATA LOCAL INFILE 제한 – my.cnf 의 [mysqld] 난에 다음을 추가
  • 138. 138 MySQL Security • 관리자(root) 패스워드 변경 – mysql 클라이언트를 실행하여 패스워드 변경 – 기본적으로 root 계정에 패스워드가 설정되어 있지 않음 – 쉽게 유추할 수 없는 패스워드로 설정 – mysql 접속시 password 가 노출되지 않도록 –p 옵션으로 접속 – mysqladmin 를 이용하여 변경하는 것이 보안에 뛰어남 – ps aux 커맨드 사용시 타 사용자가 password 를 확인할 수 있음 – history 파일(~/.history, ~/.bash_history)을 보면 패스워드가 쉽게 노출
  • 139. 139 MySQL Security • 기본 제공되는 사용자/데이터베이스 삭제 – MySQL 설치 시 제공하는 anonymous 계정과 test 데이터베이스 삭제 – 사용되지 않는 root 를 제외한 계정을 정리하도록 권고 – 익명 접속으로 데이터베이스를 설정하는 것을 막을 수 있음 – 또는 mysql_secure_installation 수행
  • 140. 140 MySQL Security • 관리자 (root) 계정 변경 – default 설정인 관리자 계정(root) 를 말함 – 무차별 대입 & 딕셔너리 공격 등으로 추측해 내기 어려운 이름으로 변경 – root 계정을 제외하고 타 계정에 권한만 부여하여 사용 • history 삭제 – client에 의해 실행되는 모든 SQL 커맨드가 저장 – ~/.mysql_history 에 기록됨 – 패스워드 정보도 노출될 수 있음
  • 141. Next Opensource Cloud Value MySQL Management
  • 142. 142 MySQL Management  MySQL Log  MySQL DDL  MySQL Partition  MySQL Stored Routines / Triggers / Events  MySQL User  MySQL Admin Command
  • 143. 143 MySQL Log  에러 로그 (error log) – 서버 시작 및 종료 기록을 포함 – 문제가 되는 쿼리에 대한 로그  느린 쿼리 로그 (slow query log) – long_query_time 설정 보다 길게 수행 하는 쿼리에 대한 로그 – mysqldumpslow 유틸리티를 이용해서 분석
  • 144. 144 MySQL Log  일반 쿼리 로그 (general query log) – 클라이언트의 연결, 클라이언트로부터의 쿼리 등 다양한 이벤트가 기록 – 서버로 수신되는 모든 쿼리를 기록 – 서버의 활동상황(누가 연결하며, 무엇을 하고 있는지)을 감시하는데 유용
  • 145. 145 MySQL Log  바이너리 로그 (binary log) – UPDATE, DELETE, INSERT, CREATE TABLE, GRANT 등의 명령문에 의해서 수정이 발생한 명령문을 기록 – 서버가 비정상 종료할 경우, 백업 이후의 데이터를 복원하기 위해 사용  릴레이 로그 (relay log) – 서버가 리플리케이션 리플리카(replication replica) 서버로 동작하는 경우, primary 서버로부터 수신 한 데이터 수정 이벤트를 기록
  • 146. 146 MySQL Log  Log output – log_output 을 FILE 또는 TABLE 로 설정 할 수 있음  로그 관리 – 파일이 일정 사이트가 되면 rename 등으로 관리 – https://dev.mysql.com/doc/refman/8.0/en/log-file-maintenance.html – https://mariadb.com/kb/en/rotating-logs-on-unix-and-linux/
  • 147. 147 MySQL Log  MariaDB audit log – Includes Table Event Logging (Triggers, Stored Procedure Calls) – Optional Field Substitution of Placeholders in Query Log to Improve Security – Filtering Audit Logs by Role & User Accounts – Records Privilege Changes – Password Change Logging – https://mariadb.com/kb/en/library/mariadb-audit-plugin/
  • 149. 149 MySQL DDL  Create Table – Column : Data Type, Default Value, Character Set, Collation – Index – Storage Engine
  • 150. 150 MySQL DDL  Alter Table – Add / Drop / Change / Modify Column – Add / Drop Index
  • 151. 151 MySQL DDL  Create View – 어플리케이션에 대한 테이블 스키마 표준화 – 특정 사용자 및 어플리케이션에 대한 데이터 접근 제한 – 복잡한 쿼리의 단순화, 분할 – Views are Not Materialized
  • 152. 152 MySQL Partition  Table Partitioning – 데이터와 인덱스 모두 분할 – 유지관리와 성능개선 – 수평 파티션(행을 분배) – 다중 저장장치에 배포, 파일구성(*.frm, *.par, *#P#파티션명.ext) – 특정파티션의 백업/분리
  • 153. 153 MySQL Partition  Partitioning Types – RANGE – LIST – HASH, LINEAR HASH – KEY, LINEAR KEY – RANGE COLUMNS, LIST COLUMNS – SYSTEM_TIME system-versioned tables ( added MariaDB 10.3) – SUBPARTITION BY HASH, LINEAR HASH KEY, LINEAR KEY
  • 154. 154 MySQL Partition  Partitioning Limitation – 최대 8192개 파티션 – Each table can contain a maximum of 8192 partitions (from MariaDB 10.0.4) – The maximum possible number of partitions for a given table not using the NDB storage engine is 8192 – SQL은 병렬화 안됨 – 지원하는 일부 Storage Engine – 모든 파티션은 동일 Storage Engine – query cache는 파티션 프루닝 인식못함 – FK 포함 or 참조 불가능(INNODB) – binlog_format=ROW 경우 업데이트속도 상대적 느림 – 파티션용 컬럼은 PK/UK에 반드시 포함되어야 함
  • 155. 155 MySQL Partition  Partitioning Maintenance – RANGE PARTITION 유용 – 시계열 데이터에 유용 – ALTER TABLE – DROP PARTITION – REMOVE PARTITIONING – ADD PARTITION – REORGANIZE PARTITION – EXCHANGE PARTITION https://dev.mysql.com/doc/refman/8.0/en/partitioning-management.html https://mariadb.com/kb/en/partition-maintenance/
  • 156. 156 MySQL Stored Routines  Method and Value of Stored Routines – Procedures and Functions are Supported – Database Level Functions — Isolating Certain Functionality – Databases Used as Namespaces (e.g., CALL db_name.my_proc()) – Routines are Dropped with Database – Library of Common Functions to make Complex Logic Accessible  Stored Routines Limitations – 재귀 호출 제한 (max_sp_recursion_depth) – PREPARE 에서 미지원 명령어 대부분 지원 안함 – SBR(Statement Based Replication) : Primary / Replica 서버의 수행 결과 다를 수 있음
  • 157. 157 MySQL Stored Routines  Stored Routines Privileges – CREATE ROUTINE – ALTER ROUTINE – EXECUTE – Routine 내부 OBJECT 권한과 무관하게 단지 EXECUTE 권한 – DEFINER와 SQL SECURITY의 활용
  • 158. 158 MySQL Stored Routines  Procedures vs Functions – Stored Procedures Called Directly (e.g., CALL show_user()) Can Replace SQL statements, Encapsulate Complex Logic Can Recurse (see, max_sp_recursion_depth and thread_stack) Returns One or More Results Sets – User Defined Functions Called within other SQL Statements (e.g., SELECT DELTA_PCT(n, n)) Performs Smaller Data Manipulation, Calculations, or Conversion Cannot Recurse Returns a Single Scalar Value https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html https://mariadb.com/kb/en/stored-routines/
  • 159. 159 MySQL Triggers  Triggers – 테이블에 이벤트 발생시 각 행마다 수행 – 트리거 시점 : BEFORE / AFTER – 트리거 이벤트 : INSERT / UPDATE / DELETE – NEW, OLD – Limitations  Routines 제약사항 모두  FK시 미작동  DEFINER 계정 미존재 시 trigger의 미작동이 아니라 이벤트가 취소됨  slave_run_triggers_for_rbr (MariaDB 10.1) https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html https://mariadb.com/kb/en/triggers/
  • 160. 160 MySQL Events  Events – 정기적으로 실행될 DB OBJECT – event_scheduler = ON – Limitations  Routines 제약사항 모두  결과셋 반환 안함, 대소문자 구분 안함  본문내 명령문 실행마다 새 연결 사용  실행시 서버상태변수에 반영 안함 https://dev.mysql.com/doc/refman/8.0/en/events-configuration.html https://mariadb.com/kb/en/events/
  • 161. 161 MySQL User  User Accounts – Authentication Based on User, Host, and Password – Empty String is User Wildcard – Percent Sign (%) is a Host Wildcard – Host is an IP or Host Name – localhost is used by Local Socket on Linux Systems – Privileges are Based on User and Host Combined
  • 162. 162 MySQL User  Granting Privileges – Users given Permission with GRANT Statement – Privilege Levels — Global, Database, Table, Column, or Routine – Grant / Revoke
  • 163. 163 MySQL User  User SQL Statements – RENAME USER : User Names and Hosts can be Changed – SET PASSWORD : Users Passwords can be Changed – DROP USER : Users can be Deleted
  • 164. 164 MySQL User  Limiting User – User-Host Accounts may be Limited by Resources – https://dev.mysql.com/doc/refman/8.0/en/user-resources.html – Usage Related to Limits are kept in mysql Database – Counters Reset when Server Starts or FLUSH PRIVILEGES Executed – User Counters may be Reset Specifically — Not MAX_USER_CONNECTIONS
  • 165. 165 MySQL User  Creating a User Roles – Use CREATE ROLE to Create Group Privileges – Use GRANT to Grant Privileges to Role – Use GRANT to Grant Privileges to Role
  • 166. 166 MySQL User  Granting a Role to a User – Use GRANT to Designate Users for Role – Use WITH ADMIN OPTION so Grantee may Grant Role – Check mysql.roles_mapping for Roles Granted
  • 167. 167 MySQL User  Assuming and Relinquishing a Role – User Assumes a Role for Session with SET ROLE – User Relinquishes a Role by Setting it to None Or by Ending Session – User can Set Default Role to NONE or Preferred Role
  • 168. 168 MySQL User  Revoking a Role – Check mysql.roles_mapping for a List of Roles Granted – Use REVOKE to take Role Option from User
  • 169. 169 MySQL User  Dropping a Role – Check mysql.user for List of Roles – Use DROP ROLE to take Eliminate a Role
  • 170. 170 MySQL Admin Command  Set 옵션 설명 옵션 설명 @사용자정의변수 := Set @v := 1 Select 2 into @v; [global | session] variable = 전역|세션 서버변수 변경 CHARSET 캐릭터셋 SQL_LOG_BIN 세션 전용 NAMES 캐릭터셋 SQL_SLAVE_SKIP_COUNTER 글로벌 전용 PASSWORD 비밀번호 STATEMENT ~ FOR ~ 쿼리별 세션변수설정 ROLE 권한 TRANSACTION Isolation level Read only
  • 171. 171 MySQL Admin Command  SHOW 옵션 설명 옵션 설명 AUTHORS 저자 목록 ENGINE ~ STATUS 서버 상태 CHARACTER SET 문자셋 ENGINES Storage engine 목록 COLLATION 정렬 ERRORS 최근 세션 오류 COLUMNS ~ 테이블의 컬럼들 EVENTS 이벤트 목록 CONTRIBUTORS 재정적 스폰서 목록 FUNCTION CODE FUNCTION 내용 CREATE ~ 오브젝트 스키마 내용 GRANTS FOR ~ 계정의 권한 DATABASES Database/schema 목록 INDEX FROM ~ 테이블의 인덱스 목록 OPEN TABLES Table open cache 목록 ~ VARIABLES [global, session] PLUGINS 로딩된 플러그인 목록 BINARY LOGS 바이너리로그 파일목록 PRIVILEGES 권한 목록 BINLOG EVENTS [IN ~] 로그 이벤트 목록 PROCESSLIST 프로세스 목록 EXPLAIN FOR ~ thread_id , 실행계획 ~ STATUS [global, session] [master, slave] SLAVE HOSTS Slave 목록 TABLES 테이블 목록 WSREP_MEMBERSHIP install soname ‘wsrep_info.so’ TRIGGERS 트리거 목록 WSREP_STATUS
  • 172. 172 MySQL Admin Command  DESC  EXPLAIN  USE  HELP
  • 173. 173 MySQL Admin Command  RESET  EXECUTE  FLUSH  KILL
  • 174. 174 MySQL Admin Command  PURGE  ANALYZE  OUTFILE  LOAD DATA
  • 175. 175 MySQL Admin Command  REPLICATION 옵션 설명 예제 SHOW MASTER STATUS Master’s binlog정보 Primary> show master status; CHANGE MASTER TO Master에 Slave 연결정보 Replica> CHANGE MASTER TO MASTER_HOST='192.168.0.1', MASTER_USER='repl', MASTER_PASSWORD='repl', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=342; START SLAVE 복제 시작 Replica> start slave; STOP SLAVE 복제 중지 Replica> stop slave; RESET SLAVE Slave 정보 삭제 Replica> reset slave; SHOW SLAVE STATUS Slave 상태 Replica> show slave status; SHOW SLAVE HOSTS 등록된 Slave 목록 Primary> show slave hosts; RESET MASTER 바이너리로그 초기화 Primary> reset master;
  • 176. Q&A
  • 177. Next Opensource Cloud Value MySQL Backup / Restore
  • 178. 178 MySQL Backup  백업이란? – 의미 있는 정보인 데이터에 대해 논리적, 물리적으로 복제하여 관리하는 것 – 동일 장비 혹은 다른 장비의 Disk 장치 혹은 별도의 백업 장치에 관리  백업의 목적 – 데이터 안정성 유지 및 데이터 소실 방지 – HW 시스템 고장 / Disk 손상 / SW 손상 / 운영데이터 소실 – 사고로 시스템이나 파일이 피해를 입더라도 최근에 백업한 시점의 내용으로 복구를 위함
  • 179. 179 MySQL Backup bin. 0004 MySQL bin. 0001 bin. 0002 bin. 0003 FULL 백업 사고!! MySQL 일요일 오전3시 화요일 오후5시 데이터베이스 파손 binlog.0001~0003 기록 binlog.0001~0003 적용 증분 백업
  • 180. 180 MySQL Backup  백업 정책 수립 – 백업 대상 선정  Data Files  Binary Log  Configuration File (my.cnf)  Redo / Undo Log – 백업 주기 선정  백업의 수행시간에 따른 백업 주기 산정 – 백업 방법 선정  논리 백업 / 물리 백업  Cold 백업 / Hot 백업
  • 181. 181 MySQL Backup  백업 정책 수립 – 백업 용량 산정  백업 정책에 따른 보관 일자 및 용량 산정 – 백업 전략 선정  full 백업  incremental 백업 – 백업 관리방법 선정  백업 정책에 따른 보관 일자 산정  incremental 백업에 대해 증분 데이터 보관 결정
  • 182. 182 MySQL Backup  복구 시나리오 – 가장 인접한 full 백업 선정 – full 백업으로 복구 수행 – 가장 인접한 증분 백업 선정 – 증분 백업을 순차적으로 실행 – full 백업 이후의 binlog에 대해 SQL 산출(Point-In-Time Recovery) – 추출한 SQL 을 적용
  • 183. 183 MySQL Backup  Logical Backup – 특징 및 장점  SQL 형태의 text 문으로 데이터 백업  데이터 검토 가능  복원 작업이 수월  물리 백업에 비해 복원 시 데이터 손상을 줄여줌  문제 발생시 원인 파악 및 해결이 수월 – 단점  수행 시간 동안 WRITE LOCK 발생(mysqldump)  시스템 리소스를 물리백업에 비해 많이 소모  부동 소수점 데이터의 정확성을 잃을 수도 있음 – 종류  mysqldump  into outfile / load data infile  mysql execute mode > text file  Physical Backup – 특징 및 장점  MariaDB의 물리적 파일을 백업  속도가 빠름  대체적으로 작업이 단순함 – 단점  논리적 백업에 비해 백업 해야 하는 파일의 크기가 큼  복구 시 문제가 발생하면 원인 파악 및 해결이 어려움  필요한 논리 개념의 data 만 백업이 불가능 – 종류  directory copy ( cold backup )  mysqlhotcopy ( myisam, archive )  xtrabackup ( percona, open source )  mariabackup ( innodb hot backup )
  • 184. Next Opensource Cloud Value MySQL Logical Backup
  • 185. 185 MySQL Logical Backup  mysqldump – 논리 백업 방식 – row 기반 데이터 백업 – insert 구문으로 데이터를 추출 및 저장하여 백업 – 데이터베이스, 테이블 단위로 백업 가능 – GRANT REPLICATION CLIENT SELECT SHOW VIEW RELOAD EVENT TRIGGER LOCK TABLES
  • 186. 186 MySQL Logical Backup  mysqldump option -A, --all-databases : 모든 DB를 덤프 --add-drop-table : 데이터베이스 앞에 drop table 명령 추가 -B, --databases : 여러 DB를 동시에 백업 할 때 사용 -T, --tab : 테이블 단위로 백업 -h, --host : 지정한 호스트의 데이터를 덤프 -p : 사용자의 암호를 지정 -P : 포트번호 지정 -u : 사용자명 지정 --default-character-set= : 덤프 시 character-set 설정 -f, --force : 에러를 무시
  • 187. 187 MySQL Logical Backup  mysqldump option -t, --no-create-info : data만 덤프 -d, --no-data : 데이터를 제외하고 스키마만 덤프 --single-transaction : Lock 을 사용하지 않는 일관성 있는 읽기 연산 사용 --extended-insert : 확장 형태의 insert 구문으로 출력 --flush-logs : 새로운 바이너리 로그파일 생성 --master-data= 1 / 2 a. dump 파일의 헤더 부분에 CHANGE MASTER TO 구문을 포함 b. 덤프 시작 시점의 Binary log 파일명과 위치 정보 및 호스트 정보를 포함 c. 1 : 수행할 수 있는 형태의 SQL 구문 , 2 : 정보만 출력 --routines : 프로시저 함수 백업 --triggers : 트리거 백업 --events : 이벤트 백업
  • 188. 188 MySQL Logical Backup  mysqldump 사용 – 스키마 백업 – 데이터 백업
  • 189. 189 MySQL Logical Backup  Source 명령 – 외부 파일의 SQL 문을 실행 – mysql client의 프롬프트에서 사용 하거나 mysql 의 –e 옵션을 이용하여 사용 – source 명령을 prompt에서 사용시 파일의 경로는 '' 대신 '/' 를 이용 – 복구 시 dump 파일의 character set, collation 확인 필요 – set names <character set>;
  • 190. 190 MySQL Logical Backup  select ... into outfile – 논리 데이터의 백업 방식 – Row 기반 데이터 백업 – 인식 가능한 구분자(separator)로 column 을 구분하여 파일로 저장 – 원하는 형태의 SQL 을 구성하여 결과값을 파일로 저장 가능 – file_priv = ‘Y’ – secure-file-priv=‘path’ 에만 export 가능 – 절대경로 혹은 상대경로 위치에 output 저장 – 해당 경로에 대한 OS 계정 user/group 의 쓰기 권한이 있어야 함
  • 191. 191 MySQL Logical Backup  select ... into outfile – https://mariadb.com/kb/en/select-into-outfile/
  • 192. 192 MySQL Logical Backup  Load data infile – 논리 백업 데이터의 복구 방식 – row 기반 데이터 백업 – 인식 가능한 구분자(separator)로 구분된 파일의 데이터를 읽어 복원 – local / non local – local-infile = 0 – file_priv = ‘Y’ – 파일의 절대경로 혹은 상대경로의 파일을 읽어서 복원
  • 193. 193 MySQL Logical Backup  Load data infile – https://mariadb.com/kb/en/load-data-infile/
  • 194. Next Opensource Cloud Value MySQL Physical Backup
  • 195. 195 MySQL Physical Backup  Cold Backup – OS 의 copy 명령을 사용하여 수행 – 물리적인 data file 의 copy 수행 중 disk block 이 변경되면 안됨 – 데이터베이스를 stop한 뒤 data block의 변경이 없는 경우 수행 – down time 이 발생하나 가장 간단하고, 장애 없이 수행 가능
  • 196. 196 MySQL Physical Backup  Xtrabackup – Percona 에서 개발한 InnoDB용 backup tool – Online Hot Backup – 물리 data file 을 백업하고 apply-log 명령을 이용하여 DML 변경분 attach – 정상 backup 완료 시 completed OK! – PERCONA_XTRABACKUP 테이블에 백업 log 저장 – 복구 시 mysqld daemon 은 shutdown 상태로 copy-back 옵션 사용 – full/incremental backup 가능
  • 197. 197 MySQL Physical Backup  Xtrabackup – 전체 데이터 백업 – 복구할 DB의 data directory 로 백업 파일 이동
  • 198. 198 MySQL Physical Backup  mariabackup – MariaDB 10.1.26 / 10.2.10 부터 제공되는 백업 툴 – Percona Xtrabackup 2.3.8기반 – Linux / Window 지원 – Online Hot Backup – 암호화(TDE)된 XtraDB / InnoDB 지원 (only) – 압축된 XtraDB / InnoDB 지원 (only) – InnoDB, MyRocks, Aria, MyISAM 지원 – Galera Cluster SST 옵션 지원 https://mariadb.com/kb/en/mariabackup-overview/
  • 199. Next Opensource Cloud Value MySQL binary log
  • 200. 200 MySQL binary log  mysqlbinlog – binary / relay log 를 직접 읽기 위한 도구 – binary format으로 작성된 binlog를 text format으로 변환하는 도구 – binlog_format = statement / row  statement-based : event 정보는 SQL문과 실행한 서버ID, 실행된 시간, 걸린 시간, 기타 정보  row-based : event 정보는 쿼리로 인해 변경된 row 에 대한 정보를 포함
  • 201. 201 MySQL binary log  mysqlbinlog option --help, -? 도움말 메시지를 출력하고 종료 --server-id=id 서버 ID 에 해당하는 로그만 출력 --start-datetime=datetime datetime 인수와 동일하거나 느린 타임 스탬프를 가지고 있는 첫 번째 이벤트에서 바이너리 로그를 읽기 시작 DATETIME 또는 TIMESTAMP 데이터 타입에 적합한 포맷 형태로 대입 mysqlbinlog --start-datetime="2005-12-25 11:25:56" binlog.000003 포인트-인-타입(point-in-time) 복구 시에 유용 --stop-datetime=datetime datetime 인수와 동일하거나 빠른 타임 스탬프를 가지고 있는 이벤트에서 바이너리 로그를 읽기 종료 포인트-인-타입(point-in-time) 복구 시에 유용
  • 202. 202 MySQL binary log  mysqlbinlog option --start-position=N N 인수와 동일한 위치를 가지고 있는 이벤트가 처음 발생할 때 바이너리 로그를 읽기 시작 명령문 라인에 지명된 첫 번째 로그 파일에 적용 --stop-position=N N 인수와 동일하거나 보다 큰 위치를 가지고 있는 이벤트 시점에 바이너리 로그를 읽기 종료 명령문 라인에 지명된 마지막 로그 파일에 적용
  • 203. 203 MySQL binary log  mysqlbinlog 사용 – mysqlbinlog 유틸을 이용하여 sql 형태로 저장 및 실행 – mysqlbinlog 결과를 직접 mysql client로 실행
  • 204. 204 MySQL binary log  Managing Binary Logs – Binary log 확인 – Binary log 삭제
  • 205. 205 MySQL binary log  Managing Binary Logs – Binary log 상세 정보 확인
  • 206. Next Opensource Cloud Value MySQL Replication
  • 207. 207 MySQL Replication  Replication - 하나 이상의 서버로부터 데이터를 선택적으로 복제 하는 기능 - binary log에 모든 업데이트를 기록 - Replica는 Primary의 binary log를 읽고 Replica에 relay log를 기록 - relay log를 수행하여 Replica 서버에 반영 Binary log Relay log I/O thread SQL thread Primary Replica Data changes Read Write Read Replay Binary log dump thread Write
  • 208. 208 MySQL Replication  Primary - Replica The terms master and slave have historically been used in replication, but the terms primary and replica are now preferred. The old terms are used throughout the documentation, and in MariaDB commands, although MariaDB 10.5 has begun the process of renaming. The documentation will follow over time. See MDEV-18777 to follow progress on this effort. https://mariadb.com/kb/en/standard-replication/
  • 209. 209 MySQL Replication  Replication Thread : Primary - Binary Log Dump Thread Primary의 binlog를 읽어서 Replica의 I/O Thread에 전달 - ACK Receiver Thread Semisync Replication의 ACK 수신  Replication Thread : Replica - Replica I/O Thread 수신된 binary log를 relay log에 기록 Primary’s binary log file 과 log position 기록 - Replica SQL Thread relay log 읽어 SQL 수행 Parallel-Replication Off : 데이터에 적용 Parallel-Replication On : Worker Thread 전달 - Worker Thread 병렬 복제 처리
  • 210. 210 MySQL Replication  GTID - Global Transaction ID - MySQL과 MariaDB의 GTID 구조 다름 - Replication 전환 구조의 편리성 - Replication 안정성 (충돌 방지)  MySQL GTID - source_id:transaction_id 3E11FA47-71CA-11E1-9E33-C80AA9429562:23 - source_id : the server generates a true UUID - transaction_id : sequence number - MySQL 5.6 부터 지원  MariaDB GTID - Domain ID – Server ID – Sequence Number 0-1-10 - Domain ID : 32비트 정수 - Server ID : 32비트 정수 - Sequence Number : 64비트 정수 - MariaDB 10.0 부터 지원
  • 211. 211 MySQL Replication  Replication 구성 - my.cnf 설정 - Replication 계정 생성
  • 212. 212 MySQL Replication  Replication 구성 - binary log 확인 Replica 설정 할 때 Primary의 File 정보를 MASTER_LOG_FILE에, Position 정보를 MASTER_LOG_POS에 사용 - Primary 백업 – Replica 복원
  • 213. 213 MySQL Replication  Replication 구성 - Replica 설정
  • 214. 214 MySQL Replication  Replication 구성 - Replica 상태 확인
  • 215. 215 MySQL Replication  Replication 구성 - Replica 삭제
  • 216. Next Opensource Cloud Value MySQL Monitoring
  • 217. 217 MySQL Monitoring  서버 과부하  데이터베이스 shutdown  데이터베이스 복구  테이블 메타 정보 불일치  로그 파일 관리  테이블 및 레코드의 잠금 해결  호스트 잠금
  • 218. 218 MySQL Monitoring  서버 과부하 - CPU : 사용량, idle (top, vmstat) - MEMORY : used, free, swap (free) - DISK : read / write (vmstat, iostat, iotop) - NETWORK : Received / Send / time wait (netstat) - PROCESS : resource per process (top) - Log : system log, cron log
  • 219. 219 MySQL Monitoring  데이터베이스 startup / shutdown - Startup  MariaDB 서버가 기동 후 error.log 확인  Warning, Error 이벤트가 발생했는지 확인  log_warnings=2 (기본값 10.2이상 2, 미만 1) - Shutdown  MariaDB 서버가 자동으로 Shutdown 되는 경우 error.log 확인  Normal Shutdown 이외의 메시지로 내려가는 경우 서버 재시작  mysqld_safe 옵션으로 mysqld daemon 이 시작된 경우 자동 복구  Killed 등의 메시지로 원인확인이 불가능 할 때 OS log 를 통해 원인 분석
  • 220. 220 MySQL Monitoring  데이터베이스 복구 - Data 복구  MyISAM 테이블 손상의 경우 repair table 명령으로 복구  InnoDB 의 손상 시 innodb_force_recovery 옵션을 my.cnf에 추가하여 복구 - Metadata 복구  Data Dictionary 와 .frm 파일의 정보가 불일치 하는 경우 발생  Data Dictionary 에서 정상 삭제된 경우 이상 없음  .frm 데이터가 삭제되고 Data Dictionary 에 남아 있다면 에러 발생  다른 database 에서 해당 테이블과 동일한 구조의 테이블을 만들고 .frm 파일을 복사하여 복구
  • 221. 221 MySQL Monitoring  데이터베이스 log - Error log  MySQL 서버에 문제가 발생하는 경우 기본적으로 Error Log 에 기록됨  장애 시 Error Log 의 마지막 부분은 반드시 확인  MySQL 에러로그파일은 기본적으로 ‘log_error’로 설정한 경로파일에 존재  log_error 파라메터를 설정함으로써 directory 및 filename 지정 가능  파일이 너무 큰 경우 tail 명령이나 less 명령을 이용하여 마지막 라인만 확인  vi로 큰 파일을 열 때는 주의가 필요
  • 222. 222 MySQL Monitoring  데이터베이스 log - Slow Query Log  slow-log 옵션을 활성화하는 경우 기록  로그파일 혹은 테이블로 기록 ( log_output=‘FILE,TABLE’ )  지정된 시간 이상 정상 수행 및 종료된 SQL 에 대해 기록  mysqldumpslow 유틸을 이용하여 slow log 의 통계 집계 가능  -s 옵션에 count(c) , lock(l) , record(r) 기준으로 출력 가능  hostname-slow.log 형태로 기록
  • 223. 223 MySQL Monitoring  데이터베이스 log - Log 파일 관리  Error Log 파일의 사이즈가 warning 으로 인해 커지는 경우  warning 메시지를 error log 에 출력하지 않도록 설정  error log 나 binary log 의 경우 파일 삭제 후 flush logs 를 통해 새로운 log 생성  Slow Log 파일 일시적인 사용(slow_query_log=OFF)  General Log 파일 (general_log=OFF)  Binary Log 파일 (expire_log_days=0)  Relay Log 파일 (relay_log_purge=ON)
  • 224. 224 MySQL Monitoring  데이터베이스 log - Log 파일 관리  binary log 의 사이즈가 커지는 경우  일정기간 이외의 파일을 지우도록 설정 ( expire_logs_days )  직접적으로 binary log purge 하여 용량 확보
  • 225. 225 MySQL Monitoring  데이터베이스 Locks - 테이블 및 레코드 lock 해결  transaction이 특정 이유로 commit이 되지 않은 상태로 남아있는 경우  Lock wait timeout exceeded error 발생  Lock 을 유발하는 transaction 을 종료하여 처리  processlist 상의 id 항목에 대해 kill query id 로 처리  innodb_lock_wait_timeout 변수를 통해 대기시간을 줄일 수 있음
  • 226. 226 MySQL Monitoring  데이터베이스 Locks - 서버 host 잠금  client host별 에러count값이 max_connect_errors 값 초과시 발생  hostname is blocked because of many connection errors 발생  flush hosts 명령으로 처리 가능  max_connect_errors 값을 증가시켜서 처리가능
  • 227. 227 MySQL Monitoring  데이터베이스 status - Connections - Thread / Processlist - QPS (query per second) - Table Cache - InnoDB Buffer Pool - Table Full scan - Replication status
  • 228. 228 MySQL Monitoring  데이터베이스 status - Processlist 확인  데이터베이스에 접속하거나 mysqladmin utility 를 이용하여 확인  현재 실행중인 SQL 확인 가능  show (full) processlist 명령으로 확인 가능  각 프로세스의 command / state / time 값을 확인하여 현재 상태와 실행시간 확인 State 항목이 Waiting 인 경우 타 프로세스에 의한 잠금 확인 필요 Copy to tmp table 인 경우 해당 SQL 의 튜닝포인트 확인 Command 및 State 항목이 동일 항목이 여러 개 반복해서 나타나는 경우 SQL 튜닝 필요 Command 및 State 항목이 여러 종류가 다양하게 나타난다면 서버 외부 요인 파악 서버의 부하는 높으나 Command 항목이 대부분 Sleep 상태인 경우 network in 확인
  • 229. 229 MySQL Monitoring  데이터베이스 status - Max Connection 확인  평상시보다 많은 Network In 이 발생하는 경우  서버가 처리할 수 있는 허용량 보다 많은 connection 이 동시에 몰리는 경우 부하  Session 메모리를 고려한 max connection 설정 필요  status 항목의 max_used_connection을 모니터링하여 connection 허용값을 증가하여 운영  max_connections 시스템 변수로 조정 가능
  • 230. 230 MySQL Monitoring  데이터베이스 status - SQL 실행 상태 확인  mysqladmin 의 status항목으로 (Uptime, Threads, Questions, Slow, Open…, QPS) 확인  mysqladmin 의 extended-status 항목으로 서버 상태 값 출력  egrep 커맨드로 필요한 항목만 확인  초당 처리되는 쿼리의 수를 확인하고 평상시보다 과부하가 발생하는지 확인
  • 231. 231 MySQL Monitoring  mytop (innotop) https://github.com/jzawodn/mytop https://github.com/innotop/innotop
  • 233. 233 MySQL Monitoring  PMM (Percona Monitoring and Management) https://www.percona.com/software/database-tools/percona-monitoring-and-management
  • 234. Q&A
  • 235. Next Opensource Cloud Value NeoClova
  • 236. 236 NeoClova 회사명 임직원 대표이사 설립년도 주소 대표전화 홈페이지 주식회사 네오클로바 19명 이 재 중 2011년 11월 서울시 강서구 양천로 583, 우림블루나인 B동 12층 02-539-4880 www.neoclova.co.kr 기업 개요 주요 파트너쉽 주요사업분야 IT 통합유지보수 Red Hat Enterprise Linux, JBoss, Apache / Tomcat, MySQL / MariaDB / Percona Technical Support Red Hat Ready Partner T2 Partner Registered Partner Registered Partner Registered Partner
  • 237. 237 NeoClova reference 주요 고객사 구축 부분 오픈소스 구축 업무분석 운영지원 컨설팅 - 운영시스템 전반 유지보수 - 장애 및 성능 분석 지원 - U.Key 3.0 U2L PI - Unix Oracle RAC to Linux구축 - Jboss EWS/EAP 전환 및 성능 측정 - MySQL/MariaDB 컨설팅 서비스 - 통합시스템 내 리눅스 부분 유지보수 및 분석 지원 - 정보시스템 클라우드 전환 컨설팅 (ISP) - 전체운영시스템 클라우드 전환 ISP - G-Box플랫폼 구축 관련 오픈소스 지원 - ITO 오픈소스 컴플라이언스 검증 - New Kt.com 구축 관련 오픈소스 지원 - 오픈소스 SW 전사기술지원 - 가족관계 등록정보시스템 구축 사업내 오픈소스 구축 - 온라인 출생신고시스템 전산장비 도입 사업내 오픈소스 구축 - 스마트 산업입지 플랫폼 시범사업 전산장비 구축내 오픈소스 부분 - 빅데이터 기반의 차세대 공장설립온라인지원시스템 구축내 오픈소스 부분 - 차세대 운영정보시스템 구축내 오픈소스 부분 - 운영시스템 오픈소스(Linux부분) 운영지원 - 운영시스템 통합유지보수 지원
  • 238. 238 NeoClova 지원제품 List 1.3 Amazon Web Services 2.1 Red Hat OpenStack Platform 3.1 MySQL 4.1 Red Hat JBoss EAP 2.4 Red Hat Gluster Storage 5.1 Red Hat Enterprise Linux 1.1 Google Cloud Platform 2.2 Red Hat OpenShift Container Platform 2.3 Red Hat Ceph Storage 2.6 Azure Stack 2.5 Red Hat Virtualization 3.2 MariaDB 4.2 Red Hat JBoss Web Server 1.2 Microsoft Azure 4.3 Red Hat OpenShift 4.4 ACCORDION 4.5 Apache / Tomcat / NginX 5.2 CentOS 5.3 Ubuntu 5.4 Oracle Linux 3.4 DBMON-Star(DB 모니터링 자체솔루션) 3.5 DB CHECKER(DataBase 검증 및 자체튜닝 솔루션) 3.3 Percona Server for MySQL