반응형

파티션 테이블 유무에 따라 사용법이 나뉩니다.

 

 

1. Non 파티션 테이블 백업

 

- 대상 데이터베이스 : test

- 대상 테이블 : ZIPDB

 

a. FLASH TABLES 권한이 있는 계정으로 접속합니다. (어려우면 root 접속)

   

    MariaDB [TEST]> FLUSH TABLES test.ZIPDB FOR EXPORT;

    Query OK, 0 rows affected (0.013 sec)

 

b. 위의 명령어가 정상적으로 끝나면 기본 데이터 저장하는 곳에 파일 생성됩니다.

   (기본 yum 설치시 : /var/lib/mysql 이며 그 밑에 데이터베이스 명 폴더로 갑니다.)

   cd /var/lib/mysql/test

   ls -lsa를 수행하면 

 

 

  일반적으로 보이지 않는 zipdb.cfg 파일이 하나더 생성됨을 알 수 있습니다.

   ※ 현재 이상태는 백업을 위해 TABLE LOCK을 한 상태입니다.

 

c. 테이블 이동을 위한 복사 작업을 수행합니다

   cp /var/lib/mysql/test/zipdb.ibd /tmp

   cp /var/lib/mysql/test/zipdb.cfg /tmp

 

d. 복사가 정상적으로 끝나면 TABLE LOCK을 풀어줍니다.

  MariaDB [TEST]> UNLOCK TABLES;
  Query OK, 0 rows affected (0.019 sec)

 

위의 작업을 마치면 정상적으로 해당 테이블을 백업 받은 상태입니다.

 

2. Non 파티션 테이블 복구하기

복구할 Database로 2개의 파일(zipdb.ibd, zipdb.cfg)을 복사합니다.

복사시에는 같은 망인 경우 scp를 사용하면 편리합니다.

(scp /tmp/zipdb.* root@대상hostIP:/tmp)

 

a. 먼저 테이블 생성 구문을 동일하게 수행합니다.   

CREATE TABLE `zipdb` (
`ZONE_NO` VARCHAR(5) NOT NULL COMMENT '구역번호(우편번호)',
`CTPRVN` VARCHAR(20) NULL DEFAULT NULL COMMENT '시도',
`CTPRVN_ENG` VARCHAR(40) NULL DEFAULT NULL COMMENT '시도영문',
`SIGNGU` VARCHAR(20) NULL DEFAULT NULL COMMENT '시군구',
`SIGNGU_ENG` VARCHAR(40) NULL DEFAULT NULL COMMENT '시군구영문',
`EUP_MYEON` VARCHAR(20) NULL DEFAULT NULL COMMENT '읍면',
`EUP_MYEON_ENG` VARCHAR(40) NULL DEFAULT NULL COMMENT '읍면영문',
`RN_CODE` VARCHAR(12) NULL DEFAULT NULL COMMENT '도로명코드',
`RN` VARCHAR(80) NULL DEFAULT NULL COMMENT '도로명',
`RN_ENG` VARCHAR(80) NULL DEFAULT NULL COMMENT '도로명영문',
`UNDGRND_AT` VARCHAR(1) NULL DEFAULT NULL COMMENT '지하여부(0:지상, 1:지하)',
`BDNBR_MNNM` INT(5) NULL DEFAULT NULL COMMENT '건물번호본번',
`BDNBR_DUCA` INT(5) NULL DEFAULT NULL COMMENT '건물번호부번',
`BULD_MANAGE_NO` VARCHAR(25) NULL DEFAULT NULL COMMENT '건물관리번호',
`MUCH_DLVR_OFFIC_NM` VARCHAR(40) NULL DEFAULT NULL COMMENT '다량배달처명(null)',
`SIGNGU_BDNBR_NM` VARCHAR(200) NULL DEFAULT NULL COMMENT '시군구용건물명',
`LEGALDONG_CODE` VARCHAR(10) NULL DEFAULT NULL COMMENT '법정동코드',
`LEGALDONG_NM` VARCHAR(20) NULL DEFAULT NULL COMMENT '법정동명',
`LI_NM` VARCHAR(20) NULL DEFAULT NULL COMMENT '리명',
`ADSTRD_NM` VARCHAR(40) NULL DEFAULT NULL COMMENT '행정동명',
`MNTN_AT` VARCHAR(1) NULL DEFAULT NULL COMMENT '산여부(0:토지, 1:산)',
`LNM_MNNM` INT(4) NULL DEFAULT NULL COMMENT '지번본번',
`EMD_SN` VARCHAR(2) NULL DEFAULT NULL COMMENT '읍면동일련번호',
`LNM_DUCA` INT(4) NULL DEFAULT NULL COMMENT '지번부번',
`OLD_ZIP` VARCHAR(6) NULL DEFAULT NULL COMMENT '구 우편번호(null)',
`ZIP_SN` VARCHAR(3) NULL DEFAULT NULL COMMENT '우편번호일련번호(null)', INDEX `ZIPDB_IX1` (`ZONE_NO`), INDEX `ZIPDB_IX2` (`CTPRVN`, `SIGNGU`, `EUP_MYEON`), INDEX `ZIPDB_IX3` (`RN_CODE`), INDEX `ZIPDB_IX4` (`RN`)
) COLLATE='utf8_general_ci' ENGINE=InnoDB
;

