2013년 11월 27일 수요일

Postgresql 관리 통계 정보

postgresql 통계 정보

시스템을 운영하다보면 시스템의 상태를 확인하고 싶을때가 많다. 시스템의 구석구석을 아는것도 중요하지만 시스템을 모니터링을 통해 시스템의 상태를 정확하게 파악하고 있느것도 매운 중요한 일이다.
PostgreSQL도 마찬가지다. 현재 난 PostgreSQL에 대해서 잘 모른다. 하지만 PostgreSQL의 상태를 알고 싶은 마음은 굴뚝같다. 그래서 여기저기 알아보고 내용을 정리해봤다.

■ PostgreSQL 의 통계정보.
PosgtgreSQL의 통계 정보는 시스템 카탈로그의 pg_stat 로 시작하는 테이블에 저장된다. 현재 데이터베이스 리스트와 OID, 데이터베이스별 사용용량등을 쿼리문을 통해서 확인할수 있다. 이뿐아니라 통계관련 함수도 많이 지원한다.

postgres=# SELECT * FROM pg_stat
pg_stat_activity          pg_statio_all_indexes     pg_statio_sys_sequences   pg_statio_user_tables     pg_stat_sys_tables       
pg_stat_all_indexes       pg_statio_all_sequences   pg_statio_sys_tables      pg_statistic              pg_stat_user_indexes     
pg_stat_all_tables        pg_statio_all_tables      pg_statio_user_indexes    pg_stats                  pg_stat_user_tables      
pg_stat_database          pg_statio_sys_indexes     pg_statio_user_sequences  pg_stat_sys_indexes


많은 통계 테이블이 존재한다. 모든 것을 알면 좋지만 많이 활용하는 순으로 간단하게 하나씩 살펴보도록 하자.

1.pg_stat_activity
이 테이블은 현재 PostgreSQL에서 실행되어지는 쿼리문들을 보여준다. mysql 에서는 show processlist 와 유사하다.
=#\d pg_stat_activity;
          View "pg_catalog.pg_stat_activity"
    Column     |           Type           | Modifiers
---------------+--------------------------+-----------
 datid         | oid                      |
 datname       | name                     |  procpid       | integer                  |  usesysid      | oid                      |
 usename       | name                     |  current_query | text                     |  waiting       | boolean                  |
 xact_start    | timestamp with time zone |
 query_start   | timestamp with time zone |
 backend_start | timestamp with time zone |
 client_addr   | inet                     |
 client_port   | integer                  |
=#SELECT datname, procpid, usename, current_query FROM pg_stat_activity;

이것을 보면 누가 어디에서 접속해서 어느 데이터베이스에 무슨 쿼리를 쓰고 있는지를 알수 있다.

>현재 데이터베이스에 접속한 사람 수.  
=#SELECT COUNT(*) FROM pg_stat_activity;
현재 쿼리 개수. 그런데 한쿼리당 클라이언트 포트를 할당하므로 접속자수라고 할수 있다.
쿼리를 날렸는데 느리거나 할때는 한번 최대 접속자 수(max_connections) 설정값과 비교해 보자

2.pg_stat_database
데이터베이스의 상태 통계를 가지고 있다. 각 컬럼별 의미는 다음과 같다.
 View "pg_catalog.pg_stat_database"
    Column     |  Type   | Modifiers
---------------+---------+-----------
 datid         | oid     |     데이터베이스 OID
 datname       | name    |  데이터베이스 이름
 numbackends   | integer |  활성화된 서버프로세스 개수
 xact_commit   | bigint  | 데이터베이스에서 커밋된 트랜잭션 개수
 xact_rollback | bigint  | 데이터베이스에서 롤백된 트랜잭션 개수
 blks_read     | bigint  | 읽힌 총 디스크 블록 수
 blks_hit      | bigint  |  총 버퍼 히트 수
 tup_returned  | bigint  | 반환된 로우(row) 개수
 tup_fetched   | bigint  | 가져간 로우(row) 개수
 tup_inserted  | bigint  | Insert 되어진 로우 개수
 tup_updated   | bigint  | Update 되어진 로우 개수
 tup_deleted   | bigint  | Delete 도어진 로우 개수

