MariaDB
Administrator
2
목차
구분 내용
Section 1
- MariaDB 소개
- MariaDB 서버 구성 및 아키텍처 이해
Section 2
- MariaDB 스토리지 엔진
- MariaDB 데이터베이스 관리
Section 3
- 트랜잭션 / Locking 의 이해
- MariaDB 보안
Section 4
- 백업과 복구를 통한 데이터베이스 관리
- MariaDB upgrade
Section 5
- MariaDB 모니터링
- MySQL 에서 MariaDB 로의 전환
MariaDB Administrator
Section 1
4
세부내용
ㆍMariaDB 소개
ㆍMariaDB Architecture
ㆍMariaDB 설치 및 접속
ㆍMariaDB 변수 및 my.cnf 설정
Section 1
5
MariaDB 소개
6
MariaDB Overview
• Open Source Relational Database
• 사용이 편리하고, 확장성이 좋으며, 우수한 성능
• 연결성 : full networking support
• 이식성 : run on most OSes, such as Unix, Windows, Mac
• 보안 : SSL support
• 타 DB 대비 상대적으로 작은 size
• MySQL AB -> Sun (2008) -> Oracle (2010)
• MariaDB Initial release : January 2009
7
MariaDB Overview
• Scale Up or Scale Out
– 일반적인 상용 RDBMS 들은 일반적으로 Scale Up 을 지향
– MariaDB는 Scale Out 에 기반을 두고 DB Architecture 설계시 고성능 발휘
Scale Up 분류 Scale Out
• 높은 안정성
• 고성능
장점
• 저비용
• 장애시 서비스 Impact 적음
• 부분적 증설이 가능
• 지속적인 시스템 확장 가능
• 고비용
• 장애시 대형 장애로 연결
• 한대의 고성능 서버로 감당이 어려운
경우 문제 발생
단점
• 많은 서버로 인한 관리 부담
• 각 서버의 장애 발생 가능성이 높음
8
MariaDB Database Server Editions
• GPL ( General Public License )
– MariaDB Community
• MariaDB TX
– MariaDB Server
– MariaDB Cluster
– MariaDB MaxScale (BSL)
– MariaDB Connectors
– MariaDB Tools
– MariaDB Services
• MariaDB AX
– MariaDB Server
– MariaDB ColumnStore
– MariaDB MaxScale (BSL)
– Bulk data adapters
– Streaming data adapters
– Tools
9
MariaDB Database Server Editions
10
MariaDB Architecture
11
MariaDB Server Structure
12
MariaDB Server Structure
• MariaDB Server
– MariaDB Engine (instance) + Storage Engine (+ Handler API)
 MariaDB Engine
• 요청된 SQL 문장을 분석 & 최적화하는 등의 일을 처리
• Connection Handler, SQL Parser, Precompiler, Optimizer, Cache, Buffer
 Storage Engine
• 실제 데이터를 disk 스토리지에 저장
• disk 스토리지로부터 데이터를 추출
MariaDB Engine Storage Engine
13
MariaDB Server Thread
• A MariaDB server process (mysqld) can create a number of threads
• A global thread (per server process) is responsible for creating and
managing each user connection thread
• A thread is created to handle each new user connection
• Each connection thread also performs authentication and query execution
• A signal thread handles alarms and forces timeouts on connections that
have been idle too long
• A thread is allocated to handle shutdown events
• Threads are used for table flushing, maintenance tasks, and so on
• MariaDB uses a data cache, record cache, key cache, table cache, hostname
cache, and privilege cache for the caching and retrieval of different
types of data used by all the threads executing within the server process
• In addition, the MariaDB main process (mysqld) has threads to handle
database management activities such as backup, restore, concurrency
control, and so on
14
MariaDB Server Thread
Connection Manager Thread Signal Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
....
Client
Client
Client
Client
Client
Client
Insert Buffer Thread
InnoDB File I/O Threads
MariaDB – innodb plugin
Log Thread
Read Thread
Write Thread
Storage Engine
innodb_read_io_threads
innodb_write_io_threads
15
MariaDB Server Process Flow
Application
Handler API
InnoDB ColumnStore Connect MyRocks ....
SQL
Thread
Cache
Logging
Thread
Cache
Connection
Manager
User
Authentication
Command
Diaspatcher
Query Cache
Module
Optimizer
Access
Control
Table
manager
Parser
Table Open
Cache
Table
Definition
Cache
16
MariaDB Server Process Flow
• MariaDB Engine
– SQL 구문 분석
– 해당 테이블에 Open & Lock
– 실행계획 분석
– 테이블 lock 해제 및 close
• Storage Engine
– Handler API 를 통해 접근
– Write Thread & Read Thread 를 이용하여 I/O 발생
17
MariaDB Structure : 3 layer
• 1’st layer: Connectors
– MariaDB client
– MariaDB에 접근하기 위해 Application에서 설치하여 사용
– C, API, JDBC 등 언어에 따라 여러 가지 connector를 사용
• 2’nd layer: MariaDB Instance (MariaDB server header)
– SQL 구문 분석
– 옵티마이저 최적화로 실행계획 작성
– 필요하면 메모리에 캐쉬
• 3’rd layer: Storage Engine
– 데이터를 저장하고 추출
– 각각의 storage engine은 서로 다른 데이터 저장 및 추출 방법을 가짐
– InnoDB, ColumnStore, Connect, MyRocks, …
18
MariaDB Structure : 3 layer
• Connection Manager
– MariaDB 내부에서 관리하는 Manager
– 새로운 user connection thread를 DB에 할당하여 저장함
– Connection 생성과 함께 SQL 작업을 위한 메모리를 자동 할당
• SQL Interface
– DDL, DML, Stored Procedure, Trigger 지원을 위한 모듈 제공
– SQL 함수에 대한 지원을 제공
19
MariaDB Structure : 3 layer
• Cache & Buffer
– 자주 사용되는 데이터, 인덱스 등을 빠르게 사용하기 위해 메모리에
저장하는 영역
– Query Cache 는 Select 문과 결과의 조합을 캐시하여 매우 빠른 응답을 지원
– 데이터베이스 Metadata 메모리 캐시를 제공
– 스토리지 엔진에 따라 기능의 차이가 존재함
– 서버전체, 엔진별, 유저별 캐시를 포함
• Parser / Optimizer
– 유저의 오브젝트 접근 권한 확인
– SQL문 실행을 위한 준비 작업
– SQL 권한 확인, SQL 문을 Database 내부 언어로 변환, 실행경로 분석
– 모든 storage engine에 동일하게 적용
20
MariaDB Structure : 3 layer
• 관리도구
– 데이터베이스 관리, 데이터베이스 디자인, 마이그레이션 등을 위한 툴 제공
• Subscription Service
– MariaDB Admin (SQLyog Ultimate)
– MariaDB Monitor (Monyog Ultimate Monitor)
– Technical support : 24x7
– Technical support : 30 minute response time (S1)
– Consultative support
– Notification services (e.g., security alerts)
– Security patches and bug fixes
– Limited indemnification
– Access to expert services
21
MariaDB connectors
• Connector/ODBC
– The MariaDB Connector/ODBC 2.0 series is built on top of MariaDB Connector/C
2.2 and uses the binary prepared statement protocol. It is basically MariaDB
Connector/ODBC 1.0, ported to work on Linux
• Connector/J
– MariaDB Connector/J is used to connect applications developed in Java to
MariaDB and MySQL databases. The client library is LGPL licensed
• Connector/C (libmysql)
– MariaDB Connector/C is used to connect applications developed in C/C++ to
MariaDB and MySQL databases. The library is LGPL licensed
22
MariaDB 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++)
23
Protocol and memory / disk
• Supported communication protocol
– TCP/IP
– Unix socket
– Shared memory
– Named pipes
• Memory
– Global buffers and caches
– For Memory storage engine
24
Memory
• Global buffers and caches
25
Memory
26
MariaDB Server - mysqld
• mysqld server program 역할
– Connection을 핸들링
 TCP/IP, Unix sockets, Shared memory..
– SQL 문을 처리
 Parser, query execution, authorization, query cache, optimizer,
query logging
– Data storage 핸들링
27
MariaDB 설치 및 접속
28
MariaDB 설치
http://www.slideshare.net/ohnew/documents
29
MariaDB 실행 및 접속
• MariaDB 실행
• MariaDB 접속
30
MariaDB 변수 및 my.cnf 설정
31
MariaDB Setting File
• MariaDB 설정파일 경로 확인
– MariaDB서버는 단 하나의 설정파일(my.cnf)만 사용
– 설정파일을 명시적으로 지정함으로서 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
32
my.cnf
• support-files 디렉토리에 my.cnf 샘플파일
• my-huge.cnf, my-large.cnf, my-medium.cnf, my-small.cnf 시스
템 최적화용으로 사용 가능
• client, mysqld 등의 항목을 기준으로 환경변수 설정가능
– [mysqld] , [server] , [mysqld-X.X] , [mariadb] , [mariadb-X.X]
– [client] , [client-server] -- (MariaDB 5.3 and higher)
• 사용할 engine 의 옵션에 따라 변수 설정
33
my.cnf
• my.cnf setting 예시
34
my.cnf
• port 및 data path 설정
35
my.cnf
• Cache Settings
36
my.cnf
• InnoDB Parameter Setting
37
my.cnf
• Connection, Log, Character Set Settings
38
my.cnf
• Replication Settings, Thread Pool Settings
39
MariaDB Programs
40
MariaDB Programs
• mysql
– Data 를 select / insert / update / delete 하기 위한 SQL client
• mysqladmin
– MariaDB Server를 관리하는 tool로 Server 환경설정이나 현재 상태를 체크
및 데이터베이스를 create / drop 등을 할 수 있음
41
MariaDB Programs
• mysqlcheck
– Table maintenance 기능
• mysqldump
– 일련의 SQL statement 를 실행해서 논리적 백업기능 (스키마, 테이블 데이터)
– 백업 혹은 타 DBMS 로 이관하기 위해 하나 이상의 데이터베이스 덤프 가능
42
MariaDB Programs
• mysqlshow
– 테이블과 데이터베이스 구조 정보
– SHOW 구문과 비슷
– 데이터베이스, 테이블, 컬럼, 인덱스 빠르게 조회해 보기
– mysqlshow [옵션] [데이터베이스 명[테이블 명[컬럼 명]]]
43
MariaDB Programs
• mysqlslap
– 쿼리 진단 프로그램
– Slow query log 출력
44
Section 1
MariaDB Administrator
Section 2
46
세부내용
ㆍMariaDB 스토리지 엔진 소개
ㆍInnoDB 스토리지 엔진의 아키텍처 및 특성
ㆍ메타데이터정보
ㆍ서버 로그들 활용 및 관리
ㆍ실시간으로 MariaDB 서버 옵션 설정
Section 2
47
MariaDB Storage Engine
48
MariaDB Architecture
49
What are Storage Engines
• MariaDB Storage Engine
– 스토리지 엔진은 하나의 모듈로서 작동
– 스토리지 엔진을 별도 컴파일 하여 서버에 적재가 가능
– 지속적으로 새로운 내부 스토리지 엔진을 개발
– 개별적인 스토리지 엔진이 다양하게 개발됨
50
MariaDB DataFile 구성
• MariaDB 기본 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
51
MariaDB Storage Engine
스토리지 엔진 MariaDB 버전 트랜잭션 잠금 주요 응용 프로그램
InnoDB >= 10.2.x Yes MVCC 트랜잭션 처리
XtraDB
>= 5.1.x
<= 10.1.x
Yes MVCC 트랜잭션 처리
ColumnStore >= 10.1.x Yes MVCC 대용량 분석 (OLAP)
FederatedX >= 10.0.x Yes N/A 원격 서버 연결
CONNECT >= 10.0.x Yes N/A 이기종 DB 및 파일 연결
TokuDB >= 5.5.x Yes MVCC 트랜잭션 처리, 로깅
MyRocks >= 10.2.x Yes MVCC 트랜잭션 처리
52
MariaDB Storage Engine
스토리지 엔진 버전 트랜잭션 잠금 주요 응용 프로그램
MyISAM > 3.23 No 동시 삽입 가능 테이블 SELECT, INSERT 대량 적재
Aria >= 5.1 No 동시 삽입 가능 테이블 MyISAM 대용(내부 디스크 테이블)
MEMORY >= 4.0 No 테이블 중간 계산, 통계 참조 데이터
Archive >= 4.1 No row 로깅, 집계 분석
CSV >= 4.1 No 테이블 로깅, 외부 데이터 대량 적재
BLACKHOLE >= 4.1 N/A N/A 로깅, 복제 아카이브
SphinxSE >= 10.0 N/A N/A Full text search
53
MariaDB Storage Engine
스토리지 엔진 버전 트랜잭션 잠금 주요 응용 프로그램
OQGRAPH >= 10.0 N/A N/A 계층구조, 그래프 처리
Sequence >= 10.0 Yes Read-only 임시테이블용 시퀀스
Spider >= 10.0 Yes row 샤딩
Cassandra >= 10.0 N/A N/A SQL/NoSQL간 데이터 통합
MRG_MyISAM >= 3.23 No 동시 삽입 가능 테이블 MyISAM 테이블의 모음
Mroonga >= 10.0 No No Groonga기반 전체 텍스트 검색
54
Storage engines
• Storage Engine 요약
– Archive : 삽입후 레코드 변환 없음
– BLACKHOLE : 쓰기 무시하고 읽기는 NULL로 반환하지 않는 테이블
– ColumnStore : OLAP 엔진
– CONNECT : 이기종 데이터베이스를 사용할 수 있는 엔진
– CSV : 콤마 구분 값 포맷으로 저장
– EXAMPLE : 저장 엔진의 시작 방법에 대한 최소한의 예제를 제공
– FederatedX : 원격 테이블 접속을 위한 엔진
– InnoDB : 외부 키를 가지는 트랜잭션 엔진
– MEMORY : In-memory 테이블
– MERGE : MyISAM 테이블의 집합 관리
– MyISAM : ISAM 방식의 저장 엔진
– MyRocks : 압축률이 뛰어난 엔진
– SphinxSE : Full Text Search를 위한 엔진
– Spider : 샤딩을 위한 엔진
– TokuDB : 프랙탈 인덱스를 사용하는 엔진
55
Show Storage Engine
• show engines
– 현재 사용가능한 engine 조회
– transactional 지원 여부 조회 가능
56
Types of Storage Engines
• General Purpose Storage Engines
– Transactional
 InnoDB, TokuDB, MyRocks
– Non-Transactional
 MyISAM
• Analytics and Data Warehousing
– ColumnStore
• Special Purpose Storage Engines
– Connect, Memory, Spider, Archive, Blackhole, CSV,...
• Search Storage Engines
– SphinxSE, Mroonga
57
Storage engines
• Chose one default storage engine for the application
– InnoDB is standard at this point, actually
– ColumnStore is solution for modern data warehousing
• User other storage engines for what they are good
– MyISAM
 compact, non transactional, temporary storage
– MEMORY
 temporary tables
– Connect
 Light duty remote data access, etc
58
MyISAM
• MyISAM Engine 특징
– MySQL 3.23.x 이후 버전에서 사용 가능
– Data 저장이 효율적이고 빈번한 Data 사용의 부하를 잘 소화함
– B-tree, R-tree & Full-text Index를 지원
– 특정 Index에 대한 Memory Cache를 지원 ( key_buffer_size )
– Data 압축에 대한 옵션을 제공 ( fixed / dynamic / compressed )
– 지리적 Data를 지원
– Table 레벨의 Lock을 지원 & Transaction을 미지원
– Backup 및 특정 시점으로의 복구 지원
– DB 는 directory 별로 생성 및 관리
– .frm / .myd / .myi 파일로 구성 ( Table 구조정보 / data / index )
– engine = myisam 형태로 지정
59
MyISAM
• MyISAM Engine 의 적합한 사용
– 변경작업이 별로없는 select 위주의 Table
– 빠른 쓰기 성능이 필요한 경우
 동일 테이블에 읽기와 쓰기가 혼합되어 있지 않아야 함
 Logging, Temporary Table, 데이터 생성
– 복구에 대해 시간이 다소 소요되어도 괜찮은 경우
 대용량 MyISAM 테이블은 crash 후 복구하는 데 많은 시간이 걸림
– 정적인 Table, 로그 Table
• Aria Storage Engine
– Aria is a crash safe MyISAM + more
– This should speed up some GROUP BY and DISTINCT queries because Aria
has better caching than MyISAM
60
Memory
• Memory Engine 특징
– Non-transacional Storage Engine
– Memory 에 모든 data 가 저장됨
– 고정길이열의 열만을 사용 가능함 (varchar, blob, text 컬럼 사용불가)
– 타 Engine 에 비해 DML 속도가 월등히 빠름 (고정 길이열 기반으로 인함)
– Server 의 재 구동 시 Data는 모두 소실
– 동등조건( ex) where a=10 ) 검색에 HASH기반 검색을 제공
– 범위 검색 시 Index 를 사용할 수 없음
– temporary table 과 다르게 타 세션에서도 조회가 가능
61
Archive
• Archive Engine 특징
– 자동적인 Data 압축을 지원
– 다른 Storage Engine 대비 80%의 저장공간 절약
– 실제적인 저장용량의 제한 없슴
– Index 미지원
– 빠른 Insert 속도를 위해 특별한 입력 버퍼를 제공
– Insert와 select만을 지원
– row레벨 Lock을 지원
– Backup 및 특정 시점으로의 복구 지원
– 데이터 웨어하우스, 데이터 감사등에 사용
62
FederatedX
• FederatedX Engine 특징
– MySQL 5.0에 Federated engine 도입
– 원격의 물리적 Data 객체에 대한 논리적 Data 객체를 생성
– 하나의 Data 객체에서 다른 타겟 객체로의 ‘포인터’역할
– 원격 Data 접근을 위한 특별한 미들웨어가 필요하지 않음
– 실행 속도는 네트워크 요소에 따라 좌우됨
– 실제 Data 객체의 Engine 특성에 따라 처리됨
– Table 정의를 통한 SSL보안 처리
– 모든 SQL 오퍼레이션 지원( as per target object )
– 분산데이터베이스 환경에서 사용
63
InnoDB Storage Engine
64
InnoDB
• Heikki Tuuri 에 의해 개발됨
• Oracle Corp 에서 소유권을 가지고 있음
• XtraDB는 Percona의 open source
• 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/
65
InnoDB
• Transaction-Safe 스토리지 엔진
• Primary Key 에 의한 클러스터링
– 모든 InnoDB 테이블은 기본적으로 PK 를 기준으로 클러스터링되어 저장
 PK 에 의한 range 스캔에 최적화
 optimizer 가 PK 에 의한 실행계획을 더 선호함
 Oracle 의 IOT 와 동일한 구조
• 읽기 일관성 보장 ( Non-locking consistent read )
– MVCC ( Multi Version Concurrency Control )
• Foreign Key 지원
66
InnoDB
• 자동 Deadlock 감지
– Deadlock 발생시 Server 에서 바로 감지
– Deadlock 유발한 트랜잭션 중 Rollback이 가장 용이한 트랜잭션 강제 종료
– show engine innodb status 구문 혹은 monitoring 을 활성화해서 확인
• 자동 장애 복구
– MariaDB 서버의 구동시 완료되지 못한 트랜잭션 복구
– disk에 일부만 기록된 데이터 페이지 복구
– mysqld_safe 를 이용한 mysqld 의 모니터링 및 장애시 restart 수행
67
Using InnoDB
• 동시접속 퍼포먼스가 뛰어나 대용량 데이터 처리에 적합
• 메인 메모리내 데이터 캐싱 및 인덱싱 위한 버퍼 풀(pool)을 관리
– innodb_buffer_pool_size
• 테이블과 인덱스를 테이블 스페이스에 저장
– 테이블 스페이스를 몇개의 서버파일이나 disk 파티션으로 구성
cf) MyISAM은 테이블과 인덱스를 각각 분리된 파일로 관리
• InnoDB 테이블은 OS 파일 사이즈에 독립적인 파일 사이즈를 가짐
• 트랜잭션의 동시성 퍼포먼스가 필요한 대용량 사이트에 적합
69
InnoDB Server Thread
Connection Manager Thread Signal Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
Connection Thread
...
Client
Client
Client
Client
Client
Client
Insert Buffer Thread
InnoDB File I/O Threads
MariaDB – innodb plugin
Log Thread
Read Thread
Write Thread
Storage Engine
innodb_read_io_threads
innodb_write_io_threads
70
InnoDB Memory / Disk
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
InnDB-std : can grow unlimitedly
XtraDB : innodb_dict_size_limit
XtraDB : Check sizes in
SHOW ENGINE INNODB
STATUS
innodb_buffer_pool_size is
cretical paramter
Thumb rule : 60-80% of RAM
Table1.ibd
Table2.ibd
Table3.ibd
Primary Key
== data
Secondary
indexes
.ibd are placed separetely if
innodb_file_per_table=1
Ohterwise 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_rsegments
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 backgroud “log thread”
on disk with fsync() command.
innodb_flush_log_at_trx_commit
controls how to fsync
innodb_log_buffer_siz
e
4M-16M is good value
Changes
are fiex
in log
file via
log buffer
Insert buffer is
written
from BP to disk
Pages are written in background
innodb_write_io_threads.
innodb_fulsh_method=O_DIRECT
To avid 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
71
InnoDB Log / Data Disk Write
Log Buffer
( buffered log
records )
Buffer Pool
( buffered data
pages )
Additional Mem
Pool
Commit
( + checkpoint )
Log File 1
Log File 2
Log File 3
RedoLog
ibdata1
data file
checkpoint
In Memory On Disk
LogFilesTablespace
Undo Log
ibdata2
data file
iblogfile1
innodb_file_per_table=0
innodb_max_purge_log
72
InnoDB Redo log Write
commit – Write to disk
commit
Write & Flush to disk - every 1 Second
Log FilesO/S bufferLog BufferInnoDB
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=?innodb_flush_log_at_trx_commit
73
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 filecheckpoint
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
74
InnoDB Parameter
• INNODB_DATA_HOME_DIR
– 테이블스페이스 파일의 생성 위치 설정
• INNODB_DATA_FILE_PATH
– 테이블스페이스 파일 명 및 크기, 옵션 설정
– ibdata1:256M:autoextend:max:2000M
 ibdata1라는 파일명으로 생성
 256MB의 고정크기로 최초 생성
 256MB가 넘을 경우 “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
