CentOS 7 - MariaDB 10.4.18 DB를 mariabackup 을 이용 백업해서 복구 하는 테스트 입니다.

운영중인 서비스에서 하기가 부담스러워서 Virtual Box에 CentOS 7과 MariaDB 10.4.X를 설치 해서 검증을 하는 작업입니다.

mariabackup을 이용해서 상용 DB Full 백업은 완료 후 테스트용 가상 머신에 내려받아 놓은 상태이며, 운영중인 MariaDB와 비슷한 버전인 10.4.27 버전으로 설치 완료된 상태 입니다.

지난 버전의 MariaDB 설치 방법은 아래 링크에서 확인 할 수 있습니다.

https://opensrc.tistory.com/218

 

CentOS7 에 MariaDB 지난 버전(10.4.27) 설치

운영중인 시스템에 mariabackup 을 통해서 받은 백업에 대해 복구 테스트를 진행해야 하는 상황 운영중인 시스템은 CentOS 7, MariaDB 10.4.18 로 운영중이어서 최대한 비슷한 환경으로 맞춰서 테스트 진

opensrc.tistory.com

 

1. 운영환경과 동일한 설정 적용

스크립트등 운영에 적용을 위해 운영과 최대한 동일한 환경으로 맞춘 후 작업 하려고 합니다.

작업 후 추가
mariadb datadir이 최초 설치 했을때는 /var/lib/mysql 로 지정되어 있습니다.
운영환경에서는 데이터 크기 문제로 별도의 물리적 파티션에 지정하여 사용하였기 때문에 /data/mysql 로 지정되어 있습니다.
백업 및 복원 스크립트 작성을 염두에 두고 동일한 경로로 지정하기 위해 datadir을 /data/mysql로 변경하면서 몇가지 작업이 추가 되었습니다.
아래 작업 내용에서는 /data/mysql 디렉토리를 미리 생성하고 소유자 권한을 mysql:mysql로 수정하는 등 작업을 했지만 백업 데이터를 풀어 놓고 다시 작업해야 했습니다.

운영 환경 

  • MariaDB 데이터 디렉토리 : /data/mysql  (복원 할 때 생성해야 함)
  • MariaDB 로그 디렉토리 : /data/mysql-logs
[root@DEVSVR01 data]# systemctl status mariadb
● mariadb.service - MariaDB 10.4.27 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: inactive (dead)
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
[root@DEVSVR01 data]# 
[root@DEVSVR01 data]# 
[root@DEVSVR01 data]# systemctl start mariadb
[root@DEVSVR01 data]# systemctl status mariadb
● mariadb.service - MariaDB 10.4.27 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: active (running) since Fri 2022-12-02 11:08:48 KST; 7s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
  Process: 62859 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 62815 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
  Process: 62813 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 62826 (mysqld)
   Status: "Taking your SQL requests now..."
   CGroup: /system.slice/mariadb.service
           └─62826 /usr/sbin/mysqld

Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] InnoDB: 10.4.27 started; log sequence number 60943; transaction id 20
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Plugin 'FEEDBACK' is disabled.
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] InnoDB: Buffer pool(s) load completed at 221202 11:08:48
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Server socket created on IP: '::'.
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Reading of all Master_info entries succeeded
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Added new Master_info '' to hash table
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] /usr/sbin/mysqld: ready for connections.
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: Version: '10.4.27-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server
Dec 02 11:08:48 DEVSVR01 systemd[1]: Started MariaDB 10.4.27 database server.
[root@DEVSVR01 data]#

maradb 를 처음 설치하고 아무런 조치를 하지 않으면 root 권한으로 비밀번호 입력 하지 않고 접속이 가능합니다.

백업 복원 후 가상머신을 제거 할 것 이기 때문에 별다른 조치를 하지 않고 바로 진행했습니다.

MariaDB 실행 및 접속

[root@DEVSVR01 data]# systemctl status mariadb
● mariadb.service - MariaDB 10.4.27 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: inactive (dead)
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
[root@DEVSVR01 data]# 
[root@DEVSVR01 data]# 
[root@DEVSVR01 data]# systemctl start mariadb
[root@DEVSVR01 data]# systemctl status mariadb
● mariadb.service - MariaDB 10.4.27 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: active (running) since Fri 2022-12-02 11:08:48 KST; 7s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
  Process: 62859 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 62815 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
  Process: 62813 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 62826 (mysqld)
   Status: "Taking your SQL requests now..."
   CGroup: /system.slice/mariadb.service
           └─62826 /usr/sbin/mysqld

Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] InnoDB: 10.4.27 started; log sequence number 60943; transaction id 20
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Plugin 'FEEDBACK' is disabled.
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] InnoDB: Buffer pool(s) load completed at 221202 11:08:48
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Server socket created on IP: '::'.
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Reading of all Master_info entries succeeded
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] Added new Master_info '' to hash table
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: 2022-12-02 11:08:48 0 [Note] /usr/sbin/mysqld: ready for connections.
Dec 02 11:08:48 DEVSVR01 mysqld[62826]: Version: '10.4.27-MariaDB'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MariaDB Server
Dec 02 11:08:48 DEVSVR01 systemd[1]: Started MariaDB 10.4.27 database server.
[root@DEVSVR01 data]# mysql -uroot
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.4.27-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>
MariaDB [(none)]> show global variables like 'datadir';
+---------------+-----------------+
| Variable_name | Value           |
+---------------+-----------------+
| datadir       | /var/lib/mysql/ |
+---------------+-----------------+
1 row in set (0.000 sec)

MariaDB [(none)]>
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| fb_ebmp            |
| information_schema |
| lcs                |
| mysql              |
| oneshot_sms        |
| performance_schema |
| server_audit       |
+--------------------+
7 rows in set (0.031 sec)

MariaDB [(none)]> quit
Bye
[root@DEVSVR01 data]#

기본 설정된 datadir은 /var/lib/mysql 입니다.

2. mariabackup 설치

데이터 복원을 위해 새로 설치한 CentOS 가상 머신에 mariabackup 을 설치 해야 합니다.

[root@DEVSVR01 ~]# yum install MariaDB-backup
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
 * epel: mirror-jp.misakamikoto.network
 * extras: mirror.kakao.com
 * updates: mirror.navercorp.com
Resolving Dependencies
--> Running transaction check
---> Package MariaDB-backup.x86_64 0:10.4.27-1.el7.centos will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=================================================================================================================================================================================
 Package                                     Arch                                Version                                              Repository                            Size
=================================================================================================================================================================================
Installing:
 MariaDB-backup                              x86_64                              10.4.27-1.el7.centos                                 mariadb                              6.6 M

Transaction Summary
=================================================================================================================================================================================
Install  1 Package

Total download size: 6.6 M
Installed size: 27 M
Is this ok [y/d/N]: y
Downloading packages:
MariaDB-backup-10.4.27-1.el7.centos.x86_64.rpm                                                                                                            | 6.6 MB  00:00:01     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : MariaDB-backup-10.4.27-1.el7.centos.x86_64                                                                                                                    1/1 
  Verifying  : MariaDB-backup-10.4.27-1.el7.centos.x86_64                                                                                                                    1/1 

Installed:
  MariaDB-backup.x86_64 0:10.4.27-1.el7.centos                                                                                                                                   

Complete!

이전 게시물에서 mariadb.repo에 버전을 지정했기 때문에 해당 버전에 맞는 mariabackup 이 설치 되었습니다.

3. 백업 데이터 복원

미리 운영 DB 에서 백업 받은 풀 데이터를 다운받아 두었습니다.

[root@DEVSVR01 ~]# cd /usr/download
[root@DEVSVR01 download]# ls -al
total 11994704
drwxr-xr-x.  3 root root          79 Dec  2 09:02 .
drwxr-xr-x. 14 root root         171 Dec  2 09:02 ..
drwx------.  8 root root        4096 Nov 27 04:43 PROD_full_20221127040001
-rw-r--r--.  1 root root 12282569817 Dec  1 20:12 PROD_full_20221127040001.tar.gz
[root@DEVSVR01 download]# cd PROD_full_20221127040001
[root@DEVSVR01 PROD_full_20221127040001]# ls -al
total 418276
drwx------. 8 root root      4096 Nov 27 04:43 .
drwxr-xr-x. 3 root root        79 Dec  2 09:02 ..
-rw-r-----. 1 root root    442368 Nov 27 04:43 aria_log.00000001
-rw-r-----. 1 root root        52 Nov 27 04:43 aria_log_control
-rw-r-----. 1 root root       391 Nov 27 04:43 backup-my.cnf
drwx------. 2 root root     12288 Nov 27 04:43 XXXXX
-rw-r-----. 1 root root 213909504 Nov 27 04:43 ibdata1
-rw-r-----. 1 root root 213909504 Nov 27 04:00 ibdata2
-rw-r-----. 1 root root         0 Nov 27 04:43 ib_logfile0
drwx------. 2 root root      4096 Nov 27 04:43 lcs
drwx------. 2 root root      4096 Nov 27 04:43 mysql
drwx------. 2 root root      4096 Nov 27 04:43 xxxxxxxxx
drwx------. 2 root root        20 Nov 27 04:43 performance_schema
drwx------. 2 root root       256 Nov 27 04:43 xxxxxxxxx
-rw-r-----. 1 root root        40 Nov 27 04:43 xtrabackup_binlog_info
-rw-r-----. 1 root root        85 Nov 27 04:43 xtrabackup_checkpoints
-rw-r-----. 1 root root       634 Nov 27 04:43 xtrabackup_info
[root@DEVSVR01 PROD_full_20221127040001]#

 