보통 다음과 같은 쿼를 많이 쓴다. 
=#SELECT datname, xact_commit, xact_rollback, tup_inserted, tup_updated, tup_deleted FROM pg_stat_database ORDER BY tup_inserted DESC;
위의 쿼리를 수행하면 누가 데이터베이스를 많이 쓰는지를 알수가 있다.

3.pg_stat_all_tables
현재 접속한 데이터베이스의 각 테이블별 통계를 볼수가 있다. 근데 시스템 카탈로그 테이블도 포함해서 나온다.
View "pg_catalog.pg_stat_all_tables"
    Column     |  Type  | Modifiers
---------------+--------+-----------
 relid         | oid    | 테이블의 OID
 schemaname    | name   | 스키마 이름
 relname       | name   | 테이블 이름
 seq_scan      | bigint | number of sequential scans initiated
 seq_tup_read  | bigint | number of live rows fetched by sequential scans
 idx_scan      | bigint |  number of index scans initiated
 idx_tup_fetch | bigint | number of live rows fetched by index scans
 n_tup_ins     | bigint | 인서트 개수
 n_tup_upd     | bigint | 업데이트 개수
 n_tup_del     | bigint |삭제 개수

위의 테이블로 요약해서 데이터베이스의 인서트, 업데이트, 삭제 개수를 알 수 있다.
=#SELECT SUM(n_tup_ins), SUM(n_tup_upd), SUM(n_tup_del) FROM pg_stat_all_tables;

4.pg_database_size('name')
데이터베이스 사이즈 사용하는 사이즈를 알수 있다.
=#SELECT pg_database_size('abcd');
 pg_database_size
------------------
         12979820
(1 row)
이렇게 하면 byte 단위로 나온다.
이것을 아래와 같이하면 더 쉽게 볼수 있다.
=#SELECT pg_size_pretty(pg_database_size('abcd')) AS size;
 size 
-------
 12 MB
(1 row)
그런데 문제가 있다. pg_database_size는 시스템테이블 크기도 포함한 크기이다. 그래서 실제 순수 데이터베이스 크기를 알기 위해서는 다음과 같이 한다.
=#select pg_size_pretty(cast (sum(pg_total_relation_size(tablename)) as bigint)) as size from pg_tables where schemaname in (current_database());
이렇게 하면 순수 데이터베이스 크기를 알수 있다.

5.pg_tablespace_size('name')
테이블 스페이스의 사이즈를 알수가 있다. 사용법은 위와 같다.

6.특정 namespace(PostgreSQL에서는 스키마라고 함)속한 테이블의 사이즈 알기
각 테이블별 사이즈를 보여준다.
=#select tablename, pg_size_pretty(pg_relation_size(tablename)) as size from pg_tables where schemaname=current_schema() order by pg_relation_size(tablename) desc;

=#select tablename, pg_size_pretty(pg_total_relation_size(tablename)) as size from pg_tables where schemaname=current_schema() order by pg_total_relation_size(tablename) desc;
첫번째거와 두번째에 사이즈 차이가 존재한다. 첫번째에 것이 물리적이 디스크 크기와 같다. 두번째거는 아마 인덱스라든지 스키마정보등의 크기를 모두 합한 사이즈를 나타내는듯하다.

7.PostgreSQL 8.0 버전.
PostgresQL 8.0 버전에서는 위의 몇가지가 동작하지 않는다. 이럴때는 어쩔수 없이 수동으로 해야만 한다.

7-1.데이터베이스 크기 알아내기.
=#SELECT oid, datname FROM pg_database;
abcd | 247690
]#du -hs data/base/247690
13.5M

7-2.테이블 사이즈 알기.
=#SELECT relname, relnamespzce, relfilenode FROM pg_class WHERE relname='abcd';
 relname      | relnamespace | relfilenode
-------------------+--------------+-------------
abcd |       555703 |      556171

]#du -hs data/base/247690/556171

DBMS CONNECTION POOL

DBMS CONNECTION POOL

Administrating Database Resident Connection Pools