75
InnoDB Parameter
• INNODB_FILE_PER_TABLE
– 공용 테이블스페이스 사용 대신에 테이블 별 테이블스페이스 사용 옵션
– TableName.idb 파일 생성
• INNODB_BUFFER_POOL_SIZE
– 테이블의 데이터와 인덱스를 캐시하기 위해 사용하는 메모리 버퍼의 크기
– 크게 설정하면 할수록, data의 disk I/O가 적어짐
– 전체 물리메모리의 60~80%로 설정하나, 세션수가 많으면 50%로 설정
– ORACLE DB_BUFFER_CACHE와 유사
• INNODB_BUFFER_POOL_DUMP_AT_SHUTDOWN/STARTUP
– 데이터와 인덱스 캐시를 위한 메모리 버퍼의 재사용을 위해
중지/재시작 시 버퍼정보를 파일에 기록/로딩함.
76
InnoDB Parameter
• INNODB_LOG_FILE_SIZE
– Redo 로그 파일의 크기 설정
– 순차적으로 파일이 일정한 크기와 용량으로 순환식으로 생성
– The combined size can be no more than 4GB prior to MariaDB 10.0, and no more than
512GB in MariaDB 10.0 and later
– Larger values mean less disk I/O due to less flushing checkpoint activity, but also
slower recovery from a crash
– Default Value: 50331648 (48MB) (from MariaDB 10.0), 5242880 (5MB) (before MariaDB
10.0)
• INNODB_LOG_GROUP_HOME_DIR
– Redo 로그 파일에 대한 디렉토리 경로 설정
• INNODB_LOG_FILES_IN_GROUP
– Redo 로그파일 개수
• INNODB_LOG_BUFFER_SIZE
– Redo 로그 파일을 기록하기 위한 버퍼 사이즈
77
InnoDB Parameter
• INNODB_LOCK_WAIT_TIMEOUT
– 롤백이 진행되기 전에 락을 대기하는 시간 ( 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초 간격으로 동작
 3 : (from MariaDB 10.0) Emulates MariaDB 5.5 group commit
(3 syncs per group commit)
78
InnoDB Parameter
• INNODB_FLUSH_METHOD
– Flush 명령어 방식 설정, 디폴트는 fdatasync
 fdatasync : fsync()를 사용해서 데이터와 로그 파일을 flush
 O_SYNC : 로그 파일을 열고 flush 하지만, 데이터 파일을 flush하기 위해서는
fsync()를 사용
 O_DIRECT : O_DIRECT를 사용해서 데이터 파일을 열고, 데이터 파일과 로그 파
일을 flush (몇몇 GNU/Linux 버전에서 사용 가능함)
 Windows에서는 flush 방식은 항상 async_unbuffered 사용
79
InnoDB Statistics Parameter
• 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 수
80
InnoDB Statistics Parameter
• INNODB_STATS_AUTO_RECALC
– Default는 on, table에서 10% 이상의 row가 변경되면 자동으로 persistent
statistics를 재계산 함
• INNODB_STATS_ON_METADATA
– Show table status, Show index 또는 INFORMATION_SCHEMA의
tables/statisticstable 접근 시 자동으로 통계정보 수집
– Default Value: OFF (from MariaDB 10.0), ON (before MariaDB 10.0)
81
ColumnStore Storage Engine
82
ColumnStore Storage Engine
• SCALING BIG DATA ANALYTICS
– Harvest new value from large historical datasets by deriving new
insights
– Support growth in your business, while continue to deliver high
service levels for data analytics
83
ColumnStore Storage Engine
• DATA WAREHOUSING
– Selective column based queries
– Large number of dimensions
• ANALYTICS REQUIRING
– Complex Joins, Windowing Functions
• HIGH PERFORMANCE ANALYTICS ON LARGE VOLUME OF DATA
– Reporting and analysis on billions of rows
– From datasets containing trillions of rows
– Terabytes to Petabytes of datasets
84
ColumnStore Storage Engine
85
ColumnStore Storage Engine
• USER MODULES
– mysqld : The MariaDB server
– ExeMgr : MariaDB’s interface to ColumnStore
– cpimport : high-performance data import
• QUERY PROCESSING - UM
– SQL Operations are translated into thousands of Primitives
– Parallel/Distributed SQL
– Extensible with Parallel/Distributed UDFs
– Query is parsed by mysqld on UM node
– Parsed query handed over to ExeMgr on UM node
– ExeMgr breaks down the query in primitive operations
86
ColumnStore Storage Engine
• PERFORMANCE MODULES
– PrimProc : Primitives Processor
– WriteEngineServer : Database file writing processor
– DMLProc : DML writes processor
– DDLProc : DDL processor
• QUERY PROCESSING - PM
– Primitives are processed on PM
– One thread working on a range of rows
– Typically 1/2 million rows, stored in a few hundred blocks of data
– Execute all column operations required (restriction and projection)
– Execute any group by/aggregation against local data
– Each primitive executes in a fraction of a second
– Primitives are run in parallel and fully distributed
87
Connect Storage Engine
88
Connect Storage Engine
89
Connect Storage Engine
• MAIN FEATURES
– 외부 데이터 형식(DBMS, file, datasource, virtual) 연결
– ODBC, JDBC, MySQL or MongoDB API 통해 DataSource에 직접 연결
– JSON, XML, HTML파일 및 JSON UDF통한 NOSQL 쿼리지원
– WHERE절에 대한 푸시다운
– Special & Virtual Columns 지원
– 다중테이블의 병렬실행 가능
– 서브 테이블별 파티셔닝 지원
– SELECT, UPDATE 및 DELETE에 대한 MRR 지원
90
Connect Storage Engine
• CONNECT PARAMETERS
– connect_class_path : java class path
– connect_conv_size : text유형 변환 시 varchar크기
– connect_enable_mongo : mongo table type enable
– connect_exact_info : 정확한 레코드번호 리턴 여부
– connect_index_map : 인덱스 파일에 대한 파일매핑 활성화여부
– connect_java_wrapper : java wrapper
– connect_json_grp_size : JSON 집계함수의 최대 행 수
– connect_json_null : JSON NULL값
– connect_jvm_path : JVM 경로
– connect_type_conv : TEXT 컬럼의 변환 처리 옵션
– connect_use_tempfile
– connect_work_size : 메모리할당에 사용되는 크기
– connect_xtrace : 콘솔추적값
91
Variables / Status
92
Server System Variables
• Global variables
• Server startup 때 사용: command-line 과 option이용
• Server 구동 중에는 SET 명령어로 바꿀 수 있음
– System variable 이름과 값 보기
 mysqld --verbose –help
– 현재 사용중인 server variable 보기
 SHOW VARIBALES
93
Dynamic Server Setting
• 동적 변수와 정적 변수
– 동적변수
 기동중인 상태에서 변경 가능 한 변수
– 정적변수
 기동중인 상태에서 변경 불가능한 변수로 설정파일을 통해 변경 후 MariaDB
서비스를 재시작 해야 함
• 세션변수와 글로벌 변수
– 세션변수
 MariaDB 클라이언트가 MariaDB 서버에 접속 할 때 기본적으로 부여하는 옵션의
기본값을 제어하는데 사용하는 변수
– 글로벌변수
 하나의 MariaDB서버 인스턴스에서 전체적으로 영향을 미치는 시스템 변수
 SHOW GLOBAL VARIABLES로 확인
94
Dynamic Server Setting
• 실시간 서버옵션 설정(동적변수 변경) 예
– GLOBAL VARIABLES 수정
 SET global log_slow_queries = ON;
– SESSION VARIABLES 수정
 SET read_buffer_size=262144;
 SET session read_buffer_size=262144;
• 서버가 실행되는 동안 설정파일 변경 없이 시스템변수를 변경 할
수 있음
• 동적변수 설정 시 주의사항
– MB,GB와 같은 단위 표기법 사용불가
– 2 * 1024 * 1024 같은 수식 사용 가능
95
Buffer & Cache variables
• KEY_BUFFER_SIZE
– dynamic / global
– Index block에서 사용하는 buffer 크기
– Index가 많은 table에서 insert, delete 작업이 많은 경우 늘려줌
• JOIN_BUFFER_SIZE
– dynamic / global / session
– Full join 에서 사용하는 버퍼의 크기
• MAX_JOIN_SIZE
– dynamic / global / session
– 최대 join 되는 크기
96
Buffer & Cache variables
• READ_BUFFER_SIZE
– dynamic / global / session
– 순차적인 검색을 하는 thread에 할당하는 버퍼의 크기
• SORT_BUFFER_SIZE
– dynamic / global / session
– 정렬할 때 thread에 할당하는 버퍼의 크기
– Order by나 group by를 빠르게 하려면 sort_buffer size를 증가시킴
97
Buffer & Cache variables
• TABLE_OPEN_CACHE
– dynamic / global
– 모든 thread에서 열 수 있는 TABLE 수
• QUERY_CACHE_SIZE
– dynamic / global
– 기 사용된 SQL 쿼리를 저장해 놓는 cache 크기
– 같은 쿼리를 반복적으로 사용하는 경우가 많으면 증가
98
Buffer & Cache variables
• THREAD_CACHE_SIZE
– dynamic / global
– cache 에 저장해둔 thread 숫자
– thread 생성시 cahce 에 thread 가 있는 경우 생성하지 않고 재사용함
• TABLE_OPEN_CACHE_INSTANCES
– static / global
– Removed MariaDB 10.0.7, reintroduced MariaDB 10.2.2
– Default Value: 8 (>= MariaDB 10.2.2), 1 (<= MariaDB 10.0.7)
99
Server System Status
• Global status
• Server 구동중에서의 상태값 확인
– 현재 사용중인 server status 보기
 SHOW STATUS
100
Status Monitor
• CONNECTIONS
– 연결시도 횟수 = 사용량
• ABORTED_CONNECTS
– 연결을 시도해서 실패한 횟수, MAX_USED_CONNECTIONS 를 확인
• MAX_USED_CONNECTIONS
– 최대 동시 접속자수
– 이 값을 보고 MAX_CONNECTIONS의 값을 조정
• ABORTED_CLIENTS
– 클라이언트에서 연결이 적절하게 닫지 못해서 취소된 연결 횟수
– 네트워크 연결에 문제 가능성 높음
101
Status Monitor
• KEY_READS
– disk에서 물리적으로 키 BLOCK을 읽은 횟수
– 시스템의 성능을 고려하여 가능한 만큼 KEY_BUFFER_SIZE를 증가시켜 줌
• KEY_READS, KEY_READ_REQUEST
– Cache Hit Ratio = KEY_READS/KEY_READ_REQUEST
– Cache Hit Ratio 값이 클 경우 KEY_BUFFER_SIZE 조정
• SELECT_FULL_JOIN
– INDEX를 사용하지 않은 조인 쿼리 실행 횟수
– 이 값이 너무 크면 TABLE의 INDEX 검토
– 쿼리 튜닝 검토
102
Status Monitor Parameter
• OPENED_TABLES
– 열었던 TABLE 수
– 이 값이 너무 크면 TABLE_CACHE 값을 증가
• QUESTIONS
– SERVER로 보낸 쿼리 횟수
– 초당 쿼리 수: QUESTIONS와 UPTIME 이용
• TABLE_LOCKS_WAITED
– TABLE LOCK을 위해 대기한 시간
103
Information Schema
104
Metadata
• INFORMATION_SCHEMA
• SHOW
• DESCRIBE
• mysqlshow
105
INFORMATION_SCHEMA
• 메타데이터를 저장하는 데이터베이스/스키마
• 가상데이터베이스
• 정보를 얻기 위해 SELECT사용
106
INFORMATION_SCHEMA
• INFORMATION_SCHEMA 테이블
항목 설명
CHARACTER_SETS 사용 가능한 캐릭터 셋
COLLATIONS 각각의 캐릭터 셋을 위한 콜래이션
COLLATION_CHARACTER_SET_AP
PLICABILITY
캐릭터 셋은 각각의 콜래이션에 적용
COLUMNS 테이블 안에 컬럼
COLUMN_PRIVILEGES 컬럼 권한은 사용자 계정에 의해서 따름
ENGINES 스토리지 엔진
EVENTS 스케줄된 이벤트
KEY_COLUMN_USAGE 키 컬럼 제한
107
INFORMATION_SCHEMA
항목 설명
PARTITIONS 테이블 파티션
PLUGINS 서버 플러그인
PROCESSLIST 스레드 운영하기
REFERENTIAL_CONSTRAINTS foreign keys
ROUTINES 저장 프로시저와 함수
SCHEMATA 데이터베이스
SCHEMA_PRIVILEGES 데이터베이스 권한은 사용자 계정에 따름
STATISTICS 테이블 통계
TABLES 데이터베이스 안에 테이블
TABLE_CONSTRAINTS 테이블 제약
TABLE_PRIVILEGES 테이블 권한은 사용자 계정에 따름
108
INFORMATION_SCHEMA
항목 설명
TRIGGERS 데이터베이스 안에 트리거
USER_PRIVILEGES 전역 권한은 사용자 권한에 따름
VIEWS 뷰
INNODB_LOCKS 트랜잭션의 잠금 요청에 대한 대기정보 및 차단하는 정보
INNODB_LOCK_WAITS 트랜잭션 차단된 대기정보
INNODB_TRX 실행중인 트랜잭션 정보
TokuDB_file_map 디렉토리명 및 테이블, 인덱스 파일명
109
SHOW Syntax
• SHOW DATABASES
• SHOW [FULL] TABLES
• SHOW [FULL] COLUMNS
• SHOW INDEX
• SHOW CHARACTER SET
• SHOW COLLATION
110
DESCRIBE Syntax
• 문법
– DESCRIBE 테이블 명
– DESC 테이블 명
– SHOW COLUMNS FROM 테이블 명
• DESCRIBE는 FROM을 지원하지 않음
• INFORMATION_SCHEMA 테이블 정보를 보여줌
111
Logs
112
MariaDB LOG Type
• 에러로그(error log)
– 서버 시작 및 종료 기록을 포함
– 문제가 되는 쿼리에 대한 로그
– 설정 확인
 log_error = /ohnew/log/error/maria-error.log
• 일반쿼리로그(general query log)
– 클라이언트의 연결, 클라이언트로부터의 쿼리 등 다양한 이벤트가 기록
– 서버로 수신되는 모든 쿼리를 기록
– 서버의 활동상황(누가 연결하며, 무엇을 하고 있는지)을 감시하는데 유용
– 설정 확인
 general_log = ON
 general_log_file = /ohnew/log/general/maria-general.log
113
MariaDB LOG Type
• 이진로그( binary log )
– UPDATE, DELTE, INSERT, CREATE TABLE, GRANT 등의 명령문에 의해서 수정
이 발생한 명령문을 기록
– 서버가 비정상 종료할 경우, 백업 이후의 데이터를 복원하기 위해 사용
• 릴레이 로그( relay log )
– 서버가 리플리케이션 슬레이브(replication slave) 서버로 동작하는 경우,
마스터 서버로부터 수신한 데이터 수정 이벤트를 기록
114
MariaDB Log Output
• log_output을 FILE 또는 TABLE로 설정 할 수 있음
• FILE
– 로그 데이터가 파일에 기록 됨
• TABLE
– 로그 데이터가 테이블에 기록 됨
– 일반 쿼리 로그 : mysql.general_log
– 느린 쿼리 로그 : mysql.slow_log
115
Variables & Log
• Server Variable 관리
– Server Variable 정보를 DB 화 하여 관리
– error code 정보를 DB 화 하여 관리
– 필요시 쉽게 찾아 적용할 수 있도록 테이블화하여 관리
• Slow & General Log 관리
– log_output 을 table 로 관리하면 추후 장애시 확인이 용이
– file 형태로 관리시 mysqlsla 혹은 mysqldumpslow 의 유틸을 이용하여 분
석
– 파일이 일정사이즈가 되면 rename 되도록 관리
116
Section 2
MariaDB Administrator
Section 3
118
세부내용
ㆍMariaDB transaction
ㆍLOCKING의 개념
ㆍMariaDB InnoDB Locking
ㆍMariaDB deadlock
ㆍMariaDB 보안 수준
Section 3
119
Transaction
120
Transaction
• Transaction
– 트랜잭션(Transaction) 은 더 이상 나뉠 수 없는 하나의 업무단위
– 데이터베이스 내에서 한꺼번에 수행되어야 할 일련의 연산
– All or Nothing
– Commit 시 모든 작업 결과는 데이터베이스에 반영
– Rollback 시 모든 작업 결과가 데이터베이스에 미반영
121
Transaction
• 예시) 은행 입출금
122
Transaction
• 예시) 은행 입출금
1. 카드삽입 2. 거래선택
3. 비밀번호입력4. 거래완료
YES
YES
YES
NO
NO
NO
YES/NO?
YES/NO?
YES/NO?
123
Transaction
• ACID
– 원자성 (Atomicity)
 Transaction 은 더 이상 분류할 수 없는 작업 단위
 모든 데이터 수정 작업이 수행되거나 되지 않아야 함
– 일관성 (Consistency)
 Business Logic 에 위배되는 일관되지 않은 Transaction 은 중단되어야 함
– 독립성 (격리성) (Isolation)
 동시 Transaction 에 의한 수정은 다른 동시 Transaction 에 의한 수정과 격리
 Transaction 중간의 데이터는 변경을 수행한 Transaction 에서만 확인됨
– 영속성 (Durability)
 Transaction 이 완료되면 영구적으로 시스템에 적용
 시스템 오류와 무관하게 데이터는 보존
124
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
125
Isolation Level
Isolation Level Phenomena Allowed
Read uncommitted
Dirty Read
Non Repeatable Read
Phantoms
Read committed
Non Repeatable Read
Phantoms
Repeatable read Phantoms
Serializable
Concurrency
Row
Row
High
High
Consistency
126
Isolation Level
• READ UNCOMMITTED
BEGIN
INSERT
COMMIT
select name from School where ID=501
결과값 : Dorothy
ID NAME
500 Hans
501 Dorothy
School
ID NAME
500 Hans
501 Dorothy
ID NAME
500 Hans
501 Dorothy
TransactionA
TransactionB
Dirty Read
127
Isolation Level
• READ COMMITTED
TransactionA
TransactionB
BEGIN
COMMIT
SELECT name FROM School WHERE ID=501
결과값 : Dorothy
ID NAME
500 Hans
501 Ally
UNDO
ID NAME
501 Dorothy
ID NAME
500 Hans
501 Ally
ID NAME
500 Hans
501 Dorothy
School
UPDATE SET name = ‘Ally’ WHERE ID = 501
Undo 영역에
name = Dorothy
데이터 백업
128
Isolation Level
• NON-REPEATABLE READ
TransactionA
TransactionB
BEGIN
COMMIT
SELECT ID FROM School WHERE NAME = ‘Ally’
결과값 : 501
ID NAME
500 Hans
501 Ally
ID NAME
500 Hans
501 Ally
ID NAME
500 Hans
501 Dorothy
School
UPDATE SET name = ‘Ally’ WHERE ID = 501
BEGIN
SELECT ID FROM School WHERE NAME = ‘Ally’
결과값 : empty
129
Isolation Level
• REPEATABLE READ
TransactionA
TransactionB
COMMIT
SELECT .. ID = 501
결과값 : Dorothy
TRX-ID ID NAME
1 500 Hans
1 501 Dorothy
School
UPDATE SET name = ‘Ally’
BEGIN
(Trx ID : 2 )
BEGIN
(Trx ID : 3 )
UNDO
TRX-ID ID NAME
1 501 Dorothy
TRX-ID ID NAME
1 500 Hans
3 501 Ally
Undo
영역 백업
TRX-ID ID NAME
1 500 Hans
3 501 Ally
UNDO
TRX-ID ID NAME
1 501 Dorothy
결과값 : Dorothy
SELECT .. ID = 501
TRX-ID 3 이 변경전 Undo
영역 백업 데이터
130
Isolation Level
• PHANTOM READ
TransactionA
TransactionB
COMMIT
SELECT NAME FROM School WHERE ID > 500
결과값 : Ally
TRX-ID ID NAME
1 500 Hans
1 501 Ally
School
INSERT INTO School
values (502, ‘Kerry’)
BEGIN
(Trx ID : 2 )
BEGIN
(Trx ID : 3 )
TRX-ID ID NAME
1 500 Hans
1 501 Ally
TRX-ID ID NAME
1 500 Hans
1 501 Ally
3 502 Kerry
결과값 : Ally, Kerry
TRX-ID ID NAME
1 500 Hans
1 501 Ally
3 502 Kerry
SELECT NAME FROM School WHERE ID > 500
131
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 발생 가능
 InnoDB 의 경우 Gap Lock 방식으로 PHANTOM READ 발생하지 않음
• SERIALIZABLE
– 읽기 작업 시에도 공유 잠금을 획득 해야 함
132
Transaction
• Undo 의 필요성
– Transaction 수행 중에 수정된 페이지를 타 세션에서 조회 ( MVCC )
– Transaction 의 ACID 를 보장하기 위함
– Transaction 의 Rollback 수행을 정상적으로 처리하기 위함
• Redo 의 필요성
– Commit 한 Transaction 의 수정된 내용에 대해 일관성을 보장하기 위함
– Database crash 복구시 데이터의 일관성을 보장하기 위함
– Database 의 지연된 쓰기를 지원하여 performance 향상을 도와주기 위함
133
 Multi-Version Concurrency Control
InnoDB MVCC
SessionA
SessionB
134
InnoDB MVCC
• InnoDB MVCC
– Snapshot과 거의 흡사한 개념
– row-level locking DBMS들의 일반적인 기능
– Lock 을 사용하지 않는 일괄된 읽기를 제공
– InnoDB는 Undo log ( ibdata file ) 를 이용
– DML 발생시 변경 대상 레코드에 대해서 Undo 를 이용하여 읽기 일관성을
제공하는 방식
135
Locking
136
Locking
• Lock 이란?
– 데이터베이스에서 동일 자원 사용시 자원의 경합을 최소화 하기 위한 장치
– Transaction 의 순차적 진행을 보장하기 위한 직렬화 장치
– 다중 Transaction 의 일관성과 무결성을 유지하기 위한 장치
– MVCC 를 구현하기 위한 필요 장치
– 사용의도에 따라 공유, 배타, 갱신, 의도, 스키마 lock 등이 존재
137
MariaDB Locking
• Table Lock
– A세션에서 테이블 자원을 사용하기 위하여 데이터를 읽거나 쓰기를 할때
타세션에서는 테이블 자원에 대한 사용을 제한 하는 lock
– A세션에서 명시적으로 테이블 lock 을 사용하면 해당 세션에서 lock 을
해지하지 않으면 다른 세션에서는 접근을 할 수 없음
– 테이블 lock 을 사용려면 테이블 lock 권한을 가지고 있어야 가능
138
MariaDB Locking
• Table Write Lock
– TABLE level Lock
– lock을 건 thread 에서만 read, write가 가능
– lock 을 건 thread 를 제외하고는 해당 테이블에 대해 read, write 불가능
– unlock 은 lock 을 건 thread 에서만 가능
139
MariaDB Locking
• Table Write Lock
140
MariaDB Locking
• Table Write Lock
141
MariaDB Locking
• Table Read Lock
– TABLE level Lock
– 모든 thread 에서 select 가능
– 모든 thread 에서 DML 불가능
– unlock 은 lock 을 건 thread 에서만 가능
– lock_wait_timeout parameter 로 대기시간 설정 가능
142
MariaDB Locking
• LOW_PRIORITY
– MariaDB에서 기본적으로 WRITE LOCK 이 READ LOCK 보다 우선됨
– DML 수행의 우선 순위를 변경시 이용
 LOW_PRIORITY : 다른 클라이언트가 SELECT 를 모두 마칠때까지 기다린 후 실행
 DELAYED : 데이터를 추가할 경우에 해당되며, 메모리에 저장해 놓고 처리함
a. 클라이언트는 SELECT 가 끝날때까지 기다리지 않음
b. 항상 '1 rows affected' 의 결과를 냄
 IGNORE : PRIMARY KEY, UNIQUE KEY 에 대한 동일한 데이터를 추가, 수정, 삭제할
경우에 해당되며, 에러를 무시하고 계속 진행함
143
MariaDB Locking
• Global Lock
– 글로벌 읽기 잠금 (Global Read Lock)
– A세션 자체에서 글로벌하게 READ LOCK 이 필요할 경우 사용
144
MariaDB Locking
• Name Lock
– 테이블 이름이 변경/삭제시 테이블 레벨에서 묵시적인 네임 lock 을 사용
– 명시적으로 USER 가 설정할 수 없음
– MariaDB Internal Lock
145
MariaDB Locking
• User Lock
– User Level Lock
– Lock 의 이름과 timeout 을 정의해서 사용
– GET_LOCK(str, timeout), RELEASE_LOCK(str), IS_FREE_LOCK(str) 함수 사용
– 문자열에 대해 사용중이면 0, 사용중이지 않으면 1 을 RETURN
146
Metadata locking
• Metadata Lock
– 데이터 이외의 메타데이터 변경시 발생하는 lock
– 주로 table, trigger 등을 drop 또는 alter 할 때 발생
Metalock 발생
147
Storage Engine Locking Level
InnoDB Row-level locking
MyISAM
Memory
Merge
Table-level locking
Storage Engine Locking
 Row-level lock 은 Table-level 에 비해 많은 메모리를 사용
 Row-level lock 은 Table-level lock 에 비해 많은 lock 이 필요
 상대적으로 Row-level lock 이 Table-level lock 보다 자원을 더 소모함