미리 만들어 놓은 datadir 때문에 복원을 하면서 에러가 발생합니다. /data/mysql를 삭제 한 후 다시 진행 했습니다.

[root@DEVSVR01 download]# which mariabackup
/usr/bin/mariabackup
[root@DEVSVR01 download]# mariabackup --copy-back --target-dir=/usr/download/PROD_full_20221127040001 --datadir=/var/lib/mysql --user root
mariabackup based on MariaDB server 10.4.27-MariaDB Linux (x86_64)
[00] 2022-12-02 12:13:55 Original data directory /var/lib/mysql is not empty!
[root@DEVSVR01 download]# mariabackup --copy-back --target-dir=/usr/download/PROD_full_20221127040001 --datadir=/data/mysql --user root
mariabackup based on MariaDB server 10.4.27-MariaDB Linux (x86_64)
[00] 2022-12-02 12:14:24 Original data directory /data/mysql is not empty!
[root@DEVSVR01 download]# rm -rf /data/mysql
[root@DEVSVR01 download]# mariabackup --copy-back --target-dir=/usr/download/PROD_full_20221127040001 --datadir=/data/mysql --user root
mariabackup based on MariaDB server 10.4.27-MariaDB Linux (x86_64)
[01] 2022-12-02 12:14:34 Copying ibdata1 to /data/mysql/ibdata1
... 생략...
[01] 2022-12-02 13:24:10 Copying ./aria_log_control to /data/mysql/aria_log_control
[01] 2022-12-02 13:24:10         ...done
[01] 2022-12-02 13:24:10 Copying ./aria_log.00000001 to /data/mysql/aria_log.00000001
[01] 2022-12-02 13:24:10         ...done
[01] 2022-12-02 13:24:10 Copying ./xtrabackup_info to /data/mysql/xtrabackup_info
[01] 2022-12-02 13:24:11         ...done
[00] 2022-12-02 13:24:11 completed OK!
[root@DEVSVR01 download]#

 

복원된 데이터를 확인하고 root 계정으로 생성된 데이터를 mysql:mysql 로 오너쉽을 변경합니다.

(서비스와 연관된 디렉토리 명은 xxxx로 마스킹 했습니다.)

[root@DEVSVR01 download]# ls -al /data
total 0
drwxr-xr-x.  4 root  root   37 Dec  2 12:14 .
dr-xr-xr-x. 18 root  root  236 Nov 30 18:46 ..
drwx------.  8 root  root  212 Dec  2 13:24 mysql
drwxr-xr-x.  3 mysql mysql  18 Dec  2 11:57 mysql-logs
[root@DEVSVR01 download]# ls -al /data/mysql
total 418260
drwx------. 8 root root       212 Dec  2 13:24 .
drwxr-xr-x. 4 root root        37 Dec  2 12:14 ..
-rw-r-----. 1 root root    442368 Dec  2 13:24 aria_log.00000001
-rw-r-----. 1 root root        52 Dec  2 13:24 aria_log_control
drwx------. 2 root root     12288 Dec  2 12:59 xxxxx
-rw-r-----. 1 root root 213909504 Dec  2 12:14 ibdata1
-rw-r-----. 1 root root 213909504 Dec  2 12:14 ibdata2
drwx------. 2 root root      4096 Dec  2 12:59 xxxx
drwx------. 2 root root      4096 Dec  2 12:57 mysql
drwx------. 2 root root      4096 Dec  2 12:59 xxxxxx
drwx------. 2 root root        20 Dec  2 13:24 performance_schema
drwx------. 2 root root       256 Dec  2 13:24 xxxxxx
-rw-r-----. 1 root root       634 Dec  2 13:24 xtrabackup_info
[root@DEVSVR01 download]# chown -R mysql:mysql /data/mysql
[root@DEVSVR01 download]# ls -al /data/mysql
total 418260
drwx------. 8 mysql mysql       212 Dec  2 13:24 .
drwxr-xr-x. 4 root  root         37 Dec  2 12:14 ..
-rw-r-----. 1 mysql mysql    442368 Dec  2 13:24 aria_log.00000001
-rw-r-----. 1 mysql mysql        52 Dec  2 13:24 aria_log_control
drwx------. 2 mysql mysql     12288 Dec  2 12:59 xxxx
-rw-r-----. 1 mysql mysql 213909504 Dec  2 12:14 ibdata1
-rw-r-----. 1 mysql mysql 213909504 Dec  2 12:14 ibdata2
drwx------. 2 mysql mysql      4096 Dec  2 12:59 xxxxx
drwx------. 2 mysql mysql      4096 Dec  2 12:57 mysql
drwx------. 2 mysql mysql      4096 Dec  2 12:59 xxxxxx
drwx------. 2 mysql mysql        20 Dec  2 13:24 performance_schema
drwx------. 2 mysql mysql       256 Dec  2 13:24 xxxxxx
-rw-r-----. 1 mysql mysql       634 Dec  2 13:24 xtrabackup_info
[root@DEVSVR01 download]#

 

/etc/my.cnf 를 수정해서 운영환경과 동일하게 맞추겠습니다.

[root@DEVSVR01 lib]# vi /etc/my.cnf
#
# This group is read both by the client and the server
# use it for options that affect everything
#
[mysqld]
# DB의 데이터가 생성될 기본 경로
datadir=/data/mysql

# 소켓파일 경로(로컬서버 접속에 사용), 리모트 서버에는 ip와 port를 이용해서 TCP/IP 프로토콜로 접근
socket=/data/mysql/mysql.sock

# 타입존 설정
default-time-zone='+9:00'

## General LOG
general_log=1
log_output='FILE'
general_log_file=/data/mysql-logs/logs/mysql_history.log

## Slow LOG
slow_query_log=1
slow_query_log_file=/data/mysql-logs/logs/mysql_slow.log
long_query_time=10

## Error LOG
log-error=/data/mysql-logs/logs/mysql_error.log

## Binary LOG
log-bin=/data/mysql-logs/logs/mysql_binary
binlog_cache_size=2M
max_binlog_size=50M
expire_logs_days=2

[client-server]

#
# include *.cnf from the config directory
#
!includedir /etc/my.cnf.d

~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~

[mysqld] 부분을 추가 하고 몇가지 설정을 추가 했습니다.

중요한 것은 위에서 복사한 경로를 지정 하는 datadir = /data/mysql 입니다. (저장 공간등의 이슈가 없으면 설치시 지정된 디렉토리 그대로 진행해도 관계 없습니다.)

3. 복원된 데이터로 mariadb 실행

 