/******* Oracle Client Upgrade : oracle 11g client install
ERROR:
ORA-56606: DRCP: Client version does not support the feature
56606, 0000, "DRCP: Client version does not support the feature"
// *Cause: The client version is lower than 11g.
// *Action: Upgrade to a higher client version or turn off (SERVER=POOLED)
//          in the connect string.
********/
To implement database resident connection pooling, it must first be enabled on the system by a user with SYSDBA privileges. See Example 3-12 for steps necessary to initiate and maintain a database resident connection pool.
Example 3-12 How to Administer the Database Resident Connection Pools
A user with SYSDBA privileges must perform the next steps.
  1. Connect to the database.
    SQLPLUS / AS SYSDBA
    
  2. [Optional] Configure the parameters of the database resident connection pool. The default values of a pool are set in the following way:
    EXECUTE DBMS_CONNECTION_POOL.CONFIGURE_POOL('SYS_DEFAULT_CONNECTION_POOL',MINSIZE=>10,MAXSIZE=>200);
  3. [Optional] Alter specific parameters of the database resident connection pool without affecting other parameters.
    DBMS_CONNECTION_POOL.ALTER_PARAM(  'SYS_DEFAULT_CONNECTION_POOL', 
                                       'INACTIVITY_TIMEOUT', 
                                        10);
    
  4. Start the connection pool. After this step, the connection pool is available to all qualified clients.
    DBMS_CONNECTION_POOL.START_POOL( 'SYS_DEFAULT_CONNECTION_POOL');
    
  5. [Optional] Change the parameters of the database resident connection pool.
    DBMS_CONNECTION_POOL.ALTER_PARAM( 'SYS_DEFAULT_CONNECTION_POOL', 
                                      'MAXSIZE', 
                                       20);
    
  6. [Optional] The configuration of the connection pool can be reset to default values.
    DBMS_CONNECTION_POOL.RESTORE_DEFAULTS ( 'SYS_DEFAULT_CONNECTION_POOL');
    
  7. Stop the pool. Note that pool information is persistent: stopping the pool does not destroy the pool name and configuration parameters.
    DBMS_CONNECTION_POOL.STOP_POOL();
    

  • Routing Client Connection Requests to the Connection Pool
In the client application, the connect string must specify the connect type as POOLED.
The following example shows an easy connect string that enables clients to connect to a database resident connection pool:
examplehost.company.com:1521/books.company.com:POOLED
The following example shows a TNS connect descriptor that enables clients to connect to a database resident connection pool:
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost)
       (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
       (SERVER=POOLED)))

  • Data Dictionary Views for Database Resident Connection Pooling

ViewDescription
DBA_CPOOL_INFO
Contains information about the connection pool such as the pool status, the maximum and minimum number of connections, and timeout for idle sessions.
V$CPOOL_CONN_INFO
Contains information about each connection to the connection broker.
V$CPOOL_STATS
Contains pool statistics such as the number of session requests, number of times a session that matches the request was found in the pool, and total wait time for a session request.
V$CPOOL_CC_STATS
Contains connection class level statistics for the pool.

2013년 11월 21일 목요일

standby database rebuild

disable fast_start failover;
disable configuration;
EDIT CONFIGURATION SET PROTECTION MODE AS MaxPerformance;
--duplicate database : for standby database
/home/oracle/DBA/dgrmanconfig.sql
enable configuration;
startup mount;
alter database flashback on;
EDIT CONFIGURATION SET PROTECTION MODE AS MaxAvailability;
enable fast_start failover;


  • STBY 장애시RMAN BACKUP을이용한STBY 재구성.
$ rman target sys/oraclego@tomatosb catalog rman/rmann@suica
 
RMAN> run {
startup nomount;
restore database;
restore controlfile;
alter database mount;
recover database;
alter database flashback on;
}
 
SQL> alter database open;
SQL> RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT FROM SESSION;
 
DGMGRL> enable fast_start failover;
 

  • STBY Trouble 時 DUPLICATEを利用STBY 再構築 
--tomatosbを STANDBY 再構築
/*
PRIMARY
alter database create standby controlfile as '/oracle/oradata/stby.ctl';
 
scp stby.ctl suica-2:/oracle/oradata/SUICASB/control01.ctl
scp stby.ctl suica-2:/oracle/oradata/SUICASB/control02.ctl
 
 
STBY
SQL> startup nomount  -> rman에서하지말것
 
*/
 
rman target sys/oraclego@suicapr catalog rman/rmann@tomato
connect auxiliary sys/oraclego@suicasb
run {
duplicate target database for standby from active database;
}
 
SQL> alter database flasthback on
SQL> alter database open;
 
SQL> RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT FROM SESSION;
 
DGMGRL> enable fast_start failover;
 