148
• InnoDB Lock
– InnoDB Row Level Lock 지원
– Shared, Exclusive, Intention Lock 을 이용
– 동시에 같은 자원을 사용하는 경우 transaction 의 순서대로 진행
– 현재 존재하는 Lock 과 호환성이 있는 경우의 lock 은 승인됨
– Deadlock 이 발생하는 경우 undo 가 높은 transaction 이 Rollback 됨
InnoDB Locking
149
X IX S IS
X Conflict Conflict Conflict Conflict
IX Conflict Compatible Conflict Compatible
S Conflict Conflict Compatible Compatible
IS Conflict Compatible Compatible Compatible
 Shared ( S ) lock
 Exclusive ( X ) lock
 Intention shared ( IS ) lock
 Intention exclusive ( IX ) lock
InnoDB Locking
150
InnoDB Locking
• InnoDB Lock 확인 방법
– SHOW ENGINE INNODB STATUS
– Information_schema 의 INNODB_TRX, INNODB_LOCKS, INNODB_LOCK_WAIT
 INNODB_TRX : 어떤 트랜잭션이 어떤 프로세스에 의해 기동되고, 어떤 lock을
기다리는지를 관리
 INNODB_LOCKS : 어떤 lock이 존재하는지 관리
 INNODB_LOCK_WAIT : lock에 의한 프로세스 간의 의존 관계를 관리
– InnoDB Lock monitoring 으로 확인
 create table innodb_lock_monitor (a int) engine = innodb ;
 error.log 에 일정 간격으로 lock 정보가 저장됨
151
InnoDB Lock Escalation
• InnoDB Lock Escalation
– innodb_lock_tables
 0 : LOCK TABLES doesn’t work
 1 : LOCK TABLE work like set autocommit = 0
– The lock information in InnoDB is stored so space-efficiently that
lock escalation is not needed
– Typically, several users are permitted to lock every row in InnoDB
tables, or any random subset of the rows, without causing InnoDB
memory exhaustion
152
InnoDB Internal Lock
wwcck
ssauravy
dorothy
Anthony
lcd
Nice
Hans
Next-Key
Lock
Next-Key
Lock
Next-Key
Lock
Gap Lock
Record
Lock
Record
Lock
Record
Lock
Record
Lock
153
InnoDB Internal Lock
• Record Lock
– Record 자체만을 잠그는 lock
– Index 의 Record 를 잠금
– 인덱스가 없는 경우에는 내부적으로 생성된 cluster PK 를 이용하여 잠금
– primary key, unique index 에 의한 변경작업은 Record lock 만을 이용
• Gap Lock
– Record 와 인접한 Record 사이를 잠그는 lock
– Record 자체를 잠그지 않음
– Record 사이에 새로운 Record 가 생기는 것을 제어 ( Phantom 방지 )
– 자체적으로 동작하지 않고 Next Key Lock 의 일부로 동작
– “dorothy” 데이터에 변경작업이 발생하는 경우 “wwcck” ~ “dorothy”,
“dorothy” ~ “lcd” 사이에 gap lock 으로 잠금
154
InnoDB Internal Lock
• Next Key Lock
– Record Lock + Gap Lock
– “dorothy” 데이터에 변경작업이 일어나는 경우 “wwcck” ~ Gap + Record ~ “lcd”
범위에 대해 lock 이 발생함
– binlog format 을 statement 로 사용하여 Repeatable read isolation level 을
사용하는 경우에 Next Key Lock 을 사용
• Auto-increment Lock
– Auto Increment 속성의 컬럼을 가진 테이블에 Insert가 실행되는 경우
– Table Level Lock
– Statement Level Lock 으로 SQL 이 수행되면 해제됨
– Transaction Level 의 lock 이 아니므로 이미 사용된 Auto-increment 는
Rollback 되지 않음
– innodb_autoinc_lock_mode 로 제어
 1 : insert 에 대해 lock 을 걸지 않음
 2 : 어떠한 경우에도 lock 을 걸지 않음
155
Deadlock
• Deadlock
156
Deadlock
• Deadlock 개요
– Transaction Database 의 공통 문제
– Application 설계의 문제로 인해 발생
– show engine innodb status 명령으로 최신의 deadlock 정보 확인 가능
– InnoDB Engine 사용시 Deadlock 자동 감지 및 즉시 처리
– InnoDB Engine 에서 Deadlock 발생시 undo 가 작은 transaction rollback
157
Deadlock
• Deadlock 방지
– Application 에서 Deadlock 으로 종료된 Transaction 을 재수행하도록
작성필요
– Transaction 의 단위를 작게 나누어서 실행
– 고정순서로 테이블과 열에 접근하도록 Application 설계
– Index 설계를 통해서 Deadlock 발생을 최소화
158
Deadlock Detection
• Show Engine Innodb Status G
159
Deadlock Detection
• Show Engine Innodb Status G
– 구문 실행 시간
 LOG 의 시작부분에 status 파일의 시간 표현
– 자료 수집 시간
 Per second averages calculated from the 52 seconds
– SEMAPHORES
 운영체제상에서 SEMAPHORES 에 대한 정보를 표현
 wait 발생 여부와 spin wait 및 spin round 의 발생 여부 정보를 표현
– TRANSACTIONS
 현재 실행중인 transaction 에 대한 정보
 Trx id 는 transaction 의 현재 id
– FILE I/O
 FILE I/O helper thread 동작 정보를 표현
160
Deadlock Detection
• Show Engine Innodb Status G
– INSERT BUFFER AND ADAPTIVE HASH INDEX
 insert buffer 와 adaptive hash 정보 표현
– BUFFER POOL AND MEMORY
 InnoDB Buffer Pool 사용상태와 Memory 사용 상태 표현
– LASTEST DETECTED DEADLOCK / LASTEST FOREIGN KEY ERROR
 최신의 deadlock 정보 / 최신의 foreign key error 정보
– ROW OPERATIONS
 DML 및 select 한 row operation 정보 표현
– LOGS
 InnoDB 의 log 정보 확인
 LSN 및 flush 된 log 번호 확인 가능
161
MariaDB Security
162
MariaDB Security
• MariaDB Security 를 위한 설정
– MariaDB 데이터베이스는 chroot 환경에서 실행
– mysqld 프로세스는 다른 프로세스가 사용하지 않는 유일한 UID/GID로 실행
– 인가된 계정을 제외한 시스템 계정은 로컬 엑세스만 허용
– root user 계정의 패스워드는 추정하기 어렵도록 설정
– 관리자(root) 어카운트명을 변경
– history 의 주기적인 삭제 필요
– 데이터베이스로의 익명 접속(anonymous 계정 사용)을 금지
– test 및 미사용 데이터베이스와 테이블을 모두 삭제
– local-infile 파일 경로 제한
– load_file() 함수의 사용 권한 제한
– DB 관련 directory 의 권한 제한
– mysql user, db, table, column 권한 설정
163
MariaDB Security
• Remote Access 제한
– default port 인 3306 을 차단 혹은 타 port 로 변경
– port 를 변경하여도 mysql.sock socket 으로 통신은 가능
– skip-networking 설정시 3306/tcp 포트로 접근 불가능
– Remote 데이터 백업등 Remote 작업 수행시 ssh 사용
• 로컬 보안 개선
– LOAD DATA LOCAL INFILE 제한
– /ohnew/mariadb/etc/my.cnf 의 [mysqld] 난에 다음을 추가
164
MariaDB Security
• 관리자(root) 패스워드 변경
– mysql 클라이언트를 실행하여 패스워드 변경
– 기본적으로 root 계정에 패스워드가 설정되어 있지 않음
– 쉽게 유추할 수 없는 패스워드로 설정
– mysql 접속시 password 가 노출되지 않도록 –p 옵션으로 접속
– mysqladmin 를 이용하여 변경하는 것이 보안에 뛰어남
– ps aux 커맨드사용시 타 사용자가 password 를 확인할 수 있음
– history 파일(~/.history, ~/.bash_history)을 보면 패스워드가 쉽게 노출
165
MariaDB Security
• 기본제공되는 사용자/데이터베이스 삭제
– MariaDB 설치시 제공하는 anonymous 계정과 test 데이터베이스 삭제
– 사용되지 않는 root 를 제외한 계정을 정리하도록 권고
– 익명 접속으로 데이터베이스를 설정하는 것을 막을 수 있음
166
MariaDB Security
• 관리자 (root) 계정 변경
– default 설정인 관리자 어카운트(root) 를 말함
– 무차별 대입 & 딕셔너리 공격 등으로 추측해 내기 어려운 이름으로 변경
– root 계정을 제외하고 타 계정에 권한만 부여하여 사용
• history 삭제
– MariaDB daemon 에 의해 실행되는 모든 SQL 커맨드가 저장
– ~/.mysql_history 에 기록됨
– 패스워드 정보도 노출될 수 있음
167
Section 3
MariaDB Administrator
Section 4
169
세부내용
ㆍMariaDB backup 개념 및 방법
ㆍMariaDB 논리적 백업과 물리적 백업
ㆍmysqlbinlog
ㆍmariabackup 및 xtrabackup
ㆍmysql_upgrade
Section 4
170
BACKUP
171
• 백업이란?
– 의미있는 정보인 데이터에 대해 논리적, 물리적으로 복제하여 관리하는 것
– 동일 장비 혹은 다른 장비의 disk 장치 혹은 별도의 백업 장치에 관리
• 백업의 목적
– 데이터 안정성 유지 및 데이터 소실 방지
– 하드웨어 시스템 고장 / disk 손상 / 소프트웨어 손상 / 운영데이터 소실
– 사고로 시스템이나 파일이 피해를 입더라도 최근에 백업한 시점의 내용으로
복구를 위함
BACKUP
172
• 백업 정책 수립
– 백업 대상 선정
 data file
 binlog
 my.cnf
 iblogfile
– 백업 주기 선정
 백업의 수행 시간에 따른 백업 주기 산정
BACKUP
173
• 백업 정책 수립
– 백업 용량 산정
 백업 정책에 따른 보관 일자 및 용량 산정
– 백업 전략 선정
 full 백업
 incremental 백업
– 백업 관리 방법 선정
 백업 정책에 따른 보관 일자 산정
 incremental 백업에 대해 증분치 보관 결정
BACKUP
174
BACKUP
• 복구 시나리오 설정
– 가장 인접한 full 백업 선정
– full 백업으로 복구 수행
– 가장 인접한 증분 백업 선정
– 증분 백업을 순차적으로 실행
– full 백업 이후의 binlog 에 대해 SQL 산출 (Point-In-Time Recovery)
– 추출한 SQL 을 적용
175
BACKUP
MariaDB
bin.
001
bin.
002
bin.
003
정기
백업
사고!!
MariaDB
정기
백업
일요일 오전3시
화요일 오후5시
데이터베이스 파손
binlog.0001~0003 기록
MariaDB
bin.
001
bin.
002
bin.
003
binlog.0001~0003 적용
176
MariaDB Backup Type
• Logical Backup
– 특징 및 장점
 SQL 형태의 text 문으로 데이터 백업
 데이터 검토 가능
 복원 작업이 수월
 물리 백업에 비해 복원시 데이터 손상을 줄여줌
 문제 발생시 원인 파악 및 해결이 수월
– 단점
 백업/복원시 시스템 리소스를 물리백업에 비해 많이 소모
 부동 소수점 데이터의 백업&복원시 정확성을 잃을 수도 있음
– 종류
 mysqldump
 into outfile / load data infile
 mysql execute mode > text file
177
MariaDB Backup Type
• Physical Backup
– 특징 및 장점
 MariaDB의 물리적 파일을 백업
 속도가 빠름
 대체적으로 작업이 단순함
– 단점
 논리적 백업에 비해 백업해야하는 파일의 크기가 큼
 데이터 복구시 문제가 발생하면 원인 파악 및 해결이 어려움
 필요한 논리개념의 data 만 백업이 불가능
– 종류
 directory copy ( cold backup )
 mysqlhotcopy ( myisam, archive )
 mariabackup ( innodb hot backup )
 xtrabackup ( percona, open source )
178
Logical Backup & Restore
179
Logical Backup & Restore
• mysqldump
– 논리 백업 방식
– row 기반 데이터 백업
– insert 구문으로 데이터를 추출 및 저장하여 백업
– 데이터베이스, 테이블 단위로 백업 가능
180
Logical Backup & Restore
• mysqldump
– [ options ]
181
Logical Backup & Restore
• mysqldump
– 기타옵션
 --single-transaction : Lock 을 사용하지 않는 일관성 있는 읽기 연산 사용
 --flush-logs : 새로운 바이너리 로그파일 생성
 --master-data= 1 / 2
a. dump 파일의 헤더 부분에 CHANGE MASTER TO 구문을 포함
b. 덤프 시작 시점의 Binary log 파일명과 위치 정보 및 호스트 정보를 포함
c. 1 : 수행할 수 있는 형태의 SQL 구문 , 2 : 정보만 출력
 --extended-insert : 확장 형태의 insert 구문으로 출력
 --no-data : 테이터를 제외하고 구조만 백업
 --create-options : 테이블 생성 옵션을 모두 포함
 --routines / triggers : 프로시저 함수 / 트리거를 포함하여 백업
– mysqldump 백업시 로그
182
Logical Backup & Restore
• source 명령어
– 외부 파일의 SQL 문을 실행
– mysql prompt 에서 사용하거나 mysql 의 –e 옵션을 이용하여 사용
– source 명령을 prompt 에서 사용시 파일의 경로는 ‘’ 대신 ‘/’ 를 이용
– 복구시 dump 파일의 character set, collation 확인 필요
– set names <character set>;
183
Logical Backup & Restore
• select ... into outfile
– 논리 백업 데이터의 복구 방식
– row 기반 데이터 백업
– 인식 가능한 구분자 ( seperator ) 로 column 을 구분하여 파일로 저장
– 원하는 형태의 SQL 을 구성하여 결과값을 파일로 저장 가능
– file_priv = ‘Y’
– 절대경로 혹은 상대경로 위치에 output 저장
– 해당 경로에 대한 OS 계정 user/group 의 쓰기 권한이 있어야 함
184
Logical Backup & Restore
• select ... into outfile
– [ options ]
185
Logical Backup & Restore
• load data infile
– 논리 백업 데이터의 복구 방식
– row 기반 데이터 백업
– 인식 가능한 구분자 ( seperator ) 로 구분된 파일의 데이터를 읽어 복원
– local / non local
– local-infile = 0
– file_priv = ‘Y’
– 파일의 절대경로 혹은 상대경로의 파일을 읽어서 복원
186
Logical Backup & Restore
• load data infile
– [ options ]
187
mysqlbinlog
188
mysqlbinlog
• mysqlbinlog
– binary / relay log 를 직접 읽기 위한 도구
– binary format 으로 작성된 binlog 를 text format 으로 변환하는 도구
– binlog_format = statement / row
 statement-based
a. event 정보는 SQL 문과 실행한 서버 ID, 실행된 시간, 실행시 걸린 시간, 기타 정보
 row-based
a. event 정보는 쿼리로 인해 변경된 row 에 대한 정보를 포함
189
mysqlbinlog
• mysqlbinlog
– [ options ]
 --help, -?
a. 도움말 메시지를 출력하고 종료
 --base64-output
a. base64 인코딩을 이용하여 모든 로그 엔트리를 출력
 --character-sets-dir=path
a. 문자 셋이 설치되어 있는 디렉토리
 --database=db_name, -d db_name
a. 하나의 데이터베이스만을 지정, 다중--database 옵션을 지정한다면, 마지막 하나만 사용
b. default-database 가 db_name인 바이너리 로그로부터 엔트리를 출력
c. 크로스-데이터베이스 명령문을 복제하지 않음
190
mysqlbinlog
 --debug[=debug_option], -# [debug_option]
a. 디버깅 로그를 작성한다. 전형적인 debug_options 스트링은 'd:t:o,file_name'
 --disable-log-bin, -D
a. 바이너리 로깅을 비활성화
b. SUPER 권한을 필요
 --force-read, -f
a. 로그읽기중 발생하는 에러를 무시하고 수행
 --hexdump, -H
a. 코멘트에 있는 로그의 헥스(hex)덤프를 출력
 --host=host_name, -h host_name
a. host 지정
191
mysqlbinlog
 --password[=password], -p[password]
a. 서버에 접속 패스워드
b. 축약옵션 (-p)을 사용할 경우, 이 옵션과 패스워드 사이에는 스페이스를 사용하지
않음
 --port=port_num, -P port_num
a. 원격 서버에 접속을 하기 위해 사용되는 TCP/IP 포트 번호
 --protocol={TCP|SOCKET|PIPE|MEMORY}
a. 사용할 접속 프로토콜
 --read-from-remote-server, -R
a. 로컬 로그 파일을 읽는 대신에 서버에서 바이너리 로그를 읽음
b. 모든 접속 파라미터 옵션은 이 옵션을 같이 지정하지 않는 한 무시
c. --host, --password, --port, --protocol, --socket, --user 옵션을 함께 사용
 --result-file=name, -r name
a. 주어진 파일에 직접 결과를 출력
192
mysqlbinlog
 --server-id=id
a. 서버 ID 에 해당하는 로그만 출력
 --set-charset=charset_name
a. 결과에 SET NAMES charset_name 명령문을 추가
 --local-load=path, -l path
a. 지정된 디렉토리에 있는 LOAD DATA INFILE을 위한 로컬 임시 파일을 준비
 --offset=N, -o N
a. 로그에 있는 첫 번째 N 엔트리를 무시(skip)
193
mysqlbinlog
 --short-form, -s
a. 로그에 포함되어 있는 명령문만을 다른 정보 없이 표시
 --socket=path, -S path
a. 유닉스 소켓 파일 또는 윈도우에서의 지명된 파이프 이름
 --start-datetime=datetime
a. datetime 인수와 동일하거나 느린 타임 스탬프를 가지고 있는 첫 번째 이벤트에서
바이너리 로그를 읽기 시작
b. DATETIME 또는 TIMESTAMP 데이터 타입에 적합한 포맷 형태로 대입
c. mysqlbinlog --start-datetime="2005-12-25 11:25:56" binlog.000003
d. 포인트-인-타입(point-in-time) 복구 시에 유용
 --stop-datetime=datetime
a. datetime 인수와 동일하거나 빠른 타임 스탬프를 가지고 있는 이벤트가 처음으로 발
생할 때 바이너리 로그를 읽기를 종료
b. 포인트-인-타입(point-in-time) 복구 시에 유용
194
mysqlbinlog
 --start-position=N
a. N 인수와 동일한 위치를 가지고 있는 이벤트가 처음 발생할 때 바이너리 로그를 읽
기 시작
b. 명령문 라인에 지명된 첫 번째 로그 파일에 적용
 --stop-position=N
a. N 인수와 동일하거나 보다 큰 위치를 가지고 있는 첫 번째 이벤트 시점에 바이너리
로그를 읽기를 종료
b. 명령문 라인에 지명된 마지막 로그 파일에 적용
 --user=user_name, -u user_name
a. 서버에 접속을 할 때 사용하는 MariaDB 사용자 이름
 --version, -V
a. 버전 정보를 출력하고 종료
195
mysqlbinlog
• mysqlbinlog 사용
– mysqlbinlog 유틸을 이용하여 sql 형태로 저장 및 실행
– mysqlbinlog 결과를 직접 mysql 로 실행
196
Physical Backup & Restore
197
Physical Backup & Restore
• Cold Backup
– OS 의 copy 명령을 사용하여 수행
– 물리적인 data file 의 copy 수행중 disk block 이 변경되면 안됨
– MariaDB daemon 을 stop 한 뒤 data block 의 변경이 없는 경우 수행
– down time 이 발생하나 가장 간단하고, 장애 없이 수행 가능
198
Physical Backup & Restore
• mysqlhotcopy
– Perl 스크립트로 작성됨
– LOCK TABLES, FLUSH TABLES, cp, scp 를 이용하여 백업함
– 단일 데이터베이스, 테이블 백업이 가장 빠름
– SELECT, RELOAD, LOCK TABLES 권한 필요
– MyISAM, ARCHIVE 테이블만 백업 가능
199
Physical Backup & Restore
• mariabackup
– 10.1.26부터 제공되는 backup tool
– MariaDB Backup is based on Percona XtraBackup 2.3.8
– Windows 지원
– Online Hot Backup 제공
– Backup/Restore of Data-at-Rest encrypted XtraDB/InnoDB tables
– Backup/Restore when MariaDB Compression is used for table types
XtraDB/InnoDB
200
Physical Backup & Restore
• 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 옵션 사용
– incremental backup 가능
201
XtraBackup
• xtrabackup
a. 백업 대상 서버에서 xtrabackup 으로 전체 데이터 백업
b. 데이터 이관
 복구할 DB의 data directory 로 백업된 directory를 이동
202
XtraBackup
• xtrabackup
 xtrabackup 복구를 이용한 데이터 이관
c. 복구할 DB 기동
 ib_logfile 을 기존과 동일하게 사용하는 경우 my.cnf 의 ib_logfile 옵션을
기존과 동일하게 설정
 새로운 ib_logfile 을 이용할 경우 ib_logfile 을 새로 생성할 수 있도록 삭제
d. 복구할 DB에서 mysql_upgrade 실행
203
Cold Backup
• cold backup & restore
a. 백업 대상 서버 중지
b. 복구 서버로 데이터 이관
 복구할 DB의 data directory 로 백업 서버의 datadir 이동
204
Cold Backup
c. 복구 DB 기동
 ib_logfile 을 기존과 동일하게 사용하는 경우 my.cnf 의 ib_logfile 옵션을
기존 과 동일하게 설정
 새로운 ib_logfile 을 이용할 경우 ib_logfile 을 새로 생성할 수 있도록 삭제