b. 생성후에는 ALTER TABLE ... DISCARD TABLESPACE 명령을 사용하여 새로운 테이블의 테이블스페이스를 폐기합니다.

MariaDB [TEST]> ALTER TABLE test.zipdb DISCARD TABLESPACE;

c. ibd 파일과 cfg 파일을 데이터베이스 (test) 폴더에 붙여 넣습니다.

복구할 서버 데이터베이스 저장 위치 : /var/lib/mysql/test

 

# cp /tmp/zipdb.* /var/lib/mysql/test/

 

root 권한으로 복사시에는 아래의 퍼미션을 부여합니다.

# chown -R mysql:mysql /var/lib/mysql/test/zipdb.*

 

.ibd 파일 만으로도 테이블 스페이스로 파일을 가지고 올 수 있습니다.   

(.cfg 파일은 테이블 스페이스 정보 가지고 있음)

 

d. 다음 명령을 사용하여 새 테이블에 데이터를 가지고 옵니다.

 

MariaDB [(none)]> ALTER TABLE test.zipdb IMPORT TABLESPACE;

퍼미션이 맞지 않는 경우 다음의 에러가 발생

ERROR 1030 (HY000): Got error 194 "Tablespace is missing for a table" from storage engine InnoDB

 

 

e. 복구 결과

   정상적으로 모든 데이터 건수가 일치하는 것을 알 수 있습니다.

 

파티셔닝 복구 방식

https://mariadb.com/kb/en/library/innodb-file-per-table-tablespaces/

 

InnoDB File-Per-Table Tablespaces

InnoDB file-per-table tablespaces: what they are, where they're located, how to copy them, and other details.

mariadb.com

 

반응형

'Database > MYSQL' 카테고리의 다른 글

MariaDB connect 설치  (0) 2019.11.07
MariaDB JSON 컬럼 및 함수들  (0) 2019.11.04
MariaDB 우편번호 Import 하기  (0) 2019.11.01
MariaDB SHA2 512 방식으로 암호화 예제  (0) 2019.10.25
Mysql & MariaDB 튜닝 쉘  (0) 2019.08.14
반응형

MariaDB와 Mysql 성능을 테스트하기 위해

 

HammerDB를 사용하다가

 

보니...

 

정작 중요한 my.cnf 설정이 정상적인가? 물음에 도달하게 되었습니다.

 

정확한 설정값을 위해 자동 튜닝 스크립트를 제공하는 사이트를 발견하였습니다.

 

보통 정상적으로 튜닝 범주라고 체크 할려면 48시간이상 이용해야 한다는 사실은 존재합니다.

 


 

virtualbox 상에서 실행한 결과 (OK : 정상 / !! 설정 이상 / -- SKIP)

 

 >>  MySQLTuner 1.7.15 - Major Hayden <major@mhtx.net>
 >>  Bug reports, feature requests, and downloads at http://mysqltuner.com/
 >>  Run with '--help' for additional options and output filtering

[--] Skipped version check for MySQLTuner script
[OK] Logged in using credentials passed on the command line
[OK] Currently running supported MySQL version 10.3.17-MariaDB
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: /var/lib/mysql/hammerdb.err(0B)
[!!] Log file /var/lib/mysql/hammerdb.err doesn't exist
[!!] Log file /var/lib/mysql/hammerdb.err isn't readable.

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE
[--] Data in InnoDB tables: 999.9M (Tables: 9)
[OK] Total fragmented tables: 0