Configure Protection Mode & Fast-Start Failover , Observer Start

  • Setting the Configuration Protection Mode
DGMGRL> EDIT DATABASE 'SUICAPR' SET PROPERTY 'LogXptMode'='SYNC';
DGMGRL> EDIT DATABASE 'SUICASB' SET PROPERTY 'LogXptMode'='SYNC';
DGMGRL> EDIT CONFIGURATION SET PROTECTION MODE AS MAXAVAILABILITY;
  • Setting Database Properties
EDIT DATABASE 'SUICAPR' SET PROPERTY 'StaticConnectIdentifier' = '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=suica-1.gamechu.jp)(PORT=1543))(CONNECT_DATA=(SERVICE_NAME=SUICAPR_DGB)(INSTANCE_NAME=SUICAPR)(SERVER=DEDICATED)))';

EDIT DATABASE 'SUICASB' SET PROPERTY 'StaticConnectIdentifier' = '(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=suica-2.gamechu.jp)(PORT=1543))(CONNECT_DATA=(SERVICE_NAME=SUICASB_DGB)(INSTANCE_NAME=SUICASB)(SERVER=DEDICATED)))';
 
  • Enable Flashback Database on the primary and target standby databases
ALTER SYSTEM SET UNDO_RETENTION=3600 SCOPE=SPFILE;
ALTER SYSTEM SET UNDO_MANAGEMENT='AUTO' SCOPE=SPFILE;
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
SHOW PARAMETER UNDO;
ALTER SYSTEM SET DB_FLASHBACK_RETENTION_TARGET=4320 SCOPE=BOTH;
ALTER DATABASE ARCHIVELOG;
--ALTER SYSTEM SET db_recovery_file_dest_size=<size>;
--ALTER SYSTEM SET db_recovery_file_dest=<directory-specification>;
ALTER DATABASE FLASHBACK ON;
ALTER DATABASE OPEN;
----
scope = both : memory, spfile => 현재 적용
scope = spfile : spfile => db restart 후 적용
ALTER SYSTEM SET UNDO_RETENTION=3600 scope=both;
ALTER SYSTEM SET UNDO_MANAGEMENT='AUTO' scope=spfile;
ALTER SYSTEM SET db_recovery_file_dest_size=100G scope=both;
ALTER SYSTEM SET db_recovery_file_dest='/backup/flash_recovery_area' scope=both;
alter system set db_domain='' scope=spfile;

-------------------------------------------------
col db_unique_name for a10
col protection_mode for a20
col flashback_on for a10
col open_mode for a10
col database_role for a20
SELECT DB_UNIQUE_NAME,PROTECTION_MODE,FLASHBACK_ON,OPEN_MOdE,DATABASE_ROLE FROM V$DATABASE
  • enable Fast-Start Failover
DGMGRL>enable fast_start failover;
show fast_start failover;
-- trouble shoot
start observer 
Oracle Error : DGM-16954: Unable to open and lock the Observer configuration file

Cause: The Observer configuration file cannot be opened or cannot be locked for exclusive access.

Action: Make sure the Observer has the correct operating system privileges to write the file and there is no other Observer that is using the same file. Try the command again.

  • ★★★★★ Execute SwitchOver ★★★★★
-- in primary
[oracle@suica-1 ~]$ dgmgrl /DGMGRL> show configuration
Configuration - SUICA
  Protection Mode: MaxAvailability
  Databases:
    SUICAPR - Primary database
    SUICASB - (*) Physical standby database
Fast-Start Failover: ENABLED
Configuration Status:
SUCCESS

DGMGRL> switchover to 'SUICASB'
shutdown immediate;
--startup nomount;
--alter database mount standby database;
alter database open;

  • ★★★★★ Execute Fast-Start Failover ★★★★★
-- primary
sql> shutdown abort
-- new primary
DGMGRL> reinstate database 'SUICAPR';show configuration;
Configuration - SUICA
  Protection Mode: MaxAvailability
  Databases:
    SUICASB - Primary database
    SUICAPR - (*) Physical standby database
Fast-Start Failover: ENABLED
Configuration Status:
SUCCESS
 
DGMGRL> show fast_start failover
Fast-Start Failover: ENABLED
  Threshold:        30 seconds
  Target:           SUICASB
  Observer:         (none)
  Lag Limit:        30 seconds (not in use)
  Shutdown Primary: TRUE
  Auto-reinstate:   TRUE