d. 복구할 DB에서 mysql_upgrade 실행
205
mysql_upgrade
206
- fix_priv_tables represents a script generated internally by mysql_upgrade that contains SQL statements
to upgrade the tables in the mysql database.
- All checked and repaired tables are marked with the current MariaDB version number. This ensures that next
time you run mysql_upgrade with the same version of the server, it can tell whether there is any need to check
or repair the table again.
- mysql_upgrade also saves the MariaDB version number in a file named mysql_upgrade_info in the data directory.
This is used to quickly check whether all tables have been checked for this release so that table-checking can
be skipped. To ignore this file and perform the check regardless, use the --force option.
mysql_upgrade
207
mysql_upgrade
• Options
· --basedir=path
Old option accepted for backward compatibility but ignored.
· --datadir=path
Old option accepted for backward compatibility but ignored.
· --default-character-set=name
Old option accepted for backward compatibility but ignored.
· --force
Ignore the mysql_upgrade_info file and force execution of
mysqlcheck even if mysql_upgrade has already been executed for
the current version of MariaDB.
· --host
Connect to MariaDB on the given host.
208
mysql_upgrade
• Options
· --password[=password], -p[password]
The password to use when connecting to the server. If you use the
short option form (-p), you cannot have a space between the
option and the password. If you omit the password value following
the --password or -p option on the command line, mysql_upgrade
prompts for one.
Specifying a password on the command line should be considered
insecure. You can use an option file to avoid giving the password
on the command line.
· --port=port_num, -P port_num
The TCP/IP port number to use for the connection.
· --protocol={TCP|SOCKET|PIPE|MEMORY}
The connection protocol to use for connecting to the server. It
is useful when the other connection parameters normally would
cause a protocol to be used other than the one you want.
209
mysql_upgrade
• Options
· --silent
Print less information.
· --socket=path, -S path
For connections to localhost, the Unix socket file to use, or, on
Windows, the name of the named pipe to use.
· --tmpdir=path, -t path
The path name of the directory to use for creating temporary
files.
· --upgrade-system-tables, -s
Only upgrade the system tables in the mysql database. Tables in
other databases are not checked or touched.
· --user=user_name, -u user_name
The MariaDB user name to use when connecting to the server and
not using the current login.
210
mysql_upgrade
• Options
· --verbose
Display more output about the process. Using it twice will print
connection arguments; using it 3 times will print out all CHECK,
RENAME and ALTER TABLE commands used during the check phase;
using it 4 times (added in MariaDB 10.0.14) will also write out
all mysqlcheck commands used.
· --version, -V
Output version information and exit.
· --version-check, -k
Run this program only if its 'server version' matches the version
of the server to which it's connecting. Note: the 'server
version' of the program is the version of the MariaDB server with
which it was built/distributed. Defaults to on; use
--skip-version-check to disable.
· --write-binlog
Cause binary logging to be enabled while mysql_upgrade runs
211
Section 4
MariaDB Administrator
Section 5
213
세부내용
ㆍMariaDB 서버 로그
ㆍMariaDB 모니터링
ㆍMySQL 에서 MariaDB 로의 전환 방법
ㆍMariaDB High Availability
Section 5
214
MariaDB Log
215
MariaDB Log
• error log
– 서버 시작 및 종료 기록을 포함
– 문제가 되는 쿼리에 대한 로그
• general query log
– 클라이언트의 연결, 클라이언트로부터의 쿼리 등 다양한 이벤트가 기록
– 서버로 수신되는 모든 쿼리를 기록
– 서버의 활동상황(누가 연결하며, 무엇을 하고 있는지)을 감시하는데 유용
• slow query log
– slow query 를 활성화 하는 경우 log 파일에 SQL 을 기록
– “느림"의 기준은 /etc/my.cnf 설정 파일에 long_query_time에 초단위로 기록
– Default Value: 10.000000 >= MariaDB 10.1.13, 10 <= MariaDB 10.1.12
216
MariaDB Log
• binary log
– UPDATE, DELETE, INSERT, CREATE TABLE, GRANT 등의 명령문에 의해서 수정
이 발생한 명령문을 기록
– 서버가 비정상 종료할 경우, 백업 이후의 데이터를 복원하기 위해 사용
• relay log
– 서버가 리플리케이션 슬레이브(replication slave) 서버로 동작하는 경우,
마스터 서버로부터 수신한 데이터 수정 이벤트를 기록
217
MariaDB 모니터링
218
MariaDB 모니터링
• 서버 과부하
• MariaDB shutdown
• MariaDB 복구
• 테이블 메타 정보 불일치
• 로그 파일 관리
• 테이블 및 레코드의 잠금 해결
• MariaDB 서버의 호스트 잠금
219
MariaDB 모니터링
• 서버 과부하
– OS utility 를 이용한 부하 확인
 uptime 명령어
a. CPU 에 처리해야 하는 작업이 쌓여있는 정도를 표현
b. load average 항목 확인
c. CPU 작업이 대기 큐에서 처리를 기다리는 프로세스의 평균값을 1,5,15분 간격으로 표현
 vmstat 명령
a. 현재 CPU 가 어떤 작업에 주로 사용되는지 확인
b. 초단위 시간간격으로 표현
220
MariaDB 모니터링
-- proc 항목
r : 현재 실행중인 프로세스의 수
b : 인터럽트가 불가능한 sleep 상태에 있는 프로세스의 수 (I/O 처리를 하는 동안 블럭 처리된 프로세스)
w : 강제로 스왑아웃된 프로세스
-- memory 항목
swpd : 사용하고 있는 swap 메모리 양
free : 사용가능한 메모리 양
buff : 버퍼로 사용되고 있는 메모리 양
cache : 캐시로 사용되고 있는 메모리 양
-- swap 항목
si : swap in
so : swap out
221
MariaDB 모니터링
-- io 항목
bi : 초당 블럭 디바이스로 보내는 블럭 수
bo : 초당 블럭 디바이스로부터 받은 블럭 수
-- system 항목
in : 초당 인터럽트 되는 양
cs : 초당 context switch되는 양
-- cpu 항목
us : 사용자의 CPU 사용 시간 비율
sy : 시스템의 CPU 사용 시간 비율
id : idle
222
MariaDB 모니터링
 free 명령어
a. OS 의 물리적 메모리나 스왑 영역의 상태 확인
b. 주로 –m –t 옵션을 사용 ( m : MB 표기 , t : TOTAL 라인 표시 )
223
MariaDB 모니터링
 free 명령어
-- Mem 항목
1) 시스템의 물리적인 메모리에 대한 사용량을 각 필드로 표시
2) total은 전체 메모리의 용량은 byte단윈로 표시
3) used는 현재 시스템에서 사용중인 메모리의 량을 표시
4) free는 현재 시스템에서 사용중이지 않은 메모리의 량을 표시
5) shared는 현재 시스템에서 공유한 메모리의 용량을 표시
6) buffers는 현재 시스템에서 버퍼링(buffering)된 메모리의 량을 표시
7) cached는 현재 시스템에서 캐싱(caching)된 메모리의 량을 표시
-- Swap 항목
1) total은 시스템의 전체 Swap메모리의 량을 표시
2) used는 전체 스왑메모리에서 현재 사용중인 스왑메모리의 양
3) free는 전체 스왑메모리중에서 사용되지 않고 남아 있는 메모리의 양
224
MariaDB 모니터링
 iostat 명령어
a. OS 의 물리적 메모리나 스왑 영역의 상태 확인
b. -dx 옵션으로 디바이스별 확장 통계 조회가능
225
MariaDB 모니터링
 iostat 명령어
-- Device 항목
1) rrqm/s : 디바이스 큐에 대기중인 초당 읽기 요청의 건수
2) wrqm/s : 디바이스 큐에 대기중인 초당 쓰기 요청의 건수
3) r/s : 디바이스에 요청한 초당 읽기 요청의 건수
4) w/s : 디바이스에 요청한 초당 쓰기 요청의 건수
5) rsec/s : 디바이스에서 초당 읽어들인 섹터의 갯수
6) wsec/s : 디바이스에서 초당 기록한 섹터의 갯수
7) avgrq-sz : 디바이스에 요청한 초당 평균 데이터의 크기
8) avgqu-sz : 디바이스에 요청한 초당 평균 큐 길이
9) await : 디바이스에서 처리되기 위해서 요청된 I/O 평균 시간(밀리초, 1/1000초). 큐에서
소요된 시간과 처리된 시간이 합쳐져 출력
10) svctm : 디바이스에서 처리한 I/O 평균 시간 (밀리초, 1/1000초)
11) %util : 디바이스에서 요청한 I/O 작업을 수행하기 위해 사용한 CPU 시간 비율. 이 값이
100%에 가까워지면 디바이스가 한계에 도달
226
MariaDB 모니터링
– MariaDB Error Log 확인
 MySQL 서버에 문제가 발생하는 경우 기본적으로 Error Log 에 기록됨
 장애시 Error Log 의 마지막 부분은 반드시 확인
 MySQL 에러로그 파일은 기본적으로 data directory에 hostname.err 로 생성됨
 log-error 파라메터를 설정함으로써 directory 및 filename 지정 가능
 파일이 너무 큰 경우 tail 명령이나 less 명령을 이용하여 마지막 라인만 확인
227
MariaDB 모니터링
– MariaDB Processlist 확인
 MariaDB 서버에 접속하거나 mysqladmin utility 를 이용하여 확인
 현재 실행중인 SQL 확인 가능
 show (full) processlist 명령으로 확인 가능
 각 프로세스의 command / state / time 값을 확인하여 현재 상태와 실행시간 확인
a. State 항목이 Waiting 인 경우 타 프로세스에 의한 잠금 확인 필요
b. Copy to tmp table 인 경우 해당 SQL 의 튜닝포인트 확인
c. Command 및 State 항목이 동일 항목이 여러개 반복해서 나타나는 경우 SQL 튜닝 필요
d. Command 및 State 항목이 여러종류가 다양하게 나타난다면 서버 외부 요인 파악
e. 서버의 부하는 높으나 Command 항목이 대부분 Sleep 상태인 경우 network in 확인
228
MariaDB 모니터링
– MariaDB Max Connection 확인
 평상시보다 많은 Network In 이 발생하는 경우
 서버가 처리할 수 있는 허용량 보다 많은 connection 이 동시에 몰리는 경우
부하
 Session 메모리를 고려한 max connection 설정 필요
 status 항목의 max_used_connection 을 모니터링하여 최대사용량에 도달한 경
우 connection 허용값을 증가하여 운영
 max_connections 시스템 변수로 조정 가능
229
MariaDB 모니터링
– MariaDB Slow Query Log 분석
 MariaDB 의 slow-log 옵션을 활성화하는 경우 기록
 로그파일 혹은 테이블로 기록 ( log_output=‘FILE,TABLE’ )
 지정된 시간 이상 정상 수행 및 종료된 SQL 에 대해 기록
 mysqldumpslow 유틸을 이용하여 slow log 의 통계 집계 가능 ( 기본적으로 설
치 )
 mysqlsla utility 를 이용해서 확인 가능 ( 별도 설치 )
 -s 옵션에 count(c) , lock(l) , record(r) 기준으로 출력 가능
 hostname-slow.log 형태로 기록
230
MariaDB 모니터링
– MariaDB SQL 실행 빈도 확인
 mysqladmin 의 extended-status 항목으로 서버 상태값 출력
 egrep 커맨드로 필요한 항목만 확인
 초당 처리되는 쿼리의 수를 확인하고 평상시보다 과부하가 발생하는지 확인
231
MariaDB 모니터링
• MariaDB Shutdown
– MariaDB 서버가 자동으로 Shutdown 되는 경우 error.log 확인
– Normal Shutdown 이외의 메시지로 내려가는 경우 서버 재시작
– mysqld_safe 옵션으로 mysqld daemon 이 시작된 경우 자동 복구
– Killed 등의 메시지로 원인확인이 불가능 할 때 OS log 를 통해 원인 분석
• MariaDB data 복구
– MyISAM 테이블 손상의 경우 repair table 명령으로 복구
– InnoDB 의 손상 시 innodb_force_recovery 옵션을 my.cnf 에 추가하여 복구
 1~6 까지의 옵션을 낮은 번호부터 증가시키면서 복구
 default 0 : 비복구 모드
232
MariaDB 모니터링
• MariaDB Table Meta 복구
– MariaDB Data Dictionary 와 .frm 파일의 정보가 불일치 하는 경우 발생
– Data Dictionary 에서 정상 삭제된 경우 이상 없음
– .frm 데이터가 삭제되고 Data Dictionary 에 남아 있다면 에러 발생
– 타 database 에서 해당 테이블과 동일한 구조의 테이블을 만들고 .frm 파일
을 복사하여 인식하도록 할 수 있음
• MariaDB ERROR Log 문제
– Error Log 파일의 사이즈가 warning 으로 인해 커지는 경우
– warning 메시지를 error log 에 출력하지 않도록 설정
– error log 나 binary log 의 경우 파일 삭제 후 flush logs 를 통해
새로운 log 생성
233
MariaDB 모니터링
• MariaDB 테이블 및 레코드 잠금 해결
– transaction 이 특정 이유로 commit 이 되지 않은 상태로 남아있는 경우
– Lock wait timeout exceeded error 발생
– Lock 을 유발하는 transaction 을 종료하여 처리
– processlist 상의 id 항목에 대해 kill query id 로 처리
– innodb_lock_wait_timeout 변수를 통해 대기시간을 줄일 수 있음
234
MariaDB 모니터링
• MariaDB binary Log 문제
– binary log 의 사이즈가 커지는 경우
– 일정기간 이외의 파일을 지우도록 설정 ( expire_logs_days )
– 직접적으로 binary log purge 하여 용량 확보
235
MariaDB 모니터링
• MariaDB Server Host 잠금
– client host 별 error count 값이 max_connect_errors 설정값 초과시 발생
– default 10
– hostname is blocked because of many connection errors 발생
– flush hosts 명령으로 처리 가능
– max_connect_errors 값을 증가시켜서 처리가능
236
MariaDB 전환
237
From MySQL to MariaDB
• DB 전환
• 주의사항
• 버전별 DB 전환
• mysql_upgrade
238
mysqldump
• mysqldump 논리 백업 도구 이용 ( 버전에 관계 없이 가장 안전함 )
a. 이관 대상 MySQL 서버에서 mysqldump 로 전체 데이터 백업
b. 전환할 DB 인 MariaDB 를 설치 후 기동
239
mysqldump
• mysqldump 논리 백업 도구 이용 ( 버전에 관계 없이 가장 안전함 )
c. mysqldump 로 백업된 덤프 파일을 새로운 버전의 MariaDB 에서 실행
※ dump 파일의 내용이 수행되는 내용을 모두 확인 가능
d. 전환할 DB 인 MariaDB 에서 데이터 이관이 완료되면 mysql_upgrade 실행
240
전환시 주의사항
• temporary 테이블의 원활한 사용을 위해 옵션값 조정 필요
– aria-pagecache-buffer-size = 64M ( MySQL : key-buffer-size )
• Replication 구성의 경우 slave 를 먼저 전환 필요
– MariaDB 의 binary log 를 MySQL 의 하위버전이 인식 못할 수 있음
– Master DB 를 전환 시 --skip-write-binlog 옵션을 이용하여
mysql_upgrade 수행 필요
• 항상 전환 전 backup 을 받아둘 것
– 데이터 및 환경설정 파일까지 모두 백업
– binlog 로 복원 가능한 데이터가 존재할 수 있으므로 binlog 까지 백업
241
전환시 주의사항
• mysql_upgrade 수행
– 버전이 동일하더라도 system 테이블 내용이 변경될 수 있으므로 항시 수행
– 버전이 다른 경우 반드시 수행
– 시스템 테이블의 업데이트만 수행하는 경우 –s 옵션 사용
• unix_timestamp 범위 및 datetime 의 %f 옵션 차이
– 인식 가능한 timestamp 의 범위가 상이함 ( MySQL – INT 의 MAX VALUE ,
MariaDB – 상이 )
– datetime 의 %f 옵션에 대해 MySQL 은 표현하지 못함 ( 5.5 이하 )
• MySQL 에서 deprecated 되었거나 MariaDB 전용 variables에 대한
확인 필요
242
버전별 DB 전환
• 확인사항 ( MySQL 5.0 이하에서 MariaDB 5.5 전환 시 주의 )
– 인덱스 칼럼의 collation 변경
– MySQL 4.1 과 5.0 간의 DECIMAL 과 VARCHAR 데이터 타입 저장 방식
변경
– MySQL 5.1 부터 모든 플랫폼에서 테이블 명이 동일하도록 인코딩
되어서 저장
243
버전별 DB 전환
• 확인사항 ( MySQL 5.1 에서 MariaDB 5.5 전환 시 주의 )
– 데이터 파일 포멧간의 차이가 거의 없음
– mysql 시스템 데이터베이스의 dictionary 정보가 상이할 수 있음
– 변경된 parameter 확인 ( 예 default-character-set )
– 전환한 MariaDB 구동시 deprecated 된 parameter 에 대해 error
log 에서 확인가능
244
버전별 DB 전환
• 확인사항 ( MySQL 5.5 에서 MariaDB 5.5 전환 시 주의 )
– 데이터 파일 포맷이 동일함
– OS 파라메터 fs.max-aio-nr 의 값이 상향 조정됨
– thread pool 관련 설정이 변경됨
245
MariaDB High Availability
246
MariaDB High Availability
• Replication
• MaxScale
• Galera Cluster
• ProxySQL
• MHA
247
MariaDB Replication
248
MariaDB Replication
249
MariaDB Replication
250
MariaDB Replication
251
MariaDB MaxScale
252
MariaDB MaxScale
• Security
– SQL-Injection, DDoS등 보안위협으로부터 보호
• Flexibility
– Query Routing, Replication, Multi-tenant DB Scaling
• High Availability
– SPOF없는 HA지원
• Data Streaming
– 실시간 분석을 위한 Data Lake에 Trx Data제공
253
MariaDB Galera Cluster
254
MariaDB Galera Cluster
255
ProxySQL
Query Caching
- mysqld QC대비 3배 향상
Query Routing
- 다른 포트 R/W 분할
- 수신 포트 R/W 분할
- RegEX 통한 R/W 분할
Supports Failover SQL Firewall
256
MHA (MySQL High Availability)
MHA Manager Active Master Slave #1 Slave #n
…
Application Server
MHA Zone Replication Zone
Master 감지
MHA Manager Active Master Slave #1 Slave #n
…
Application Server
MHA Zone Replication Zone
Binary log
Copy
장
애
발
생
Save_binary_logs
Apply_diff_relay_logs
장애 처리를 위한 파일
257
Section 5
고맙습니다
고맙습니다
참고자료
261
MariaDB 10.x
262
MariaDB 10.2
• 주요 기능 및 변경 사항
– InnoDB as Default
– MyRocks storage engine added
– Window functions
– CTE (Common Table Expressions)
– InnoDB tables now support spatial indexed
– TokuDB has been split into a separate package, mariadb-plugin-tokudb
– Multiple triggers for the same event
– DML_only flashback can rollback instances/databases/tables to an old
snapshot
– The JSON data type (an alias for LONGTEXT) was introduced
– The CONNECT engine now supports the JDBC Table type
– Persistent AUTO_INCREMENT for InnoDB
263
MariaDB 10.3
• 주요 기능 및 변경 사항
– Oracle compatibility stage 1
– Sequences can now be used with DEFAULT
– INTERSECT and EXCEPT
– The PL/SQL stored procedure dialect (enabled with sql_mode=ORACLE)
now supports Oracle style packages
– Invisible Columns
– Instant ADD COLUMN for InnoDB
– Storage-engine Independent Column Compression
– The Spider storage engine has been updated to 3.3.13
– Numerous improvements for the partition engine
264
MariaDB 10.4
• Plans for MariaDB 10.4
– Better Security
 Automatic DOS attacks detection
 Automatic password crack detection
 Column encryption
– Compatibility
 Oracle stage 2
 CONNECT BY
– Re-Entrant Items
 Building block for parallel query and be able to share stored procedures
between threads (Stored procedure cache)
 Reading and updating my.cnf from server
265
Oracle Compatibility
• MariaDB ups the stakes in database war with Oracle
• http://www.channelworld.in/news/mariadb-ups-stakes-database-
war-oracle
• Michael Howard, who worked at Oracle for four years between
1996-2000, has been CEO of MariaDB since December 2015.
• "Isn't it ironic that Oracle Enterprise, MySQL's bigger
brother, provides data warehousing yet it is MariaDB that is
delivering it to you, this community? They don't want you to
succeed with MySQL, they certainly don't want MySQL to
cannibalise things like Exadata."
266
MariaDB Client Program
267
MySQL Client Program
• MySQL Workbench
• innotop
• mysqlsla
• mysqldumpslow
• mysqladmin
268
MySQL Workbench
• Install: http://dev.mysql.com/downloads/workbench/
• 지원 기능
– SQL Development
 접속, SQL 문 실행
– Server Administration
 MySQL 설치 디렉터리를 정하거나 my.ini 환경설정파일 세팅
– Data Modeling
 "Create EER model from existing database“
 기존 데이터베이스의 database diagram을 생성할 수 있음