[root@DEVSVR01 download]# systemctl start mariadb
Job for mariadb.service failed because the control process exited with error code. See "systemctl status mariadb.service" and "journalctl -xe" for details.
[root@DEVSVR01 download]# 
[root@DEVSVR01 download]# journalctl -xe
... 생략 ...
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [Note] /usr/sbin/mysqld (mysqld 10.4.27-MariaDB-log) starting as process 2831 ...
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [Warning] Can't create test file /data/mysql/DEVSVR01.lower-test
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: /usr/sbin/mysqld: Can't create file '/data/mysql-logs/logs/mysql_error.log' (errno: 13 "Permission denied")
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] mysqld: File '/data/mysql/aria_log_control' not found (Errcode: 13 "Permission denied")
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] mysqld: Got error 'Can't open file' when trying to use aria control file '/data/mysql/aria_log_control'
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Plugin 'Aria' init function returned error.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Plugin 'Aria' registration as a STORAGE ENGINE failed.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [Note] InnoDB: Using Linux native AIO
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] InnoDB: Operating system error number 13 in a file operation.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] InnoDB: The error means mysqld does not have the access rights to the directory.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] InnoDB: os_file_get_status() failed on './ibdata1'. Can't determine file permissions
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Plugin 'InnoDB' init function returned error.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [Note] Plugin 'FEEDBACK' is disabled.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Could not open mysql.plugin table. Some plugins may be not loaded
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Failed to initialize plugins.
Dec 02 15:11:47 DEVSVR01 mysqld[2831]: 2022-12-02 15:11:47 0 [ERROR] Aborting
Dec 02 15:11:47 DEVSVR01 systemd[1]: mariadb.service: main process exited, code=exited, status=1/FAILURE
Dec 02 15:11:47 DEVSVR01 systemd[1]: Failed to start MariaDB 10.4.27 database server.
-- Subject: Unit mariadb.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
-- 
-- Unit mariadb.service has failed.
-- 
-- The result is failed.
Dec 02 15:11:47 DEVSVR01 systemd[1]: Unit mariadb.service entered failed state.
Dec 02 15:11:47 DEVSVR01 systemd[1]: mariadb.service failed.
Dec 02 15:11:47 DEVSVR01 polkitd[582]: Unregistered Authentication Agent for unix-process:2782:16916940 (system bus name :1.134, object path /org/freedesktop/PolicyKit1/Authenti
[root@DEVSVR01 download]#

퍼미션 문제로 정상 실행이 안됩니다.

journalctl -xe 명령으로 원인을 찾아 보면 

/usr/sbin/mysqld: Can't create file '/data/mysql-logs/logs/mysql_error.log' (errno: 13 "Permission denied") Dec 02 [ERROR] mysqld: File '/data/mysql/aria_log_control' not found (Errcode: 13 "Permission denied") Dec 02 15:11:47 [ERROR] mysqld: Got error 'Can't open file' when trying to use aria control file '/data/mysql/aria_log_control'

mysql_error.log, 

aria_log_control 등의 파일에 퍼미션이 없어서 실행이 안된다고 나옵니다.

[root@DEVSVR01 download]# ls -al /data/
total 0
drwxr-xr-x.  4 root  root   37 Dec  2 12:14 .
dr-xr-xr-x. 18 root  root  236 Nov 30 18:46 ..
drwx------.  8 mysql mysql 212 Dec  2 13:24 mysql
drwxr-xr-x.  3 mysql mysql  18 Dec  2 11:57 mysql-logs
[root@DEVSVR01 download]# chmod 755 /data/mysql
[root@DEVSVR01 download]# ls -al /data/
total 0
drwxr-xr-x.  4 root  root   37 Dec  2 12:14 .
dr-xr-xr-x. 18 root  root  236 Nov 30 18:46 ..
drwxr-xr-x.  8 mysql mysql 212 Dec  2 13:24 mysql
drwxr-xr-x.  3 mysql mysql  18 Dec  2 11:57 mysql-logs
[root@DEVSVR01 download]# ls -al /data/mysql
total 418260
drwxr-xr-x. 8 mysql mysql       212 Dec  2 13:24 .
drwxr-xr-x. 4 root  root         37 Dec  2 12:14 ..
-rw-r-----. 1 mysql mysql    442368 Dec  2 13:24 aria_log.00000001
-rw-r-----. 1 mysql mysql        52 Dec  2 13:24 aria_log_control
drwx------. 2 mysql mysql     12288 Dec  2 12:59 xxxxxxx
-rw-r-----. 1 mysql mysql 213909504 Dec  2 12:14 ibdata1
-rw-r-----. 1 mysql mysql 213909504 Dec  2 12:14 ibdata2
drwx------. 2 mysql mysql      4096 Dec  2 12:59 xxxxxxx
drwx------. 2 mysql mysql      4096 Dec  2 12:57 mysql
drwx------. 2 mysql mysql      4096 Dec  2 12:59 xxxxxxx
drwx------. 2 mysql mysql        20 Dec  2 13:24 performance_schema
drwx------. 2 mysql mysql       256 Dec  2 13:24 xxxxxxx
-rw-r-----. 1 mysql mysql       634 Dec  2 13:24 xtrabackup_info
[root@DEVSVR01 download]#

권한 및 퍼미션을 설정해 줘도 안됩니다.

구글링 구글링

4. SELinux 로 보호되는 mysql 컨텍스트 해제

원인은 SELinux로 mysql 관련 디렉토리들이 보호되고 있어서 생긴 문제였습니다.

자세한 내용은 MariaDB 공식 문서를 확인 해주세요

https://mariadb.com/kb/en/selinux/

 

SELinux

SELinux is a Linux kernel module that provides a framework for configuring mandatory access control (MAC). Learn how we can help configure your framework.

mariadb.com

문서의 내용을 보면 semanage 라는 파이썬 패키지를 통해 관리 가능하다고 나옵니다.

[root@DEVSVR01 download]# semanage fcontext -a -t mysqld_db_t "/data/mysql(/.*)?"
-bash: semanage: command not found
[root@DEVSVR01 download]# semanage 
-bash: semanage: command not found
[root@DEVSVR01 download]#

아래 링크에서 semanage 패키지를 설치 하는 방법이 나옵니다.

https://ko.linux-console.net/?p=528#gsc.tab=0 

[root@DEVSVR01 download]# yum provides /usr/sbin/semanage
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
 * epel: mirror-jp.misakamikoto.network
 * extras: mirror.kakao.com
 * updates: mirror.navercorp.com
policycoreutils-python-2.5-34.el7.x86_64 : SELinux policy core python utilities
Repo        : base
Matched from:
Filename    : /usr/sbin/semanage


[root@DEVSVR01 download]# yum install policycoreutils-python
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.kakao.com
 * epel: mirror-jp.misakamikoto.network
 * extras: mirror.kakao.com
 * updates: mirror.navercorp.com
Resolving Dependencies

... 생략 ...

Installed:
  policycoreutils-python.x86_64 0:2.5-34.el7                                                                                                                                     

Dependency Installed:
  audit-libs-python.x86_64 0:2.8.5-4.el7  checkpolicy.x86_64 0:2.5-8.el7  libcgroup.x86_64 0:0.41-21.el7  libsemanage-python.x86_64 0:2.5-14.el7  python-IPy.noarch 0:0.75-6.el7 
  setools-libs.x86_64 0:3.3.8-4.el7      

Complete!
[root@DEVSVR01 download]#

mysql에서 허용된 정책을 살펴 보고 동일한 정책으로 /data/mysql, /data/mysql-logs 디렉토리를 추가 합니다.

(중간에 디렉토리 경로를 안써주고 추가한 fcontext 는 -d 옵션으로 삭제 했습니다. 참고용으로 기록 남깁니다.)

[root@DEVSVR01 download]# semanage fcontext --list | grep mysqld_db_t
/var/lib/mysql(-files|-keyring)?(/.*)?             all files          system_u:object_r:mysqld_db_t:s0 
[root@DEVSVR01 download]# semanage fcontext -d "(-files|-keyring)?(/.*)?"
[root@DEVSVR01 download]# semanage fcontext --list | grep mysqld_db_t
/var/lib/mysql(-files|-keyring)?(/.*)?             all files          system_u:object_r:mysqld_db_t:s0 
(-files|-keyring)?(/.*)?                           all files          system_u:object_r:mysqld_db_t:s0 
[root@DEVSVR01 download]# semanage fcontext -d "/data/mysql(-files|-keyring)?(/.*)?"
[root@DEVSVR01 download]# semanage fcontext -d "/data/mysql-logs(-files|-keyring)?(/.*)?"
[root@DEVSVR01 download]# semanage fcontext --list | grep mysqld_db_t
/var/lib/mysql(-files|-keyring)?(/.*)?             all files          system_u:object_r:mysqld_db_t:s0 
/data/mysql(-files|-keyring)?(/.*)?                all files          system_u:object_r:mysqld_db_t:s0 
/data/mysql-logs(-files|-keyring)?(/.*)?           all files          system_u:object_r:mysqld_db_t:s0 
[root@DEVSVR01 download]#

 

mysqld 는 정상 실행 되지만 접속하려고 하면 mysql.sock을 /var/lib/mysql/mysql.sock 에서 찾고 있습니다.

/etc/my.cnf를 수정 하면서
[mysqld] 섹션에
socket=/data/mysql/mysql.sock 라고 수정 했습니다.
이것은 mariadb 서버가 실행 될 때 참고 하는 섹션입니다.
cli에서 mysql 을 접속 하는 것은 mysql client 로 서버에 접속하는 행위 이므로 mysql.sock 파일의 위치를 찾지 못하는 것 입니다.
[root@DEVSVR01 download]# systemctl start mariadb
[root@DEVSVR01 download]# mysql -uroot -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
[root@DEVSVR01 download]# vi /etc/my.cnf.d/
enable_encryption.preset  mysql-clients.cnf         server.cnf                
[root@DEVSVR01 download]# vi /etc/my.cnf.d/mysql-clients.cnf 
#
# These groups are read by MariaDB command-line tools
# Use it for options that affect only one utility
#

[mysql]
socket=/data/mysql/mysql.sock

[mysql_upgrade]

[mysqladmin]

[mysqlbinlog]

[mysqlcheck]

[mysqldump]

[mysqlimport]

[mysqlshow]

[mysqlslap]

~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~  
:wq

/etc/my.cnf.d/mysql-clients.conf 에 [mysql] 섹션에 해당 소켓의 위치를 지정해 줍니다.

관리가 불편하면 /etc/my.cnf 파일 하단에 [mysql] 테그를 추가하고 해당 위치에 추가 해도 됩니다.

이외에 innodb 관련 설정들 몇가지가 달라서 mariadb 서버 실행에 에러가 발생했었습니다.

See "systemctl status mariadb.service" and "journalctl -xe" for details. 메시지 대로

journalctl -xe 명령으로 어디서 에러가 발생했는지 살펴 보시면서 하나씩 해결 하면 됩니다.

 

6. mariadb 실행 및 데이터 복원 확인

[root@DEVSVR01 download]# mysql -uroot -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 13
Server version: 10.4.27-MariaDB-log MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| fb_ebmp            |
| information_schema |
| lcs                |
| mysql              |
| oneshot_sms        |
| performance_schema |
| server_audit       |
+--------------------+
7 rows in set (0.031 sec)

MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> select user, host, password from user;
+---------------+--------------+-------------------------------------------+
| User          | Host         | Password                                  |
+---------------+--------------+-------------------------------------------+
| mariadb.sys   | localhost    |                                           |
| root          | localhost    | *보안삭제                                 |
| mysql         | localhost    | invalid                                   |
... 생략 ...
+---------------+--------------+-------------------------------------------+
26 rows in set (0.001 sec)

MariaDB [mysql]> 
MariaDB [(none)]> quit
Bye
[root@DEVSVR01 download]#

정상 복원이 완료 되었습니다.

7. 외부에서 접근하기 위해서는 OS 방화벽 설정이 필요합니다.

[root@DEVSVR01 download]# vi /etc/firewalld/zones/public.xml
<?xml version="1.0" encoding="utf-8"?>
<zone>
  <short>Public</short>
  <description>For use in public areas. You do not trust the other computers on networks to not harm your computer. Only selected incoming connections are accepted.</description>
  <service name="ssh"/>
  <service name="dhcpv6-client"/>
  <!-- mariadb start -->
  <rule family="ipv4">
    <port protocol="tcp" port="3306"/>
    <accept/>
  </rule>
  <!-- mariadb end -->
</zone>
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                                                                                                                                                                                                         
~                        
[root@DEVSVR01 download]# firewall-cmd --reload
success
[root@DEVSVR01 download]#

 

끝.

운영중인 시스템에 mariabackup 을 통해서 받은 백업에 대해 복구 테스트를 진행해야 하는 상황

운영중인 시스템은 CentOS 7, MariaDB 10.4.18 로 운영중이어서 최대한 비슷한 환경으로 맞춰서 테스트 진행하기 위해

Virtual Box 에 CentOS 7을 설치하고 덤프 파일을 내려 받음

MariaDB 10.4.X 버전을 설치 하기로 함

0. 도움 받은 글

https://bangu4.tistory.com/128

1. OS 버전 확인

[root@DEVSVR01 download]# rpm --query centos-release
centos-release-7-9.2009.1.el7.centos.x86_64
[root@DEVSVR01 download]# cat /etc/centos-release
CentOS Linux release 7.9.2009 (Core)
[root@DEVSVR01 download]# cat /etc/system-release
CentOS Linux release 7.9.2009 (Core)
[root@DEVSVR01 download]# id
uid=0(root) gid=0(root) groups=0(root) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
[root@DEVSVR01 download]#

$ rpm --query centos-release 명령이 가장 정확한 버전을 보여줌

2. yum 에 MariaDB Repository 추가

원하는 버전의 Repository 확인

https://downloads.mariadb.org/mariadb/repositories

 

Download MariaDB Server - MariaDB.org

REST API Release Schedule Reporting Bugs … Continue reading "Download MariaDB Server"

mariadb.org

사이트에서 CentOS 7 (x86_64)를 선택하면 MariaDB 버전은 10.4 밖에 나오지 않는다.

다운 받을 미러 사이트 선택 (그나마 일본이 좀 안전하다는 뇌피셜...)

다른 버전이 없는지 사이트 확인

https://mirror.mariadb.org/yum/

10.4.27 버전이 사용하고 있는 10.4.17 보다 약간 상위 버전으로 해당 패키시 설치 하기로 선택함

위 사이트에서 나온 내용에 baseurl 을 https://mirrors.xtom.jp/mariadb/yum/10.4.27/centos7-amd64

로 바꾸고 미러사이트에 존재 하는지 확인 (브라우저로 확인)후 mariadb.repo 생성

[root@DEVSVR01 download]# vi /etc/yum.repos.d/mariadb.repo
# MariaDB 10.4 CentOS repository list - created 2022-12-02 01:12 UTC
# https://mariadb.org/download/
[mariadb]
name = MariaDB
baseurl = https://mirrors.xtom.jp/mariadb/yum/10.4.27/centos7-amd64
gpgkey=https://mirrors.xtom.jp/mariadb/yum/RPM-GPG-KEY-MariaDB
gpgcheck=1
~                                                                                                                                                                                
~                                                                                                                                                                                
~                                                                                                                                                                                
~

 

3. yum 을 이용하여 MariaDB 설치

[root@DEVSVR01 download]# yum install MariaDB-server MariaDB-client
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                                                                                                      | 7.0 kB  00:00:00     
 * base: mirror.kakao.com
 * epel: mirror-jp.misakamikoto.network
 * extras: mirror.kakao.com
 * updates: mirror.navercorp.com
base                                                                                                                                                      | 3.6 kB  00:00:00     
epel                                                                                                                                                      | 4.7 kB  00:00:00     
extras                                                                                                                                                    | 2.9 kB  00:00:00     
mariadb                                                                                                                                                   | 3.4 kB  00:00:00     
updates                                                                                                                                                   | 2.9 kB  00:00:00     
(1/5): mariadb/updateinfo                                                                                                                                 | 5.9 kB  00:00:00     
(2/5): mariadb/primary_db                                                                                                                                 |  65 kB  00:00:00     
(3/5): epel/x86_64/primary_db                                                                                                                             | 7.0 MB  00:00:01     
(4/5): epel/x86_64/updateinfo                                                                                                                             | 1.0 MB  00:00:01     
(5/5): updates/7/x86_64/primary_db                                                                                                                        |  18 MB  00:00:02     
Resolving Dependencies
--> Running transaction check
---> Package MariaDB-client.x86_64 0:10.4.27-1.el7.centos will be installed
--> Processing Dependency: libaio.so.1(LIBAIO_0.1)(64bit) for package: MariaDB-client-10.4.27-1.el7.centos.x86_64
--> Processing Dependency: libaio.so.1(LIBAIO_0.4)(64bit) for package: MariaDB-client-10.4.27-1.el7.centos.x86_64
--> Processing Dependency: MariaDB-common for package: MariaDB-client-10.4.27-1.el7.centos.x86_64
--> Processing Dependency: libaio.so.1()(64bit) for package: MariaDB-client-10.4.27-1.el7.centos.x86_64
---> Package MariaDB-server.x86_64 0:10.4.27-1.el7.centos will be installed
--> Processing Dependency: perl(DBI) for package: MariaDB-server-10.4.27-1.el7.centos.x86_64
--> Processing Dependency: galera-4 for package: MariaDB-server-10.4.27-1.el7.centos.x86_64
--> Processing Dependency: lsof for package: MariaDB-server-10.4.27-1.el7.centos.x86_64
--> Running transaction check
---> Package MariaDB-common.x86_64 0:10.4.27-1.el7.centos will be installed
--> Processing Dependency: MariaDB-compat for package: MariaDB-common-10.4.27-1.el7.centos.x86_64
---> Package galera-4.x86_64 0:26.4.13-1.el7.centos will be installed
--> Processing Dependency: socat for package: galera-4-26.4.13-1.el7.centos.x86_64
--> Processing Dependency: libboost_program_options-mt.so.1.53.0()(64bit) for package: galera-4-26.4.13-1.el7.centos.x86_64
---> Package libaio.x86_64 0:0.3.109-13.el7 will be installed
---> Package lsof.x86_64 0:4.87-6.el7 will be installed
---> Package perl-DBI.x86_64 0:1.627-4.el7 will be installed
--> Processing Dependency: perl(RPC::PlServer) >= 0.2001 for package: perl-DBI-1.627-4.el7.x86_64
--> Processing Dependency: perl(RPC::PlClient) >= 0.2000 for package: perl-DBI-1.627-4.el7.x86_64
--> Running transaction check
---> Package MariaDB-compat.x86_64 0:10.4.27-1.el7.centos will be obsoleting
---> Package boost-program-options.x86_64 0:1.53.0-28.el7 will be installed
---> Package mariadb-libs.x86_64 1:5.5.68-1.el7 will be obsoleted
---> Package perl-PlRPC.noarch 0:0.2020-14.el7 will be installed
--> Processing Dependency: perl(Net::Daemon) >= 0.13 for package: perl-PlRPC-0.2020-14.el7.noarch
--> Processing Dependency: perl(Net::Daemon::Test) for package: perl-PlRPC-0.2020-14.el7.noarch
--> Processing Dependency: perl(Net::Daemon::Log) for package: perl-PlRPC-0.2020-14.el7.noarch
--> Processing Dependency: perl(Compress::Zlib) for package: perl-PlRPC-0.2020-14.el7.noarch
---> Package socat.x86_64 0:1.7.3.2-2.el7 will be installed
--> Running transaction check
---> Package perl-IO-Compress.noarch 0:2.061-2.el7 will be installed
--> Processing Dependency: perl(Compress::Raw::Zlib) >= 2.061 for package: perl-IO-Compress-2.061-2.el7.noarch
--> Processing Dependency: perl(Compress::Raw::Bzip2) >= 2.061 for package: perl-IO-Compress-2.061-2.el7.noarch
---> Package perl-Net-Daemon.noarch 0:0.48-5.el7 will be installed
--> Running transaction check
---> Package perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7 will be installed
---> Package perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=================================================================================================================================================================================
 Package                                            Arch                              Version                                           Repository                          Size
=================================================================================================================================================================================
Installing:
 MariaDB-client                                     x86_64                            10.4.27-1.el7.centos                              mariadb                             12 M
 MariaDB-compat                                     x86_64                            10.4.27-1.el7.centos                              mariadb                            2.2 M
     replacing  mariadb-libs.x86_64 1:5.5.68-1.el7
 MariaDB-server                                     x86_64                            10.4.27-1.el7.centos                              mariadb                             26 M
Installing for dependencies:
 MariaDB-common                                     x86_64                            10.4.27-1.el7.centos                              mariadb                             81 k
 boost-program-options                              x86_64                            1.53.0-28.el7                                     base                               156 k
 galera-4                                           x86_64                            26.4.13-1.el7.centos                              mariadb                             10 M
 libaio                                             x86_64                            0.3.109-13.el7                                    base                                24 k
 lsof                                               x86_64                            4.87-6.el7                                        base                               331 k
 perl-Compress-Raw-Bzip2                            x86_64                            2.061-3.el7                                       base                                32 k
 perl-Compress-Raw-Zlib                             x86_64                            1:2.061-4.el7                                     base                                57 k
 perl-DBI                                           x86_64                            1.627-4.el7                                       base                               802 k
 perl-IO-Compress                                   noarch                            2.061-2.el7                                       base                               260 k
 perl-Net-Daemon                                    noarch                            0.48-5.el7                                        base                                51 k
 perl-PlRPC                                         noarch                            0.2020-14.el7                                     base                                36 k
 socat                                              x86_64                            1.7.3.2-2.el7                                     base                               290 k

Transaction Summary
=================================================================================================================================================================================
Install  3 Packages (+12 Dependent packages)

Total download size: 52 M
Is this ok [y/d/N]: y
Downloading packages:
warning: /var/cache/yum/x86_64/7/mariadb/packages/MariaDB-common-10.4.27-1.el7.centos.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID 1bb943db: NOKEYB/s |    0 B  --:--:-- ETA 
Public key for MariaDB-common-10.4.27-1.el7.centos.x86_64.rpm is not installed
(1/15): MariaDB-common-10.4.27-1.el7.centos.x86_64.rpm                                                                                                    |  81 kB  00:00:00     
(2/15): MariaDB-compat-10.4.27-1.el7.centos.x86_64.rpm                                                                                                    | 2.2 MB  00:00:00     
(3/15): boost-program-options-1.53.0-28.el7.x86_64.rpm                                                                                                    | 156 kB  00:00:00     
(4/15): MariaDB-server-10.4.27-1.el7.centos.x86_64.rpm                                                                                                    |  26 MB  00:00:02     
(5/15): libaio-0.3.109-13.el7.x86_64.rpm                                                                                                                  |  24 kB  00:00:00     
(6/15): perl-Compress-Raw-Zlib-2.061-4.el7.x86_64.rpm                                                                                                     |  57 kB  00:00:00     
(7/15): lsof-4.87-6.el7.x86_64.rpm                                                                                                                        | 331 kB  00:00:00     
(8/15): perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64.rpm                                                                                                    |  32 kB  00:00:00     
(9/15): perl-IO-Compress-2.061-2.el7.noarch.rpm                                                                                                           | 260 kB  00:00:00     
(10/15): perl-PlRPC-0.2020-14.el7.noarch.rpm                                                                                                              |  36 kB  00:00:00     
(11/15): perl-Net-Daemon-0.48-5.el7.noarch.rpm                                                                                                            |  51 kB  00:00:00     
(12/15): perl-DBI-1.627-4.el7.x86_64.rpm                                                                                                                  | 802 kB  00:00:00     
(13/15): socat-1.7.3.2-2.el7.x86_64.rpm                                                                                                                   | 290 kB  00:00:00     
(14/15): galera-4-26.4.13-1.el7.centos.x86_64.rpm                                                                                                         |  10 MB  00:00:01     
(15/15): MariaDB-client-10.4.27-1.el7.centos.x86_64.rpm                                                                                                   |  12 MB  00:00:05     
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                            8.9 MB/s |  52 MB  00:00:05     
Retrieving key from https://mirrors.xtom.jp/mariadb/yum/RPM-GPG-KEY-MariaDB
Importing GPG key 0x1BB943DB:
 Userid     : "MariaDB Package Signing Key <package-signing-key@mariadb.org>"
 Fingerprint: 1993 69e5 404b d5fc 7d2f e43b cbcb 082a 1bb9 43db
 From       : https://mirrors.xtom.jp/mariadb/yum/RPM-GPG-KEY-MariaDB
Is this ok [y/N]: y
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : libaio-0.3.109-13.el7.x86_64                                                                                                                                 1/16 
  Installing : lsof-4.87-6.el7.x86_64                                                                                                                                       2/16 
  Installing : MariaDB-common-10.4.27-1.el7.centos.x86_64                                                                                                                   3/16 
  Installing : MariaDB-compat-10.4.27-1.el7.centos.x86_64                                                                                                                   4/16 
  Installing : MariaDB-client-10.4.27-1.el7.centos.x86_64                                                                                                                   5/16 
  Installing : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64                                                                                                                   6/16 
  Installing : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64                                                                                                                  7/16 
  Installing : perl-IO-Compress-2.061-2.el7.noarch                                                                                                                          8/16 
  Installing : boost-program-options-1.53.0-28.el7.x86_64                                                                                                                   9/16 
  Installing : perl-Net-Daemon-0.48-5.el7.noarch                                                                                                                           10/16 
  Installing : perl-PlRPC-0.2020-14.el7.noarch                                                                                                                             11/16 
  Installing : perl-DBI-1.627-4.el7.x86_64                                                                                                                                 12/16 
  Installing : socat-1.7.3.2-2.el7.x86_64                                                                                                                                  13/16 
  Installing : galera-4-26.4.13-1.el7.centos.x86_64                                                                                                                        14/16 
  Installing : MariaDB-server-10.4.27-1.el7.centos.x86_64                                                                                                                  15/16 


Two all-privilege accounts were created.
One is root@localhost, it has no password, but you need to
be system 'root' user to connect. Use, for example, sudo mysql
The second is mysql@localhost, it has no password either, but
you need to be the system 'mysql' user to connect.
After connecting you can set the password, if you would need to be
able to connect as any of these users with a password and without sudo

See the MariaDB Knowledgebase at http://mariadb.com/kb

Please report any problems at http://mariadb.org/jira

The latest information about MariaDB is available at http://mariadb.org/.

Consider joining MariaDB's strong and vibrant community:
https://mariadb.org/get-involved/

  Erasing    : 1:mariadb-libs-5.5.68-1.el7.x86_64                                                                                                                          16/16 
  Verifying  : galera-4-26.4.13-1.el7.centos.x86_64                                                                                                                         1/16 
  Verifying  : socat-1.7.3.2-2.el7.x86_64                                                                                                                                   2/16 
  Verifying  : perl-Net-Daemon-0.48-5.el7.noarch                                                                                                                            3/16 
  Verifying  : MariaDB-compat-10.4.27-1.el7.centos.x86_64                                                                                                                   4/16 
  Verifying  : MariaDB-client-10.4.27-1.el7.centos.x86_64                                                                                                                   5/16 
  Verifying  : boost-program-options-1.53.0-28.el7.x86_64                                                                                                                   6/16 
  Verifying  : lsof-4.87-6.el7.x86_64                                                                                                                                       7/16 
  Verifying  : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64                                                                                                                  8/16 
  Verifying  : perl-PlRPC-0.2020-14.el7.noarch                                                                                                                              9/16 
  Verifying  : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64                                                                                                                  10/16 
  Verifying  : perl-DBI-1.627-4.el7.x86_64                                                                                                                                 11/16 
  Verifying  : libaio-0.3.109-13.el7.x86_64                                                                                                                                12/16 
  Verifying  : MariaDB-server-10.4.27-1.el7.centos.x86_64                                                                                                                  13/16 
  Verifying  : perl-IO-Compress-2.061-2.el7.noarch                                                                                                                         14/16 
  Verifying  : MariaDB-common-10.4.27-1.el7.centos.x86_64                                                                                                                  15/16 
  Verifying  : 1:mariadb-libs-5.5.68-1.el7.x86_64                                                                                                                          16/16 

Installed:
  MariaDB-client.x86_64 0:10.4.27-1.el7.centos              MariaDB-compat.x86_64 0:10.4.27-1.el7.centos              MariaDB-server.x86_64 0:10.4.27-1.el7.centos             

Dependency Installed:
  MariaDB-common.x86_64 0:10.4.27-1.el7.centos   boost-program-options.x86_64 0:1.53.0-28.el7   galera-4.x86_64 0:26.4.13-1.el7.centos        libaio.x86_64 0:0.3.109-13.el7  
  lsof.x86_64 0:4.87-6.el7                       perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7   perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7   perl-DBI.x86_64 0:1.627-4.el7   
  perl-IO-Compress.noarch 0:2.061-2.el7          perl-Net-Daemon.noarch 0:0.48-5.el7            perl-PlRPC.noarch 0:0.2020-14.el7             socat.x86_64 0:1.7.3.2-2.el7    

Replaced:
  mariadb-libs.x86_64 1:5.5.68-1.el7                                                                                                                                             

Complete!
[root@DEVSVR01 download]#

정상 설치 완료

[root@DEVSVR01 download]# systemctl status mariadb
● mariadb.service - MariaDB 10.4.27 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; disabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: inactive (dead)
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
[root@DEVSVR01 download]#
[root@DEVSVR01 download]# mariadb --version
mariadb  Ver 15.1 Distrib 10.4.27-MariaDB, for Linux (x86_64) using readline 5.1
[root@DEVSVR01 download]#

 

MySQL 설치후 초기 root 패스워드를 설정 하는 방법은 아래 링크를 참고 하세요.

https://opensrc.tistory.com/207

 

[MySQL] MySQL 5.7 설치 후 초기 root 계정 비밀번호 변경 하기

이전 포스트 [CentOS 7 minimal 설치 #3] MySQL 5.7 설치에서도 한번 언급을 했었습니다만, 이전 버전과 방식이 좀 바뀐것 같습니다. MySQL 5.6 까지는 설치후 콘솔에서 바로 root 로 접속 해서 비밀번호를

opensrc.tistory.com

============================================================================

MySQL root 계정의 패스워드 분실 했을 경우 바꾸는 방법

MySQL 이전 버전에서 root 비밀번호를 분실 했을때 유용하게 이용되던 mysqld-safe 명령이 MySQL 7 부터는 없어진 것 같습니다.

MySQL 5.7버전을 설치 한 후에 저 명령을 아무리 찾아도 없었습니다. 구글링 끝에 

https://stackoverflow.com/questions/33510184/change-mysql-root-password-on-centos7

이런 내용의 글을 보았습니다.

간단히 요약해 보면

1. mysqld-safe  명령은 사라졌음

2. user 테이블의 구조가 바뀌었음

그래서 아래의 순서에 따라서 비밀번호를 바꿀 수 있습니다.

1. MySQL 서버 중지

[root@localhost ~]# systemctl stop mysqld

2. MySQL 환경변수 설정

[root@localhost ~]# systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

3. MySQL  서버 가동

[root@localhost ~]# systemctl start mysqld

4. 비번 없이  root 로그인

[root@localhost ~]# mysql -u root

5.  root 비밀번호 업데이트

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('새비밀번호')

    -> WHERE User = 'root' AND Host = 'localhost';
    
ERROR 1348 (HY000): Column 'authentication_string' is not updatable
마리아 DB  10.4.12 에서는 위와 같은 방법으로는 에러가 발생합니다.
아래 방법으로 해결 가능합니다.

mysql> ALTER mysql.user 'root'@'localhost' identified by '새비밀번호';
Query OK, 0 rows affected (0.012 sec)

mysql> COMMIT;

mysql> FLUSH PRIVILEGES;

mysql> quit

6.  MySQL 중지

[root@localhost ~]# systemctl stop mysqld

7. MySQL 환경변수 초기화

[root@localhost ~]# systemctl unset-environment MYSQLD_OPTS

8. MySQL 서버 시작

[root@localhost ~]# systemctl start mysqld

9. 새 비밀번호로 로그인 확인

[root@localhost ~]# mysql -u root -p

참고로  user 테이블이 변경 된것은 user 테이블의 접근을 쿼리가 아닌 시스템 명령으로 하면 큰 차이는 없을 것 같습니다.

MySQL 공식 문서에서도

alter user 'root'@'localhost' identified by '새비밀번호';

이런 형태를 권장 하는 것 같습니다.

유저 생성 및 비밀번호, 권한 부여는 [CentOS 7 minimal 설치] MySQL DB생성, User 생성 글을 참고 하시기 바랍니다.

이전 포스트 [CentOS 7 minimal 설치 #3] MySQL 5.7 설치에서도 한번 언급을 했었습니다만, 이전 버전과 방식이 좀 바뀐것 같습니다.

MySQL 5.6 까지는 설치후 콘솔에서 바로 root 로 접속 해서 비밀번호를 변경할 수 있었지만 MySQL 7 (ver 5.7) 부터는 설치 되면서 랜덤스트링을 암호화 한 비밀번호가 자동으로 부여되고 그것을 찾아서 접속해서 원하는 비밀번호를 부여하는 방식으로 바뀐것 같습니다.

왜 그럴까... 생각해 보면 많은 분들이 MySQL을 설치하고 root 비밀번호를 관리 하지 않아서 외부로 부터 쉽게 칩입을 당하는 케이스들 때문에 변경 된 것이라고 생각합니다.

그런데 이런 것을 모르는 상태에서 MySQL 7 버전을 설치 했다가 root 접속을 못해서 난감했던 기억이 나네요.

일단 설치는 위에 올린 링크를 참고 하시고 (이 포스트와 같은 내용이 설치에도 나옵니다.)  mysqld-safe --skip-grant-tables 명령을 대신헤서 5.7이상 버전에서는 비밀번호 분실시 어떻게 비밀번호를 변경하는지 확인해 보겠습니다.

MySQL 5.7 공식 설치 문서 (https://dev.mysql.com/doc/refman/5.7/en/linux-installation-yum-repo.html)에 보시면 중간쯤에 설치후 superuser 계정 'root'@'localhost' 에 대한 접근 방법이 나옵니다.

shell> sudo grep 'temporary password' /var/log/mysqld.log

이렇게 나오는데요... 유닉스 명령이 익숙하지 않은 분들을 위해 설명하면... root 권한으로 설치 로그에서 'temporary password' 라는 문자열이 들어 있는 행을 표시하라는 내용 정도로 이해하시면 될 것같습니다.

shell> cat /var/log/mysql.log | grep 'temporary password'

이런 거랑 비슷한 명령 일 것 같네요. 

 

설치후 임시 비밀번호 바꾸는 방법

저의 경우 설치 후 데몬을 가동후에 확인해 보니

[root@localhost ~]# grep 'temporary password' /var/log/mysqld.log

2018-02-13T14:49:45.720116Z 1 [Note] A temporary password is generated for root@localhost: tur++-dvf7tI

tur++-dvf7tI 이게 초기 비밀번호 입니다.

임시 비밀번호로 로그인 해서 비번을 바꾸는 내용입니다.

[root@localhost ~]# mysql -u root -p

Enter password : tur++-dvf7tI

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 2

Server version: 5.7.21



Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.



Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.



Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.



mysql> use mysql

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.


/* 임시 비번을 변경하기 전에는 아무것도 할 수가 없네요 */

/* 새로운 비밀번호로 변경 */
mysql> alter user 'root'@'localhost' identified by '새비밀번호';

Query OK, 0 rows affected (0.00 sec)



mysql> commit;

Query OK, 0 rows affected (0.00 sec)



mysql> quit

Bye

 

비밀번호가 잘 바뀌었는지 확인해 보도록 하겠습니다.

[root@localhost download]# mysql -u root -p

Enter password:변경한비밀번호

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 3

Server version: 5.7.21 MySQL Community Server (GPL)



Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.



Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.



Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.



mysql> use mysql

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A



Database changed

mysql> show tables;

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

| Tables_in_mysql           |

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

| columns_priv              |

| db                        |

| engine_cost               |

| event                     |

| func                      |

| general_log               |

| gtid_executed             |

| help_category             |

| help_keyword              |

| help_relation             |

| help_topic                |

| innodb_index_stats        |

| innodb_table_stats        |

| ndb_binlog_index          |

| plugin                    |

| proc                      |

| procs_priv                |

| proxies_priv              |

| server_cost               |

| servers                   |

| slave_master_info         |

| slave_relay_log_info      |

| slave_worker_info         |

| slow_log                  |

| tables_priv               |

| time_zone                 |

| time_zone_leap_second     |

| time_zone_name            |

| time_zone_transition      |

| time_zone_transition_type |

| user                      |

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

31 rows in set (0.00 sec)

mysql> quit

Bye

잘 변경이 된 것 같습니다.

 

 

root 계정의 비밀번호를 분실 했을 경우 바꾸는 방법

끝으로 이전 버전에서 root 비밀번호를 분실 했을때 유용하게 이용되던 mysqld-safe 명령에 대해서 알아 보겠습니다.

MySQL 5.7버전을 설치 한 후에 저 명령을 아무리 찾아도 없었습니다. 구글링 끝에 

https://stackoverflow.com/questions/33510184/change-mysql-root-password-on-centos7

이런 내용의 글을 보았습니다.

간단히 요약해 보면

1. mysqld-safe  명령은 사라졌음

2. user 테이블의 구조가 바뀌었음

그래서 아래의 순서에 따라서 비밀번호를 바꿀 수 있습니다.

 

1. MySQL 서버 중지

[root@localhost ~]# systemctl stop mysqld

2. MySQL 환경변수 설정

[root@localhost ~]# systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

3. MySQL  서버 가동

[root@localhost ~]# systemctl start mysqld

4. 비번 없이  root 로그인

[root@localhost ~]# mysql -u root

5.  root 비밀번호 업데이트

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('새비밀번호')

    -> WHERE User = 'root' AND Host = 'localhost';

mysql> FLUSH PRIVILEGES;

mysql> quit

6.  MySQL 중지

[root@localhost ~]# systemctl stop mysqld

7. MySQL 환경변수 초기화

[root@localhost ~]# systemctl unset-environment MYSQLD_OPTS

8. MySQL 서버 시작

[root@localhost ~]# systemctl start mysqld

9. 새 비밀번호로 로그인 확인

[root@localhost ~]# mysql -u root -p

참고로  user 테이블이 변경 된것은 user 테이블의 접근을 쿼리가 아닌 시스템 명령으로 하면 큰 차이는 없을 것 같습니다.

MySQL 공식 문서에서도

alter user 'root'@'localhost' identified by '새비밀번호';

이런 형태를 권장 하는 것 같습니다.

유저 생성 및 비밀번호, 권한 부여는 [CentOS 7 minimal 설치] MySQL DB생성, User 생성 글을 참고 하시기 바랍니다.



이전 편에서 CentOS 7에 MySQL 5.7을 설치 하는 법을 살펴 보았습니다.

MySQL 5.7에서 User 테이블에 구조가 변경되었다는 언급이 있었는데요 어떻게 바뀌었는지는 살펴보지는 않겠습니다.

MySQL 시스템 명령어로  datebase와 user을 생성하면 실제 테이블 구조와는 관계 없이 작업이 가능합니다.

USER 테이블에 Insert 쿼리 문장을 만들어서 사용자를 생성했던 분들은 MySQL 버전이 올라가면서 바뀌면서 테이블 구조가 약간씩 달라지고 하는 통에 애를 먹었을 것입니다.

오라클에서 처럼 문장으로 만들어진 명령어로 사용할 DB와 사용자를 생성해 보도록 하겠습니다.

 

Character set  확인

요즘은 대부분 UTF-8이 표준이기 때문에 나중에 골치 아픈 문제를 만나기 전에 미리 설정을 확인하고 넘어가겠습니다.

[root@localhost ~]# mysql -uroot -p

Enter password:

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 2

Server version: 5.7.21 MySQL Community Server (GPL)

 

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> status;

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

mysql  Ver 14.14 Distrib 5.7.21, for Linux (x86_64) using  EditLine wrapper

 

Connection id:          2

Current database:

Current user:           root@localhost

SSL:                    Not in use

Current pager:          stdout

Using outfile:          ''

Using delimiter:        ;

Server version:         5.7.21 MySQL Community Server (GPL)

Protocol version:       10

Connection:             Localhost via UNIX socket

Server characterset:    utf8

Db     characterset:    utf8

Client characterset:    utf8

Conn.  characterset:    utf8

UNIX socket:            /var/lib/mysql/mysql.sock

Uptime:                 22 sec

 

Threads: 1  Questions: 5  Slow queries: 0  Opens: 105  Flush tables: 1  Open tables: 98  Queries per second avg: 0.227

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

 

mysql>

 

붉은색 표시한 부분이  utf8로 되어 있는지 확인합니다.

만일 latin1 같은 형식이라면 /etc/my.cnf 에 아래 두줄을 추가 한 후  MySQL 데몬을 재시작 합니다.(systemctl restart mysqld)

[mysqld]

collation-server = utf8_unicode_ci

character-set-server = utf8

... 생략 ...

한글 설정이 확실히 정해지지 않은 상태에서 database를 생성하는 경우 나중에 테이블에 한글 입력 등의 문제가 봉착 될 수 있으니 반드시 확실하게 utf8로 지정이 되었는지 확인하고 넘어가도록 합니다.

다음은 WEBService 라는 DataBase를 생성해 보겠습니다.

[root@localhost ~]# mysql -u root -p

Enter password:

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 5

Server version: 5.7.21 MySQL Community Server (GPL)

 

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> show databases;

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

| Database           |

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

| information_schema |

| mysql              |

| performance_schema |

| sys                |

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

5 rows in set (0.00 sec)

 

mysql> create database WEBService ;

Query OK, 1 row affected (0.05 sec)

 

mysql> show databases;

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

| Database           |

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

| information_schema |

| WEBService          |

| mysql              |

| performance_schema |

| sys                |

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

5 rows in set (0.00 sec)

 

 

coludnine 라는 사용자를 추가 하도록 하겠습니다.

mysql> use mysql

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

 

Database changed

mysql> create user 'cloudnine'@'localhost' identified by '사용할비밀번호';

Query OK, 0 rows affected (0.00 sec)

 

mysql> create user 'cloudnine'@'%' identified by '사용할비밀번호';

Query OK, 0 rows affected (0.00 sec)

 

mysql> select host, user, password from user;

ERROR 1054 (42S22): Unknown column 'password' in 'field list'

※ mysql 구버전에서 사용하던 password 컬럼은 authentication_string 으로 이름이 바뀌었음

mysql> select host, user, authentication_string from user;

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

| host      | user          | authentication_string                     |

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

| localhost | root          | *암호화된비밀번호문자열 |

| localhost | mysql.session | *암호화된비밀번호문자열 |

| localhost | mysql.sys     | *암호화된비밀번호문자열 |

| localhost | cloudnine      | *암호화된비밀번호문자열 |

| %         | cloudnine      | *암호화된비밀번호문자열 |

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

mysql 특성상 user가 같아도 host가 다르면 별개의 사용자로 간주합니다.

위의 예에서 하나는 localhost용 이고 또 하나는 외부 모든 IP로 부터 접속을 허용한다는 의미입니다.

보안상 문제가 있을 수 있지만 우리는 방화벽에서 외부 접속을 엄격히 차단 할 것이므로 크게 상관은 없어 보입니다.

만일 특정 IP에서만 접속을 허용하고 싶다면 '%' 대신 IP주소를 입력하면 됩니다.

 

위에서 User테이블의 스키마가 약간 바뀐것 같다고 말씀드렸었는데 바로 password 컬럼이 authentication_string 컬럼으로 변경된것 같습니다.

user 테이블을 조회 해 보면 계정이 잘 생성 되었습니다.

 

이제 생성한 user에 database 사용권한을 부여하고 잘 접속 되는지 확인 하도록 하겠습니다.

mysql> grant all privileges on WEBService.* to 'cloudnine'@'localhost';

Query OK, 0 rows affected (0.00 sec)

 

mysql>  grant all privileges on WEBService.* to 'cloudnine'@'%';

Query OK, 0 rows affected (0.00 sec)

 

mysql> flush privileges;

Query OK, 0 rows affected (0.00 sec)

 

mysql> quit

Bye

[root@localhost ~]# mysql -u cloudnine-p

Enter password:

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 8

Server version: 5.7.21 MySQL Community Server (GPL)

 

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> use WEBService

Database changed

mysql> show tables;

Empty set (0.01 sec)

 

mysql> quit

 

권한 역시 localhost용과 외부접속용 두가지 모두  부여합니다.

 

 

■ 날짜 관련 postfix

DATE 타입 : _DATE

예 ) REG_DATE DATETIME NOT NULL

TEXT 변환 타입 : _DT

예) BIRTH_DT VARCHAR(10) DEFAULT '2016-01-01' NOT NULL

/* 현재월 마지막 ?요일 날짜 구하기  */

SELECT 

    CASE WHEN DDAY < 0 THEN LAST_DAY(SYSDATE) -7 + DDAY * -1

             ELSE LAST_DAY(SYSDATE) - DDAY

             END AS DD

FROM (

    SELECT

        /* 원하는 요일 상수

           일요일:1

           월요일:2

           화요일:3

           수요일:4

           목요일:5

           금요일:6

           토요일:7

        */

        TO_NUMBER(TO_CHAR(LAST_DAY(SYSDATE),'D')) - 4 AS DDAY /* 4=수요일 */

    FROM DUAL

);



모 거래처에서 의뢰를 받아서 Batch 처리 프로그램을 개발하던 중...

테이블을 생성하고 데이터를 조작 해야 할 일이 있어서 실 서버의 특정 테이블을 개발서버로 옮겨서 작업 하기로 했다.

 

실무 담당자의 양해를 구하고 개발이 끝나면 삭제하는 조건으로 실서버에서 원하는 테이블만 추출해서 회사내의 개발 서버로 옮겨서 imp 했더니 아래와 같은 에러가 발생 했다. 

IMP-00010: 엑스포트 파일이 유효하지 않고, 헤더가 검증에 실패했습니다
IMP-00000: 임포트가 실패로 끝났습니다


 

구글링 해보니 dump 받은 파일을 FTP로 전송 할 때 Binary 모드가 아니고 Ascii 모드로 전송하면 저런 에러가 발생 한다는 블로그가 검색 되었지만... 나의 경우는 이문제가 아니고 오라클 버전의 차이때문에 발생하는 문제 였다.

 

운영서버의 오라클은 11g, 회사 내부의 개발 서버가 Windows 2008 Server라서 11g 64bit 설치중 에러가 발생해서 10g로 설치 했었다.

즉 11g에서 exp 명령으로 받은 dump 파일을 10g에서 imp명령으로 올릴 경우 저런 에러가 발생 하는 것 같다. (반대의 경우는 괜찮 겠지...)

 

exp또는 imp 명령의 인자로 버전을 지정 할 수도 있다고 하던데... 귀찮아서 패스

개발 서버의 exp 명령으로 실서버에 접속하여 덤프 받아서 개발서버에 import 하기로 했다.

 

앞서 했던 방법이랑 동일 한 방법 같지만 에러가 발생한 방법은 11g 오라클 클라이언트로 11g에 접속 해서 DB를 덤프 받아서 10g서버의 오라클 클라이언트로 10g서버에 접속해서 import 하는 방법이라면 후자는 10g의 오라클 클라이언트를 이용하여 11g 서버에 접속해서 export 받고 10g의 오라클 클라이언트를 이용하여 10g 서버에 import 하는 것으로 말장난 같지만 확연히 다른 방법이다.

 

 

1. TNS정보 추가

 

10g의 오라클 클라이언트에서 11g를 접속 할 수 있도록 tnsnames.ora 파일에 11g의 TNS정보 추가

 

 

 

2. sqlplus로 접속 테스트

 

sqlplus userid=USERID/PASSWORD@TNSNAME

 

 

 

3. 10g에서 export

 

exp userid=11g_USERID/11g_ASSWORD@11g_TNSNAME file='DUMP_FILE_NAME.dmp' tables=(11g_TABLE1_NAME,11g_TABLE2_NAME)

어찌 하다보니 import 화면을 캡쳐하지 못했다.

 

 

 

4. 10g 에서 import

 

imp userid=10g_USERID/10g_PASSWORD file='DUMP_FILE_NAME.dmp' tables=10g_TABLE_NAME commit=y ignore=y

화면에 보이는 IMP-00017, IMP-00003, ORA-01917등의 오류는 11g에서 받아온 테이블에 CONSTRAINTS, USER 등이 10g에는 존재하지 않아서 발생한 오류로 나의경우 무시해도 상관 없는 것들 이었다.

 

 

5. TOAD로 10g에 접속 해서 확인하니 모두 잘 옮겨짐 

 

 

 

 

6. 참고

 

10g에 import 하기전에 11g에서 옮길 테이블의 동일한 빈테이블을 10g에 생성한 후 작업 했다. 예전의 기억으로 테이블이 없는 경우 에러가 발생했던 기억이...

 

toad 같은 툴에서 테이블 스크립트를 복사해서 그대로 생성해 주면 끝.

MySQL 기반의 제로보드 게시판을 오라클로 옮길때 몇가지 문제점 중 하나.

게시물 등록일자인 reg_date 필드가 속성이 int(13) 형으로 실제 데이터를 보면

1294018642

이처럼 들어간다.

이 숫자는 UNIX 시스템 타임인데

1970년 1월 1일을 기준으로 누적된 초이다.

오라클로 변환할 경우 그냥 number 타입 같은거로 써도 되지만

date 형으로 변환할 방법을 궁리 해 봤다.

 

우선 유닉스 시간을 오라클 형으로 바꾸는 법은

select to_char(to_date('19700101000000','YYYYMMDDHH24MISS') + 1362965195 / 86400 , 'yyyy-mm-dd hh24:mi:ss') as oracle_time from dual;

이것을 참고 하여 reg_date number 형을 reg_date date 형으로 바꿔 보자

변경할 reg_date 컬럼이 있는 테이블 명이 member_table 이라고 하고

 

alter table member_table add reg_date2 date null;

update member_table set reg_date2 = to_date('19700101000000','YYYYMMDDHH24MISS') + reg_date/86400;

commit;

alter table member_table drop column reg_date;

alter table member_table add reg_date date null;

update member_table set reg_date = reg_date2;

commit;

alter table member_table modify reg_date not null;

alter table member_table drop column reg_date2;

select * from member_table;

 

사실은 컬럼의 형을 바꾸는 것은 아니고

컬럼을 새로 추가 하고 날짜 형식으로 복사하는 것이다.

 

오라클 이용시 Toad 나 Orange PL/SQL Developer 같은 클라이언트를 이용 하는경우

무거운 오라클 클라이언트 패키지를 설치 하지 않고

용량작고 필요한 기능만있는 인스턴스 클라이언트를 사용해 보자.

 

다운로드 : http://www.oracle.com/technetwork/database/features/instant-client/index.html

1. 원하는 버전 받아서 적당한 위치에 압축 풀고 환경변수 추가

PATH = %PATH%;C:\oracle\instantclient_11_2
ORACLE_HOME = C:\oracle\instantclient_11_2
TNS_ADMIN = C:\oracle\instantclient_11_2
NLS_LANG = KOREAN_KOREA.KO16MSWIN949

2. 설치 경로에 tnsnames.ora 파일 생성 및 접속하고자 하는 곳의 TNS 정보 추가

이후 Toad로 접속 하면 된다.

+ Recent posts