Configurable Failover Conditions
  Health Conditions:
    Corrupted Controlfile          YES
    Corrupted Dictionary           YES
    Inaccessible Logfile            NO
    Stuck Archiver                  NO
    Datafile Offline               YES
  Oracle Error Conditions:
    (none)
 

  • start observer
start observer file="/oracle/orabase/observer/suica_fsfo.dat"
start observer file="/oracle/orabase/observer/tomato_fsfo.dat"
 
oracle   21957     1  0 Sep07 ?        00:00:01 dgmgrl -logfile /oracle/orabase/observer/suica.log                    START OBSERVER FILE='/oracle/orabase/observer/suica.dat';
oracle   21991     1  0 Sep07 ?        00:00:02 dgmgrl -logfile /oracle/orabase/observer/tomato.log                     START OBSERVER FILE='/oracle/orabase/observer/tomato.dat';
 
------ troubleshoot
dgmgrl /
[P001 08/19 16:03:40.45] Authentication failed.
DGM-16979: Unable to log on to the primary or standby database as SYSDBA
Failed.
answer>
dgmgrl>connect sys/xxxxx@suicapr
--------
DGM-16954: Unable to open and lock the Observer configuration file
Failed.
Cause: The Observer configuration file cannot be opened or cannot be locked for exclusive access.

Action: Make sure the Observer has the correct operating system privileges to write the file and there is no other Observer that is using the same file. Try the command again.
 

Oracle DataGuard Setting

Reference : DataGuard Configuration USING RMAN
  • oracle online document : http://download.oracle.com/docs/cd/E11882_01/server.112/e10700/create_ps.htm#i63561
  • http://www.oracle.com/technology/obe/11gr1_db/ha/dataguard/physstby/physstdby.htm#t2
  • http://hungrydba.com/DataGuard_via_RMAN.aspx
Reference : DataGuard Broker Configuration USING DBMGRL
  • http://download.oracle.com/docs/cd/E11882_01/server.112/e10702/toc.htm
Reference : Duplicating Database
  • http://download.oracle.com/docs/cd/E11882_01/backup.112/e10642/rcmdupdb.htm#BRADV423
Backup & Recovery 構築
  • Backup & Recovery POLICY
  • Backup & Recovery METHOD - RMAN
  • Duplicating Database Script - Daily Execute
  • Maintenance for Flashback database
New Features
  • DBMS_CONNECTION_POOL 
  • RMAN
  • RESOURCE MANAGER
  • Automatic Client Failover
  • DBMS_NETWORK_ACL_ADMIN
DataGuard 構築 (PHYSICAL STANDBY)- SUICA : SUICAPR,SUICASB
1. OS User Setting
2. CreateDB.sql create controlfile
3. initSUICAPR.ora & initSUICASB.ora
initTOMATPR.ora & initTOMATOSB.ora
4. ORACLE PASSWORD FILE CREATION
5. ORA*Net Files : listener.ora, tnsnames.ora, sqlnet.ora
6. Enable archive log mode - ALTER DATABASE ARCHIVELOG;
7. Enable Force Logging - ALTER DATABASE FORCE LOGGING;
8. Create Standby logfile
9. Copy Files from the Primary System to the Standby System Using RMAN
10. Configure DataGuard Broker
convert to snapshot stnadby
★★★★★11. Configure Protection Mode & Fast-Start Failover , Observer Start
★★★★★ Standby Database Rebuild ★★★★★
------------------------------------------------------------------------------------------------- 
ØPreparing the Primary Database for Standby Database Creation - 준비작업
üEnable Forced Logging
üConfigure Redo Transport Authentication
üConfigure the Primary Database to Receive Redo Data
üSet Primary Database Initialization Parameters
üEnable Archiving 
 