269
Tadpole DB hub
http://tadpoledbhub.atlassian.net/
270
Other Graphical Tools
• Other Graphical Tools
– PhpMyAdmin
– HeidiSQL
– SQLyog
– TOAD for MySQL
271
MariaDB installation
272
source Package binary
• 서버 환경에 맞는 옵션을 지정
하여 사용 가능
• configure 명령을 통하여 옵션
지정
• OS 버전에 구애 받지 않고 설치
가능
• 각 OS 별 최적화된 설치 제공
• 지정된 repository 에서
compile 된 binary 파일 및
환경설정을 모두 가져와 설치
• 설치가 간편함
• 각 OS 별 최적화된 compile 된
binary 제공
• core 의 옵션을 제외한
환경변수 설정 가능
• 원하는 환경변수를 이용하여
설치 가능
MariaDB Installation
273
MariaDB source compile
274
MariaDB source compile
1. 설치에 필요한 패키지 설치
 cmake 설치 후 mariadb 설치시 없는 package 는 추가로 설치
 ( binary 설치시 : http://www.cmake.org/cmake/resources/software.html )
2. MariaDB source file download
– https://downloads.mariadb.org/ : source file download
– wget 을 이용한 file download
3. 다운받은 소스 압축 해제 및 compile 을 위한 디렉토리 생성
275
MariaDB source compile
4. compile
276
MariaDB source compile
5. 사용자 그룹 및 사용자 생성
6. 디렉토리 생성 및 퍼미션 변경
277
MariaDB source compile
7. 시스템 테이블 생성
8. mysqld startup script 설정
278
MariaDB source compile
9. library 등록 ( lib 경로를 등록하는 모든 방법중 하나 사용 )
10. my.cnf 생성
279
MariaDB source compile
11. 주요 명령어 등록
12. MariaDB 실행
280
MariaDB binary installation
281
MariaDB binary Installation
1. MariaDB stable binary file 다운로드
– /usr/local 경로에 다운로드 가정
– wget 혹은 https://mariadb.org 사이트를 이용하여 binary 다운로드
2. binary 파일의 압축 해제 및 디렉토리 생성
3. 사용자 그룹 및 사용자 생성
282
MariaDB binary Installation
4. my.cnf 생성 ( DATADIR 생성 기준 )
5. init script 생성
283
MariaDB binary Installation
6. my.cnf path 수정
284
MariaDB binary Installation
7. library 등록 ( lib 경로를 등록하는 모든 방법중 하나 사용 )
8. MariaDB 실행

More Related Content

PPTX
Maria db 이중화구성_고민하기
DOCX
MySQL_SQL_Tunning_v0.1.3.docx
PDF
MySQL Administrator 2021 - 네오클로바
PPTX
MySQL_MariaDB-성능개선-202201.pptx
PDF
MariaDB 제품 소개
PDF
[2018] MySQL 이중화 진화기
PDF
Maxscale_메뉴얼
PPTX
Maxscale 소개 1.1.1
Maria db 이중화구성_고민하기
MySQL_SQL_Tunning_v0.1.3.docx
MySQL Administrator 2021 - 네오클로바
MySQL_MariaDB-성능개선-202201.pptx
MariaDB 제품 소개
[2018] MySQL 이중화 진화기
Maxscale_메뉴얼
Maxscale 소개 1.1.1

What's hot (20)

PDF
MariaDB 마이그레이션 - 네오클로바
PDF
The Full MySQL and MariaDB Parallel Replication Tutorial
PDF
MariaDB Performance Tuning and Optimization
DOCX
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
PDF
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11
PPTX
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
PDF
MariaDB MaxScale monitor 매뉴얼
PDF
MySQL InnoDB Cluster - A complete High Availability solution for MySQL
PDF
MariaDB MaxScale
PDF
MySQL Parallel Replication: All the 5.7 and 8.0 Details (LOGICAL_CLOCK)
PDF
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
PPTX
MaxScale이해와활용-2023.11
PDF
MySQL Advanced Administrator 2021 - 네오클로바
PDF
AWS 환경에서 MySQL BMT
PDF
Upgrade from MySQL 5.7 to MySQL 8.0
PDF
InnoDB Performance Optimisation
PDF
MySQL/MariaDB Proxy Software Test
PDF
InnoDb Vs NDB Cluster
PDF
Disaster Recovery with MySQL InnoDB ClusterSet - What is it and how do I use it?
PDF
MySQL 상태 메시지 분석 및 활용
MariaDB 마이그레이션 - 네오클로바
The Full MySQL and MariaDB Parallel Replication Tutorial
MariaDB Performance Tuning and Optimization
Keepalived+MaxScale+MariaDB_운영매뉴얼_1.0.docx
MySQL Database Architectures - MySQL InnoDB ClusterSet 2021-11
[135] 오픈소스 데이터베이스, 은행 서비스에 첫발을 내밀다.
MariaDB MaxScale monitor 매뉴얼
MySQL InnoDB Cluster - A complete High Availability solution for MySQL
MariaDB MaxScale
MySQL Parallel Replication: All the 5.7 and 8.0 Details (LOGICAL_CLOCK)
The Proxy Wars - MySQL Router, ProxySQL, MariaDB MaxScale
MaxScale이해와활용-2023.11
MySQL Advanced Administrator 2021 - 네오클로바
AWS 환경에서 MySQL BMT
Upgrade from MySQL 5.7 to MySQL 8.0
InnoDB Performance Optimisation
MySQL/MariaDB Proxy Software Test
InnoDb Vs NDB Cluster
Disaster Recovery with MySQL InnoDB ClusterSet - What is it and how do I use it?
MySQL 상태 메시지 분석 및 활용
Ad

Similar to MariaDB Administrator 교육 (20)

PDF
MariaDB Other Features
PDF
개발자가 도전하는 MariaDB 서버구축
PDF
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
PDF
MariaDB 기본 소개 20201216.pdf
PDF
Azure Databases for PostgreSQL MYSQL and MariaDB
PPTX
Maria db
PDF
MySQL InnoDB Cluster 소개
PDF
MariaDB Xpand 고객사례 안내.pdf
PPTX
MariaDB
PPTX
개발자도 알아야 하는 DBMS튜닝
PPTX
Azure databases for PostgreSQL, MySQL and MariaDB
PDF
Migration to Azure Database for MySQL
PDF
MySQL Deep dive with FusionIO
PPTX
마이크로서비스 아키텍처로 개발하기
PDF
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
PPSX
Cubrid Inside 5th Session 4 Replication
PDF
AWS 9월 웨비나 | AWS 데이터베이스 마이그레이션 서비스 활용하기
PDF
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
PPTX
Vectorized processing in_a_nutshell_DeView2014
PPTX
CDNetowks MariaDB 5.5 Upgrade Case Study
MariaDB Other Features
개발자가 도전하는 MariaDB 서버구축
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
MariaDB 기본 소개 20201216.pdf
Azure Databases for PostgreSQL MYSQL and MariaDB
Maria db
MySQL InnoDB Cluster 소개
MariaDB Xpand 고객사례 안내.pdf
MariaDB
개발자도 알아야 하는 DBMS튜닝
Azure databases for PostgreSQL, MySQL and MariaDB
Migration to Azure Database for MySQL
MySQL Deep dive with FusionIO
마이크로서비스 아키텍처로 개발하기
Cloud-Barista 제3차 오픈 컨퍼런스 : CB-Spider - 멀티 클라우드 인프라 연동(Multi-Cloud Infrastruc...
Cubrid Inside 5th Session 4 Replication
AWS 9월 웨비나 | AWS 데이터베이스 마이그레이션 서비스 활용하기
[스마트스터디]모바일 애플리케이션 서비스에서의 로그 수집과 분석
Vectorized processing in_a_nutshell_DeView2014
CDNetowks MariaDB 5.5 Upgrade Case Study
Ad

MariaDB Administrator 교육

  • 2. 2 목차 구분 내용 Section 1 - MariaDB 소개 - MariaDB 서버 구성 및 아키텍처 이해 Section 2 - MariaDB 스토리지 엔진 - MariaDB 데이터베이스 관리 Section 3 - 트랜잭션 / Locking 의 이해 - MariaDB 보안 Section 4 - 백업과 복구를 통한 데이터베이스 관리 - MariaDB upgrade Section 5 - MariaDB 모니터링 - MySQL 에서 MariaDB 로의 전환
  • 4. 4 세부내용 ㆍMariaDB 소개 ㆍMariaDB Architecture ㆍMariaDB 설치 및 접속 ㆍMariaDB 변수 및 my.cnf 설정 Section 1
  • 6. 6 MariaDB Overview • Open Source Relational Database • 사용이 편리하고, 확장성이 좋으며, 우수한 성능 • 연결성 : full networking support • 이식성 : run on most OSes, such as Unix, Windows, Mac • 보안 : SSL support • 타 DB 대비 상대적으로 작은 size • MySQL AB -> Sun (2008) -> Oracle (2010) • MariaDB Initial release : January 2009
  • 7. 7 MariaDB Overview • Scale Up or Scale Out – 일반적인 상용 RDBMS 들은 일반적으로 Scale Up 을 지향 – MariaDB는 Scale Out 에 기반을 두고 DB Architecture 설계시 고성능 발휘 Scale Up 분류 Scale Out • 높은 안정성 • 고성능 장점 • 저비용 • 장애시 서비스 Impact 적음 • 부분적 증설이 가능 • 지속적인 시스템 확장 가능 • 고비용 • 장애시 대형 장애로 연결 • 한대의 고성능 서버로 감당이 어려운 경우 문제 발생 단점 • 많은 서버로 인한 관리 부담 • 각 서버의 장애 발생 가능성이 높음
  • 8. 8 MariaDB Database Server Editions • GPL ( General Public License ) – MariaDB Community • MariaDB TX – MariaDB Server – MariaDB Cluster – MariaDB MaxScale (BSL) – MariaDB Connectors – MariaDB Tools – MariaDB Services • MariaDB AX – MariaDB Server – MariaDB ColumnStore – MariaDB MaxScale (BSL) – Bulk data adapters – Streaming data adapters – Tools
  • 12. 12 MariaDB Server Structure • MariaDB Server – MariaDB Engine (instance) + Storage Engine (+ Handler API)  MariaDB Engine • 요청된 SQL 문장을 분석 & 최적화하는 등의 일을 처리 • Connection Handler, SQL Parser, Precompiler, Optimizer, Cache, Buffer  Storage Engine • 실제 데이터를 disk 스토리지에 저장 • disk 스토리지로부터 데이터를 추출 MariaDB Engine Storage Engine
  • 13. 13 MariaDB Server Thread • A MariaDB server process (mysqld) can create a number of threads • A global thread (per server process) is responsible for creating and managing each user connection thread • A thread is created to handle each new user connection • Each connection thread also performs authentication and query execution • A signal thread handles alarms and forces timeouts on connections that have been idle too long • A thread is allocated to handle shutdown events • Threads are used for table flushing, maintenance tasks, and so on • MariaDB uses a data cache, record cache, key cache, table cache, hostname cache, and privilege cache for the caching and retrieval of different types of data used by all the threads executing within the server process • In addition, the MariaDB main process (mysqld) has threads to handle database management activities such as backup, restore, concurrency control, and so on
  • 14. 14 MariaDB Server Thread Connection Manager Thread Signal Thread Connection Thread Connection Thread Connection Thread Connection Thread Connection Thread Connection Thread .... Client Client Client Client Client Client Insert Buffer Thread InnoDB File I/O Threads MariaDB – innodb plugin Log Thread Read Thread Write Thread Storage Engine innodb_read_io_threads innodb_write_io_threads
  • 15. 15 MariaDB Server Process Flow Application Handler API InnoDB ColumnStore Connect MyRocks .... SQL Thread Cache Logging Thread Cache Connection Manager User Authentication Command Diaspatcher Query Cache Module Optimizer Access Control Table manager Parser Table Open Cache Table Definition Cache
  • 16. 16 MariaDB Server Process Flow • MariaDB Engine – SQL 구문 분석 – 해당 테이블에 Open & Lock – 실행계획 분석 – 테이블 lock 해제 및 close • Storage Engine – Handler API 를 통해 접근 – Write Thread & Read Thread 를 이용하여 I/O 발생
  • 17. 17 MariaDB Structure : 3 layer • 1’st layer: Connectors – MariaDB client – MariaDB에 접근하기 위해 Application에서 설치하여 사용 – C, API, JDBC 등 언어에 따라 여러 가지 connector를 사용 • 2’nd layer: MariaDB Instance (MariaDB server header) – SQL 구문 분석 – 옵티마이저 최적화로 실행계획 작성 – 필요하면 메모리에 캐쉬 • 3’rd layer: Storage Engine – 데이터를 저장하고 추출 – 각각의 storage engine은 서로 다른 데이터 저장 및 추출 방법을 가짐 – InnoDB, ColumnStore, Connect, MyRocks, …
  • 18. 18 MariaDB Structure : 3 layer • Connection Manager – MariaDB 내부에서 관리하는 Manager – 새로운 user connection thread를 DB에 할당하여 저장함 – Connection 생성과 함께 SQL 작업을 위한 메모리를 자동 할당 • SQL Interface – DDL, DML, Stored Procedure, Trigger 지원을 위한 모듈 제공 – SQL 함수에 대한 지원을 제공
  • 19. 19 MariaDB Structure : 3 layer • Cache & Buffer – 자주 사용되는 데이터, 인덱스 등을 빠르게 사용하기 위해 메모리에 저장하는 영역 – Query Cache 는 Select 문과 결과의 조합을 캐시하여 매우 빠른 응답을 지원 – 데이터베이스 Metadata 메모리 캐시를 제공 – 스토리지 엔진에 따라 기능의 차이가 존재함 – 서버전체, 엔진별, 유저별 캐시를 포함 • Parser / Optimizer – 유저의 오브젝트 접근 권한 확인 – SQL문 실행을 위한 준비 작업 – SQL 권한 확인, SQL 문을 Database 내부 언어로 변환, 실행경로 분석 – 모든 storage engine에 동일하게 적용
  • 20. 20 MariaDB Structure : 3 layer • 관리도구 – 데이터베이스 관리, 데이터베이스 디자인, 마이그레이션 등을 위한 툴 제공 • Subscription Service – MariaDB Admin (SQLyog Ultimate) – MariaDB Monitor (Monyog Ultimate Monitor) – Technical support : 24x7 – Technical support : 30 minute response time (S1) – Consultative support – Notification services (e.g., security alerts) – Security patches and bug fixes – Limited indemnification – Access to expert services
  • 21. 21 MariaDB connectors • Connector/ODBC – The MariaDB Connector/ODBC 2.0 series is built on top of MariaDB Connector/C 2.2 and uses the binary prepared statement protocol. It is basically MariaDB Connector/ODBC 1.0, ported to work on Linux • Connector/J – MariaDB Connector/J is used to connect applications developed in Java to MariaDB and MySQL databases. The client library is LGPL licensed • Connector/C (libmysql) – MariaDB Connector/C is used to connect applications developed in C/C++ to MariaDB and MySQL databases. The library is LGPL licensed
  • 22. 22 MariaDB 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++)
  • 23. 23 Protocol and memory / disk • Supported communication protocol – TCP/IP – Unix socket – Shared memory – Named pipes • Memory – Global buffers and caches – For Memory storage engine
  • 26. 26 MariaDB Server - mysqld • mysqld server program 역할 – Connection을 핸들링  TCP/IP, Unix sockets, Shared memory.. – SQL 문을 처리  Parser, query execution, authorization, query cache, optimizer, query logging – Data storage 핸들링
  • 29. 29 MariaDB 실행 및 접속 • MariaDB 실행 • MariaDB 접속
  • 30. 30 MariaDB 변수 및 my.cnf 설정
  • 31. 31 MariaDB Setting File • MariaDB 설정파일 경로 확인 – MariaDB서버는 단 하나의 설정파일(my.cnf)만 사용 – 설정파일을 명시적으로 지정함으로서 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
  • 32. 32 my.cnf • support-files 디렉토리에 my.cnf 샘플파일 • my-huge.cnf, my-large.cnf, my-medium.cnf, my-small.cnf 시스 템 최적화용으로 사용 가능 • client, mysqld 등의 항목을 기준으로 환경변수 설정가능 – [mysqld] , [server] , [mysqld-X.X] , [mariadb] , [mariadb-X.X] – [client] , [client-server] -- (MariaDB 5.3 and higher) • 사용할 engine 의 옵션에 따라 변수 설정
  • 34. 34 my.cnf • port 및 data path 설정
  • 37. 37 my.cnf • Connection, Log, Character Set Settings
  • 38. 38 my.cnf • Replication Settings, Thread Pool Settings
  • 40. 40 MariaDB Programs • mysql – Data 를 select / insert / update / delete 하기 위한 SQL client • mysqladmin – MariaDB Server를 관리하는 tool로 Server 환경설정이나 현재 상태를 체크 및 데이터베이스를 create / drop 등을 할 수 있음
  • 41. 41 MariaDB Programs • mysqlcheck – Table maintenance 기능 • mysqldump – 일련의 SQL statement 를 실행해서 논리적 백업기능 (스키마, 테이블 데이터) – 백업 혹은 타 DBMS 로 이관하기 위해 하나 이상의 데이터베이스 덤프 가능
  • 42. 42 MariaDB Programs • mysqlshow – 테이블과 데이터베이스 구조 정보 – SHOW 구문과 비슷 – 데이터베이스, 테이블, 컬럼, 인덱스 빠르게 조회해 보기 – mysqlshow [옵션] [데이터베이스 명[테이블 명[컬럼 명]]]
  • 43. 43 MariaDB Programs • mysqlslap – 쿼리 진단 프로그램 – Slow query log 출력
  • 46. 46 세부내용 ㆍMariaDB 스토리지 엔진 소개 ㆍInnoDB 스토리지 엔진의 아키텍처 및 특성 ㆍ메타데이터정보 ㆍ서버 로그들 활용 및 관리 ㆍ실시간으로 MariaDB 서버 옵션 설정 Section 2
  • 49. 49 What are Storage Engines • MariaDB Storage Engine – 스토리지 엔진은 하나의 모듈로서 작동 – 스토리지 엔진을 별도 컴파일 하여 서버에 적재가 가능 – 지속적으로 새로운 내부 스토리지 엔진을 개발 – 개별적인 스토리지 엔진이 다양하게 개발됨
  • 50. 50 MariaDB DataFile 구성 • MariaDB 기본 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
  • 51. 51 MariaDB Storage Engine 스토리지 엔진 MariaDB 버전 트랜잭션 잠금 주요 응용 프로그램 InnoDB >= 10.2.x Yes MVCC 트랜잭션 처리 XtraDB >= 5.1.x <= 10.1.x Yes MVCC 트랜잭션 처리 ColumnStore >= 10.1.x Yes MVCC 대용량 분석 (OLAP) FederatedX >= 10.0.x Yes N/A 원격 서버 연결 CONNECT >= 10.0.x Yes N/A 이기종 DB 및 파일 연결 TokuDB >= 5.5.x Yes MVCC 트랜잭션 처리, 로깅 MyRocks >= 10.2.x Yes MVCC 트랜잭션 처리
  • 52. 52 MariaDB Storage Engine 스토리지 엔진 버전 트랜잭션 잠금 주요 응용 프로그램 MyISAM > 3.23 No 동시 삽입 가능 테이블 SELECT, INSERT 대량 적재 Aria >= 5.1 No 동시 삽입 가능 테이블 MyISAM 대용(내부 디스크 테이블) MEMORY >= 4.0 No 테이블 중간 계산, 통계 참조 데이터 Archive >= 4.1 No row 로깅, 집계 분석 CSV >= 4.1 No 테이블 로깅, 외부 데이터 대량 적재 BLACKHOLE >= 4.1 N/A N/A 로깅, 복제 아카이브 SphinxSE >= 10.0 N/A N/A Full text search
  • 53. 53 MariaDB Storage Engine 스토리지 엔진 버전 트랜잭션 잠금 주요 응용 프로그램 OQGRAPH >= 10.0 N/A N/A 계층구조, 그래프 처리 Sequence >= 10.0 Yes Read-only 임시테이블용 시퀀스 Spider >= 10.0 Yes row 샤딩 Cassandra >= 10.0 N/A N/A SQL/NoSQL간 데이터 통합 MRG_MyISAM >= 3.23 No 동시 삽입 가능 테이블 MyISAM 테이블의 모음 Mroonga >= 10.0 No No Groonga기반 전체 텍스트 검색
  • 54. 54 Storage engines • Storage Engine 요약 – Archive : 삽입후 레코드 변환 없음 – BLACKHOLE : 쓰기 무시하고 읽기는 NULL로 반환하지 않는 테이블 – ColumnStore : OLAP 엔진 – CONNECT : 이기종 데이터베이스를 사용할 수 있는 엔진 – CSV : 콤마 구분 값 포맷으로 저장 – EXAMPLE : 저장 엔진의 시작 방법에 대한 최소한의 예제를 제공 – FederatedX : 원격 테이블 접속을 위한 엔진 – InnoDB : 외부 키를 가지는 트랜잭션 엔진 – MEMORY : In-memory 테이블 – MERGE : MyISAM 테이블의 집합 관리 – MyISAM : ISAM 방식의 저장 엔진 – MyRocks : 압축률이 뛰어난 엔진 – SphinxSE : Full Text Search를 위한 엔진 – Spider : 샤딩을 위한 엔진 – TokuDB : 프랙탈 인덱스를 사용하는 엔진
  • 55. 55 Show Storage Engine • show engines – 현재 사용가능한 engine 조회 – transactional 지원 여부 조회 가능
  • 56. 56 Types of Storage Engines • General Purpose Storage Engines – Transactional  InnoDB, TokuDB, MyRocks – Non-Transactional  MyISAM • Analytics and Data Warehousing – ColumnStore • Special Purpose Storage Engines – Connect, Memory, Spider, Archive, Blackhole, CSV,... • Search Storage Engines – SphinxSE, Mroonga
  • 57. 57 Storage engines • Chose one default storage engine for the application – InnoDB is standard at this point, actually – ColumnStore is solution for modern data warehousing • User other storage engines for what they are good – MyISAM  compact, non transactional, temporary storage – MEMORY  temporary tables – Connect  Light duty remote data access, etc
  • 58. 58 MyISAM • MyISAM Engine 특징 – MySQL 3.23.x 이후 버전에서 사용 가능 – Data 저장이 효율적이고 빈번한 Data 사용의 부하를 잘 소화함 – B-tree, R-tree & Full-text Index를 지원 – 특정 Index에 대한 Memory Cache를 지원 ( key_buffer_size ) – Data 압축에 대한 옵션을 제공 ( fixed / dynamic / compressed ) – 지리적 Data를 지원 – Table 레벨의 Lock을 지원 & Transaction을 미지원 – Backup 및 특정 시점으로의 복구 지원 – DB 는 directory 별로 생성 및 관리 – .frm / .myd / .myi 파일로 구성 ( Table 구조정보 / data / index ) – engine = myisam 형태로 지정
  • 59. 59 MyISAM • MyISAM Engine 의 적합한 사용 – 변경작업이 별로없는 select 위주의 Table – 빠른 쓰기 성능이 필요한 경우  동일 테이블에 읽기와 쓰기가 혼합되어 있지 않아야 함  Logging, Temporary Table, 데이터 생성 – 복구에 대해 시간이 다소 소요되어도 괜찮은 경우  대용량 MyISAM 테이블은 crash 후 복구하는 데 많은 시간이 걸림 – 정적인 Table, 로그 Table • Aria Storage Engine – Aria is a crash safe MyISAM + more – This should speed up some GROUP BY and DISTINCT queries because Aria has better caching than MyISAM
  • 60. 60 Memory • Memory Engine 특징 – Non-transacional Storage Engine – Memory 에 모든 data 가 저장됨 – 고정길이열의 열만을 사용 가능함 (varchar, blob, text 컬럼 사용불가) – 타 Engine 에 비해 DML 속도가 월등히 빠름 (고정 길이열 기반으로 인함) – Server 의 재 구동 시 Data는 모두 소실 – 동등조건( ex) where a=10 ) 검색에 HASH기반 검색을 제공 – 범위 검색 시 Index 를 사용할 수 없음 – temporary table 과 다르게 타 세션에서도 조회가 가능
  • 61. 61 Archive • Archive Engine 특징 – 자동적인 Data 압축을 지원 – 다른 Storage Engine 대비 80%의 저장공간 절약 – 실제적인 저장용량의 제한 없슴 – Index 미지원 – 빠른 Insert 속도를 위해 특별한 입력 버퍼를 제공 – Insert와 select만을 지원 – row레벨 Lock을 지원 – Backup 및 특정 시점으로의 복구 지원 – 데이터 웨어하우스, 데이터 감사등에 사용
  • 62. 62 FederatedX • FederatedX Engine 특징 – MySQL 5.0에 Federated engine 도입 – 원격의 물리적 Data 객체에 대한 논리적 Data 객체를 생성 – 하나의 Data 객체에서 다른 타겟 객체로의 ‘포인터’역할 – 원격 Data 접근을 위한 특별한 미들웨어가 필요하지 않음 – 실행 속도는 네트워크 요소에 따라 좌우됨 – 실제 Data 객체의 Engine 특성에 따라 처리됨 – Table 정의를 통한 SSL보안 처리 – 모든 SQL 오퍼레이션 지원( as per target object ) – 분산데이터베이스 환경에서 사용
  • 64. 64 InnoDB • Heikki Tuuri 에 의해 개발됨 • Oracle Corp 에서 소유권을 가지고 있음 • XtraDB는 Percona의 open source • 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/
  • 65. 65 InnoDB • Transaction-Safe 스토리지 엔진 • Primary Key 에 의한 클러스터링 – 모든 InnoDB 테이블은 기본적으로 PK 를 기준으로 클러스터링되어 저장  PK 에 의한 range 스캔에 최적화  optimizer 가 PK 에 의한 실행계획을 더 선호함  Oracle 의 IOT 와 동일한 구조 • 읽기 일관성 보장 ( Non-locking consistent read ) – MVCC ( Multi Version Concurrency Control ) • Foreign Key 지원
  • 66. 66 InnoDB • 자동 Deadlock 감지 – Deadlock 발생시 Server 에서 바로 감지 – Deadlock 유발한 트랜잭션 중 Rollback이 가장 용이한 트랜잭션 강제 종료 – show engine innodb status 구문 혹은 monitoring 을 활성화해서 확인 • 자동 장애 복구 – MariaDB 서버의 구동시 완료되지 못한 트랜잭션 복구 – disk에 일부만 기록된 데이터 페이지 복구 – mysqld_safe 를 이용한 mysqld 의 모니터링 및 장애시 restart 수행
  • 67. 67 Using InnoDB • 동시접속 퍼포먼스가 뛰어나 대용량 데이터 처리에 적합 • 메인 메모리내 데이터 캐싱 및 인덱싱 위한 버퍼 풀(pool)을 관리 – innodb_buffer_pool_size • 테이블과 인덱스를 테이블 스페이스에 저장 – 테이블 스페이스를 몇개의 서버파일이나 disk 파티션으로 구성 cf) MyISAM은 테이블과 인덱스를 각각 분리된 파일로 관리 • InnoDB 테이블은 OS 파일 사이즈에 독립적인 파일 사이즈를 가짐 • 트랜잭션의 동시성 퍼포먼스가 필요한 대용량 사이트에 적합
  • 68. 69 InnoDB Server Thread Connection Manager Thread Signal Thread Connection Thread Connection Thread Connection Thread Connection Thread Connection Thread Connection Thread ... Client Client Client Client Client Client Insert Buffer Thread InnoDB File I/O Threads MariaDB – innodb plugin Log Thread Read Thread Write Thread Storage Engine innodb_read_io_threads innodb_write_io_threads
  • 69. 70 InnoDB Memory / Disk 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 InnDB-std : can grow unlimitedly XtraDB : innodb_dict_size_limit XtraDB : Check sizes in SHOW ENGINE INNODB STATUS innodb_buffer_pool_size is cretical paramter Thumb rule : 60-80% of RAM Table1.ibd Table2.ibd Table3.ibd Primary Key == data Secondary indexes .ibd are placed separetely if innodb_file_per_table=1 Ohterwise 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_rsegments 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 backgroud “log thread” on disk with fsync() command. innodb_flush_log_at_trx_commit controls how to fsync innodb_log_buffer_siz e 4M-16M is good value Changes are fiex in log file via log buffer Insert buffer is written from BP to disk Pages are written in background innodb_write_io_threads. innodb_fulsh_method=O_DIRECT To avid 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
  • 70. 71 InnoDB Log / Data Disk Write Log Buffer ( buffered log records ) Buffer Pool ( buffered data pages ) Additional Mem Pool Commit ( + checkpoint ) Log File 1 Log File 2 Log File 3 RedoLog ibdata1 data file checkpoint In Memory On Disk LogFilesTablespace Undo Log ibdata2 data file iblogfile1 innodb_file_per_table=0 innodb_max_purge_log
  • 71. 72 InnoDB Redo log Write commit – Write to disk commit Write & Flush to disk - every 1 Second Log FilesO/S bufferLog BufferInnoDB 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=?innodb_flush_log_at_trx_commit
  • 72. 73 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 filecheckpoint 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
  • 73. 74 InnoDB Parameter • INNODB_DATA_HOME_DIR – 테이블스페이스 파일의 생성 위치 설정 • INNODB_DATA_FILE_PATH – 테이블스페이스 파일 명 및 크기, 옵션 설정 – ibdata1:256M:autoextend:max:2000M  ibdata1라는 파일명으로 생성  256MB의 고정크기로 최초 생성  256MB가 넘을 경우 “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
  • 74. 75 InnoDB Parameter • INNODB_FILE_PER_TABLE – 공용 테이블스페이스 사용 대신에 테이블 별 테이블스페이스 사용 옵션 – TableName.idb 파일 생성 • INNODB_BUFFER_POOL_SIZE – 테이블의 데이터와 인덱스를 캐시하기 위해 사용하는 메모리 버퍼의 크기 – 크게 설정하면 할수록, data의 disk I/O가 적어짐 – 전체 물리메모리의 60~80%로 설정하나, 세션수가 많으면 50%로 설정 – ORACLE DB_BUFFER_CACHE와 유사 • INNODB_BUFFER_POOL_DUMP_AT_SHUTDOWN/STARTUP – 데이터와 인덱스 캐시를 위한 메모리 버퍼의 재사용을 위해 중지/재시작 시 버퍼정보를 파일에 기록/로딩함.
  • 75. 76 InnoDB Parameter • INNODB_LOG_FILE_SIZE – Redo 로그 파일의 크기 설정 – 순차적으로 파일이 일정한 크기와 용량으로 순환식으로 생성 – The combined size can be no more than 4GB prior to MariaDB 10.0, and no more than 512GB in MariaDB 10.0 and later – Larger values mean less disk I/O due to less flushing checkpoint activity, but also slower recovery from a crash – Default Value: 50331648 (48MB) (from MariaDB 10.0), 5242880 (5MB) (before MariaDB 10.0) • INNODB_LOG_GROUP_HOME_DIR – Redo 로그 파일에 대한 디렉토리 경로 설정 • INNODB_LOG_FILES_IN_GROUP – Redo 로그파일 개수 • INNODB_LOG_BUFFER_SIZE – Redo 로그 파일을 기록하기 위한 버퍼 사이즈
  • 76. 77 InnoDB Parameter • INNODB_LOCK_WAIT_TIMEOUT – 롤백이 진행되기 전에 락을 대기하는 시간 ( 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초 간격으로 동작  3 : (from MariaDB 10.0) Emulates MariaDB 5.5 group commit (3 syncs per group commit)
  • 77. 78 InnoDB Parameter • INNODB_FLUSH_METHOD – Flush 명령어 방식 설정, 디폴트는 fdatasync  fdatasync : fsync()를 사용해서 데이터와 로그 파일을 flush  O_SYNC : 로그 파일을 열고 flush 하지만, 데이터 파일을 flush하기 위해서는 fsync()를 사용  O_DIRECT : O_DIRECT를 사용해서 데이터 파일을 열고, 데이터 파일과 로그 파 일을 flush (몇몇 GNU/Linux 버전에서 사용 가능함)  Windows에서는 flush 방식은 항상 async_unbuffered 사용
  • 78. 79 InnoDB Statistics Parameter • 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 수
  • 79. 80 InnoDB Statistics Parameter • INNODB_STATS_AUTO_RECALC – Default는 on, table에서 10% 이상의 row가 변경되면 자동으로 persistent statistics를 재계산 함 • INNODB_STATS_ON_METADATA – Show table status, Show index 또는 INFORMATION_SCHEMA의 tables/statisticstable 접근 시 자동으로 통계정보 수집 – Default Value: OFF (from MariaDB 10.0), ON (before MariaDB 10.0)
  • 81. 82 ColumnStore Storage Engine • SCALING BIG DATA ANALYTICS – Harvest new value from large historical datasets by deriving new insights – Support growth in your business, while continue to deliver high service levels for data analytics
  • 82. 83 ColumnStore Storage Engine • DATA WAREHOUSING – Selective column based queries – Large number of dimensions • ANALYTICS REQUIRING – Complex Joins, Windowing Functions • HIGH PERFORMANCE ANALYTICS ON LARGE VOLUME OF DATA – Reporting and analysis on billions of rows – From datasets containing trillions of rows – Terabytes to Petabytes of datasets
  • 84. 85 ColumnStore Storage Engine • USER MODULES – mysqld : The MariaDB server – ExeMgr : MariaDB’s interface to ColumnStore – cpimport : high-performance data import • QUERY PROCESSING - UM – SQL Operations are translated into thousands of Primitives – Parallel/Distributed SQL – Extensible with Parallel/Distributed UDFs – Query is parsed by mysqld on UM node – Parsed query handed over to ExeMgr on UM node – ExeMgr breaks down the query in primitive operations
  • 85. 86 ColumnStore Storage Engine • PERFORMANCE MODULES – PrimProc : Primitives Processor – WriteEngineServer : Database file writing processor – DMLProc : DML writes processor – DDLProc : DDL processor • QUERY PROCESSING - PM – Primitives are processed on PM – One thread working on a range of rows – Typically 1/2 million rows, stored in a few hundred blocks of data – Execute all column operations required (restriction and projection) – Execute any group by/aggregation against local data – Each primitive executes in a fraction of a second – Primitives are run in parallel and fully distributed
  • 88. 89 Connect Storage Engine • MAIN FEATURES – 외부 데이터 형식(DBMS, file, datasource, virtual) 연결 – ODBC, JDBC, MySQL or MongoDB API 통해 DataSource에 직접 연결 – JSON, XML, HTML파일 및 JSON UDF통한 NOSQL 쿼리지원 – WHERE절에 대한 푸시다운 – Special & Virtual Columns 지원 – 다중테이블의 병렬실행 가능 – 서브 테이블별 파티셔닝 지원 – SELECT, UPDATE 및 DELETE에 대한 MRR 지원
  • 89. 90 Connect Storage Engine • CONNECT PARAMETERS – connect_class_path : java class path – connect_conv_size : text유형 변환 시 varchar크기 – connect_enable_mongo : mongo table type enable – connect_exact_info : 정확한 레코드번호 리턴 여부 – connect_index_map : 인덱스 파일에 대한 파일매핑 활성화여부 – connect_java_wrapper : java wrapper – connect_json_grp_size : JSON 집계함수의 최대 행 수 – connect_json_null : JSON NULL값 – connect_jvm_path : JVM 경로 – connect_type_conv : TEXT 컬럼의 변환 처리 옵션 – connect_use_tempfile – connect_work_size : 메모리할당에 사용되는 크기 – connect_xtrace : 콘솔추적값
  • 91. 92 Server System Variables • Global variables • Server startup 때 사용: command-line 과 option이용 • Server 구동 중에는 SET 명령어로 바꿀 수 있음 – System variable 이름과 값 보기  mysqld --verbose –help – 현재 사용중인 server variable 보기  SHOW VARIBALES
  • 92. 93 Dynamic Server Setting • 동적 변수와 정적 변수 – 동적변수  기동중인 상태에서 변경 가능 한 변수 – 정적변수  기동중인 상태에서 변경 불가능한 변수로 설정파일을 통해 변경 후 MariaDB 서비스를 재시작 해야 함 • 세션변수와 글로벌 변수 – 세션변수  MariaDB 클라이언트가 MariaDB 서버에 접속 할 때 기본적으로 부여하는 옵션의 기본값을 제어하는데 사용하는 변수 – 글로벌변수  하나의 MariaDB서버 인스턴스에서 전체적으로 영향을 미치는 시스템 변수  SHOW GLOBAL VARIABLES로 확인
  • 93. 94 Dynamic Server Setting • 실시간 서버옵션 설정(동적변수 변경) 예 – GLOBAL VARIABLES 수정  SET global log_slow_queries = ON; – SESSION VARIABLES 수정  SET read_buffer_size=262144;  SET session read_buffer_size=262144; • 서버가 실행되는 동안 설정파일 변경 없이 시스템변수를 변경 할 수 있음 • 동적변수 설정 시 주의사항 – MB,GB와 같은 단위 표기법 사용불가 – 2 * 1024 * 1024 같은 수식 사용 가능
  • 94. 95 Buffer & Cache variables • KEY_BUFFER_SIZE – dynamic / global – Index block에서 사용하는 buffer 크기 – Index가 많은 table에서 insert, delete 작업이 많은 경우 늘려줌 • JOIN_BUFFER_SIZE – dynamic / global / session – Full join 에서 사용하는 버퍼의 크기 • MAX_JOIN_SIZE – dynamic / global / session – 최대 join 되는 크기
  • 95. 96 Buffer & Cache variables • READ_BUFFER_SIZE – dynamic / global / session – 순차적인 검색을 하는 thread에 할당하는 버퍼의 크기 • SORT_BUFFER_SIZE – dynamic / global / session – 정렬할 때 thread에 할당하는 버퍼의 크기 – Order by나 group by를 빠르게 하려면 sort_buffer size를 증가시킴
  • 96. 97 Buffer & Cache variables • TABLE_OPEN_CACHE – dynamic / global – 모든 thread에서 열 수 있는 TABLE 수 • QUERY_CACHE_SIZE – dynamic / global – 기 사용된 SQL 쿼리를 저장해 놓는 cache 크기 – 같은 쿼리를 반복적으로 사용하는 경우가 많으면 증가
  • 97. 98 Buffer & Cache variables • THREAD_CACHE_SIZE – dynamic / global – cache 에 저장해둔 thread 숫자 – thread 생성시 cahce 에 thread 가 있는 경우 생성하지 않고 재사용함 • TABLE_OPEN_CACHE_INSTANCES – static / global – Removed MariaDB 10.0.7, reintroduced MariaDB 10.2.2 – Default Value: 8 (>= MariaDB 10.2.2), 1 (<= MariaDB 10.0.7)
  • 98. 99 Server System Status • Global status • Server 구동중에서의 상태값 확인 – 현재 사용중인 server status 보기  SHOW STATUS
  • 99. 100 Status Monitor • CONNECTIONS – 연결시도 횟수 = 사용량 • ABORTED_CONNECTS – 연결을 시도해서 실패한 횟수, MAX_USED_CONNECTIONS 를 확인 • MAX_USED_CONNECTIONS – 최대 동시 접속자수 – 이 값을 보고 MAX_CONNECTIONS의 값을 조정 • ABORTED_CLIENTS – 클라이언트에서 연결이 적절하게 닫지 못해서 취소된 연결 횟수 – 네트워크 연결에 문제 가능성 높음
  • 100. 101 Status Monitor • KEY_READS – disk에서 물리적으로 키 BLOCK을 읽은 횟수 – 시스템의 성능을 고려하여 가능한 만큼 KEY_BUFFER_SIZE를 증가시켜 줌 • KEY_READS, KEY_READ_REQUEST – Cache Hit Ratio = KEY_READS/KEY_READ_REQUEST – Cache Hit Ratio 값이 클 경우 KEY_BUFFER_SIZE 조정 • SELECT_FULL_JOIN – INDEX를 사용하지 않은 조인 쿼리 실행 횟수 – 이 값이 너무 크면 TABLE의 INDEX 검토 – 쿼리 튜닝 검토
  • 101. 102 Status Monitor Parameter • OPENED_TABLES – 열었던 TABLE 수 – 이 값이 너무 크면 TABLE_CACHE 값을 증가 • QUESTIONS – SERVER로 보낸 쿼리 횟수 – 초당 쿼리 수: QUESTIONS와 UPTIME 이용 • TABLE_LOCKS_WAITED – TABLE LOCK을 위해 대기한 시간
  • 104. 105 INFORMATION_SCHEMA • 메타데이터를 저장하는 데이터베이스/스키마 • 가상데이터베이스 • 정보를 얻기 위해 SELECT사용
  • 105. 106 INFORMATION_SCHEMA • INFORMATION_SCHEMA 테이블 항목 설명 CHARACTER_SETS 사용 가능한 캐릭터 셋 COLLATIONS 각각의 캐릭터 셋을 위한 콜래이션 COLLATION_CHARACTER_SET_AP PLICABILITY 캐릭터 셋은 각각의 콜래이션에 적용 COLUMNS 테이블 안에 컬럼 COLUMN_PRIVILEGES 컬럼 권한은 사용자 계정에 의해서 따름 ENGINES 스토리지 엔진 EVENTS 스케줄된 이벤트 KEY_COLUMN_USAGE 키 컬럼 제한
  • 106. 107 INFORMATION_SCHEMA 항목 설명 PARTITIONS 테이블 파티션 PLUGINS 서버 플러그인 PROCESSLIST 스레드 운영하기 REFERENTIAL_CONSTRAINTS foreign keys ROUTINES 저장 프로시저와 함수 SCHEMATA 데이터베이스 SCHEMA_PRIVILEGES 데이터베이스 권한은 사용자 계정에 따름 STATISTICS 테이블 통계 TABLES 데이터베이스 안에 테이블 TABLE_CONSTRAINTS 테이블 제약 TABLE_PRIVILEGES 테이블 권한은 사용자 계정에 따름
  • 107. 108 INFORMATION_SCHEMA 항목 설명 TRIGGERS 데이터베이스 안에 트리거 USER_PRIVILEGES 전역 권한은 사용자 권한에 따름 VIEWS 뷰 INNODB_LOCKS 트랜잭션의 잠금 요청에 대한 대기정보 및 차단하는 정보 INNODB_LOCK_WAITS 트랜잭션 차단된 대기정보 INNODB_TRX 실행중인 트랜잭션 정보 TokuDB_file_map 디렉토리명 및 테이블, 인덱스 파일명
  • 108. 109 SHOW Syntax • SHOW DATABASES • SHOW [FULL] TABLES • SHOW [FULL] COLUMNS • SHOW INDEX • SHOW CHARACTER SET • SHOW COLLATION
  • 109. 110 DESCRIBE Syntax • 문법 – DESCRIBE 테이블 명 – DESC 테이블 명 – SHOW COLUMNS FROM 테이블 명 • DESCRIBE는 FROM을 지원하지 않음 • INFORMATION_SCHEMA 테이블 정보를 보여줌
  • 111. 112 MariaDB LOG Type • 에러로그(error log) – 서버 시작 및 종료 기록을 포함 – 문제가 되는 쿼리에 대한 로그 – 설정 확인  log_error = /ohnew/log/error/maria-error.log • 일반쿼리로그(general query log) – 클라이언트의 연결, 클라이언트로부터의 쿼리 등 다양한 이벤트가 기록 – 서버로 수신되는 모든 쿼리를 기록 – 서버의 활동상황(누가 연결하며, 무엇을 하고 있는지)을 감시하는데 유용 – 설정 확인  general_log = ON  general_log_file = /ohnew/log/general/maria-general.log
  • 112. 113 MariaDB LOG Type • 이진로그( binary log ) – UPDATE, DELTE, INSERT, CREATE TABLE, GRANT 등의 명령문에 의해서 수정 이 발생한 명령문을 기록 – 서버가 비정상 종료할 경우, 백업 이후의 데이터를 복원하기 위해 사용 • 릴레이 로그( relay log ) – 서버가 리플리케이션 슬레이브(replication slave) 서버로 동작하는 경우, 마스터 서버로부터 수신한 데이터 수정 이벤트를 기록
  • 113. 114 MariaDB Log Output • log_output을 FILE 또는 TABLE로 설정 할 수 있음 • FILE – 로그 데이터가 파일에 기록 됨 • TABLE – 로그 데이터가 테이블에 기록 됨 – 일반 쿼리 로그 : mysql.general_log – 느린 쿼리 로그 : mysql.slow_log
  • 114. 115 Variables & Log • Server Variable 관리 – Server Variable 정보를 DB 화 하여 관리 – error code 정보를 DB 화 하여 관리 – 필요시 쉽게 찾아 적용할 수 있도록 테이블화하여 관리 • Slow & General Log 관리 – log_output 을 table 로 관리하면 추후 장애시 확인이 용이 – file 형태로 관리시 mysqlsla 혹은 mysqldumpslow 의 유틸을 이용하여 분 석 – 파일이 일정사이즈가 되면 rename 되도록 관리
  • 117. 118 세부내용 ㆍMariaDB transaction ㆍLOCKING의 개념 ㆍMariaDB InnoDB Locking ㆍMariaDB deadlock ㆍMariaDB 보안 수준 Section 3
  • 119. 120 Transaction • Transaction – 트랜잭션(Transaction) 은 더 이상 나뉠 수 없는 하나의 업무단위 – 데이터베이스 내에서 한꺼번에 수행되어야 할 일련의 연산 – All or Nothing – Commit 시 모든 작업 결과는 데이터베이스에 반영 – Rollback 시 모든 작업 결과가 데이터베이스에 미반영
  • 121. 122 Transaction • 예시) 은행 입출금 1. 카드삽입 2. 거래선택 3. 비밀번호입력4. 거래완료 YES YES YES NO NO NO YES/NO? YES/NO? YES/NO?
  • 122. 123 Transaction • ACID – 원자성 (Atomicity)  Transaction 은 더 이상 분류할 수 없는 작업 단위  모든 데이터 수정 작업이 수행되거나 되지 않아야 함 – 일관성 (Consistency)  Business Logic 에 위배되는 일관되지 않은 Transaction 은 중단되어야 함 – 독립성 (격리성) (Isolation)  동시 Transaction 에 의한 수정은 다른 동시 Transaction 에 의한 수정과 격리  Transaction 중간의 데이터는 변경을 수행한 Transaction 에서만 확인됨 – 영속성 (Durability)  Transaction 이 완료되면 영구적으로 시스템에 적용  시스템 오류와 무관하게 데이터는 보존
  • 123. 124 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. 125 Isolation Level Isolation Level Phenomena Allowed Read uncommitted Dirty Read Non Repeatable Read Phantoms Read committed Non Repeatable Read Phantoms Repeatable read Phantoms Serializable Concurrency Row Row High High Consistency
  • 125. 126 Isolation Level • READ UNCOMMITTED BEGIN INSERT COMMIT select name from School where ID=501 결과값 : Dorothy ID NAME 500 Hans 501 Dorothy School ID NAME 500 Hans 501 Dorothy ID NAME 500 Hans 501 Dorothy TransactionA TransactionB Dirty Read
  • 126. 127 Isolation Level • READ COMMITTED TransactionA TransactionB BEGIN COMMIT SELECT name FROM School WHERE ID=501 결과값 : Dorothy ID NAME 500 Hans 501 Ally UNDO ID NAME 501 Dorothy ID NAME 500 Hans 501 Ally ID NAME 500 Hans 501 Dorothy School UPDATE SET name = ‘Ally’ WHERE ID = 501 Undo 영역에 name = Dorothy 데이터 백업
  • 127. 128 Isolation Level • NON-REPEATABLE READ TransactionA TransactionB BEGIN COMMIT SELECT ID FROM School WHERE NAME = ‘Ally’ 결과값 : 501 ID NAME 500 Hans 501 Ally ID NAME 500 Hans 501 Ally ID NAME 500 Hans 501 Dorothy School UPDATE SET name = ‘Ally’ WHERE ID = 501 BEGIN SELECT ID FROM School WHERE NAME = ‘Ally’ 결과값 : empty
  • 128. 129 Isolation Level • REPEATABLE READ TransactionA TransactionB COMMIT SELECT .. ID = 501 결과값 : Dorothy TRX-ID ID NAME 1 500 Hans 1 501 Dorothy School UPDATE SET name = ‘Ally’ BEGIN (Trx ID : 2 ) BEGIN (Trx ID : 3 ) UNDO TRX-ID ID NAME 1 501 Dorothy TRX-ID ID NAME 1 500 Hans 3 501 Ally Undo 영역 백업 TRX-ID ID NAME 1 500 Hans 3 501 Ally UNDO TRX-ID ID NAME 1 501 Dorothy 결과값 : Dorothy SELECT .. ID = 501 TRX-ID 3 이 변경전 Undo 영역 백업 데이터
  • 129. 130 Isolation Level • PHANTOM READ TransactionA TransactionB COMMIT SELECT NAME FROM School WHERE ID > 500 결과값 : Ally TRX-ID ID NAME 1 500 Hans 1 501 Ally School INSERT INTO School values (502, ‘Kerry’) BEGIN (Trx ID : 2 ) BEGIN (Trx ID : 3 ) TRX-ID ID NAME 1 500 Hans 1 501 Ally TRX-ID ID NAME 1 500 Hans 1 501 Ally 3 502 Kerry 결과값 : Ally, Kerry TRX-ID ID NAME 1 500 Hans 1 501 Ally 3 502 Kerry SELECT NAME FROM School WHERE ID > 500
  • 130. 131 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 발생 가능  InnoDB 의 경우 Gap Lock 방식으로 PHANTOM READ 발생하지 않음 • SERIALIZABLE – 읽기 작업 시에도 공유 잠금을 획득 해야 함
  • 131. 132 Transaction • Undo 의 필요성 – Transaction 수행 중에 수정된 페이지를 타 세션에서 조회 ( MVCC ) – Transaction 의 ACID 를 보장하기 위함 – Transaction 의 Rollback 수행을 정상적으로 처리하기 위함 • Redo 의 필요성 – Commit 한 Transaction 의 수정된 내용에 대해 일관성을 보장하기 위함 – Database crash 복구시 데이터의 일관성을 보장하기 위함 – Database 의 지연된 쓰기를 지원하여 performance 향상을 도와주기 위함
  • 132. 133  Multi-Version Concurrency Control InnoDB MVCC SessionA SessionB
  • 133. 134 InnoDB MVCC • InnoDB MVCC – Snapshot과 거의 흡사한 개념 – row-level locking DBMS들의 일반적인 기능 – Lock 을 사용하지 않는 일괄된 읽기를 제공 – InnoDB는 Undo log ( ibdata file ) 를 이용 – DML 발생시 변경 대상 레코드에 대해서 Undo 를 이용하여 읽기 일관성을 제공하는 방식
  • 135. 136 Locking • Lock 이란? – 데이터베이스에서 동일 자원 사용시 자원의 경합을 최소화 하기 위한 장치 – Transaction 의 순차적 진행을 보장하기 위한 직렬화 장치 – 다중 Transaction 의 일관성과 무결성을 유지하기 위한 장치 – MVCC 를 구현하기 위한 필요 장치 – 사용의도에 따라 공유, 배타, 갱신, 의도, 스키마 lock 등이 존재
  • 136. 137 MariaDB Locking • Table Lock – A세션에서 테이블 자원을 사용하기 위하여 데이터를 읽거나 쓰기를 할때 타세션에서는 테이블 자원에 대한 사용을 제한 하는 lock – A세션에서 명시적으로 테이블 lock 을 사용하면 해당 세션에서 lock 을 해지하지 않으면 다른 세션에서는 접근을 할 수 없음 – 테이블 lock 을 사용려면 테이블 lock 권한을 가지고 있어야 가능
  • 137. 138 MariaDB Locking • Table Write Lock – TABLE level Lock – lock을 건 thread 에서만 read, write가 가능 – lock 을 건 thread 를 제외하고는 해당 테이블에 대해 read, write 불가능 – unlock 은 lock 을 건 thread 에서만 가능
  • 140. 141 MariaDB Locking • Table Read Lock – TABLE level Lock – 모든 thread 에서 select 가능 – 모든 thread 에서 DML 불가능 – unlock 은 lock 을 건 thread 에서만 가능 – lock_wait_timeout parameter 로 대기시간 설정 가능
  • 141. 142 MariaDB Locking • LOW_PRIORITY – MariaDB에서 기본적으로 WRITE LOCK 이 READ LOCK 보다 우선됨 – DML 수행의 우선 순위를 변경시 이용  LOW_PRIORITY : 다른 클라이언트가 SELECT 를 모두 마칠때까지 기다린 후 실행  DELAYED : 데이터를 추가할 경우에 해당되며, 메모리에 저장해 놓고 처리함 a. 클라이언트는 SELECT 가 끝날때까지 기다리지 않음 b. 항상 '1 rows affected' 의 결과를 냄  IGNORE : PRIMARY KEY, UNIQUE KEY 에 대한 동일한 데이터를 추가, 수정, 삭제할 경우에 해당되며, 에러를 무시하고 계속 진행함
  • 142. 143 MariaDB Locking • Global Lock – 글로벌 읽기 잠금 (Global Read Lock) – A세션 자체에서 글로벌하게 READ LOCK 이 필요할 경우 사용
  • 143. 144 MariaDB Locking • Name Lock – 테이블 이름이 변경/삭제시 테이블 레벨에서 묵시적인 네임 lock 을 사용 – 명시적으로 USER 가 설정할 수 없음 – MariaDB Internal Lock
  • 144. 145 MariaDB Locking • User Lock – User Level Lock – Lock 의 이름과 timeout 을 정의해서 사용 – GET_LOCK(str, timeout), RELEASE_LOCK(str), IS_FREE_LOCK(str) 함수 사용 – 문자열에 대해 사용중이면 0, 사용중이지 않으면 1 을 RETURN
  • 145. 146 Metadata locking • Metadata Lock – 데이터 이외의 메타데이터 변경시 발생하는 lock – 주로 table, trigger 등을 drop 또는 alter 할 때 발생 Metalock 발생
  • 146. 147 Storage Engine Locking Level InnoDB Row-level locking MyISAM Memory Merge Table-level locking Storage Engine Locking  Row-level lock 은 Table-level 에 비해 많은 메모리를 사용  Row-level lock 은 Table-level lock 에 비해 많은 lock 이 필요  상대적으로 Row-level lock 이 Table-level lock 보다 자원을 더 소모함
  • 147. 148 • InnoDB Lock – InnoDB Row Level Lock 지원 – Shared, Exclusive, Intention Lock 을 이용 – 동시에 같은 자원을 사용하는 경우 transaction 의 순서대로 진행 – 현재 존재하는 Lock 과 호환성이 있는 경우의 lock 은 승인됨 – Deadlock 이 발생하는 경우 undo 가 높은 transaction 이 Rollback 됨 InnoDB Locking
  • 148. 149 X IX S IS X Conflict Conflict Conflict Conflict IX Conflict Compatible Conflict Compatible S Conflict Conflict Compatible Compatible IS Conflict Compatible Compatible Compatible  Shared ( S ) lock  Exclusive ( X ) lock  Intention shared ( IS ) lock  Intention exclusive ( IX ) lock InnoDB Locking
  • 149. 150 InnoDB Locking • InnoDB Lock 확인 방법 – SHOW ENGINE INNODB STATUS – Information_schema 의 INNODB_TRX, INNODB_LOCKS, INNODB_LOCK_WAIT  INNODB_TRX : 어떤 트랜잭션이 어떤 프로세스에 의해 기동되고, 어떤 lock을 기다리는지를 관리  INNODB_LOCKS : 어떤 lock이 존재하는지 관리  INNODB_LOCK_WAIT : lock에 의한 프로세스 간의 의존 관계를 관리 – InnoDB Lock monitoring 으로 확인  create table innodb_lock_monitor (a int) engine = innodb ;  error.log 에 일정 간격으로 lock 정보가 저장됨
  • 150. 151 InnoDB Lock Escalation • InnoDB Lock Escalation – innodb_lock_tables  0 : LOCK TABLES doesn’t work  1 : LOCK TABLE work like set autocommit = 0 – The lock information in InnoDB is stored so space-efficiently that lock escalation is not needed – Typically, several users are permitted to lock every row in InnoDB tables, or any random subset of the rows, without causing InnoDB memory exhaustion
  • 152. 153 InnoDB Internal Lock • Record Lock – Record 자체만을 잠그는 lock – Index 의 Record 를 잠금 – 인덱스가 없는 경우에는 내부적으로 생성된 cluster PK 를 이용하여 잠금 – primary key, unique index 에 의한 변경작업은 Record lock 만을 이용 • Gap Lock – Record 와 인접한 Record 사이를 잠그는 lock – Record 자체를 잠그지 않음 – Record 사이에 새로운 Record 가 생기는 것을 제어 ( Phantom 방지 ) – 자체적으로 동작하지 않고 Next Key Lock 의 일부로 동작 – “dorothy” 데이터에 변경작업이 발생하는 경우 “wwcck” ~ “dorothy”, “dorothy” ~ “lcd” 사이에 gap lock 으로 잠금
  • 153. 154 InnoDB Internal Lock • Next Key Lock – Record Lock + Gap Lock – “dorothy” 데이터에 변경작업이 일어나는 경우 “wwcck” ~ Gap + Record ~ “lcd” 범위에 대해 lock 이 발생함 – binlog format 을 statement 로 사용하여 Repeatable read isolation level 을 사용하는 경우에 Next Key Lock 을 사용 • Auto-increment Lock – Auto Increment 속성의 컬럼을 가진 테이블에 Insert가 실행되는 경우 – Table Level Lock – Statement Level Lock 으로 SQL 이 수행되면 해제됨 – Transaction Level 의 lock 이 아니므로 이미 사용된 Auto-increment 는 Rollback 되지 않음 – innodb_autoinc_lock_mode 로 제어  1 : insert 에 대해 lock 을 걸지 않음  2 : 어떠한 경우에도 lock 을 걸지 않음
  • 155. 156 Deadlock • Deadlock 개요 – Transaction Database 의 공통 문제 – Application 설계의 문제로 인해 발생 – show engine innodb status 명령으로 최신의 deadlock 정보 확인 가능 – InnoDB Engine 사용시 Deadlock 자동 감지 및 즉시 처리 – InnoDB Engine 에서 Deadlock 발생시 undo 가 작은 transaction rollback
  • 156. 157 Deadlock • Deadlock 방지 – Application 에서 Deadlock 으로 종료된 Transaction 을 재수행하도록 작성필요 – Transaction 의 단위를 작게 나누어서 실행 – 고정순서로 테이블과 열에 접근하도록 Application 설계 – Index 설계를 통해서 Deadlock 발생을 최소화
  • 157. 158 Deadlock Detection • Show Engine Innodb Status G
  • 158. 159 Deadlock Detection • Show Engine Innodb Status G – 구문 실행 시간  LOG 의 시작부분에 status 파일의 시간 표현 – 자료 수집 시간  Per second averages calculated from the 52 seconds – SEMAPHORES  운영체제상에서 SEMAPHORES 에 대한 정보를 표현  wait 발생 여부와 spin wait 및 spin round 의 발생 여부 정보를 표현 – TRANSACTIONS  현재 실행중인 transaction 에 대한 정보  Trx id 는 transaction 의 현재 id – FILE I/O  FILE I/O helper thread 동작 정보를 표현
  • 159. 160 Deadlock Detection • Show Engine Innodb Status G – INSERT BUFFER AND ADAPTIVE HASH INDEX  insert buffer 와 adaptive hash 정보 표현 – BUFFER POOL AND MEMORY  InnoDB Buffer Pool 사용상태와 Memory 사용 상태 표현 – LASTEST DETECTED DEADLOCK / LASTEST FOREIGN KEY ERROR  최신의 deadlock 정보 / 최신의 foreign key error 정보 – ROW OPERATIONS  DML 및 select 한 row operation 정보 표현 – LOGS  InnoDB 의 log 정보 확인  LSN 및 flush 된 log 번호 확인 가능
  • 161. 162 MariaDB Security • MariaDB Security 를 위한 설정 – MariaDB 데이터베이스는 chroot 환경에서 실행 – mysqld 프로세스는 다른 프로세스가 사용하지 않는 유일한 UID/GID로 실행 – 인가된 계정을 제외한 시스템 계정은 로컬 엑세스만 허용 – root user 계정의 패스워드는 추정하기 어렵도록 설정 – 관리자(root) 어카운트명을 변경 – history 의 주기적인 삭제 필요 – 데이터베이스로의 익명 접속(anonymous 계정 사용)을 금지 – test 및 미사용 데이터베이스와 테이블을 모두 삭제 – local-infile 파일 경로 제한 – load_file() 함수의 사용 권한 제한 – DB 관련 directory 의 권한 제한 – mysql user, db, table, column 권한 설정
  • 162. 163 MariaDB Security • Remote Access 제한 – default port 인 3306 을 차단 혹은 타 port 로 변경 – port 를 변경하여도 mysql.sock socket 으로 통신은 가능 – skip-networking 설정시 3306/tcp 포트로 접근 불가능 – Remote 데이터 백업등 Remote 작업 수행시 ssh 사용 • 로컬 보안 개선 – LOAD DATA LOCAL INFILE 제한 – /ohnew/mariadb/etc/my.cnf 의 [mysqld] 난에 다음을 추가
  • 163. 164 MariaDB Security • 관리자(root) 패스워드 변경 – mysql 클라이언트를 실행하여 패스워드 변경 – 기본적으로 root 계정에 패스워드가 설정되어 있지 않음 – 쉽게 유추할 수 없는 패스워드로 설정 – mysql 접속시 password 가 노출되지 않도록 –p 옵션으로 접속 – mysqladmin 를 이용하여 변경하는 것이 보안에 뛰어남 – ps aux 커맨드사용시 타 사용자가 password 를 확인할 수 있음 – history 파일(~/.history, ~/.bash_history)을 보면 패스워드가 쉽게 노출
  • 164. 165 MariaDB Security • 기본제공되는 사용자/데이터베이스 삭제 – MariaDB 설치시 제공하는 anonymous 계정과 test 데이터베이스 삭제 – 사용되지 않는 root 를 제외한 계정을 정리하도록 권고 – 익명 접속으로 데이터베이스를 설정하는 것을 막을 수 있음
  • 165. 166 MariaDB Security • 관리자 (root) 계정 변경 – default 설정인 관리자 어카운트(root) 를 말함 – 무차별 대입 & 딕셔너리 공격 등으로 추측해 내기 어려운 이름으로 변경 – root 계정을 제외하고 타 계정에 권한만 부여하여 사용 • history 삭제 – MariaDB daemon 에 의해 실행되는 모든 SQL 커맨드가 저장 – ~/.mysql_history 에 기록됨 – 패스워드 정보도 노출될 수 있음
  • 168. 169 세부내용 ㆍMariaDB backup 개념 및 방법 ㆍMariaDB 논리적 백업과 물리적 백업 ㆍmysqlbinlog ㆍmariabackup 및 xtrabackup ㆍmysql_upgrade Section 4
  • 170. 171 • 백업이란? – 의미있는 정보인 데이터에 대해 논리적, 물리적으로 복제하여 관리하는 것 – 동일 장비 혹은 다른 장비의 disk 장치 혹은 별도의 백업 장치에 관리 • 백업의 목적 – 데이터 안정성 유지 및 데이터 소실 방지 – 하드웨어 시스템 고장 / disk 손상 / 소프트웨어 손상 / 운영데이터 소실 – 사고로 시스템이나 파일이 피해를 입더라도 최근에 백업한 시점의 내용으로 복구를 위함 BACKUP
  • 171. 172 • 백업 정책 수립 – 백업 대상 선정  data file  binlog  my.cnf  iblogfile – 백업 주기 선정  백업의 수행 시간에 따른 백업 주기 산정 BACKUP
  • 172. 173 • 백업 정책 수립 – 백업 용량 산정  백업 정책에 따른 보관 일자 및 용량 산정 – 백업 전략 선정  full 백업  incremental 백업 – 백업 관리 방법 선정  백업 정책에 따른 보관 일자 산정  incremental 백업에 대해 증분치 보관 결정 BACKUP
  • 173. 174 BACKUP • 복구 시나리오 설정 – 가장 인접한 full 백업 선정 – full 백업으로 복구 수행 – 가장 인접한 증분 백업 선정 – 증분 백업을 순차적으로 실행 – full 백업 이후의 binlog 에 대해 SQL 산출 (Point-In-Time Recovery) – 추출한 SQL 을 적용
  • 175. 176 MariaDB Backup Type • Logical Backup – 특징 및 장점  SQL 형태의 text 문으로 데이터 백업  데이터 검토 가능  복원 작업이 수월  물리 백업에 비해 복원시 데이터 손상을 줄여줌  문제 발생시 원인 파악 및 해결이 수월 – 단점  백업/복원시 시스템 리소스를 물리백업에 비해 많이 소모  부동 소수점 데이터의 백업&복원시 정확성을 잃을 수도 있음 – 종류  mysqldump  into outfile / load data infile  mysql execute mode > text file
  • 176. 177 MariaDB Backup Type • Physical Backup – 특징 및 장점  MariaDB의 물리적 파일을 백업  속도가 빠름  대체적으로 작업이 단순함 – 단점  논리적 백업에 비해 백업해야하는 파일의 크기가 큼  데이터 복구시 문제가 발생하면 원인 파악 및 해결이 어려움  필요한 논리개념의 data 만 백업이 불가능 – 종류  directory copy ( cold backup )  mysqlhotcopy ( myisam, archive )  mariabackup ( innodb hot backup )  xtrabackup ( percona, open source )
  • 178. 179 Logical Backup & Restore • mysqldump – 논리 백업 방식 – row 기반 데이터 백업 – insert 구문으로 데이터를 추출 및 저장하여 백업 – 데이터베이스, 테이블 단위로 백업 가능
  • 179. 180 Logical Backup & Restore • mysqldump – [ options ]
  • 180. 181 Logical Backup & Restore • mysqldump – 기타옵션  --single-transaction : Lock 을 사용하지 않는 일관성 있는 읽기 연산 사용  --flush-logs : 새로운 바이너리 로그파일 생성  --master-data= 1 / 2 a. dump 파일의 헤더 부분에 CHANGE MASTER TO 구문을 포함 b. 덤프 시작 시점의 Binary log 파일명과 위치 정보 및 호스트 정보를 포함 c. 1 : 수행할 수 있는 형태의 SQL 구문 , 2 : 정보만 출력  --extended-insert : 확장 형태의 insert 구문으로 출력  --no-data : 테이터를 제외하고 구조만 백업  --create-options : 테이블 생성 옵션을 모두 포함  --routines / triggers : 프로시저 함수 / 트리거를 포함하여 백업 – mysqldump 백업시 로그
  • 181. 182 Logical Backup & Restore • source 명령어 – 외부 파일의 SQL 문을 실행 – mysql prompt 에서 사용하거나 mysql 의 –e 옵션을 이용하여 사용 – source 명령을 prompt 에서 사용시 파일의 경로는 ‘’ 대신 ‘/’ 를 이용 – 복구시 dump 파일의 character set, collation 확인 필요 – set names <character set>;
  • 182. 183 Logical Backup & Restore • select ... into outfile – 논리 백업 데이터의 복구 방식 – row 기반 데이터 백업 – 인식 가능한 구분자 ( seperator ) 로 column 을 구분하여 파일로 저장 – 원하는 형태의 SQL 을 구성하여 결과값을 파일로 저장 가능 – file_priv = ‘Y’ – 절대경로 혹은 상대경로 위치에 output 저장 – 해당 경로에 대한 OS 계정 user/group 의 쓰기 권한이 있어야 함
  • 183. 184 Logical Backup & Restore • select ... into outfile – [ options ]
  • 184. 185 Logical Backup & Restore • load data infile – 논리 백업 데이터의 복구 방식 – row 기반 데이터 백업 – 인식 가능한 구분자 ( seperator ) 로 구분된 파일의 데이터를 읽어 복원 – local / non local – local-infile = 0 – file_priv = ‘Y’ – 파일의 절대경로 혹은 상대경로의 파일을 읽어서 복원
  • 185. 186 Logical Backup & Restore • load data infile – [ options ]
  • 187. 188 mysqlbinlog • mysqlbinlog – binary / relay log 를 직접 읽기 위한 도구 – binary format 으로 작성된 binlog 를 text format 으로 변환하는 도구 – binlog_format = statement / row  statement-based a. event 정보는 SQL 문과 실행한 서버 ID, 실행된 시간, 실행시 걸린 시간, 기타 정보  row-based a. event 정보는 쿼리로 인해 변경된 row 에 대한 정보를 포함
  • 188. 189 mysqlbinlog • mysqlbinlog – [ options ]  --help, -? a. 도움말 메시지를 출력하고 종료  --base64-output a. base64 인코딩을 이용하여 모든 로그 엔트리를 출력  --character-sets-dir=path a. 문자 셋이 설치되어 있는 디렉토리  --database=db_name, -d db_name a. 하나의 데이터베이스만을 지정, 다중--database 옵션을 지정한다면, 마지막 하나만 사용 b. default-database 가 db_name인 바이너리 로그로부터 엔트리를 출력 c. 크로스-데이터베이스 명령문을 복제하지 않음
  • 189. 190 mysqlbinlog  --debug[=debug_option], -# [debug_option] a. 디버깅 로그를 작성한다. 전형적인 debug_options 스트링은 'd:t:o,file_name'  --disable-log-bin, -D a. 바이너리 로깅을 비활성화 b. SUPER 권한을 필요  --force-read, -f a. 로그읽기중 발생하는 에러를 무시하고 수행  --hexdump, -H a. 코멘트에 있는 로그의 헥스(hex)덤프를 출력  --host=host_name, -h host_name a. host 지정
  • 190. 191 mysqlbinlog  --password[=password], -p[password] a. 서버에 접속 패스워드 b. 축약옵션 (-p)을 사용할 경우, 이 옵션과 패스워드 사이에는 스페이스를 사용하지 않음  --port=port_num, -P port_num a. 원격 서버에 접속을 하기 위해 사용되는 TCP/IP 포트 번호  --protocol={TCP|SOCKET|PIPE|MEMORY} a. 사용할 접속 프로토콜  --read-from-remote-server, -R a. 로컬 로그 파일을 읽는 대신에 서버에서 바이너리 로그를 읽음 b. 모든 접속 파라미터 옵션은 이 옵션을 같이 지정하지 않는 한 무시 c. --host, --password, --port, --protocol, --socket, --user 옵션을 함께 사용  --result-file=name, -r name a. 주어진 파일에 직접 결과를 출력
  • 191. 192 mysqlbinlog  --server-id=id a. 서버 ID 에 해당하는 로그만 출력  --set-charset=charset_name a. 결과에 SET NAMES charset_name 명령문을 추가  --local-load=path, -l path a. 지정된 디렉토리에 있는 LOAD DATA INFILE을 위한 로컬 임시 파일을 준비  --offset=N, -o N a. 로그에 있는 첫 번째 N 엔트리를 무시(skip)
  • 192. 193 mysqlbinlog  --short-form, -s a. 로그에 포함되어 있는 명령문만을 다른 정보 없이 표시  --socket=path, -S path a. 유닉스 소켓 파일 또는 윈도우에서의 지명된 파이프 이름  --start-datetime=datetime a. datetime 인수와 동일하거나 느린 타임 스탬프를 가지고 있는 첫 번째 이벤트에서 바이너리 로그를 읽기 시작 b. DATETIME 또는 TIMESTAMP 데이터 타입에 적합한 포맷 형태로 대입 c. mysqlbinlog --start-datetime="2005-12-25 11:25:56" binlog.000003 d. 포인트-인-타입(point-in-time) 복구 시에 유용  --stop-datetime=datetime a. datetime 인수와 동일하거나 빠른 타임 스탬프를 가지고 있는 이벤트가 처음으로 발 생할 때 바이너리 로그를 읽기를 종료 b. 포인트-인-타입(point-in-time) 복구 시에 유용
  • 193. 194 mysqlbinlog  --start-position=N a. N 인수와 동일한 위치를 가지고 있는 이벤트가 처음 발생할 때 바이너리 로그를 읽 기 시작 b. 명령문 라인에 지명된 첫 번째 로그 파일에 적용  --stop-position=N a. N 인수와 동일하거나 보다 큰 위치를 가지고 있는 첫 번째 이벤트 시점에 바이너리 로그를 읽기를 종료 b. 명령문 라인에 지명된 마지막 로그 파일에 적용  --user=user_name, -u user_name a. 서버에 접속을 할 때 사용하는 MariaDB 사용자 이름  --version, -V a. 버전 정보를 출력하고 종료
  • 194. 195 mysqlbinlog • mysqlbinlog 사용 – mysqlbinlog 유틸을 이용하여 sql 형태로 저장 및 실행 – mysqlbinlog 결과를 직접 mysql 로 실행
  • 196. 197 Physical Backup & Restore • Cold Backup – OS 의 copy 명령을 사용하여 수행 – 물리적인 data file 의 copy 수행중 disk block 이 변경되면 안됨 – MariaDB daemon 을 stop 한 뒤 data block 의 변경이 없는 경우 수행 – down time 이 발생하나 가장 간단하고, 장애 없이 수행 가능
  • 197. 198 Physical Backup & Restore • mysqlhotcopy – Perl 스크립트로 작성됨 – LOCK TABLES, FLUSH TABLES, cp, scp 를 이용하여 백업함 – 단일 데이터베이스, 테이블 백업이 가장 빠름 – SELECT, RELOAD, LOCK TABLES 권한 필요 – MyISAM, ARCHIVE 테이블만 백업 가능
  • 198. 199 Physical Backup & Restore • mariabackup – 10.1.26부터 제공되는 backup tool – MariaDB Backup is based on Percona XtraBackup 2.3.8 – Windows 지원 – Online Hot Backup 제공 – Backup/Restore of Data-at-Rest encrypted XtraDB/InnoDB tables – Backup/Restore when MariaDB Compression is used for table types XtraDB/InnoDB
  • 199. 200 Physical Backup & Restore • 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 옵션 사용 – incremental backup 가능
  • 200. 201 XtraBackup • xtrabackup a. 백업 대상 서버에서 xtrabackup 으로 전체 데이터 백업 b. 데이터 이관  복구할 DB의 data directory 로 백업된 directory를 이동
  • 201. 202 XtraBackup • xtrabackup  xtrabackup 복구를 이용한 데이터 이관 c. 복구할 DB 기동  ib_logfile 을 기존과 동일하게 사용하는 경우 my.cnf 의 ib_logfile 옵션을 기존과 동일하게 설정  새로운 ib_logfile 을 이용할 경우 ib_logfile 을 새로 생성할 수 있도록 삭제 d. 복구할 DB에서 mysql_upgrade 실행
  • 202. 203 Cold Backup • cold backup & restore a. 백업 대상 서버 중지 b. 복구 서버로 데이터 이관  복구할 DB의 data directory 로 백업 서버의 datadir 이동
  • 203. 204 Cold Backup c. 복구 DB 기동  ib_logfile 을 기존과 동일하게 사용하는 경우 my.cnf 의 ib_logfile 옵션을 기존 과 동일하게 설정  새로운 ib_logfile 을 이용할 경우 ib_logfile 을 새로 생성할 수 있도록 삭제 d. 복구할 DB에서 mysql_upgrade 실행
  • 205. 206 - fix_priv_tables represents a script generated internally by mysql_upgrade that contains SQL statements to upgrade the tables in the mysql database. - All checked and repaired tables are marked with the current MariaDB version number. This ensures that next time you run mysql_upgrade with the same version of the server, it can tell whether there is any need to check or repair the table again. - mysql_upgrade also saves the MariaDB version number in a file named mysql_upgrade_info in the data directory. This is used to quickly check whether all tables have been checked for this release so that table-checking can be skipped. To ignore this file and perform the check regardless, use the --force option. mysql_upgrade
  • 206. 207 mysql_upgrade • Options · --basedir=path Old option accepted for backward compatibility but ignored. · --datadir=path Old option accepted for backward compatibility but ignored. · --default-character-set=name Old option accepted for backward compatibility but ignored. · --force Ignore the mysql_upgrade_info file and force execution of mysqlcheck even if mysql_upgrade has already been executed for the current version of MariaDB. · --host Connect to MariaDB on the given host.
  • 207. 208 mysql_upgrade • Options · --password[=password], -p[password] The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the password. If you omit the password value following the --password or -p option on the command line, mysql_upgrade prompts for one. Specifying a password on the command line should be considered insecure. You can use an option file to avoid giving the password on the command line. · --port=port_num, -P port_num The TCP/IP port number to use for the connection. · --protocol={TCP|SOCKET|PIPE|MEMORY} The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want.
  • 208. 209 mysql_upgrade • Options · --silent Print less information. · --socket=path, -S path For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use. · --tmpdir=path, -t path The path name of the directory to use for creating temporary files. · --upgrade-system-tables, -s Only upgrade the system tables in the mysql database. Tables in other databases are not checked or touched. · --user=user_name, -u user_name The MariaDB user name to use when connecting to the server and not using the current login.
  • 209. 210 mysql_upgrade • Options · --verbose Display more output about the process. Using it twice will print connection arguments; using it 3 times will print out all CHECK, RENAME and ALTER TABLE commands used during the check phase; using it 4 times (added in MariaDB 10.0.14) will also write out all mysqlcheck commands used. · --version, -V Output version information and exit. · --version-check, -k Run this program only if its 'server version' matches the version of the server to which it's connecting. Note: the 'server version' of the program is the version of the MariaDB server with which it was built/distributed. Defaults to on; use --skip-version-check to disable. · --write-binlog Cause binary logging to be enabled while mysql_upgrade runs
  • 212. 213 세부내용 ㆍMariaDB 서버 로그 ㆍMariaDB 모니터링 ㆍMySQL 에서 MariaDB 로의 전환 방법 ㆍMariaDB High Availability Section 5
  • 214. 215 MariaDB Log • error log – 서버 시작 및 종료 기록을 포함 – 문제가 되는 쿼리에 대한 로그 • general query log – 클라이언트의 연결, 클라이언트로부터의 쿼리 등 다양한 이벤트가 기록 – 서버로 수신되는 모든 쿼리를 기록 – 서버의 활동상황(누가 연결하며, 무엇을 하고 있는지)을 감시하는데 유용 • slow query log – slow query 를 활성화 하는 경우 log 파일에 SQL 을 기록 – “느림"의 기준은 /etc/my.cnf 설정 파일에 long_query_time에 초단위로 기록 – Default Value: 10.000000 >= MariaDB 10.1.13, 10 <= MariaDB 10.1.12
  • 215. 216 MariaDB Log • binary log – UPDATE, DELETE, INSERT, CREATE TABLE, GRANT 등의 명령문에 의해서 수정 이 발생한 명령문을 기록 – 서버가 비정상 종료할 경우, 백업 이후의 데이터를 복원하기 위해 사용 • relay log – 서버가 리플리케이션 슬레이브(replication slave) 서버로 동작하는 경우, 마스터 서버로부터 수신한 데이터 수정 이벤트를 기록
  • 217. 218 MariaDB 모니터링 • 서버 과부하 • MariaDB shutdown • MariaDB 복구 • 테이블 메타 정보 불일치 • 로그 파일 관리 • 테이블 및 레코드의 잠금 해결 • MariaDB 서버의 호스트 잠금
  • 218. 219 MariaDB 모니터링 • 서버 과부하 – OS utility 를 이용한 부하 확인  uptime 명령어 a. CPU 에 처리해야 하는 작업이 쌓여있는 정도를 표현 b. load average 항목 확인 c. CPU 작업이 대기 큐에서 처리를 기다리는 프로세스의 평균값을 1,5,15분 간격으로 표현  vmstat 명령 a. 현재 CPU 가 어떤 작업에 주로 사용되는지 확인 b. 초단위 시간간격으로 표현
  • 219. 220 MariaDB 모니터링 -- proc 항목 r : 현재 실행중인 프로세스의 수 b : 인터럽트가 불가능한 sleep 상태에 있는 프로세스의 수 (I/O 처리를 하는 동안 블럭 처리된 프로세스) w : 강제로 스왑아웃된 프로세스 -- memory 항목 swpd : 사용하고 있는 swap 메모리 양 free : 사용가능한 메모리 양 buff : 버퍼로 사용되고 있는 메모리 양 cache : 캐시로 사용되고 있는 메모리 양 -- swap 항목 si : swap in so : swap out
  • 220. 221 MariaDB 모니터링 -- io 항목 bi : 초당 블럭 디바이스로 보내는 블럭 수 bo : 초당 블럭 디바이스로부터 받은 블럭 수 -- system 항목 in : 초당 인터럽트 되는 양 cs : 초당 context switch되는 양 -- cpu 항목 us : 사용자의 CPU 사용 시간 비율 sy : 시스템의 CPU 사용 시간 비율 id : idle
  • 221. 222 MariaDB 모니터링  free 명령어 a. OS 의 물리적 메모리나 스왑 영역의 상태 확인 b. 주로 –m –t 옵션을 사용 ( m : MB 표기 , t : TOTAL 라인 표시 )
  • 222. 223 MariaDB 모니터링  free 명령어 -- Mem 항목 1) 시스템의 물리적인 메모리에 대한 사용량을 각 필드로 표시 2) total은 전체 메모리의 용량은 byte단윈로 표시 3) used는 현재 시스템에서 사용중인 메모리의 량을 표시 4) free는 현재 시스템에서 사용중이지 않은 메모리의 량을 표시 5) shared는 현재 시스템에서 공유한 메모리의 용량을 표시 6) buffers는 현재 시스템에서 버퍼링(buffering)된 메모리의 량을 표시 7) cached는 현재 시스템에서 캐싱(caching)된 메모리의 량을 표시 -- Swap 항목 1) total은 시스템의 전체 Swap메모리의 량을 표시 2) used는 전체 스왑메모리에서 현재 사용중인 스왑메모리의 양 3) free는 전체 스왑메모리중에서 사용되지 않고 남아 있는 메모리의 양
  • 223. 224 MariaDB 모니터링  iostat 명령어 a. OS 의 물리적 메모리나 스왑 영역의 상태 확인 b. -dx 옵션으로 디바이스별 확장 통계 조회가능
  • 224. 225 MariaDB 모니터링  iostat 명령어 -- Device 항목 1) rrqm/s : 디바이스 큐에 대기중인 초당 읽기 요청의 건수 2) wrqm/s : 디바이스 큐에 대기중인 초당 쓰기 요청의 건수 3) r/s : 디바이스에 요청한 초당 읽기 요청의 건수 4) w/s : 디바이스에 요청한 초당 쓰기 요청의 건수 5) rsec/s : 디바이스에서 초당 읽어들인 섹터의 갯수 6) wsec/s : 디바이스에서 초당 기록한 섹터의 갯수 7) avgrq-sz : 디바이스에 요청한 초당 평균 데이터의 크기 8) avgqu-sz : 디바이스에 요청한 초당 평균 큐 길이 9) await : 디바이스에서 처리되기 위해서 요청된 I/O 평균 시간(밀리초, 1/1000초). 큐에서 소요된 시간과 처리된 시간이 합쳐져 출력 10) svctm : 디바이스에서 처리한 I/O 평균 시간 (밀리초, 1/1000초) 11) %util : 디바이스에서 요청한 I/O 작업을 수행하기 위해 사용한 CPU 시간 비율. 이 값이 100%에 가까워지면 디바이스가 한계에 도달
  • 225. 226 MariaDB 모니터링 – MariaDB Error Log 확인  MySQL 서버에 문제가 발생하는 경우 기본적으로 Error Log 에 기록됨  장애시 Error Log 의 마지막 부분은 반드시 확인  MySQL 에러로그 파일은 기본적으로 data directory에 hostname.err 로 생성됨  log-error 파라메터를 설정함으로써 directory 및 filename 지정 가능  파일이 너무 큰 경우 tail 명령이나 less 명령을 이용하여 마지막 라인만 확인
  • 226. 227 MariaDB 모니터링 – MariaDB Processlist 확인  MariaDB 서버에 접속하거나 mysqladmin utility 를 이용하여 확인  현재 실행중인 SQL 확인 가능  show (full) processlist 명령으로 확인 가능  각 프로세스의 command / state / time 값을 확인하여 현재 상태와 실행시간 확인 a. State 항목이 Waiting 인 경우 타 프로세스에 의한 잠금 확인 필요 b. Copy to tmp table 인 경우 해당 SQL 의 튜닝포인트 확인 c. Command 및 State 항목이 동일 항목이 여러개 반복해서 나타나는 경우 SQL 튜닝 필요 d. Command 및 State 항목이 여러종류가 다양하게 나타난다면 서버 외부 요인 파악 e. 서버의 부하는 높으나 Command 항목이 대부분 Sleep 상태인 경우 network in 확인
  • 227. 228 MariaDB 모니터링 – MariaDB Max Connection 확인  평상시보다 많은 Network In 이 발생하는 경우  서버가 처리할 수 있는 허용량 보다 많은 connection 이 동시에 몰리는 경우 부하  Session 메모리를 고려한 max connection 설정 필요  status 항목의 max_used_connection 을 모니터링하여 최대사용량에 도달한 경 우 connection 허용값을 증가하여 운영  max_connections 시스템 변수로 조정 가능
  • 228. 229 MariaDB 모니터링 – MariaDB Slow Query Log 분석  MariaDB 의 slow-log 옵션을 활성화하는 경우 기록  로그파일 혹은 테이블로 기록 ( log_output=‘FILE,TABLE’ )  지정된 시간 이상 정상 수행 및 종료된 SQL 에 대해 기록  mysqldumpslow 유틸을 이용하여 slow log 의 통계 집계 가능 ( 기본적으로 설 치 )  mysqlsla utility 를 이용해서 확인 가능 ( 별도 설치 )  -s 옵션에 count(c) , lock(l) , record(r) 기준으로 출력 가능  hostname-slow.log 형태로 기록
  • 229. 230 MariaDB 모니터링 – MariaDB SQL 실행 빈도 확인  mysqladmin 의 extended-status 항목으로 서버 상태값 출력  egrep 커맨드로 필요한 항목만 확인  초당 처리되는 쿼리의 수를 확인하고 평상시보다 과부하가 발생하는지 확인
  • 230. 231 MariaDB 모니터링 • MariaDB Shutdown – MariaDB 서버가 자동으로 Shutdown 되는 경우 error.log 확인 – Normal Shutdown 이외의 메시지로 내려가는 경우 서버 재시작 – mysqld_safe 옵션으로 mysqld daemon 이 시작된 경우 자동 복구 – Killed 등의 메시지로 원인확인이 불가능 할 때 OS log 를 통해 원인 분석 • MariaDB data 복구 – MyISAM 테이블 손상의 경우 repair table 명령으로 복구 – InnoDB 의 손상 시 innodb_force_recovery 옵션을 my.cnf 에 추가하여 복구  1~6 까지의 옵션을 낮은 번호부터 증가시키면서 복구  default 0 : 비복구 모드
  • 231. 232 MariaDB 모니터링 • MariaDB Table Meta 복구 – MariaDB Data Dictionary 와 .frm 파일의 정보가 불일치 하는 경우 발생 – Data Dictionary 에서 정상 삭제된 경우 이상 없음 – .frm 데이터가 삭제되고 Data Dictionary 에 남아 있다면 에러 발생 – 타 database 에서 해당 테이블과 동일한 구조의 테이블을 만들고 .frm 파일 을 복사하여 인식하도록 할 수 있음 • MariaDB ERROR Log 문제 – Error Log 파일의 사이즈가 warning 으로 인해 커지는 경우 – warning 메시지를 error log 에 출력하지 않도록 설정 – error log 나 binary log 의 경우 파일 삭제 후 flush logs 를 통해 새로운 log 생성
  • 232. 233 MariaDB 모니터링 • MariaDB 테이블 및 레코드 잠금 해결 – transaction 이 특정 이유로 commit 이 되지 않은 상태로 남아있는 경우 – Lock wait timeout exceeded error 발생 – Lock 을 유발하는 transaction 을 종료하여 처리 – processlist 상의 id 항목에 대해 kill query id 로 처리 – innodb_lock_wait_timeout 변수를 통해 대기시간을 줄일 수 있음
  • 233. 234 MariaDB 모니터링 • MariaDB binary Log 문제 – binary log 의 사이즈가 커지는 경우 – 일정기간 이외의 파일을 지우도록 설정 ( expire_logs_days ) – 직접적으로 binary log purge 하여 용량 확보
  • 234. 235 MariaDB 모니터링 • MariaDB Server Host 잠금 – client host 별 error count 값이 max_connect_errors 설정값 초과시 발생 – default 10 – hostname is blocked because of many connection errors 발생 – flush hosts 명령으로 처리 가능 – max_connect_errors 값을 증가시켜서 처리가능
  • 236. 237 From MySQL to MariaDB • DB 전환 • 주의사항 • 버전별 DB 전환 • mysql_upgrade
  • 237. 238 mysqldump • mysqldump 논리 백업 도구 이용 ( 버전에 관계 없이 가장 안전함 ) a. 이관 대상 MySQL 서버에서 mysqldump 로 전체 데이터 백업 b. 전환할 DB 인 MariaDB 를 설치 후 기동
  • 238. 239 mysqldump • mysqldump 논리 백업 도구 이용 ( 버전에 관계 없이 가장 안전함 ) c. mysqldump 로 백업된 덤프 파일을 새로운 버전의 MariaDB 에서 실행 ※ dump 파일의 내용이 수행되는 내용을 모두 확인 가능 d. 전환할 DB 인 MariaDB 에서 데이터 이관이 완료되면 mysql_upgrade 실행
  • 239. 240 전환시 주의사항 • temporary 테이블의 원활한 사용을 위해 옵션값 조정 필요 – aria-pagecache-buffer-size = 64M ( MySQL : key-buffer-size ) • Replication 구성의 경우 slave 를 먼저 전환 필요 – MariaDB 의 binary log 를 MySQL 의 하위버전이 인식 못할 수 있음 – Master DB 를 전환 시 --skip-write-binlog 옵션을 이용하여 mysql_upgrade 수행 필요 • 항상 전환 전 backup 을 받아둘 것 – 데이터 및 환경설정 파일까지 모두 백업 – binlog 로 복원 가능한 데이터가 존재할 수 있으므로 binlog 까지 백업
  • 240. 241 전환시 주의사항 • mysql_upgrade 수행 – 버전이 동일하더라도 system 테이블 내용이 변경될 수 있으므로 항시 수행 – 버전이 다른 경우 반드시 수행 – 시스템 테이블의 업데이트만 수행하는 경우 –s 옵션 사용 • unix_timestamp 범위 및 datetime 의 %f 옵션 차이 – 인식 가능한 timestamp 의 범위가 상이함 ( MySQL – INT 의 MAX VALUE , MariaDB – 상이 ) – datetime 의 %f 옵션에 대해 MySQL 은 표현하지 못함 ( 5.5 이하 ) • MySQL 에서 deprecated 되었거나 MariaDB 전용 variables에 대한 확인 필요
  • 241. 242 버전별 DB 전환 • 확인사항 ( MySQL 5.0 이하에서 MariaDB 5.5 전환 시 주의 ) – 인덱스 칼럼의 collation 변경 – MySQL 4.1 과 5.0 간의 DECIMAL 과 VARCHAR 데이터 타입 저장 방식 변경 – MySQL 5.1 부터 모든 플랫폼에서 테이블 명이 동일하도록 인코딩 되어서 저장
  • 242. 243 버전별 DB 전환 • 확인사항 ( MySQL 5.1 에서 MariaDB 5.5 전환 시 주의 ) – 데이터 파일 포멧간의 차이가 거의 없음 – mysql 시스템 데이터베이스의 dictionary 정보가 상이할 수 있음 – 변경된 parameter 확인 ( 예 default-character-set ) – 전환한 MariaDB 구동시 deprecated 된 parameter 에 대해 error log 에서 확인가능
  • 243. 244 버전별 DB 전환 • 확인사항 ( MySQL 5.5 에서 MariaDB 5.5 전환 시 주의 ) – 데이터 파일 포맷이 동일함 – OS 파라메터 fs.max-aio-nr 의 값이 상향 조정됨 – thread pool 관련 설정이 변경됨
  • 245. 246 MariaDB High Availability • Replication • MaxScale • Galera Cluster • ProxySQL • MHA
  • 251. 252 MariaDB MaxScale • Security – SQL-Injection, DDoS등 보안위협으로부터 보호 • Flexibility – Query Routing, Replication, Multi-tenant DB Scaling • High Availability – SPOF없는 HA지원 • Data Streaming – 실시간 분석을 위한 Data Lake에 Trx Data제공
  • 254. 255 ProxySQL Query Caching - mysqld QC대비 3배 향상 Query Routing - 다른 포트 R/W 분할 - 수신 포트 R/W 분할 - RegEX 통한 R/W 분할 Supports Failover SQL Firewall
  • 255. 256 MHA (MySQL High Availability) MHA Manager Active Master Slave #1 Slave #n … Application Server MHA Zone Replication Zone Master 감지 MHA Manager Active Master Slave #1 Slave #n … Application Server MHA Zone Replication Zone Binary log Copy 장 애 발 생 Save_binary_logs Apply_diff_relay_logs 장애 처리를 위한 파일
  • 261. 262 MariaDB 10.2 • 주요 기능 및 변경 사항 – InnoDB as Default – MyRocks storage engine added – Window functions – CTE (Common Table Expressions) – InnoDB tables now support spatial indexed – TokuDB has been split into a separate package, mariadb-plugin-tokudb – Multiple triggers for the same event – DML_only flashback can rollback instances/databases/tables to an old snapshot – The JSON data type (an alias for LONGTEXT) was introduced – The CONNECT engine now supports the JDBC Table type – Persistent AUTO_INCREMENT for InnoDB
  • 262. 263 MariaDB 10.3 • 주요 기능 및 변경 사항 – Oracle compatibility stage 1 – Sequences can now be used with DEFAULT – INTERSECT and EXCEPT – The PL/SQL stored procedure dialect (enabled with sql_mode=ORACLE) now supports Oracle style packages – Invisible Columns – Instant ADD COLUMN for InnoDB – Storage-engine Independent Column Compression – The Spider storage engine has been updated to 3.3.13 – Numerous improvements for the partition engine
  • 263. 264 MariaDB 10.4 • Plans for MariaDB 10.4 – Better Security  Automatic DOS attacks detection  Automatic password crack detection  Column encryption – Compatibility  Oracle stage 2  CONNECT BY – Re-Entrant Items  Building block for parallel query and be able to share stored procedures between threads (Stored procedure cache)  Reading and updating my.cnf from server
  • 264. 265 Oracle Compatibility • MariaDB ups the stakes in database war with Oracle • http://www.channelworld.in/news/mariadb-ups-stakes-database- war-oracle • Michael Howard, who worked at Oracle for four years between 1996-2000, has been CEO of MariaDB since December 2015. • "Isn't it ironic that Oracle Enterprise, MySQL's bigger brother, provides data warehousing yet it is MariaDB that is delivering it to you, this community? They don't want you to succeed with MySQL, they certainly don't want MySQL to cannibalise things like Exadata."
  • 266. 267 MySQL Client Program • MySQL Workbench • innotop • mysqlsla • mysqldumpslow • mysqladmin
  • 267. 268 MySQL Workbench • Install: http://dev.mysql.com/downloads/workbench/ • 지원 기능 – SQL Development  접속, SQL 문 실행 – Server Administration  MySQL 설치 디렉터리를 정하거나 my.ini 환경설정파일 세팅 – Data Modeling  "Create EER model from existing database“  기존 데이터베이스의 database diagram을 생성할 수 있음
  • 269. 270 Other Graphical Tools • Other Graphical Tools – PhpMyAdmin – HeidiSQL – SQLyog – TOAD for MySQL
  • 271. 272 source Package binary • 서버 환경에 맞는 옵션을 지정 하여 사용 가능 • configure 명령을 통하여 옵션 지정 • OS 버전에 구애 받지 않고 설치 가능 • 각 OS 별 최적화된 설치 제공 • 지정된 repository 에서 compile 된 binary 파일 및 환경설정을 모두 가져와 설치 • 설치가 간편함 • 각 OS 별 최적화된 compile 된 binary 제공 • core 의 옵션을 제외한 환경변수 설정 가능 • 원하는 환경변수를 이용하여 설치 가능 MariaDB Installation
  • 273. 274 MariaDB source compile 1. 설치에 필요한 패키지 설치  cmake 설치 후 mariadb 설치시 없는 package 는 추가로 설치  ( binary 설치시 : http://www.cmake.org/cmake/resources/software.html ) 2. MariaDB source file download – https://downloads.mariadb.org/ : source file download – wget 을 이용한 file download 3. 다운받은 소스 압축 해제 및 compile 을 위한 디렉토리 생성
  • 275. 276 MariaDB source compile 5. 사용자 그룹 및 사용자 생성 6. 디렉토리 생성 및 퍼미션 변경
  • 276. 277 MariaDB source compile 7. 시스템 테이블 생성 8. mysqld startup script 설정
  • 277. 278 MariaDB source compile 9. library 등록 ( lib 경로를 등록하는 모든 방법중 하나 사용 ) 10. my.cnf 생성
  • 278. 279 MariaDB source compile 11. 주요 명령어 등록 12. MariaDB 실행
  • 280. 281 MariaDB binary Installation 1. MariaDB stable binary file 다운로드 – /usr/local 경로에 다운로드 가정 – wget 혹은 https://mariadb.org 사이트를 이용하여 binary 다운로드 2. binary 파일의 압축 해제 및 디렉토리 생성 3. 사용자 그룹 및 사용자 생성
  • 281. 282 MariaDB binary Installation 4. my.cnf 생성 ( DATADIR 생성 기준 ) 5. init script 생성
  • 282. 283 MariaDB binary Installation 6. my.cnf path 수정
  • 283. 284 MariaDB binary Installation 7. library 등록 ( lib 경로를 등록하는 모든 방법중 하나 사용 ) 8. MariaDB 실행