-------- Analysis Performance Metrics --------------------------------------------------------------
[--] innodb_stats_on_metadata: OFF
[OK] No stat updates during querying INFORMATION_SCHEMA.

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] User 'root@%' does not specify hostname restrictions.
[!!] There is no basic password file list!

-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 34m 1s (279K q [136.873 qps], 133 conn, TX: 74M, RX: 38M)
[--] Reads / Writes: 50% / 50%
[--] Binary logging is disabled
[--] Physical Memory     : 1.8G
[--] Max MySQL memory    : 15.2G
[--] Other process memory: 0B
[--] Total buffers: 1.4G global + 28.2M per thread (500 max threads)
[--] P_S Max memory usage: 0B
[--] Galera GCache Max memory usage: 0B
[!!] Maximum reached memory usage: 1.7G (94.00% of installed RAM)
[!!] Maximum possible memory usage: 15.2G (845.58% of installed RAM)
[!!] Overall possible memory usage with other process exceeded memory
[OK] Slow queries: 0% (0/279K)
[OK] Highest usage of available connections: 2% (11/500)
[OK] Aborted connections: 1.50%  (2/133)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 1M selects)
[OK] Query cache prunes per day: 0
[OK] No Sort requiring temporary tables
[OK] No joins without indexes
[OK] Temporary tables created on disk: 0% (22 on disk / 37K total)
[OK] Thread cache hit rate: 90% (13 created / 133 connections)
[OK] Table cache hit rate: 95% (141 open / 147 opened)
[OK] Open file limit used: 1% (59/4K)
[OK] Table locks acquired immediately: 100% (108 immediate / 108 locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Performance schema is disabled.
[--] Memory used by P_S: 0B
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 2 thread(s).
[--] Using default value is good enough for your version (10.3.17-MariaDB)

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (24M used / 134M cache)
[OK] Key buffer size / total MyISAM indexes: 128.0M/123.0K
[OK] Read Key buffer hit rate: 98.9% (180 cached / 2 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 4
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 1.0G/999.9M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (99.609375 %): 340.0M * 3/1.0G should be equal to 25%
[!!] InnoDB buffer pool <= 1G and Innodb_buffer_pool_instances(!=1).
[--] Number of InnoDB Buffer Pool Chunk : 8 for 8 Buffer Pool Instance(s)
[OK] Innodb_buffer_pool_size aligned with Innodb_buffer_pool_chunk_size & Innodb_buffer_pool_instances
[OK] InnoDB Read buffer efficiency: 99.84% (26160668 hits/ 26202270 total)
[!!] InnoDB Write Log efficiency: 83.1% (617680 hits/ 743341 total)
[OK] InnoDB log waits: 0.00% (0 waits / 125661 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is enabled.
[OK] Aria pagecache size / total Aria indexes: 128.0M/1B

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] Binlog format: MIXED
[--] XA support enabled: ON
[--] Semi synchronous replication Master: OFF
[--] Semi synchronous replication Slave: OFF
[--] This is a standalone server

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Restrict Host for user@% to user@SpecificDNSorIp
    MySQL was started within the last 24 hours - recommendations may be inaccurate
    Reduce your overall MySQL memory footprint for system stability
    Dedicate this server to your database for highest performance.
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Performance schema should be activated for better diagnostics
    Consider installing Sys schema from https://github.com/mysql/mysql-sys for MySQL
    Consider installing Sys schema from https://github.com/good-dba/mariadb-sys for MariaDB
    Before changing innodb_log_file_size and/or innodb_log_files_in_group read this: https://bit.ly/2TcGgtU
Variables to adjust:
  *** MySQL's maximum memory usage is dangerously high ***
  *** Add RAM before increasing MySQL buffer variables ***
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 1M, or use smaller result sets)
    performance_schema = ON enable PFS
    innodb_log_file_size should be (=85M) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
    innodb_buffer_pool_instances (=1)

 


Perl로 작성된 쉘이 아래 주소에 있으며,

 

https://github.com/major/MySQLTuner-perl

 

major/MySQLTuner-perl

MySQLTuner is a script written in Perl that will assist you with your MySQL configuration and make recommendations for increased performance and stability. - major/MySQLTuner-perl

github.com

 

2019.08.14 

mysqltuner.pl
0.22MB

 

실행법

#> perl mysqltuner.pl --user root --pass='root'

 

지원하는 DB는

 

Test result are available here: Travis CI/MySQLTuner-perl

  • MySQL 8 (partial support, password checks don't work)
  • MySQL 5.7 (full support)
  • MySQL 5.6 (full support)
  • MariaDB 10.3 (full support)
  • MariaDB 10.2 (full support)
  • MariaDB 10.1 (full support)
  • MariaDB 10.0 (full support, 6 last month support)
  • Percona Server 5.7 (full support)
  • Percona Server 5.6 (full support)
  • Percona XtraDB cluster (full support)
  • MySQL 3.23, 4.0, 4.1, 5.0, 5.1, 5.5 (partial support - deprecated version)
  • Perl 5.6 or later (with perl-doc package)
  • Unix/Linux based operating system (tested on Linux, BSD variants, and Solaris variants)
  • Windows is not supported at this time (Help wanted !!!!!)
  • Unrestricted read access to the MySQL server (OS root access recommended for MySQL < 5.1)
  • CVE vulnerabilities detection support from https://cve.mitre.org

 

반응형
반응형


I. RECOVERY ON A TEST MACHINE:
이 부분이 다른 서버에서 복구하는 것이구요.

II. RECOVERY ON A PRODUCTION MACHINE:
이 부분이 동일 서버에서 인스턴스 하나 띄워서 복구하는 것입니다.
문서 보시고 하면 됩니다.



PURPOSE
-------

This bulletin outlines the steps to perform recovery to restore
a dropped table without recovering the entire database.  The bulletin
assumes the reader is familiar with Oracle's recovery procedures which
are documented in the Oracle documentation set.

SCOPE & APPLICATION
----------------------

This bulletin discusses dropped table recovery using traditional (Oracle7)
backup and recovery procedures. These can equally be applied to Oracle8. It
does NOT discuss tablespace point in time recovery (TSPITR) or the Recovery
Manager (RMAN) duplicate database feature.

The examples in this bulletin are UNIX-based, but can be easily applied to
other platforms with little modification.


RECOVERING A DROPPED TABLE FROM A FULL DATABASE BACKUP
------------------------------------------------------

TERMINOLOGY
-----------

PROD machine - Host computer on which the production database runs. Also
               denotes the ORACLE_SID of the production instance.
TEST machine - Host computer, physically distinct from the machine on which the
               production database runs.
TEMP         - The ORACLE_SID of the instance used to access the restored
               database.
The backup   - The set of backed up database structures (see REQUIREMENTS) used
               as the basis for recovering the dropped table. Once restored,
               this set of structures is referred to as the partially restored
               database.

REQUIREMENTS
------------

The following data structures must be available from the backup:
- All system tablespace datafiles
- All rollback segment datafiles
- All datafiles in which the table to recovered is stored
- Archive logs - see Note (a)
Notes:
 (a) If the restored datafiles are part of a hot backup, or you wish to
     roll them forward, the required archivelogs must be available.

In an ideal world the partially restored database will be made available for
recovery on a TEST machine. However this may not always be possible, and
it may be necessary to restore to the same machine on which the 'source'
(PROD) database resides. The latter is NOT RECOMMENDED as a user error in the
recovery process can corrupt the production database.

If the datafiles comprising the partially restored database were in hot
backup mode at the time the table was dropped, it is necessary to restore
a previous backup. The reason for this is that the hot backup must be rolled
forward past the 'end backup' markers (the time that the tablespaces were taken
out of hot backup mode) before the database can be opened. Failure to recover
the restored datafiles past their end backup markers will result in the
following error when an attempt is made to open the database:

  ORA-1195 "online backup of file %s needs more recovery to be consistent"

I. RECOVERY ON A TEST MACHINE:
------------------------------

The following steps are to be used when performing recovery on a TEST machine,
the assumption being that there is no instance with the ORACLE_SID "PROD"
or "TEMP" already running on the TEST machine.

 1. On the PROD database, connect as a privileged user and create an ASCII
    dump of the controlfile. For example:

      SVRMGR> connect / as sysdba
      SVRMGR> alter database backup controlfile to trace resetlogs;

    A trace file will be generated in the user_dump_dest destination. Rename
    this trace file to ccf.sql and save it.

 2. Create a directory on the TEST machine. The restored database will be
    located in this directory. In this example the directory is called
    /RESTORE. The only stipulation is that there is enough space to easily
    accomodate the restored database and any archivelogs required for recovery.
    If filesystem space is at a premium, the archivelogs may be optionally
    restored to /RESTORE as required by recovery, and removed after they have
    been applied.

 3. Restore the backup to the /RESTORE directory.

 4. Optionally, restore all archivelogs required for recovery to the /RESTORE
    directory.

 5. Copy the init.ora file (initPROD.ora) from the PROD database to the /RESTORE
    directory on the TEST machine. This assumes that all database parameters are
    specified in only the init.ora file. If an include files (ifile) is
    referenced, also copy this file to /RESTORE.

 6. Rename the initPROD.ora to initTEMP.ora on the TEST machine.

 7. Edit the initTEMP.ora and make the following modifications:
    a. control_files = /RESTORE/cntrlTEMP.dbf
    b. if applicable, change any ifile references to point to the copied
       include file
    c. log_archive% parameters should be changed to reflect the restored
       archivelogs:
         log_archive_destination
         log_archive_format
       For example:
         log_archive_destination=/RESTORE
         log_archive_format=arch_%s.dbf
    d. %dump_dest parameters should be changed to point to suitable directories

    e. If audit is on, turn it off.

 8. Ensure that the shell environment is set correctly. At the very least, the
    following environment variables must be defined:
    a. ORACLE_HOME
    b. ORACLE_SID (should be set to TEMP)

 9. Connect as a privileged user. For example:

      SVRMGR> connect / as sysdba

10. Start the instance, specifying TEMP's init.ora:

     SVRMGR> startup nomount pfile=/RESTORE/initTEMP.ora

11. The ccf.sql file (created in Step 1) contains the syntax necessary to
    create a new controlfile. Copy this script to the TEST machine and edit
    it to save only the text between (and including) 'CREATE CONTROLFILE'
    and it's terminating semi-colon. Modify the following sections:

    a. LOGFILE. Edit this section to reflect the names of the online logs to
       be created for the TEMP instance. If the PROD instance has a large
       number of large online log members, it is advisable to specify a
       reduced number of smaller log members. You MUST however specify at
       least two online log groups.
    b. DATAFILE. Edit this section to reflect the names of the restored
       datafiles only.
    c. Miscellaneous:
       - Remove the REUSE keyword
       - Optionally change the ARCHIVELOG keyword to NOARCHIVELOG (so the
         TEMP database will not operate in archivelog mode)

    An example of the completed ccf.sql script might be:

      CREATE CONTROLFILE DATABASE "PROD" RESETLOGS NOARCHIVELOG
          MAXLOGFILES 16
          MAXLOGMEMBERS 2
          MAXDATAFILES 20
          MAXINSTANCES 1
          MAXLOGHISTORY 337
      LOGFILE
        GROUP 1 '/RESTORE/log1PROD.dbf'  SIZE 1M,
        GROUP 2 '/RESTORE/log2PROD.dbf'  SIZE 1M
      DATAFILE
        '/RESTORE/sys1PROD.dbf',
        '/RESTORE/rbs1RBS.dbf',
        '/RESTORE/users1PROD.dbf'
      ;

    Then execute ccf.sql script to create control file(s).

12. Recover the database. The database is to be recovered to a time before
    the table was dropped. There are two options here:
    a. Time-based incomplete recovery. Database recovery is stopped at the
       specified date and time.
    b. Cancel-based incomplete recovery. Database recovery is stopped on
       an archivelog boundary i.e. the granularity of cance-based recovery
       is the archivelog.

    Example of time-based recovery:

      SVRMGR> recover database until time '2000-01-10:12:00:00' using backup controlfile

    In the above example, apply archivelogs as requested. Recovery will stop
    automatically at 12:00 on Januaru 10th, 2000.

    Example of cancel-based recovery:

      SVRMGR> recover database until cancel using backup controlfile

    As soon as you have applied the last desired archivelog, type CANCEL
    to stop recovery.

13. Open the database with the RESETLOGS option:

      SVRMGR> alter database open resetlogs;

14. Export the table(s).

15. Import the table(s) into the PROD database.

16. Once the necessary tables have been imported, the TEMP instance can be
    shutdown and all associated files removed. It is worthwhile verifying that
    the import has completed successfully before removing the TEMP instance.

II. RECOVERY ON A PRODUCTION MACHINE:
-------------------------------------

If a TEST machine is not available for performing recovery, the PROD machine
can be used. It is important to exercise extreme caution when doing this. The
restored database will be operate under the TEST instance as before. During
this procedure the restored database's name is changed in order to avoid
problems in acquisition of the mount lock.

 1. Take a FULL backup of the database running against the PROD instance
    before performing any recovery.

 2. While connected to the PROD instance, create an ASCII dump of the
    controlfile:

      SVRMGR> connect / as sysdba
      SVRMGR> alter database backup controlfile to trace resetlogs;

 3. Create a /RESTORE directory as before (Step 2 above).

 4. Restore the backup (and optionally the archivelogs) to the /RESTORE
    directory (Steps 3 and 4 above).

 5. Create the initTEMP.ora file (Steps 5, 6, 7 above). In addition to the
    changes already made, modify the db_name parameter, for example:
      db_name=TEMP

 6. Ensure that the shell environment is set correctly (Step 8 above):
    a. ORACLE_HOME
    b. ORACLE_SID (should be set to TEMP)

 7. Start the TEMP instance (Steps 9, 10 above). It is critical to ensure
    that the correct pfile is used to start the instance.

 8. Modify the ccf.sql file (Step 11 above). It is critical to ensure that
    the DATAFILE and LOGFILE names reference the backup location and NOT the
    PROD instance database's files. In addition to the changes already made,
    modify the first line to set the new database name, for example:
      from: CREATE CONTROLFILE DATABASE "PROD" RESETLOGS NOARCHIVELOG
        to: CREATE CONTROLFILE SET DATABASE "TEMP" RESETLOGS NOARCHIVELOG

 9. Recover the database (Step 12 above).

10. Open the database (Step 13 above).

11. Export the table(s).

12. Import the tables(s).

13. Cleanup the TEMP instance (Step 16 above).

반응형

'Database > ORACLE' 카테고리의 다른 글

tnsnames.ora 등록 없이 Database Link 만들기  (0) 2010.08.03
System Account Lock (System 계정 락 걸림)  (0) 2010.07.15
PL/SQL Exception  (0) 2010.07.06
RMAN 사용법  (0) 2010.07.06
오라클 암호화 기능  (0) 2010.07.02
반응형

--- Arup Nanda 의 사이트에 자주 들어가봅니다. DBA 로서의 장애 Case 를 대응하는 절차가 비교적 자세히 나와있더군요. 요즘 일이 많아서 빠르게 쓰다보니 오역과 중간중간 빼먹는게 많은건 이해해주시길...아래는 실제로 DMA (direct memory access)를 사용해서 처리한 사례더군요..

  

Diagnosing Library Cache Latch Contention: A Real Case Study

 

어느날 DW 서버가 갑자기 다운됐다. 그래서 데이타베이스를 올리고 다시 구동했지만 모든 접속을 시도하면
hang 이 걸리는 것이였다. 따라서 접속은 실패하고 DBA는 접속된 세션들이 구동되고 있는지 어떤지를 확인할 수 조차도
없었다. DBA 는 WAIT 이벤트를 체크했다 (그러나 로긴조차도 안되기 때문에 실행할수 없었다)
흥미롭게도 CPU는 70% 정도의 수준이였고 이는 낮시간대의 일반적인 수치이다. 그리고 I/O또한 약 90%로서 이또한
일반적인 수치였다.

따라서 전형적인 방법인 system 관리자에게 보고하고 재부팅을 하는 방법을 사용했다. 재부팅은 30분정도
소요되었고 그 후로 10여분간은 모든것이 정상적으로 보였다. 그러나 얼마되지 않아 아까와같은 똑같은 문제에 부딪쳤다- 데이타베이스가 먹통이 되어버린 것이였다.

이것 때문에 DBA가 나에게 도움을 요청하였다. 이 블로그에서는 내가 이후의 30분동안에 어떻게 수행했고 문제를
해결했는지에 대해서 기술해보도록 하겠다.

 

증상


(1) 데이타베이스 접속 Hanging
(2) SQL*PLUS AS SYSDBA 로 접속해도 동일한 HANGING 현상: 증상을 확인할 수도 없는 상태
(3) 시스템은 아무때나 리부팅할 수 없는 상태

 

Action

 

여기서 접속이 불가능할 때 데이타베이스 인스턴스에서 바로 써먹을 수 있는 꼼수가 존재한다.
대부분의 사람들은 SQL*Plus 에서 "prelim" 이라고 불리는 옵션을 잘알지 못한다. 이 옵션은 세션을 열지 않고
SGA에 바로 접속한수 있는 옵션이다. (10g 이상에서만 가능) 

 

(1) 먼저 SQL*plus 를 실행시키고 아래의 명령문을 실행했다.

 

$ sqlplus -prelim / AS SYSDBA
SQL>

 

명심하라. "Oracle Database 10.2.0.3 에 접속" 과 다르다. 지금 보이는 SQL> 프롬프트는 실제로는
데이타베이스에 접속한 상태가 아니다.

 

(2) 그다음 SGA 를 분석하기 위한 "oradebug" 를 사용하였다.

 

SQL> oradebug setmypid
SQL> oradebug hanganalyze 12

 

이 명령은 USER_DUMP_DEST 에 trace파일을 생성한다. 이 파일을 가장 최근에 생겨났기 때문에
쉽게 찾을 수 있다. 심지어는 내가 파일을 찾지 못해도 process ID를 사용해서 파일을 찾을 수 있다.
내가 찾은 파일은 프로세스ID 가 13392인 crmprd1_ora_13392.trc 였다.

(3) 파일을 조사하니 다음과 같았다.

 

*** 2008-08-23 01:21:44.200
==============
HANG ANALYSIS:
==============
Found 163 objects waiting for
<0/226/17/0x1502dab8/16108/no>
Open chains found:
Chain 1 : :
<0/226/17/0x1502dab8/16108/no>
<0/146/1/0x1503e898/19923/latch:>

이 파일을 많은 것을 말해준다. SID 146 에 Serial# 1 이 library cache latch 를 대기하고 있는 것을 보여준다.(맨마지막줄)
그리고 blocking 세션은 SID 226 Serial# 17 로 나와있다. 

나는 일단 이 OS process ID 인 16108 과 19923 을 기록해두었다.

 

(4) 다음으로 위의 두개의 OS PID 명으로 되어 있는 TRACE 파일을 체크했다.

 

crmprd1_ora_16108.trc
crmprd1_ora_19923.trc

 

(5) 먼저 BLOCKER인 첫번째 파일을 열었다. 다음 몇줄의 예이다.

 

*** 2008-08-23 01:08:18.840
*** SERVICE NAME:(SYS$USERS) 2008-08-23 01:08:18.781
*** SESSION ID:(226.17) 2008-08-23 01:08:18.781
LIBRARY OBJECT HANDLE: handle=c0000008dc703810 mtx=c0000008dc703940(8000) cdp=32737
name=UPDATE DW_ETL.FRRS_PROFILER SET CONSUMER_LINK = :"SYS_B_0", ADDRESS_LINK = :"SYS_B_1", ADDRESS_MATCH = :"SYS_B_2", PROC
ESSED=:"SYS_B_3" WHERE RNUM = :"SYS_B_4"
hash=a029fce7bb89655493e7e51a544592a4 timestamp=08-23-2008 00:10:23
namespace=CRSR flags=RON/KGHP/TIM/OBS/PN0/MED/KST/DBN/MTX/[504100d0]
kkkk-dddd-llll=0000-0001-0001 lock=N pin=0 latch#=10 hpc=0058 hlc=0058
lwt=c0000008dc7038b8[c0000008dc7038b8,c0000008dc7038b8] ltm=c0000008dc7038c8[c0000008dc7038c8,c0000008dc7038c8]
pwt=c0000008dc703880[c0000008dc703880,c0000008dc703880] ptm=c0000008dc703890[c0000008dc703890,c0000008dc703890]
ref=c0000008dc7038e8[c0000008dc7038e8,c0000008dc7038e8] lnd=c0000008dc703900[c0000008dc703900,c0000008dc703900]
LOCK OWNERS:
lock user session count mode flags
---------------- ---------------- ---------------- ----- ---- ------------------------
c0000008d079f1b8 c0000006151744d8 c0000006151744d8 16 N [00]
c0000008d4e90c40 c0000006151bcb58 c0000006151bcb58 16 N [00]
c0000008d0812c40 c0000008151a0438 c0000008151a0438 16 N [00]

 
(6) 이것은 디버깅을 위해 보물과 같았다. 첫번째에 SID와 Serial#(226,17) 를 확인할수 있다.
이를 사용해서 정확한 SQL문장을 볼수 있다. 또한 락에 대한 전체적인 상황을 볼 수 있다. 락의 자세한 사항은 신경쓰지 않아도 되지만 SID 226 이 전체 세션의 대기를 유발시키는 것이라는 충분한 정보를 제공해주었다.

 

(7) 나의 조사는 여기서 그치지 않고  이 대기를 유발하는 세션을 찾기를 시도했다. 따라서 나는 파일의 "PROCESS STATE" 이라는 섹션을 조사했다. 다음은 이 파일의 일부분이다.

 

PROCESS STATE
-------------
Process global information:
process: c00000081502dab8, call: c000000817167890, xact: 0000000000000000, curses: c00000081519ef88, usrses: c000000815
19ef88
----------------------------------------
SO: c00000081502dab8, type: 2, owner: 0000000000000000, flag: INIT/-/-/0x00
(process) Oracle pid=370, calls cur/top: c000000817167890/c000000817167890, flag: (0) -
int error: 0, call error: 0, sess error: 0, txn error 0
(post info) last post received: 115 0 4
last post received-location: kslpsr
last process to post me: c000000615002038 1 6
last post sent: 0 0 24
last post sent-location: ksasnd
last process posted by me: c000000615002038 1 6
(latch info) wait_event=0 bits=20
holding (efd=4) c0000008d7b69598 Child library cache level=5 child#=10
Location from where latch is held: kglhdgc: child:: latch
Context saved from call: 13
state=busy, wlstate=free
waiters [orapid (seconds since: put on list, posted, alive check)]:
291 (197, 1219468295, 197)
279 (197, 1219468295, 197)
374 (197, 1219468295, 197)
267 (197, 1219468295, 197)
372 (197, 1219468295, 197)
... several lines sniped ...
307 (15, 1219468295, 15)
181 (6, 1219468295, 6)
waiter count=58
Process Group: DEFAULT, pseudo proc: c0000008e03150d8
O/S info: user: oracrmp, term: UNKNOWN, ospid: 16108
OSD pid info: Unix process pid: 16108, image: oracle@sdwhpdb1


 

 

(8) 이파일은 내가 알기를 원하는 것을 모두 말해준다. 여기에 SID 226 에 의해서 발생하는 CACHE LATCH
로 인해서 대기하는 58 session들이 있다. 여기서 OS PROCESS ID 와 BLOCKING 세션의 SQL 문장을 알 수 있다.

 

 

(9) 나는 application 사용자가 어떠한 것을 실행했는지를 조사해봤더니 사용자는 loop를 돌면서 처리하는
update 문장을 실행시킨 것이였다. 그리고 그게 다가 아니라 다른 8개의 thread 에서 실행을 하였다.(역: 아마도 화면상에서 처리 가 되지 않으니 화면을 새로고쳐서 계속해서 8번을 처리 버튼을 누른것으로 생각됨)
의심할 여지가 없이 library cache latch 경합에 걸렸다. 모든 세션은 각각의 덤프 정보를 남겼다.
그리고 나는 같은 문장을 실행한 파일을 디렉토리에서 조사해보기로 했다.

 

$ grep “UPDATE DW_ETL” *.trc

 

(10) 나는 9개 이상의 세션(프로세스) 파일을 찾았다. 이중 한개의 파일의 일부분이다.

 

350 (167, 1219470122, 167)
197 (167, 1219470122, 167)
waiter count=185
Process Group: DEFAULT, pseudo proc: c0000008e03150d8
O/S info: user: oracrmp, term: UNKNOWN, ospid: 16114

 

이 프로세스 한개가 185개 waiter 를 가졌다!!!


 

$ kill -9

 

(12) 위의 명령으로 몇개의 프로세스를 죽인 후에야 데이타베이스는 응답하기 시작했다. 모든 프로세스를 죽인 후에는 데이타베이스 wait event 가 완벽히 정상적으로 돌아왔다.

 

참고사항


(1) Hang 이라고 생각되면 너무 그것에 대해 불안해하지 마라. 세션은 언제나 어떤것을 대기한다. 드물게 행을 만날 뿐이다.

v$session (10g) 이나  v$session_wait 의 EVENT 컬럼을 조회해서 대기하는 것이 무엇인지를 먼저 체크하라.

(2) 데이타베이스에 로긴하지 못해 정보를 얻을 수 없을 때는 oradebug 명령을 사용한다.

(3) oradebug 를 사용할때 SQL*Plus 를 이용한다. 로긴하지 못할때 "sqlplus -prelim " 로 SQL prompt 를 얻을 수 있을 것이다.

(4) oradebug setmypid  이용해서 oradebug 세션을 시작하고 oradebug hanganalyze  로 모든 hang 과 관련되어 있는

문제에 대한 덤프를 생성한다.

(5) oradebug help 를 사용해서 oradebug 커맨드의 모든것을 볼 수 있다.

 

 

반응형

+ Recent posts