ØStep-by-Step Instructions for Creating a Physical Standby Database - 생성
üCreate a Backup Copy of the Primary Database Datafiles
üCreate a Control File for the Standby Database
üCreate a Parameter File for the Standby Database
üCopy Files from the Primary System to the Standby System
üSet Up the Environment to Support the Standby Database
üStart the Physical Standby Database
üVerify the Physical Standby Database Is Performing Properly
 
 
ØPost-Creation Steps – 자동 Failover 를 위한 Database Mode 변경
üUpgrade the data protection mode - Maximum availability
üEnable Flashback Database
------------------------------------------------------------------------------------------------------
Scenario 1: DataGuard Broker Configuration 생성추가
Scenario 2: Configuration Setting – Edit Database Properties 설정
Scenario 3: Enabling the Configuration and Databases – Configuration 적용
Scenario 4: Setting the Configuration Protection Mode - Maxavailability
Scenario 5: Fast-Start Failover 적용 및 Observer Start
Scenario 6: Routine Management Tasks 수행
Scenario 7: Performing a Switchover Operation – Switchover Test
Scenario 8: Performing a Manual Failover Operation – Failover Test
Scenario 9: Reinstating a Failed Primary Database – Primary Database 재구성
Scenario 10: Converting a Physical Standby to a Snapshot Standby
################################################################
  •  
############################################################################## 
----- ----- ----- ----- ----- SUMMARY : Create Physical Standby Database Using RMAN ----- ----- ----- ----- -----
## CREATE STANDBY LOGFILE (PRIMARY)
. .bash_profile1
 ALTER DATABASE ADD STANDBY LOGFILE
   ('/oracle/oradata/first/slog1.rdo') SIZE 10485760;
ALTER DATABASE ADD STANDBY LOGFILE
   ('/oracle/oradata/first/slog2.rdo') SIZE 10485760;
ALTER DATABASE ADD STANDBY LOGFILE
   ('/oracle/oradata/first/slog3.rdo') SIZE 10485760;
## RMAN FULL BACKUP (PRIMARY)
. .bash_profile1
backup database include current controlfile for standby plus archivelog;
## CREATE STANDBY DATABASE (SECOND)
sqlplus sys/oracle@second
startup nomount pfile='initSECOND.ora'
. .bash_profile1
rman
connect target /
connect auxiliary sys/oracle@second
run {   allocate channel prmy1 type disk;  
 allocate channel prmy2 type disk; 
 allocate channel prmy3 type disk;  
 allocate channel prmy4 type disk;  
 allocate auxiliary channel stby type disk;
 duplicate target database for standby from active database    
 spfile      
  parameter_value_convert 'first','second'      
  set db_unique_name='second'      
  set db_file_name_convert='/first/','/second/'      
  set log_file_name_convert='/first/','/second/'
  set control_files='/arch1/second/control1.ctl', '/arch2/second/control2.ctl'
  set log_archive_max_processes='5'    
  set fal_server='first'      
  set standby_file_management='AUTO'      
  set log_archive_config='dg_config=(first,second)'     
  set log_archive_dest_1='LOCATION=/arch1/second/   VALID_FOR=(ALL_LOGFILES,ALL_ROLES)   DB_UNIQUE_NAME=second'   
  set LOG_ARCHIVE_DEST_2='SERVICE=first ASYNC   VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE)   DB_UNIQUE_NAME=first'
     ;
     }
## standby database  into managed standby mode:
sqlplus sys/oracle@second
SQL> alter database recover managed standby database disconnect;
----- ----- ----- ----- ----- END SUMMARY  ----- ----- ----- ----- -----
 ####################################################################################
Put the DR database into managed standby mode:
SQL> shutdown immediate
SQL> startup nomount
SQL> alter database mount standby database;
SQL> alter database recover managed standby database disconnect;

Database Switchover
Using this method you can switch backwards and forwards between the primary and DR servers (e.g. so that the primary can become DR and DR can become primary) without having to rebuild either environment:
 
On Primary Server:
SQL> alter database commit to switchover to standby;
 
This may cause the following error to be generated:
ERROR at line 1:

ORA-01093: ALTER DATABASE CLOSE only permitted with no sessions connected

If this does occur then restart the database, as below, before retrying the above command:
SQL> shutdown immediate
SQL> startup
 
SQL> shutdown immediate
SQL> startup nomount
SQL> alter database mount standby database;
SQL> alter database recover managed standby database disconnect;
 
The primary server is now configured as a DR standby database.
 
On DR Server:
SQL> alter database recover managed standby database cancel;
SQL> alter database commit to switchover to primary;
SQL> shutdown immediate
SQL> startup
 
The DR server is now configured as the primary database.
To switch back you just need to repeat the above process but the other way around (e.g. convert the DR database back to a standby and the primary database back to primary).
Activating a Standby Database
If the primary database is not available the standby database can be converted into the primary database as follows:
 
SQL> alter database recover managed standby database cancel;
SQL> alter database activate standby database;
SQL> shutdown immediate
SQL> startup
 
The original primary database is now obsolete and can be rebuilt as a standby database once it is available again.
 
Opening the Standby Database in Read Only Mode
The standby database can be opened in read only mode for querying and then converted back into a standby database without affecting the primary.
 
On standby server:
SQL> alter database recover managed standby database cancel;
SQL> alter database open read only;
 
The standby database is now open and available for querying in read only mode.
To put the standby database back into standby mode:
 
SQL> shutdown immediate
SQL> startup nomount
SQL> alter database mount standby database;
SQL> alter database recover managed standby database disconnect;
---------- DGMGRL BASE Commands--------------------------
show configuration
switchover to second
failover to second
show fast_start failover
enable fast_start failover (disable)
start observer (stop)
--How to Re Instate Database (dgmgrl)
. .bash_profile1
dgmgrl>startup mount
. .bash_profile2
dgmgrl>reinstate database first

#######################################################################
#################### TROUBLESHOOT ######################################
  • troubleshoot --12537
-- password file 생성 후 remote 접속 테스트
test) sqlplus oracle@FIRSTsys/xxx@suicapr as sysdba
test) sqlplus sys/xxx@suicasb as sysdba
12537, 00000, "TNS:connection closed"
// *Cause: "End of file" condition has been reached; partner has disconnected.
// *Action: None needed; this is an information message.
 
=> confirm listener status

  • troubleshoot --1031
-- password file 생성 후 remote 접속 테스트
sqlplus '/as sysdba'
ERROR:
ORA-01031: insufficient privileges
<answer>
=> confirm sqlnet.ora
# sqlnet.ora
NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
ADR_BASE = /oracle
#SQLNET.AUTHENTICATION_SERVICES = (NONE)
#SQLNET.AUTHENTICATION_SERVICES = (NTS) 

DGMGRL> disable configuration
Error: ORA-16654: fast-start failover is enabled
Failed.
DGMGRL> disable fast_start failover;
Error: ORA-16652: fast-start failover target standby database is disabled
Failed.
DGMGRL> disable fast_start failover force;
 
  • troubleshoot --16191
-- primary open 이후 remote 연결 상태 자동 체크
ORA-16191: Primary log shipping client not logged on standby
PING[ARC2]: Heartbeat failed to connect to standby 'SECOND'. Error is 16191.
<answer>
lsnrctl reload
or
Modify SQL*Net file (sqlnet.ora, tnsnames.ora, listener.ora)
------------------------------------------------------------------------------------------------------
RMAN 사용중
ORA-17628: Oracle error 19505 returned by remote Oracle server
[oracle@suica-1 DBA]$ oerr ora 17628
17628, 00000, "Oracle error %s returned by remote Oracle server"
// *Cause:  Oracle server on the remote instance has returned an error.
// *Action: Look at remote instance alert log/trace file for more information
//          and take appropriate action or contact Oracle Support Services
//          for further assistance
[oracle@suica-1 DBA]$ oerr ora 19505
19505, 00000, "failed to identify file \"%s\""
// *Cause:  call to identify the file returned an error
// *Action: check additional messages, and check if the file exists
 
stand by file destination 확인
----------------------------------------------------------------------------------------------------------
backup database include current controlfile for standby plus archivelog;
RMAN-06059: expected archived log not found, lost of archived log
compromises recoverability
ORA-19625: error identifying file /u02/oradata/scr9/archive/1_1160.dbf
ORA-27037: unable to obtain file status
Linux Error: 2: No such file or directory
Additional information: 3

<answer>
Your options are either to restore the missing file(s), or to perform a crosscheck. To perform a crosscheck, run the following command from within RMAN:
 
change archivelog all crosscheck;
Database High Availability, B&R
  • ORACLE Data Guard
  • ORACLE Backup & Recovery 
    • Backup Policy
    • RMAN
  • MSSQL Backup & Rcovery
    • Backup Policy
    • Restore Script
  • MYSQL Backup & Rcovery
    • MySQL Dump 
    • MySQL Replication 
  • POSTGRESQL Backup & Rcovery
    • Postgresql Dump
  • Oracle auto-start script (Linux)- OS init rc3, rc5


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