ORACLE/TUNING2012. 3. 8. 11:17
반응형

-- SQL 튜닝 대상선정(10g)하기
select trunc(a.disk_reads/a.executions,0) diskreads,
       trunc(a.buffer_gets/a.executions,0) bufferget, 
       trunc(a.elapsed_time/a.executions/1000000,0) elapsetime,
       trunc(a.ROWS_PROCESSED/a.executions,0) return_rows,
       a.executions,
       a.last_load_time,
       module,action, length(sql_fulltext), sql_fulltext, address,sql_id,parsing_schema_name
  from v$sql  a 
 where executions > 0
   and command_type in ( 3, 6,7)
   and module not in ( 'SQL Developer','Orange for ORACLE DBA')
   and buffer_gets / executions > 1000
 order by elapsetime desc ;
    
command_type - 2 (insert)
command_type - 3 (select)
command_type - 7 (delete)
command_type - 6 (update)
  
-- bind 변수 확인
select * from v$sql_bind_capture where address = 'C000000095EFDDC0';
select * from dba_hist_sqlbind where sql_id = '0b5b05k3akd1w'  order by snap_id desc, position;
  
-- full text
select 'AA'||sql_text||'BB' from  v$sqltext_with_newlines where address = 'C000000095EFDDC0'
 order by Piece
select 'AA'||sql_text||'BB' from  v$sqltext_with_newlines where sql_id = 'gzcf51wp0pqxt' 
order by Piece
  
-- plan보기
select p.plan_table_output
  from (select distinct sql_id, child_number
          from v$sql_plan s
         where s.address = '' or 
               s.sql_id = '0as4u6a4fky2n') s,
        table(dbms_xplan.display_cursor (s.sql_id, s.child_number, 'typical')) p;
  
--  awr plan보기
select sql_id,lpad(' ',depth*4,'  ')||' '||operation|| ' ' ||options|| ' '
 ||object_name|| ' (' ||cost||')'plan, to_char(timestamp,'YYYY-MM-DD HH24:MI:SS') as "date"
   from DBA_HIST_SQL_PLAN 
where sql_id in ('fac0jhjuwg9k9'
order by timestamp,sql_id,plan_hash_value, id;
  
-- awr 성능 보기
select sql_id, module, b.begin_interval_time,
       trunc(buffer_gets_delta/decode(executions_delta,0,1,executions_delta)) buffer_gets,
       trunc(disk_reads_delta/decode(executions_delta,0,1,executions_delta)) disk_reads,
       trunc(fetches_delta/decode(executions_delta,0,1,executions_delta)) fetchs,
       trunc(ROWS_PROCESSED_DELTA/decode(executions_delta,0,1,executions_delta)) ROWS_PROCESSED,
       trunc(elapsed_time_delta/1000000/decode(executions_delta,0,1,executions_delta)) 
   as elapsed_time,
       trunc(IOWAIT_DELTA/1000000/decode(executions_delta,0,1,executions_delta)) IOWAIT,
       trunc(APWAIT_DELTA/1000000/decode(executions_delta,0,1,executions_delta)) APWAIT,
       trunc(CLWAIT_DELTA/1000000/decode(executions_delta,0,1,executions_delta)) CLWAIT,
       trunc(CCWAIT_DELTA/1000000/decode(executions_delta,0,1,executions_delta)) CCWAIT,
       executions_delta executions
 from DBA_HIST_SQLSTAT a, 
      dba_hist_snapshot b
where a.sql_id = '7rcjrfsh81jy2'
  and a.snap_id  = b.snap_id
  and a.dbid = b.dbid
  and b.instance_number = 1
  and b.begin_interval_time between to_timestamp('20110701','YYYYMMDD')
 and to_timestamp('2012','YYYY')
  order by a.snap_id;
  
-- trace를 못 뜰때?ㅋ 
select /*+ gather_plan_statistics */ * 
from SCOTT.TEST where key > 10000;
select * from table(dbms_xplan.display_cursor(null,null,'ALLSTATS LAST'));
  
dbms_xplan.display_cursor format 종류
   - Basic, Typical, Outline, All, Advanced, 
   - allstats last, +peeked_binds

반응형
Posted by [PineTree]
ORACLE/TUNING2012. 3. 8. 11:15
반응형

V$SQL BIND CAPTURE

EXEM Knowledge Base

Jump to: navigation, 찾기

목차

[숨기기]

[편집] 기본 정보

[편집] 개요

V$SQL_BIND_CAPTURE 뷰는 SQL 커서에서 Bind Variable이 사용된 경우 해당 Bind Variable의 이름과 유형, 값 등을 캡쳐한 정보를 제공한다.

[편집] 지원

10g 이상

[편집] 컬럼

이름 유형 설명
ADDRESS 8) Parent Cursor의 Address
HASH_VALUE NUMBER Parent Cursor의 Hash Value.
SQL_ID VARCHAR2(13) Unique SQL ID. V$SQL의 SQL_ID 컬럼과 조인 가능하다.
CHILD_ADDRESS 8) Child Cursor의 Address
CHILD_NUMBER NUMBER Child Cursor의 번호.
NAME VARCHAR2(30) Bind Variable의 이름. 예: :name
POSITION NUMBER SQL 문장에서 Bind Variable의 위치. 1부터 시작한다.
DUP_POSITION NUMBER Bind Variable의 이름이 중복되는 경우 최초 Bind Variable의 위치를 가리킨다.
DATATYPE NUMBER Bind Variable의 데이터 유형. 오라클 내부적으로 사용되는 숫자값이다.
DATATYPE_STRING VARCHAR2(15) Bind Variable의 데이터 유형에 대한 인식 가능한 이름. 예:NUMBER, VARCHAR2
CHARACTER_SID NUMBER National character set identifier
PRECISION NUMBER Precision (for numeric binds)
SCALE NUMBER Scale (for numeric binds)
MAX_LENGTH NUMBER 최대 Bind 길이
WAS_CAPTURED VARCHAR2(3) Bind 값에 대한 Capture가 이루어졌는지의 여부 (YES) 또는 (NO)
LAST_CAPTURED DATE Bind 값에 대한 Capture가 이루어진 가장 최근 시간
VALUE_STRING VARCHAR2(4000) Bind 값에 대한 String 표현
VALUE_ANYDATA ANYDATA Bind 값에 대한 Sys.AnyData에 의한 표현


[편집] 참고 사항

[편집] Bind Capture가 이루어지는 시점

Oracle은 다음과 같은 시점에 Bind Capture를 수행한다.

  • SQL 문장이 Hard Parse되는 시점에 Bind Variable이 사용되고 Bind 값이 부여된 경우
  • Bind Capture가 이루어진 이후, Bind 값이 변경된 경우. 단, 오라클의 성능상의 오버헤드를 최소화기 위해 15분 이상의 간격을 두고 Capture를 수행한다. 즉, Bind Capture된 값이 항상 최신의 값을 나타내는 것이 아니라는 것에 주의해야 한다.

[편집] Bind 값 알아내기

Oracle 10g 이전에는 특정 SQL 문장에서 사용 중인 Bind 값을 알아내고자 할 때는 Processstate Dump를 수행하거나 SQL Trace, 혹은 Audit를 수행했어야 했다. 하지만, V$SQL_BIND_CAPTURE 뷰를 사용하면 간단한 조회만으로 Bind 값을 알아낼 수 있게 되었다. 각 툴이 제공하는 값의 종류는 다음과 같이 정리할 수 있다.

  • Processstate Dump: 특정 Session(Process)가 "현재" 수행 중인 SQL 문장에서 사용되는 Bind 값의 목록
  • SQL Trace: 특정 Session이나 System 전체가 수행한 모든 SQL 문장에서 사용된 Bind 값
  • V$SQL_BIND_CAPTURE: SQL 문장별로 최근에 사용된 Bind 값
  • Audit: 특정 테이블 또는 전체 오브젝트에 대한 Select/Insert/Update/Delete에 대한 SQL 문장과 Bind 값

[편집] Bind 값의 이력

V$SQL_BIND_CAPTURE 뷰의 History 버전인 DBA_HIST_SQLBIND 뷰를 통해 과거 특정 시점에 특정 SQL 문장에서 사용된 Bind 값을 확인할 수 있다.

[편집] 예제

SQL> CREATE TABLE bind_test(id INT);
SQL> var x number;
SQL> EXEC :x := 1;
SQL> select * from bind_test where id = :x';

SQL> SELECT name, position, was_captured, 
	to_char(last_captured,'yyyy/mm/dd hh24:mi:ss'), value_string
   FROM v$sql_bind_capture
   WHERE sql_id = (SELECT sql_id FROM v$sql WHERE sql_text =
   ('select * from bind_test where id = :x')
   
NAME	POSITION	WAS_CAPTURED	LAST_CAPTURED		VALUE_STRING
----	--------	----------	--------------		------------
:X	1		YES		2007/10/13 00:16:19	1
반응형
Posted by [PineTree]
ORACLE/TroubleShooting2012. 3. 6. 16:37
반응형


SELECT a.ksppinm "Parameter", b.ksppstvl "Session Value",
  2         c.ksppstvl "Instance Value"
  3    FROM x$ksppi a, x$ksppcv b, x$ksppsv c
  4   WHERE a.indx = b.indx AND a.indx = c.indx
  5         AND a.ksppinm LIKE '%kgl_large_heap%';

Parameter
--------------------------------------------------------------------------------

Session Value
--------------------------------------------------------------------------------
--------------------
Instance Value
--------------------------------------------------------------------------------
--------------------
_kgl_large_heap_warning_threshold
52428800
52428800


출처 : http://gampol.tistory.com/entry/Memory-Notification-Library-Cache-Object-loaded-into-SGA

조치방법: (다음과 같이 조치후 서버 restart)
sqlplus “/as sysdba”
alter system set "_kgl_large_heap_warning_threshold"=8388608 scope=spfile ;
shutdown immediate
startup

 
원인: (Cause 항목 참조)
해당 오류메시지는 Error 가 아닌 Warning 입니다.
이는 shared pool 영역중 libraray cache 영역의 단편화가 심해 Free Memory를 찾는데 오랜 시간이 걸릴 때 
위와 같은 오류가 발생합니다.
새로운 트랜잭션이 발생시 SQL의 파싱결과 등이 저장되는 library cache영역에 단편화로 인한 메시지로 
10g R2의 메모리 관리 메커니즘에 따른 메시지로 보시면됩니다.
 
 
=======================================================================
Applies to:
Oracle Server - Enterprise Edition - Version: 
This problem can occur on any platform.
Symptoms
The following messages are reported in alert.log after 10g Release 2 is installed.
       Memory Notification: Library Cache Object loaded into SGA
       Heap size 2294K exceeds notification threshold (2048K)
Changes
Installed / Upgraded to 10g Release 2
Cause
These are warning messages that should not cause the program
responsible for these errors to fail.  
They appear as a result of new event messaging mechanism
and memory manager in 10g Release 2. The meaning is that the
process is just spending a lot of time in finding free memory
extents during an allocate as the memory may be heavily fragmented.
Real memory messages should be ORA-403x when  a real memory allocation problem 
occurs.
Solution
In 10g we have a new undocumented parameter that sets the KGL heap size
warning threshold.   This parameter was not present in 10gR1.
Warnings are written if heap size exceeds this threshold.
   
Set  _kgl_large_heap_warning_threshold  to a reasonable high value or zero
to prevent these warning messages. Value needs to be set in bytes. 
If you want to set this to 8192 (8192 * 1024) and are using an spfile: 
(logged in as "/ as sysdba")
SQL> alter system set "_kgl_large_heap_warning_threshold"=8388608 scope=spfile ; 
SQL> shutdown immediate SQL> startup 
SQL> show parameter _kgl_large_heap_warning_threshold
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
_kgl_large_heap_warning_threshold integer 8388608 
If using an "old-style" init parameter, 
Edit the init parameter file and add 
_kgl_large_heap_warning_threshold=8388608
In 10.2.0.2,  the threshold is increased to 50MB after regression tests, so this should be a reasonable and recommended value.
References

 

http://surachartopun.com/2008/07/memory-notification-library-cache.html

10.2.0.1 Annoying message "Memory Notification: Library Cache Object loaded into SGA"
Posted: March 5, 2006 by Frits Hoogland in Oracle EE, Oracle XE 
9In the 10.2.0.1 version of the oracle database a new heap checking mechanism, together with a new messaging system is introduced. 
This new mechanism reports memory allocations above a threshold in the alert.log, together with a tracefile in the udump directory.

In certain situations it can be handy to know if large allocations are being done in the sga heap (shared pool), 
but only to troubleshoot memory allocation problems (which eventually will appear as the infamous ORA-4031). 
For normal day to day work, I doubt the effectivity of these messages.

The default limit is set at 2048K. It appears normal usage can result in messages from the memory manager. 
During my last installation (with all options set default, all options installed), 
this resulted in 125 messages from the memory manager.

Oracle gives a solution on metalink in note 330239.1:
Set _kgl_large_heap_warning_threshold to a “reasonable high” value. This parameter is set in bytes, 
and oracle recommends the value 8388608 (8192K).


Wednesday, July 30, 2008
Memory Notification: Library Cache Object loaded into SGA
 
Today, I checked alert.log file. I found:

Memory Notification: Library Cache Object loaded into SGA
Heap size 9426K exceeds notification threshold (8192K)

When I found out on metalink:
These messages are report in alert.log after 10g Release 2 is installed.

Cause:

These are warning messages that should not cause the program responsible for these errors to fail. They appear as a result of new event messaging mechanism and memory manager in 10g Release 2.

The meaning is that the process is just spending a lot of time in finding free memory extents during an allocate as the memory may be heavily fragmented. Fragmentation in memory is impossible to eliminate completely, however, continued messages of large allocations in memory indicate there are tuning opportunities on the application.

The messages do not imply that an ORA-4031 is about to happen.

Solution:

In 10g we have a new undocumented parameter that sets the KGL heap size warning threshold. This parameter was not present in 10gR1. Warnings are written if heap size exceeds this threshold.

Set _kgl_large_heap_warning_threshold to a reasonable high value or zero to prevent these warning messages. Value needs to be set in bytes.

If you want to set this to 8192 (8192 * 1024) and are using an spfile:

(logged in as "/ as sysdba")

SQL> alter system set "_kgl_large_heap_warning_threshold"=10485760 scope=spfile ;

SQL> shutdown immediate

SQL> startup

SQL> show parameter _kgl_large_heap_warning_threshold

NAME TYPE VALUE

--------------------------------- ------- ------------------------------
_kgl_large_heap_warning_threshold integer 10485760

If using an "old-style" init parameter,

Edit the init parameter file and add

_kgl_large_heap_warning_threshold=10485760

 

반응형
Posted by [PineTree]
ORACLE/INSTALL2012. 1. 10. 23:46
반응형
 
작성자 : 박상수
작성일자 : 2010.12.08
작업환경 : VMware7 [ RHEL3 , Oracle 10g 기준 ]
참고자료 : 서진수 샘, 정성재 샘, 리눅스공유메모리, 보안구성설정(PAM&Ulimit)



오라클의 공유 메모리는 커널 작업을 수반하지 않으며 프로세스 간의 데이터 복제 작업이 불필요 하기 때문에 , IPC(inter-Process Communication)를 위한 가장 빠른 방법을 선호 되고 있습니다.
오라클은 인스턴스 구조를 보면 SGA(System Global Area)와 백 그라운드 프로세스로 구성 되어 있습니다. 여기에서 SGA는 Shared Pool, DB Cache, Redo Log Buffer  등의 저장에 활용되므로 SGA 크기에 따라 오라클 성능이 크게 달라집니다.

그럼 오라클을 설치하기 전에 Linux에서 사용하는 커널 매개변수와 Shell Limit에 대해서 알아 보도록 하겠습니다.


1. Linux 커널 매개변수의 설정

다른 UNIX 시스템과 달리, Linux 운영체제에서는 시스템이 실행 중인 상태에서 대부분의 커널 매개변수를 수정할 수 있습니다. 커널 매개변수를 변경한 뒤에 시스템을 리부팅할 필요도 없습니다. Oracle Database 10g가 요구하는 커널 매개변수 설정할 수 있으나 시스템에 이미 커널 메게변수가 높은 수치로 설정 되어있을 경우에는 변경 하지 마시기 바랍니다.

[ 매개변수 - kernel.shmmax ] SHMMAX 매개변수는 공유 메모리 세그먼트의 최대 크기(바이트 단위)를 정의하는데 사용됩니다. 오라클 SGA 메모리로 구성되며, SHMMAX가 올바르게 설정되지 않을 경우 SGA의 크기가 제약될 수도 있습니다. 따라서 SGA의 크기보다 작지 않도록 SHMMAX를 설정합니다.
총 10GB의 메모리에서 오라클이 사용할 수 있는 최대 한도를 정의 하는 것을 의미 합니다.
먄약 SHMMAX 매개변수가 잘못 설정될 경우에는 아래와 같은 오라클 에러 메시지가 발생 됩니다.

ORA-27123: unable to attach to shared memory segment

기본적으로 SHMMAX 기본 값은 32MB 입니다. SGA로 사용하기에는 너무 적은 공간이기 때문에 적당한 크기로 변경 해야 합니다.
[2010-12-09 03:26:18]-[root@calmmass:/proc/sys/kernel]
# cat /proc/sys/kernel/shmmax |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
33.554.432

[ 매개변수 - kernel.shmall ]
SHMALL 커널 매개변수는 특정 시점에 시스템에서 사용 가능한 공유 메모리의 최대 크기(페이지 단위)를 설정하는데 사용됩니다. 따라서 이 매개변수는 최소한 아래 값보다 커야 합니다.
ceil(SHMAX/PAGE_SIZE)
우선 페이지 사이즈를 확인 해보겠습니다. Red Hat Linux의 페이지 사이즈는 기본적으로 4,096 바이트 입니다.
[2010-12-09 02:51:29]-[root@calmmass:~]
# getconf PAGESIZE |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
4.096

SHMALL의 디폴트 사이즈는 아래와 같습니다. sed를 이용해서 3자리로 구분한 결과 2MB를 사용합니다.
# cat /proc/sys/kernel/shmall |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
2.097.152

[ 매개변수 - kernel.shmmni ] SHMMNI는 공유 메모리 식별자의 개수를 의미 하며 권장 값은 100 이상 으로 설정하셔야 합니다. 아래와 같이 확인 하시기 바랍니다.
[2010-12-09 03:26:07]-[root@calmmass:/proc/sys/kernel]
# cat shmmni
4096

[ 매개변수 - kernel.sem ] 세마포어(Semaphore)란 공유 리소스의 사용 과정에서 프로세스(프로세스 내 쓰레드) 간의 동기화를 위해 사용되는 일종의 카운터(counter) 입니다. 애플리케이션의 세마포어를 이용하면, 운영 체제는 SET를 통해 세마포어를 지원하게 됩니다.
그럼 세마포어 설정 값을 먼저 확인 해보겠습니다.
[2010-12-09 03:39:32]-[root@calmmass:/proc/sys/kernel]
# ipcs -lm
------ Shared Memory Limits --------
max number of segments = 4096
max seg size (kbytes) = 32768
max total shared memory (kbytes) = 8388608
min seg size (bytes) = 1

SEM 매개변수는 세마포어 최대값을 조정 가능하며 의미는 아래와 같습니다.
의미 : {배열당 최대 SEM 수}{최대SEM시스템넓이}{SEMOP호출당최대OP수}{최대배열수} 
[2010-12-09 03:37:24]-[root@calmmass:/proc/sys/kernel]
# cat /proc/sys/kernel/sem |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
250 32.000 32 128
  1  2         3   4 (필드 라고 정의 하겠습니다.)
1 필드 값(250) : SEMMSL 매개변수는 세미포어 set 당 세마포어의 최대 개수를 정의합니다. 오라클을 예로 init[SID].ora 파일(pfile, spfile 동일)의 PROCESS 인스턴스 매개변수의 (전체 데이터베이스 중) 최대값에 10을 더한 값을 사용할 것을 권장하고 있습니다. 그래서 100이상의 값을 정의하는 것을 권장 합니다.

2 필드 값(32.000) : SEMMNI 매개변수는 전체 Linux 시스템의 세마포어 set의 개수를 정의 합니다. 오라클에서는 100이상의 값을 정의하는 것을 권장합니다.

3 필드 값(32) : SEMMNS 매개변수는 전체 Linux 시스템의 ("세마포어 set"이 아닌) 세마포어의 최대 개수를 정의 합니다. 오라클은 인스턴스 매개변수의 값을 모두 더한 뒤, 가장 큰 Processes값을 두 차례 더하고, 마지막으로 각 데이터베이스 별로 10을 더한 값을 SEMMNS를 설정하도록 권장 합니다.

4. 필드 값(128) : SEMOPM 매개변수는 semop 시스템 호출(system call) 별로 수행될 수 있는 세마포어 작업의 수를 설정하는데 사용됩니다.SEMOPM을 SEMMSL과 동일하게 설정하는 것을 권장합니다. 오라클에서는 100이상의 값으로 설정할 것을 권장 하고 있습니다.


[ 매개변수 - fs.file-max ] Red Hat Linux 서버를 구성하는 과정에서, 사용 가능한 파일 핸들(file handle)의 수가 충분한지 확인하는 것을 매우 중요합니다. 파일 핸들의 최대 개수 설정에 따라 Linux 시스템에서 동시에 오픈할 수 있는 파일의 수가 달라지게 됩니다.
오라클은 전체 시스템의 파일 핸들 수를 최소 65536개 이상으로 설정 할 것을 권장 하고 있습니다.
전체 시스템에서 사용 가능한 파일 핸들의 최대 값을 확인 해보겠습니다.
[2010-12-09 04:06:03]-[root@calmmass:/proc/sys/fs]
# cat /proc/sys/fs/file-max |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
104.857

[ 매개변수 - net.Ipv4.Ip_local_port_range ] 이부분은 새 접속에서 사용할 수 있는 포트의 사용 가능 범위를 확장하는 의미를 가지고 있습니다.
시스템에서 사용하는 포트번호는 /etc/services 파일에 구성 되어있습니다.
[2010-12-09 04:06:24]-[root@calmmass:/proc/sys/fs]
# tail /etc/services
binkp  24554/udp   # Binkley
asp  27374/tcp   # Address Search Protocol
asp  27374/udp   # Address Search Protocol
.. 생략 ..

매개변수의 값을 확인 해보겠습니다. 오라클은 1024 ~ 65000까지 허용하도록 권장 합니다.
[2010-12-09 04:14:10]-[root@calmmass:/proc/sys/net/ipv4]
# cat /proc/sys/net/ipv4/ip_local_port_range |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
32.768 61.000

[ 매개변수 - net.core.rmem_default, net.core.rmem_max ] 일반적인 경우의 대용량 Serving을 위한 설정 합니다. 오라클은 기본적으로 대용량 데이터베이스를 기준으로 하기 때문에 기본 설정 된 값을 변경해야 합니다. 아래와 같은 경우에는 기본 설정 값입니다.
[2010-12-09 04:18:03]-[root@calmmass:/proc/sys/net/core]
# cat /proc/sys/net/core/rmem_default |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
65.535
[2010-12-09 04:18:29]-[root@calmmass:/proc/sys/net/core]
# cat /proc/sys/net/core/rmem_max |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
131.071

[ 매개변수 - net.core.wmem_default, net.core.wmem_max] 소켓 출력 큐의 기본 값과 최대 값을 조정하기 위한 매개변수 입니다. 일반적인 경우의 대용량 Serving을 위한 설정이므로 역시 rmem_default, rmem_max의 값과 동일하게 구성해는 것이 바랍직 합니다. 기본적으로 설정 되어있는 값을 확인 해보겠습니다.
# cat /proc/sys/net/core/wmem_default |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
65.535
[2010-12-09 04:23:05]-[root@calmmass:/proc/sys/net/core]
# cat /proc/sys/net/core/wmem_max |sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1.\2/;ta'
131.071

[ 커널 매개변수 반영 ]
이상으로 매개변수의 용도와 설정값을 확인 하는 방법을 실습 했습니다.
이번에는 커널 매개변수를 오라클 기준으로 변경해서 반영 해보도록 하겠습니다. 기본적으로는 위에 나와있는 설정 파일에 값을 변경 해도 되며, sysctl -w [매개변수명]=value 명령어를 이용 할 수 있습니다. 하지만 이번 문서에서는 리눅스의 장점을 살려 환경설정 파일로 매개변수를 반영 하겠습니다.

오라클(바로가기) 설치 메뉴얼에는 아래와 같이 설정 하길 권장합니다.
cat >> /etc/sysctl.conf <<EOF
kernel.shmall = 2097152
kernel.shmmax = 2147483648
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
EOF
/sbin/sysctl -p

파라매터를 더 추가해보겠습니다. (강추 입니다.)
kernel.shmmax=536870912
kernel.shmmni=4096
kernel.shmall=2097152
kernel.sem=250 32000 100 128
fs.file-max=65536
net.ipv4.ip_local_port_range=1024 65000
net.core.rmem_default=262144
net.core.rmem_max=262144
net.core.wmem_default=262144
net.core.wmem_max=262144



2. Shell Limit 설정

오라클은 Linux 계정 별로 실행되는 프로세스와 열린 파일의 수를 제한하는 것을 권장합니다. 이를 위해, root 계정에서 아래 내용을 /etc/security/limits.conf 설정파일에 oracle10g 라는 특정 프로그램을 제어하는 방법을 설명 하겠습니다.

[참고] /lib/security/pam_limits.so 모듈이 사용할 설정 파일이 /etc/security/limits.conf 파일 입니다. 그중에서 각각 설정에 대해서 아래와 같이 정리 하였습니다.
domain : 제한을 할 대상으로써 사용자 이름이나 그룹 이름, 그리고 와일드 문자를 사용할 수 있습니다.
type : 강하게 제한할 것인지 아니면 어느 정도 여유를 줄 것인지 결정을 합니다.(soft, hard)
item :  제한을 할 항목입니다.
    - core : core 파일 사이즈(KB)
    - data : 최대 데이터 크기(KB)
    - fsize : 최대 파일 사이즈(KB)
    - memlock : 최대 locked-in-memory 주소 공간(KB)
    - nofile : 한번에 열 수 있는 최대 파일 수
    - rss : 최대 resident set size(KB)
    - stack : 최대 스택 사이즈(KB)
    - cpu : 최대 CPU 점유 시간(MIN)
    - nproc : 최대 프로세스 개수
    - as : 주소 공간 제한
    - maxlogins : 동시 로그인 최대 수
    - priority : 사용자 프로세스가 실행되는 우선 순위

[참고] ulimit를 이용하여 리소스를 제한하는 방법입니다. ulimit는 PAM과는 조금 다르게 root계정까지도 제한을 할 수 있습니다. 여기에서 제한에는 두가지 종류가 있습니다.
Soft Limit : 새로운 프로그램이 생성되면 디폴트로 적용되는 제한
Hard Limit : Soft Limit에서 최대 늘릴 수 있는 제한
단, Hard Limit는 root 유저에 의해 조정 가능하지만 무한히 늘리 수 없기 때문에 커널에서 해당 설정 값을 조정 후 늘릴 수 있습니다.


[ oracle10g soft  nproc 2047 ] oracle10g 라는 프로그램이 처음 수행시 기본값으로 사용하는 프로세스는 최대 2047로 제한한다는 의미 입니다.
[ oracle10g hard nproc 16384 ] oracld10g 라는 프로그램이 수행시 사용하는 프로세스는 최대 16384로  제한 한다는 의미 입니다.
[ oracle10g soft  nofile 1024 ] oracle10g 라는 프로그램이 처음 수행시 기본값으로 사용하는 파일은 최대 1024로 제한 한다는 의미입니다.
[ oracle10g hard nofile 65536 ] oracle10g 라는 프로그램이 수행시 사용하는 파일은 최대 65536으로 제한 한다는 의미 입니다.


[의문점] 어떤 방식으로 해야 이상적인 설정 일까요?
이상적인 설정은 실제로 oracle database가 가동 되고 나서 개수 제한으로 에러가 발생 하지 않게 하는 것이 가장 이상적인 설정이라고 볼 수 있습니다. 그래서 최대한 해당 프로세스의 개수가 어느정도인지 파일의 개수는 평균적으로 어느정도 사용하는지 파악후 설정 해주는것이 바람직합니다.

그럼 특정 프로그램이 사용하는 프로세스의 개수를 테스트 해보도록 하겠습니다.
[2010-12-09 05:38:43]-[root@calmmass:/proc/sys/net/core]
# lsof -p 3094 |wc -l
    1370

열려있는 파일 개수 확인 하는 방법
[2010-12-09 05:39:01]-[root@calmmass:/proc/sys/net/core]
# sysctl -a |grep file
fs.file-max = 104857
fs.file-nr = 1995 472 104857

마지막으로 /etc/security/limits.conf 리소스 제한 설정파일에 oracle 설치시 필요한 설정 내역은 아래와 같습니다.
oracle10g soft nproc 2047
oracle10g hard nproc 16384
oracle10g soft nofile 1024
oracle10g hard nofile 65536




Oracle을 각 OS별 설치하면서 느낀 점은 위와 같은 설정 내역이 조금씩 다르다는 점입니다.
그렇다면 이러한 설정 내역을 모두 외우는것은 무의미하고 어떤 작업에 의해서 설정을 해야 하는지를 먼저 파악하는 것이 우선이라고 생각 합니다.
각 설정 파일의 역활과 오라클이 구동 되었을때 사용하는 용도를 보면 조금 접근하기기 편하지 않을까 생각 해봅니다.
반응형

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

오라클 11G upgrade관련문서  (0) 2013.10.29
oracle silent install  (0) 2012.05.11
오라 클 9.2.0.1에서 Patch 셋 올리기  (0) 2010.05.31
oracle enterprise manager 한글 버튼 깨짐 문제  (0) 2010.01.11
RAC 패치 절차  (0) 2009.12.15
Posted by [PineTree]
ORACLE/TUNING2012. 1. 10. 20:49
반응형
  1. SQL*Plus Autotrace 기능 활성화
    1-1 EXPLAIN PLAN 이란?
    사용자들이 SQL 문의 액세스 경로를 확인하고 튜닝을 할 수 있도록 SQL 문을 분석하고 해석하여 실행 계획을 수립한 후 실행 계획을 테이블(PLAN_TABLE)에 저장하도록 해주는 명령어 입니다.

    1-2 PLUSTRACE 권한 생성
    SQL> conn / as sysdba
    Connected.
    SQL> @?/sqlplus/admin/plustrce.sql
    SQL>
    SQL> drop role plustrace;
    Role dropped.
    SQL> create role plustrace;
    Role created.
    SQL>
    SQL> grant select on v_$sesstat to plustrace;
    Grant succeeded.
    SQL> grant select on v_$statname to plustrace;
    Grant succeeded.
    SQL> grant select on v_$mystat to plustrace;
    Grant succeeded.
    SQL> grant plustrace to dba with admin option;
    Grant succeeded.
    SQL>
    SQL> set echo off

    1-3 해당 사용자에게 PLUSTRACE 권한 부여
    SQL> grant PLUSTRACE to scott;
    Grant succeeded.

    1-4 해당 사용자로 로그인 후 PLAN Table 생성
    SQL> conn scott/oracle
    Connected.
    SQL> @?/rdbms/admin/utlxplan.sql
    Table created.



    2. SQL*Plus Autotrace 사용 방법
    2-1 Autotrace Mode 설정
    SQL> show user;
    USER is "SCOTT"
    SQL> set autotrace on
    SQL> set autotrace traceonly
    SQL> set autotrace traceonly explain
    SQL> set autotrace traceonly statistics


    2-2 EXPLAIN PLAN SQL 실행
    SQL> conn scott/oracle
    Connected.
    SQL> select dname from dept;
    DNAME
    --------------
    ACCOUNTING
    RESEARCH
    SALES
    OPERATIONS

    Execution Plan
    ----------------------------------------------------------
    Plan hash value: 3383998547
    --------------------------------------------------------------------------
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
    --------------------------------------------------------------------------
    | 0 | SELECT STATEMENT | | 4 | 40 | 3 (0)| 00:00:01 |
    | 1 | TABLE ACCESS FULL| DEPT | 4 | 40 | 3 (0)| 00:00:01 |
    --------------------------------------------------------------------------
    Statistics
    ----------------------------------------------------------
    68 recursive calls
    0 db block gets
    22 consistent gets
    8 physical reads
    0 redo size
    488 bytes sent via SQL*Net to client
    385 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    4 rows processed


    2-3 Autotrace Mode 해제
    SQL> set autotrace off;

    SQL 튜닝을 하게 되면 기본적을 가장 많이 사용 하는 툴입니다.
    다음은 SQL Trace의 기능에 대해서 설명 하도록 하겠습니다.


반응형
Posted by [PineTree]
ORACLE/ADMIN2012. 1. 2. 14:32
반응형

Maxgauge와 같은 툴의 가장 큰 장점은 Oracle Hang 상황에서도 액티브 세션의 리스트를 얻을 수 있다는 것입니다. 대기 이벤트와 SQL 정보가 포함된 액티브 세션 목록이야말로 모든 성능 트러블슈팅의 시작입니다.

Maxgauge와 같은 툴이 Oracle Hang 상황에서도 데이터를 수집할 수 있는 것은 DMA(Direct Memory Access)를 사용하기 때문입니다. 이 방법은 Oracle의 COE(Center Of Expertise) 팀이 극한의 상황, 즉 SQL로 필요한 정보를 수집하지 못할 때 사용하던 방법입니다. 이것이 Maxgauge와 같은 툴 덕분에 보편화된 것입니다.

만일 Maxgauge와 같은 툴이 없다면 어떻게 해야 할까요? Oracle이 제공하는 ASHDUMP 기능을 Preliminary Connection과 함께 사용할 수 있습니다.

  • Preliminary Connection이란 SQL*Net 방식이 아닌 Direct Memory Access 방식으로 Connection을 맺는 것을 말합니다.
  • ASHDUMP는 액티브 세션 목록의 메모리 버전인 ASH(Active Session History)를 텍스트 파일에 기록하는 기능입니다.
따라서 위 두 기능을 같이 사용하면 마치 DMA 방식으로 액티브 세션의 목록을 얻는 것과 동일한 효과가 있습니다.

아래에 간단한 예제가 있습니다.

우선 Preliminary Connection을 맺습니다.

1 #> sqlplus -prelim sys/oracle@ukja1106 as sysdba
2   
3 SQL*Plus: Release 11.1.0.6.0 - Production on Mon Apr 26 09:43:35 2010
4   
5 Copyright (c) 1982, 2007, Oracle.  All rights reserved.
일반적인 쿼리는 동작하지 않습니다.
1 alter session set nls_date_format='yyyy/mm/dd hh24:mi:ss'
2 *
3 ERROR at line 1:
4 ORA-01012: not logged on
5 Process ID: 0
6 Session ID: 0 Serial number: 0
Preliminary Connection 상태에서 ASHDUMP를 수행합니다. 레벨(10)은 10분을 의미합니다. 즉 지난 10분간의 ASH를 의미합니다.
1 SYS@ukja1106> oradebug setmypid
2 Statement processed.
3 SYS@ukja1106> oradebug dump ashdump 10
4 Statement processed.
5 SYS@ukja1106> oradebug tracefile_name
6 c:\oracle\diag\rdbms\ukja1106\ukja1106\trace\ukja1106_ora_12152.trc
Dump 파일의 내용은 다음과 같습니다. 11g부터는 액티브 세션 목록과 함께 해당 목록을 테이블로 로딩하는 스크립트까지 함께 제공합니다. Hang의 악몽이 지나간 후(대부분 리스타트) 사후 분석을 위한 것입니다.
001 Processing Oradebug command 'dump ashdump 10'
002 ASH dump
003 <<<ACTIVE BEGIN HEADER DUMP TRACE PROCESS - HISTORY SESSION>>>
004 ****************
005 SCRIPT TO IMPORT
006 ****************
007 ------------------------------------------
008 Step 1: Create destination table <ASHDUMP>
009 ------------------------------------------
010 CREATE TABLE ashdump AS
011 SELECT * FROM SYS.WRH$_ACTIVE_SESSION_HISTORY WHERE rownum < 0
012 ----------------------------------------------------------------
013 Step 2: Create the SQL*Loader control file <ASHLDR.CTL> as below
014 ----------------------------------------------------------------
015 load data 
016 infile * "str '\n####\n'"
017 append
018 into table ashdump
019 fields terminated by ',' optionally enclosed by '"'
020 (                               
021 SNAP_ID  CONSTANT 0           , 
022 DBID                          , 
023 INSTANCE_NUMBER               , 
024 SAMPLE_ID                     , 
025 SAMPLE_TIME TIMESTAMP ENCLOSED BY '"' AND '"' "TO_TIMESTAMP(:SAMPLE_TIME   ,'MM-DD-YYYY HH24:MI:SSXFF')"   , 
026 SESSION_ID                    , 
027 SESSION_SERIAL#               , 
028 SESSION_TYPE                  , 
029 USER_ID                       , 
030 SQL_ID                        , 
031 SQL_CHILD_NUMBER              , 
032 SQL_OPCODE                    , 
033 FORCE_MATCHING_SIGNATURE      , 
034 TOP_LEVEL_SQL_ID              , 
035 TOP_LEVEL_SQL_OPCODE          , 
036 SQL_PLAN_HASH_VALUE           , 
037 SQL_PLAN_LINE_ID              , 
038 SQL_PLAN_OPERATION#           , 
039 SQL_PLAN_OPTIONS#             , 
040 SQL_EXEC_ID                   , 
041 SQL_EXEC_START DATE 'MM/DD/YYYY HH24:MI:SS' ENCLOSED BY '"' AND '"' ":SQL_EXEC_START"   , 
042 PLSQL_ENTRY_OBJECT_ID         , 
043 PLSQL_ENTRY_SUBPROGRAM_ID     , 
044 PLSQL_OBJECT_ID               , 
045 PLSQL_SUBPROGRAM_ID           , 
046 QC_INSTANCE_ID                , 
047 QC_SESSION_ID                 , 
048 QC_SESSION_SERIAL#            , 
049 EVENT_ID                      , 
050 SEQ#                          , 
051 P1                            , 
052 P2                            , 
053 P3                            , 
054 WAIT_TIME                     , 
055 TIME_WAITED                   , 
056 BLOCKING_SESSION              , 
057 BLOCKING_SESSION_SERIAL#      , 
058 CURRENT_OBJ#                  , 
059 CURRENT_FILE#                 , 
060 CURRENT_BLOCK#                , 
061 CURRENT_ROW#                  , 
062 CONSUMER_GROUP_ID             , 
063 XID                           , 
064 REMOTE_INSTANCE#              , 
065 TIME_MODEL                    , 
066 SERVICE_HASH                  , 
067 PROGRAM                       , 
068 MODULE                        , 
069 ACTION                        , 
070 CLIENT_ID                       
071 )                               
072 ---------------------------------------------------
073 Step 3: Load the ash rows dumped in this trace file
074 ---------------------------------------------------
075 sqlldr userid/password control=ashldr.ctl data=<THIS_TRACE_FILENAME> errors=1000000
076 ---------------------------------------------------
077 <<<ACTIVE HEADER DUMP TRACE PROCESS - HISTORY SESSION END>>>
078 <<<ACTIVE BEGIN DUMP TRACE PROCESS - HISTORY SESSION>>>
079 ####
080 58646642,1,12519562,"04-26-2010 09:44:01.822000000",160,1,2,0,
081 "",0,0,0,"",0,0,0,0,0,
082 0,"",0,0,0,0,0,0,0,
083 3213517201,9858,0,3,1,0,69788,4294967295,0,
084 4294967295,0,0,0,0,,0,0,165959219,
085 "ORACLE.EXE (CKPT)","",
086 "",""
087 ####
088 58646642,1,12519486,"04-26-2010 09:42:45.808000000",160,1,2,0,
089 "",0,0,0,"",0,0,0,0,0,
090 0,"",0,0,0,0,0,0,0,
091 3213517201,9767,1,1,1,0,38825,4294967295,0,
092 4294967295,0,0,0,0,,0,0,165959219,
093 "ORACLE.EXE (CKPT)","",
094 "",""
095 ####
096 58646642,1,12519416,"04-26-2010 09:41:35.770000000",160,1,2,0,
097 "",0,0,0,"",0,0,0,0,0,
098 0,"",0,0,0,0,0,0,0,
099 4078387448,9683,3,3,3,0,11083,4294967295,0,
100 4294967295,0,0,0,0,,0,0,165959219,
101 "ORACLE.EXE (CKPT)","",
102 "",""
103 ####
104 58646642,1,12519384,"04-26-2010 09:41:03.774000000",163,1,2,0,
105 "",0,0,0,"",0,0,0,0,0,
106 0,"",0,0,0,0,0,0,0,
107 3176176482,40612,5,1,1000,999888,0,4294967291,0,
108 4294967295,0,0,0,0,,0,0,165959219,
109 "ORACLE.EXE (DIA0)","",
110 "",""
111 ####
112 58646642,1,12519304,"04-26-2010 09:39:43.719000000",160,1,2,0,
113 "",0,0,0,"",0,0,0,0,0,
114 0,"",0,0,0,0,0,0,0,
115 3213517201,9551,1,1,1,0,38798,4294967295,0,
116 4294967295,0,0,0,0,,0,0,165959219,
117 "ORACLE.EXE (CKPT)","",
118 "",""
119 ####
120 58646642,1,12519265,"04-26-2010 09:39:04.663000000",163,1,2,0,
121 "",0,0,0,"",0,0,0,0,0,
122 0,"",0,0,0,0,0,0,0,
123 3176176482,40493,5,1,1000,999941,0,4294967291,0,
124 4294967295,0,0,0,0,,0,0,165959219,
125 "ORACLE.EXE (DIA0)","",
126 "",""
127 ####
128 58646642,1,12519183,"04-26-2010 09:37:42.554000000",160,1,2,0,
129 "",0,0,0,"",0,0,0,0,0,
130 0,"",0,0,0,0,0,0,0,
131 3213517201,9406,0,1,1,0,54077,4294967295,0,
132 4294967295,0,0,0,0,,0,0,165959219,
133 "ORACLE.EXE (CKPT)","",
134 "",""
135 ####
136 <<<ACTIVE DUMP TRACE PROCESS - HISTORY SESSION END>>>
137   
138 *** 2010-04-26 09:45:51.625
139 Oradebug command 'dump ashdump 10' console output: <NONE>
사후 분석 용도로 사용되면 대단히 유용할 것입니다. Preliminary Connection에서는 전통적인 트러블슈팅 데이터인 Hang Analyze나 System State Dump도 사용 가능합니다. 단, Preliminary Connection와 oradebug는 비공식적인 지원 기능이기 때문에 철저한 테스트 후 사용해야 되며, 가능한 오라클 지원 엔지니어의 승인하에 사용해야 합니다.

더 자세한 정보들은 아래 문서를 참조하세요.

출처 : http://ukja.tistory.com/310

반응형
Posted by [PineTree]
ORACLE/TroubleShooting2011. 12. 28. 23:59
반응형
반응형
Posted by [PineTree]
ORACLE/SCRIPT2011. 12. 21. 10:24
반응형

 

Here are some scripts related to Session Statistics .

Session I/O By User

SESSION I/O BY USER NOTES:

  • Username - Name of the Oracle process user
  • OS User - Name of the operating system user
  • PID - Process ID of the session
  • SID - Session ID of the session
  • Serial# - Serial# of the session
  • Physical Reads - Physical reads for the session
  • Block Gets - Block gets for the session
  • Consistent Gets - Consistent gets for the session
  • Block Changes - Block changes for the session
  • Consistent Changes - Consistent changes for the session

    select	nvl(ses.USERNAME,'ORACLE PROC') username,
    	OSUSER os_user,
    	PROCESS pid,
    	ses.SID sid,
    	SERIAL#,
    	PHYSICAL_READS,
    	BLOCK_GETS,
    	CONSISTENT_GETS,
    	BLOCK_CHANGES,
    	CONSISTENT_CHANGES
    from	v$session ses, 
    	v$sess_io sio
    where 	ses.SID = sio.SID
    order 	by PHYSICAL_READS, ses.USERNAME
    
    

    CPU Usage By Session

    CPU USAGE BY SESSION NOTES:

  • Username - Name of the user
  • SID - Session id
  • CPU Usage - CPU centiseconds used by this session (divide by 100 to get real CPU seconds)

    select 	nvl(ss.USERNAME,'ORACLE PROC') username,
    	se.SID,
    	VALUE cpu_usage
    from 	v$session ss, 
    	v$sesstat se, 
    	v$statname sn
    where  	se.STATISTIC# = sn.STATISTIC#
    and  	NAME like '%CPU used by this session%'
    and  	se.SID = ss.SID
    order  	by VALUE desc
    
    

    Resource Usage By User

    RESOURCE USAGE BY USER NOTES:

  • SID - Session ID
  • Username - Name of the user
  • Statistic - Name of the statistic
  • Value - Current value

    select 	ses.SID,
    	nvl(ses.USERNAME,'ORACLE PROC') username,
    	sn.NAME statistic,
    	sest.VALUE
    from 	v$session ses, 
    	v$statname sn, 
    	v$sesstat sest
    where 	ses.SID = sest.SID
    and 	sn.STATISTIC# = sest.STATISTIC#
    and 	sest.VALUE is not null
    and 	sest.VALUE != 0            
    order 	by ses.USERNAME, ses.SID, sn.NAME
    
    

    Session Stats By Session

    SESSION STAT NOTES:

  • Username - Name of the user
  • SID - Session ID
  • Statistic - Name of the statistic
  • Usage - Usage according to Oracle

    select  nvl(ss.USERNAME,'ORACLE PROC') username,
    	se.SID,
    	sn.NAME stastic,
    	VALUE usage
    from 	v$session ss, 
    	v$sesstat se, 
    	v$statname sn
    where  	se.STATISTIC# = sn.STATISTIC#
    and  	se.SID = ss.SID
    and	se.VALUE > 0
    order  	by sn.NAME, se.SID, se.VALUE desc
    
    

    Cursor Usage By Session

    CURSOR USAGE BY SESSION NOTES:

  • Username - Name of the user
  • Recursive Calls - Total number of recursive calls
  • Opened Cursors - Total number of opened cursors
  • Current Cursors - Number of cursor currently in use

    select 	user_process username,
    	"Recursive Calls",
    	"Opened Cursors",
    	"Current Cursors"
    from  (
    	select 	nvl(ss.USERNAME,'ORACLE PROC')||'('||se.sid||') ' user_process, 
    			sum(decode(NAME,'recursive calls',value)) "Recursive Calls",
    			sum(decode(NAME,'opened cursors cumulative',value)) "Opened Cursors",
    			sum(decode(NAME,'opened cursors current',value)) "Current Cursors"
    	from 	v$session ss, 
    		v$sesstat se, 
    		v$statname sn
    	where 	se.STATISTIC# = sn.STATISTIC#
    	and 	(NAME  like '%opened cursors current%'
    	or 	 NAME  like '%recursive calls%'
    	or 	 NAME  like '%opened cursors cumulative%')
    	and 	se.SID = ss.SID
    	and 	ss.USERNAME is not null
    	group 	by nvl(ss.USERNAME,'ORACLE PROC')||'('||se.SID||') '
    )
    orasnap_user_cursors
    order 	by USER_PROCESS,"Recursive Calls"
    
    

    User Hit Ratios

    USER HIT RATIO NOTES:

  • Username - Name of the user
  • Consistent Gets - The number of accesses made to the block buffer to retrieve data in a consistent mode.
  • DB Blk Gets - The number of blocks accessed via single block gets (i.e. not through the consistent get mechanism).
  • Physical Reads - The cumulative number of blocks read from disk.

  • Logical reads are the sum of consistent gets and db block gets.
  • The db block gets statistic value is incremented when a block is read for update and when segment header blocks are accessed.
  • Hit ratio should be > 90%

    select	USERNAME,
    	CONSISTENT_GETS,
            BLOCK_GETS,
            PHYSICAL_READS,
            ((CONSISTENT_GETS+BLOCK_GETS-PHYSICAL_READS) / (CONSISTENT_GETS+BLOCK_GETS)) Ratio
    from 	v$session, v$sess_io
    where 	v$session.SID = v$sess_io.SID
    and 	(CONSISTENT_GETS+BLOCK_GETS) > 0
    and 	USERNAME is not null
    order	by ((CONSISTENT_GETS+BLOCK_GETS-PHYSICAL_READS) / (CONSISTENT_GETS+BLOCK_GETS))


  • 반응형
    Posted by [PineTree]
    ORACLE/ADMIN2011. 12. 21. 10:17
    반응형

    불량SQL을 찾을때와 락문제를 해결할때 도움이 될 것입니다.

     

    유용하게 사용되길 바라며...
     

    1. 10분이내에 수행된 쿼리중 세션에 남아있는 쿼리
      SELECT sql_text
        FROM v$sqltext a, v$session b
       WHERE a.hash_value = b.sql_hash_value
         AND logon_time <= to_date(to_char(sysdate,'yyyymmddhh24mi')-10,'yyyymmddhh24mi');
    2. Buffer Cache Hit Ratio
      SELECT ROUND(((1-(SUM(DECODE(name, 'physical reads', value,0))/
      (SUM(DECODE(name, 'db block gets', value,0))+
      (SUM(DECODE(name, 'consistent gets', value, 0))))))*100),2) || '%' "Buffer Cache Hit Ratio"
      FROM V$SYSSTAT;
    3. Library Cache Hit Ratio
      SELECT (1-SUM (reloads)/SUM(pins))*100 "Library Cache Hit Ratio"
      FROM V$LIBRARYCACHE;
    4. Data Dictionary Cache Hit Ratio
      SELECT (1-SUM(getmisses)/SUM(gets))*100 "Data Dictionary Hit Ratio"
      FROM V$ROWCACHE;
    5. 테이블 스페이스 사용량
      SELECT a.tablespace_name ,
             a.total "Total(Mb)" ,
             a.total - b.free "Used(Mb)" ,
             NVL( b.free , 0 ) "Free(Mb)" ,
             ROUND(( a.total - NVL( b.free , 0 ) ) *100/total , 0 ) "Used(%)"
      FROM   (
              SELECT tablespace_name ,
                     ROUND(( SUM( bytes ) /1024/1024 ) , 0 ) AS total
              FROM   dba_data_files
              GROUP  BY tablespace_name
             ) a ,
             (
              SELECT tablespace_name ,
                     ROUND(( SUM( bytes ) /1024/1024 ) , 0 ) AS free
              FROM   dba_free_space
              GROUP  BY tablespace_name
             ) b
      WHERE  a.tablespace_name = b.tablespace_name( + )
      ORDER  BY a.tablespace_name ;
    6. 오라클서버의 메모리
      SELECT * FROM v$sgastat
       
      SELECT pool, sum(bytes) "SIZE"
      FROM v$sgastat
      WHERE pool = 'shared pool'
      GROUP BY pool
    7. cpu를 많이 사용하는 쿼리문과 프로세스아이디,시리얼번호,머신 알아내기
      SELECT c.sql_text
      ,b.SID
      , b.SERIAL#
      ,b.machine
      ,b.OSUSER
      ,b.logon_time --이 쿼리를 호출한 시간
      FROM v$process a, v$session b, v$sqltext c
      WHERE a.addr = b.paddr
      AND b.sql_hash_value = c.hash_value
      --and a.spid = '675958'
      ORDER BY c.PIECE
    8. cpu를 많이 사용하는 쿼리문과 프로세스아이디,시리얼번호,머신 알아내기2
      SELECT c.sql_text
      FROM v$process a, v$session b, v$sqltext c
      WHERE a.addr = b.paddr
      AND b.sql_hash_value = c.hash_value
      AND a.spid = '171'
      ORDER BY c.PIECE
    9. 프로세스 아이디를 이용하여 쿼리문 알아내기
      SELECT c.sql_text
      ,b.SID
      , b.SERIAL#
      ,b.machine
      ,b.OSUSER
      ,b.logon_time --이 쿼리를 호출한 시간
      FROM v$process a, v$session b, v$sqltext c
      WHERE a.addr = b.paddr
      AND b.sql_hash_value = c.hash_value
      AND a.spid = '1708032' --1912870/
      ORDER BY c.PIECE
    10. 세션 죽이기(SID,SERAIL#)
      ALTER SYSTEM KILL SESSION '8,4093'
    11. 오라클 세션과 관련된 테이블
      SELECT count(*) FROM v$session WHERE machine ='머신이름' AND schemaname ='스키마이름'
    12. 현재 커서 수 확인
      SELECT sid, count(sid) cursor
      FROM V$OPEN_CURSOR
      WHERE user_name = 'ilips'
      GROUP BY sid
      ORDER BY cursor DESC
       
      SELECT sql_text, count(sid) cnt
      FROM v$OPEN_CURSOR
      GROUP BY sql_text
      ORDER BY cnt DESC
       
      SELECT * FROM v$session_wait
       
      SELECT sid, serial#, username, taddr, used_ublk, used_urec
      FROM v$transaction t, v$session s
      WHERE t.addr = s.taddr;
       
      SELECT *  FROM sys.v_$open_cursor
    13. V$LOCK 을 사용한 잠금 경합 모니터링
      SELECT s.username, s.sid, s.serial#, s.logon_time,
          DECODE(l.type, 'TM', 'TABLE LOCK',
            'TX', 'ROW LOCK',
             NULL) "LOCK LEVEL",
          o.owner, o.object_name, o.object_type
      FROM v$session s, v$lock l, dba_objects o
      WHERE s.sid = l.sid
      AND o.object_id = l.id1
      AND s.username IS NOT NULL
    14. 락이 걸린 세션 자세히 알아보기
      SELECT a.sid, a.serial#,a.username,a.process,b.object_name,
      decode(c.lmode,2,'RS',3,'RX',4,'S',5,'SRX',8,'X','NO') "TABLE LOCK",
      decode (a.command,2,'INSERT',3,'SELECT',6,'UPDATE',7,'DELETE',12,'DROP TABLE',26,'LOCK TABLE','UNknown') "SQL",
      decode(a.lockwait, NULL,'NO wait','Wait') "STATUS"
      FROM v$session a,dba_objects b, v$lock c
      WHERE a.sid=c.sid AND b.object_id=c.id1
      AND c.type='TM'
    15. 락이 걸린 세션 간단히 알아보기
      SELECT a.sid, a.serial#, b.type, c.object_name, a.program, a.lockwait,
             a.logon_time, a.process, a.osuser, a.terminal
      FROM v$session a, v$lock b, dba_objects c
      WHERE a.sid = b.sid
        AND b.id1 = c.object_id
        AND b.type = 'TM';
      SELECT a.sid, a.serial#, a.username, a.process, b.object_name
      FROM v$session a , dba_objects b, v$lock c
      WHERE a.sid=c.sid AND b.object_id = c.id1
      AND c.type = 'TM'
    16. 락이 걸린 세션을 찾아 내어 세션을 죽이려고 해도 죽지 않는 경우 
      아래 쿼리문으로 OS단의 PROCESS ID를 찾아내어 OS에서 죽인다. 
       # kill -9 프로세스아이디 


      SELECT substr(s.username,1,11) "ORACLE USER", p.pid "PROCESS ID",
      s.sid "SESSION ID", s.serial#, osuser "OS USER",
      p.spid "PROC SPID",s.process "SESS SPID", s.lockwait "LOCK WAIT"
      FROM v$process p, v$session s, v$access a
      WHERE a.sid=s.sid AND
      p.addr=s.paddr AND
      s.username != 'SYS'


      위 쿼리문의 결과가 있다면 락이 걸린 세션이 있다는것이므로 아래의 쿼리문으로 세션을 죽인다.

      ALTER SYSTEM KILL SESSION '11,39061'

     

    SELECT * FROM dba_External_Locations
    SELECT * FROM nls_database_parameters


    --1. Buffer Cache Hit Ratio

    SELECT ROUND(((1-(SUM(DECODE(name, 'physical reads', value,0))/
    (SUM(DECODE(name, 'db block gets', value,0))+
    (SUM(DECODE(name, 'consistent gets', value, 0))))))*100),2) || '%' "Buffer Cache Hit Ratio"
    FROM V$SYSSTAT;

    --2. Library Cache Hit Ratio

    SELECT (1-SUM (reloads)/SUM(pins))*100 "Library Cache Hit Ratio"
    From V$LIBRARYCACHE;


    --3. Data Dictionary Cache Hit Ratio

    SELECT (1-SUM(getmisses)/SUM(gets))*100 "Data Dictionary Hit Ratio"
    FROM V$ROWCACHE;

     

    -- 테이블 스페이스 사용량

    SELECT a.tablespace_name,
                 a.total "Total(Mb)",
                 a.total - b.free "Used(Mb)",
                 nvl(b.free,0) "Free(Mb)",
                 round((a.total - nvl(b.free,0))*100/total,0)  "Used(%)"
    from    (   select     tablespace_name,
                                round((sum(bytes)/1024/1024),0) as total
                   from       dba_data_files
                   group by tablespace_name) a,
             (     select     tablespace_name,
                                 round((sum(bytes)/1024/1024),0) as free
                   from        dba_free_space
                   group by  tablespace_name) b
    where      a.tablespace_name = b.tablespace_name(+)
    order by   a.tablespace_name;

     
    --오라클서버의 메모리

    select * from v$sgastat

    select pool, sum(bytes) "SIZE"
    from v$sgastat
    where pool = 'shared pool'
    group by pool

     

    --cpu를 많이 사용하는 쿼리문과 프로세스아이디,시리얼번호,머신 알아내기

    select c.sql_text
    ,b.SID
    , b.SERIAL#
    ,b.machine
    ,b.OSUSER
    ,b.logon_time --이 쿼리를 호출한 시간
    from v$process a, v$session b, v$sqltext c
    where a.addr = b.paddr
    and b.sql_hash_value = c.hash_value
    --and a.spid = '675958'
    order by c.PIECE

     
     
    --cpu를 많이 사용하는 쿼리문과 프로세스아이디,시리얼번호,머신 알아내기

    select c.sql_text
    from v$process a, v$session b, v$sqltext c
    where a.addr = b.paddr
    and b.sql_hash_value = c.hash_value
    and a.spid = '171'
    order by c.PIECE

     

    --프로세스 아이디를 이용하여 쿼리문 알아내기

    select c.sql_text
    ,b.SID
    , b.SERIAL#
    ,b.machine
    ,b.OSUSER
    ,b.logon_time --이 쿼리를 호출한 시간
    from v$process a, v$session b, v$sqltext c
    where a.addr = b.paddr
    and b.sql_hash_value = c.hash_value
    and a.spid = '1708032' --1912870/
    order by c.PIECE

     

    --세션 죽이기(SID,SERAIL#)

    --ALTER SYSTEM KILL SESSION '8,4093'

    --오라클 세션과 관련된 테이블*/

    --select count(*) from v$session where machine ='머신이름' and schemaname ='스키마이름'

     

    --현재 커서 수 확인

    SELECT sid, count(sid) cursor
    FROM V$OPEN_CURSOR
    WHERE user_name = 'ilips'
    GROUP BY sid
    ORDER BY cursor DESC

    SELECT sql_text, count(sid) cnt
    FROM v$OPEN_CURSOR
    GROUP BY sql_text
    ORDER BY cnt DESC

    select * from v$session_wait

    select sid, serial#, username, taddr, used_ublk, used_urec
     from v$transaction t, v$session s
     where t.addr = s.taddr;

    select *  from sys.v_$open_cursor

     

    --V$LOCK 을 사용한 잠금 경합 모니터링

    SELECT s.username, s.sid, s.serial#, s.logon_time,
        DECODE(l.type, 'TM', 'TABLE LOCK',
              'TX', 'ROW LOCK',
           NULL) "LOCK LEVEL",
        o.owner, o.object_name, o.object_type
    FROM v$session s, v$lock l, dba_objects o
    WHERE s.sid = l.sid
    AND o.object_id = l.id1
    AND s.username IS NOT NULL

     

    --락이 걸린 세션 자세히 알아보기

    select a.sid, a.serial#,a.username,a.process,b.object_name,
    decode(c.lmode,2,'RS',3,'RX',4,'S',5,'SRX',8,'X','NO') "TABLE LOCK",
    decode (a.command,2,'INSERT',3,'SELECT',6,'UPDATE',7,'DELETE',12,'DROP TABLE',26,'LOCK TABLE','UNknown') "SQL",
    decode(a.lockwait, NULL,'NO wait','Wait') "STATUS"
    from v$session a,dba_objects b, v$lock c
    where a.sid=c.sid and b.object_id=c.id1
    and c.type='TM'

     

    --락이 걸린 세션 간단히 알아보기

    select a.sid, a.serial#, b.type, c.object_name, a.program, a.lockwait,
           a.logon_time, a.process, a.osuser, a.terminal
    from v$session a, v$lock b, dba_objects c
    where a.sid = b.sid
      and b.id1 = c.object_id
      and b.type = 'TM';

    select a.sid, a.serial#, a.username, a.process, b.object_name
    from v$session a , dba_objects b, v$lock c
    where a.sid=c.sid and b.object_id = c.id1
    and c.type = 'TM'

     
    --락이 걸린 세션을 찾아 내어 세션을 죽이려고 해도 죽지 않는 경우
    --아래 쿼리문으로 OS단의 PROCESS ID를 찾아내어 OS에서 죽인다
    --kill -9 프로세스아이디

    select substr(s.username,1,11) "ORACLE USER", p.pid "PROCESS ID",
    s.sid "SESSION ID", s.serial#, osuser "OS USER",
    p.spid "PROC SPID",s.process "SESS SPID", s.lockwait "LOCK WAIT"
    from v$process p, v$session s, v$access a
    where a.sid=s.sid and
    p.addr=s.paddr and
    s.username != 'SYS'

    --위 쿼리문의 결과가 있다면 락이 걸린 세션이 있다는것이므로 아래의 쿼리문으로 세션을 죽인다

    ALTER SYSTEM KILL SESSION '11,39061'

     

     

    alter session으로 죽지않는 프로세스 죽이기

    1.oracle이 설치된 서버에 텔넷으로 root로 접속한다
    2.su -오라클계정
    3.sqlplus '/as sysdba''
    4.connect system/sys
    5.ALTER SYSTEM KILL SESSION '137,1723'

     

     

    -- 특정 테이블에 사용된 쿼리
    SELECT * FROM V$SQLAREA
    WHERE parsing_schema_name = 'ING'
    AND lower(sql_text) LIKE '%order_result_report_tbl%'
    ORDER BY last_active_time DESC


    -- 현재 세션에서 사용되는 쿼리
    SELECT S.SID
         , S.SERIAL#
         , S.STATUS
         , S.PROCESS
         , S.OSUSER
         , A.SQL_TEXT
         , P.PROGRAM
      FROM V$SESSION S
         , V$SQLAREA A
         , V$PROCESS P
    WHERE S.SQL_HASH_VALUE =  A.HASH_VALUE
      AND S.SQL_ADDRESS    =  A.ADDRESS
      AND S.PADDR          =  P.ADDR
      AND S.SCHEMANAME     = 'ING'
      AND S.STATUS         = 'ACTIVE'


    --
    select
     sql_text,
     sharable_mem + persistent_mem + runtime_mem memory,
     sorts,
     executions,
     first_load_time,
     invalidations,
     parse_calls,
     disk_reads,
     buffer_gets,
     rows_processed,
     round(rows_processed/greatest(executions,1)) row_ratio,
     round(disk_reads/greatest(executions,1)) disk_ratio,
     round(buffer_gets/greatest(executions,1)) buffer_ratio
    from v$sqlarea
    where
     executions > 100
    or disk_reads > 1000
    or buffer_gets > 1000
    or rows_processed > 1000
    order by
     executions * 250 + disk_reads * 25 + buffer_gets desc

     
    --
    SELECT
        PARSING_SCHEMA_NAME,
        executions,
        SQL_TEXT,
       disk_reads,
       buffer_gets,
        elapsed_time / executions AS elapsed_time,
        buffer_gets / decode(executions,0,1,executions) / 500 AS runtime,
        bind_data,
        MODULE,
        sharable_mem,
        persistent_mem,
        runtime_mem,
       rows_processed,
       round(rows_processed/greatest(executions,1)) row_ratio,
       round(disk_reads/greatest(executions,1)) disk_ratio,
       round(buffer_gets/greatest(executions,1)) buffer_ratio,
        LAST_LOAD_TIME,
        LAST_ACTIVE_TIME
    FROM
        V$SQLAREA
    WHERE
        LAST_LOAD_TIME BETWEEN SYSDATE - 1 AND SYSDATE
        AND PARSING_SCHEMA_NAME IN('WORLDGATE')
        AND SQL_TEXT LIKE 'SELECT%'
    ORDER BY
        buffer_gets / decode(executions,0,1,executions) / 500 DESC
       
       
       
    -- 10초 이상
    select translate(sql_text,'&',':') ,
    ' Expected Run Time = '||
    buffer_gets / decode(executions,0,1,executions) / 500 runt

    from v$sqlarea
    where buffer_gets / decode(executions,0,1,executions) / 500 > 10
    and upper(sql_text) not like '%BEGIN%'
    and upper(sql_text) not like '%SQLAREA%'
    and upper(sql_text) not like '%DBA_%'
    and upper(sql_text) not like '%USER_%'
    and upper(sql_text) not like '%ALL_%'
    order by executions desc

       

    평균 메모리 사용량이 많은 SQL (상위 N개)

    SELECT BUFFER_GETS,DISK_READS,

           EXECUTIONS,BUFFER_PER_EXEC,SQL_TEXT

    FROM ( SELECT BUFFER_GETS,DISK_READS, EXECUTIONS,

       BUFFER_GETS/DECODE(EXECUTIONS,0,1,EXECUTIONS) BUFFER_PER_EXEC,

       SQL_TEXT

           FROM   V$SQLAREA

    WHERE LAST_ACTIVE_TIME > trunc(SYSDATE)-8/24
    AND  ROWNUM <=  5
           ORDER BY BUFFER_GETS/DECODE(EXECUTIONS,0,1,EXECUTIONS) DESC )

     

     

    총 메모리 사용량이 많은 SQL (상위 N개)

    SELECT BUFFER_GETS,DISK_READS,EXECUTIONS,SQL_TEXT

    FROM (SELECT BUFFER_GETS,DISK_READS,EXECUTIONS,SQL_TEXT

          FROM V$SQLAREA

          ORDER BY BUFFER_GETS DESC  )

    WHERE ROWNUM <= 5



    반응형
    Posted by [PineTree]
    ORACLE/TUNING2011. 12. 16. 17:16
    반응형

    ######  What are the major tuning areas in database performance tuning  #######

      - Memory - shared pool, large pool, buffer cache, redo log buffer, and sort area size.
      - I/O - distributing I/O, striping, multiple DBWn processes, and DBWn I/O slaves.
      - CPU - CPU utilization.
      - Space management - extent allocation and Oracle block efficiency.
      - Redo log and checkpoint - redo log file configuration, redo entries, and checkpoint.
      - Rollback segment - sizing rollback segments.
      - Network


    ###### 조정해야할 메모리 영역
    전체 SGA 영역 : 2.4G
    shared_pool_size = ???
    large_pool_size = ???
    java_pool_size = ???
    db_cache_size = ???
    SHARED_POOL_RESERVED_SIZE=???

     

    ##################################################
    ### PGA 성능(할당량) 조정
    ##################################################
    PGA target advice => v$pga_target_advice를 이용하여 적당 할당량을 조사한다.

    -- PGA 어드바이스
    select round(pga_target_for_estimate/1024/1024) as target_size_MB,
    bytes_processed,estd_extra_bytes_rw as est_rw_extra_bytes,
    estd_pga_cache_hit_percentage as est_hit_pct,
    estd_overalloc_count as est_overalloc
    from v$pga_target_advice;

    =>위의 쿼리를 실행해서 최적의 PGA할당량을 찾아낸다

    PGA Memory Advisory  DB/Inst: KMSMESV1/KMSMESV1  End Snap: 886
    -> When using Auto Memory Mgmt, minimally choose a pga_aggregate_target value
       where Estd PGA Overalloc Count is 0

                                           Estd Extra    Estd PGA   Estd PGA
    PGA Target    Size           W/A MB   W/A MB Read/      Cache  Overalloc
      Est (MB)   Factr        Processed Written to Disk     Hit %      Count
    ---------- ------- ---------------- ---------------- -------- ----------
            94     0.1        326,688.8         11,869.3     96.0      2,140
           188     0.3        326,688.8         11,869.3     96.0      2,139
           375     0.5        326,688.8          2,393.2     99.0        646
           563     0.8        326,688.8            110.8    100.0          0
           750     1.0        326,688.8            110.8    100.0          0
           900     1.2        326,688.8            110.8    100.0          0
         1,050     1.4        326,688.8            110.8    100.0          0
         1,200     1.6        326,688.8            110.8    100.0          0
         1,350     1.8        326,688.8            110.8    100.0          0
         1,500     2.0        326,688.8            110.8    100.0          0
         2,250     3.0        326,688.8            110.8    100.0          0
         3,000     4.0        326,688.8            110.8    100.0          0
         4,500     6.0        326,688.8            110.8    100.0          0
         6,000     8.0        326,688.8            110.8    100.0          0
              -------------------------------------------------------------

    :::::::::::::::::::::::         결과          ::::::::::::::::::::::::::::::
    =========> PGA 사이즈 조정 : 현재 사이즈 적정 


    ##################################################
    ### SGA 크기 조정
    ##################################################

    SGA Target Advisory  DB/Inst: KMSMESV1/KMSMESV1  End Snap: 886

    SGA Target SGA Size   Est DB      Est DB   Est Physical
      Size (M)   Factor Time (s) Time Factor          Reads
    ---------- -------- -------- ----------- --------------
           752       .5   78,897         1.0      5,109,138
         1,128       .8   78,044         1.0      4,873,605
         1,504      1.0   77,494         1.0      4,723,249
         1,880      1.3   77,293         1.0      4,667,665
         2,256      1.5   77,238         1.0      4,653,967
         2,632      1.8   77,238         1.0      4,653,967
         3,008      2.0   77,239         1.0      4,653,967
    -------------------------------------------------------------


    :::::::::::::::::::::::         결과          ::::::::::::::::::::::::::::::
    =========> SGA 사이즈 조정 : 1.5GB -> 2.5GB로 사이즈 조정 
    ★★★★ statspack분석 결과에 의해  SGA_TARGET 파라메타 2.5GB로 재조정.
    alter system set SGA_MAX_SIZE=(2.5GB)

    ##################################################
    ### shared pool 성능(할당량) 조정
    ##################################################

    1.먼저 현재 사용중인 데이타베이스에 대해 라이브러리 캐시영역에 대한 크기가 적정한지 조사한다.

    select namespace,gets,gethits,gethitratio
    from v$librarycache
    where namespace = 'SQL AREA';

    => 참조 : 만약 gethitratio 컬럼의 값이 90%이상이라면 라이브러리 캐쉬영역이 개발자들의 SQL 파싱정보를 저장하기에 충분한 메모리 공간을
              확보하고 있음을 의미하며 만약 90% 이하라면 성능이 저하 될 수도 있다는 것을 의마한다.

    => Quality DB의 경우 다음과 같은 결과가 나옴.
    NAMESPACE             GETS    GETHITS GETHITRATIO
    --------------- ---------- ---------- -----------
    SQL AREA            885978     878552  .991618302
    =========> 99%

    ## 부가적으로 pins에 대한 reloads의 비율을 확인한다.

    select sum(pins),sum(reloads),sum(reloads) / sum(pins)
    from v$librarycache
    where namespace = 'SQL AREA';

    => 완성차 DB의 경우 다음과 같이 나옴.
     SUM(PINS) SUM(RELOADS) SUM(RELOADS)/SUM(PINS)
    ---------- ------------ ----------------------
      85931701          506             5.8884E-06

    ========> 참조 : PINS에 대한 reloads에 대한 비율이 1%미만일 경우 라이브러리 캐쉬 영역의 크기가 SQL 파싱정보를
                     저장하기에 충분하다는 의미이다.

     

    현재 할당된 shared_pool 사이즈를 조사한다.
    select pool, sum(bytes)/1024/1024 Mbytes from v$sgastat group by pool;

    => 완성차 DB의 경우 다음과 같이 나옴.
    POOL             MBYTES
    ------------ ----------
                 863.996956
    shared pool  511.985039
    streams pool 48.0495529
    large pool           32
    java pool            64


    2. Shared pool advice => v$shared_pool_advice 를 이용해서 oracle의 사이즈 advice를 조사한다.


    SELECT shared_pool_size_for_estimate "Size of Shared Pool in MB",
           shared_pool_size_factor "Size Factor",estd_lc_time_saved "Time Saved in sec"
      FROM v$shared_pool_advice;

    Shared Pool Advisory  DB/Inst: KMSMESV1/KMSMESV1  End Snap: 886
    -> SP: Shared Pool     Est LC: Estimated Library Cache   Factr: Factor
    -> Note there is often a 1:Many correlation between a single logical object
       in the Library Cache, and the physical number of memory objects associated
       with it.  Therefore comparing the number of Lib Cache objects (e.g. in
       v$librarycache), with the number of Lib Cache Memory Objects is invalid

                                            Est LC Est LC  Est LC Est LC
        Shared    SP   Est LC                 Time   Time    Load   Load      Est LC
          Pool  Size     Size       Est LC   Saved  Saved    Time   Time         Mem
      Size (M) Factr      (M)      Mem Obj     (s)  Factr     (s)  Factr    Obj Hits
    ---------- ----- -------- ------------ ------- ------ ------- ------ -----------
           256    .5       72        4,370 #######    1.0  33,605    1.4  32,095,562
           320    .6      132        7,162 #######    1.0  28,485    1.2  32,102,312
           384    .8      195       12,092 #######    1.0  24,534    1.0  32,102,864
           448    .9      204       13,130 #######    1.0  24,534    1.0  32,102,864
           512   1.0      204       13,130 #######    1.0  24,534    1.0  32,102,864
           576   1.1      204       13,130 #######    1.0  24,534    1.0  32,102,864
           640   1.3      204       13,130 #######    1.0  24,534    1.0  32,102,864
           704   1.4      204       13,130 #######    1.0  24,534    1.0  32,102,864
           768   1.5      204       13,130 #######    1.0  24,534    1.0  32,102,864
           832   1.6      204       13,130 #######    1.0  24,534    1.0  32,102,864
           896   1.8      204       13,130 #######    1.0  24,534    1.0  32,102,864
           960   1.9      204       13,130 #######    1.0  24,534    1.0  32,102,864
         1,024   2.0      204       13,130 #######    1.0  24,534    1.0  32,102,864
              -------------------------------------------------------------+ The above output shows the current setting of the shared pool is
      512M (for which Size factor is 1).

    + It also shows decreasing the size of the shared pool to the 50% of its
      current value will also be equally efficient as the current value.
    + Also doubling the size of the shared pool will save extra 2300 sec in parsing.
    + Using this view a DBA has the correct picture to design Shared pool.


    ========> 결론 : 현재 PEMS DB의 shared_pool 사이즈를 init*.ora 파일에서 늘려준다.
    shared_pool_size = 800M(????)

     

    ### 현재 SGA에 대한 할당 조사
    select current_size from v$buffer_pool;
    select pool, sum(bytes)/1024/1024 Mbytes from v$sgastat group by pool;

    3. SHARED_POOL_RESERVED_SIZE에 대한 성능 조절

    => SHARED_POOL_RESERVED_SIZE는 PL/SQL 블록으로 실행된 sql문의 구문분석 정보를 저장할때 사용되는 공유 풀 영역의 크기를
       지정하는 파라메타이다
    => 기본값은 SHARED_POOL_SIZE의 10%이며 최대값은 SHARED_POOL_SIZE 값의 1/2 이다.
    => v$shared_pool_reserved 자료사전의 REQUEST_FAILURES의 컬럼값이 0이 아니거나 계속 증가값을 보일때 이파라메타 값을
       크게 해준다.

    select request_failures from v$shared_pool_reserved;

    REQUEST_FAILURES
    ----------------
                   0


    ========> 결론 :SHARED_POOL_RESERVED_SIZE 변경 없음
    SHARED_POOL_RESERVED_SIZE = 25M(?????)

    ##################################################
    #### DB Cache Size 성능 조정
    ##################################################

    1. DB cache advice => v$db_cache_advice 동적 성능 뷰를 이용하여 db cache 사이즈를 시뮬레이션 해본다.

    column size_for_estimate         format 999,999,999,999 heading 'Cache Size (m)'
    column buffers_for_estimate      format 999,999,999 heading 'Buffers'
    column estd_physical_read_factor format 999.90 heading 'Estd Phys|Read Factor'
    column estd_physical_reads       format 999,999,999 heading 'Estd Phys| Reads'

    SELECT size_for_estimate, buffers_for_estimate,estd_physical_read_factor, estd_physical_reads
      FROM V$DB_CACHE_ADVICE
     WHERE name = 'DEFAULT'
       AND block_size    = (SELECT value FROM V$PARAMETER
                             WHERE name = 'db_block_size')
       AND advice_status = 'ON';


        Size for  Size      Buffers   Read     Phys Reads     Est Phys % dbtime
    P    Est (M) Factr  (thousands)  Factr    (thousands)    Read Time  for Rds
    --- -------- ----- ------------ ------ -------------- ------------ --------
    D         80    .1           10    2.1          9,703       21,737     28.0
    D        160    .2           20    1.1          5,315        5,540      7.1
    D        240    .3           30    1.1          5,029        4,485      5.8
    D        320    .4           40    1.0          4,948        4,186      5.4
    D        400    .5           50    1.0          4,897        4,001      5.2
    D        480    .6           59    1.0          4,862        3,869      5.0
    D        560    .6           69    1.0          4,829        3,750      4.8
    D        640    .7           79    1.0          4,796        3,628      4.7
    D        720    .8           89    1.0          4,761        3,497      4.5
    D        800    .9           99    1.0          4,740        3,419      4.4
    D        864   1.0          107    1.0          4,723        3,359      4.3
    D        880   1.0          109    1.0          4,709        3,306      4.3
    D        960   1.1          119    1.0          4,668        3,152      4.1
    D      1,040   1.2          129    1.0          4,649        3,083      4.0
    D      1,120   1.3          139    1.0          4,621        2,979      3.8
    D      1,200   1.4          149    1.0          4,607        2,929      3.8
    D      1,280   1.5          159    1.0          4,599        2,899      3.7
    D      1,360   1.6          169    1.0          4,594        2,882      3.7
    D      1,440   1.7          178    1.0          4,594        2,880      3.7
    D      1,520   1.8          188    1.0          4,592        2,875      3.7
    D      1,600   1.9          198    1.0          4,580        2,829      3.7
              -------------------------------------------------------------


    ========> 결론 : 현재 PEMS DB의 db_cache 사이즈를 1.6GB로 변경
    db_cache_size = 1.6GB(???)

    ##################################################
    #### Redo buffer Size 성능 조정
    ##################################################

    Check the statistic redo buffer allocation retries in the V$SYSSTAT view.
    If this value is high relative to redo blocks written, try to increase the LOG_BUFFER size.
     
    Query for the same is
     
    select * from v$sysstat where name like 'redo buffer allocation retries'
    or
    select * from v$sysstat where name like 'redo blocks written';

    혹은 v$sysstat 자료사전에서 서버 프로세스가 로그 정보를 저장했던 로그버퍼의 블록 수(REDO ENTRIES)와 로그버퍼의 경합으로
    인해 발생한 대기상태에서 다시 로그 버퍼공간을 할당 받았던 불록 수(redo buffer allocation entries)를 확인한다.

    =>이 SQL문에 의한 실행 결과
    select name,value
    from v$sysstat
    where name in ('redo buffer allocation retries','redo entries');


    NAME                                                                  VALUE
    ---------------------------------------------------------------- ----------
    redo entries                                                       23465374
    redo buffer allocation retries                                           91=>0일 수록 좋은것

    ========> 결론 : 현재 quality DB의 log_buffer 사이즈를 14MB * 2 이상으로 init*.ora 파일에서 늘려준다.
    log_buffer = 30M  
           
    ##################################################
    #### java_pool Size 성능 조정
    ##################################################

    ** Java Pool advice => v$java_pool_advice

    select JAVA_POOL_SIZE_FOR_ESTIMATE,JAVA_POOL_SIZE_FACTOR,ESTD_LC_LOAD_TIME
    from v$java_pool_advice

    JAVA_POOL_SIZE_FOR_ESTIMATE JAVA_POOL_SIZE_FACTOR ESTD_LC_LOAD_TIME
    --------------------------- --------------------- -----------------
                              4                     1              9493
                              8                     2              9493

    ========> 결론 : 현재 PEMS DB의 java_pool_size 사이즈를 8MB 이상으로 init*.ora 파일에서 늘려준다.
    java_pool_size=128M(20971520)

    ##################################################
    #### Redo-log file  Size 성능 조정
    ##################################################
    FAST_START_MTTR_TARGET='숫자값'으로 설정한다(V$MTTR_TARGET_ADVICE)
    alter system set FAST_START_MTTR_TARGET=300

    SQL> select ACTUAL_REDO_BLKS,TARGET_REDO_BLKS,TARGET_MTTR,ESTIMATED_MTTR,
        OPTIMAL_LOGFILE_SIZE,CKPT_BLOCK_WRITES  from v$instance_recovery;

    ACTUAL_REDO_BLKS TARGET_REDO_BLKS TARGET_MTTR ESTIMATED_MTTR OPTIMAL_LOGFILE_SIZE
    ---------------- ---------------- ----------- -------------- --------------------
              942            18432          71             59                     49     
    388462

    The recommended optimal redolog file size is 49 MB as seen from column -OPTIMAL_LOGFILE_SIZE.
    This is as per the setting of "fast_start_mttr_target" = 170

    각 리두로그 사이즈 600M로 조정

    $@# !! SQL 튜닝 전에

    SQL>alter session set timed_statistics=true;
    SQL>alter session set sql_trace=true;
    요거 켜주기......

    ### REDO LOG 파일 재배치 해야함.(물리적으로 서로 다른 디스크 경로에 변경 배치한다)

    ALTER DATABASE DROP LOGFILE GROUP 1;
    ALTER DATABASE ADD LOGFILE GROUP 1 ('/ora_log/KMSMESV1/rdo1/redo01a.log','/ora_dump/KMSMESV1/rdo2/redo01b.log') SIZE 500M


    ALTER DATABASE DROP LOGFILE GROUP 2;
    ALTER DATABASE ADD LOGFILE GROUP 2 ('/ora_log/KMSMESV1/rdo1/redo02a.log','/ora_dump/KMSMESV1/rdo2/redo02b.log') SIZE 500M


    ALTER DATABASE DROP LOGFILE GROUP 3;
    ALTER DATABASE ADD LOGFILE GROUP 3 ('/ora_log/KMSMESV1/rdo1/redo03a.log','/ora_dump/KMSMESV1/rdo2/redo03b.log') SIZE 500M

    ALTER DATABASE DROP LOGFILE GROUP 4;
    ALTER DATABASE ADD LOGFILE GROUP 4 ('/ora_log/KMSMESV1/rdo1/redo04a.log','/ora_dump/KMSMESV1/rdo2/redo04b.log') SIZE 500M

    ALTER DATABASE DROP LOGFILE GROUP 5;
    ALTER DATABASE ADD LOGFILE GROUP 5 ('/ora_log/KMSMESV1/rdo1/redo05a.log','/ora_dump/KMSMESV1/rdo2/redo05b.log') SIZE 500M

    ALTER DATABASE DROP LOGFILE GROUP 6;
    ALTER DATABASE ADD LOGFILE GROUP 6 ('/ora_log/KMSMESV1/rdo1/redo06a.log','/ora_dump/KMSMESV1/rdo2/redo06b.log') SIZE 500M


    ### ADDITIONAL 1 : Disk I/O 튜닝

    select tablespace_name,file_name,phyrds, phywrts
    from dba_data_files df,v$filestat fs
    where df.file_id = fs.file#;

    ===============> 결론 : 쿼리 결과 system 테이블 스페이스와 undo table space를 분리해야함. 
    1.DB SHUTDOWN

    2.undo datafile 이동 ex)F:\->H:\
     =>이동 후 기존 datafile 삭제 
    3.db startup(mount까지)

    alter database rename file 'E:\ora_data1\KMSMESP1\UNDOTBS01.DBF' to 'H:\ora_data4\KMSMESP1\undo_data\UNDOTBS01.DBF';
    alter database rename file 'E:\ora_data1\KMSMESP1\UNDOTBS02.DBF' to 'H:\ora_data4\KMSMESP1\undo_data\UNDOTBS02.DBF';
    alter database rename file 'E:\ora_data1\KMSMESP1\UNDOTBS03.DBF' to 'H:\ora_data4\KMSMESP1\undo_data\UNDOTBS03.DBF';

    4.DB OPEN  


    ##### redolog 변경 샘플

    ALTER DATABASE DROP LOGFILE GROUP 1;
    ALTER DATABASE ADD LOGFILE GROUP 1 ('I:\ora_log\KMSMESQ1\rdo1\REDO01A.LOG', 'H:\ora_dump\KMSMESQ1\rdo2\REDO01B.LOG') SIZE 200M;

    ALTER DATABASE DROP LOGFILE GROUP 2;
    ALTER DATABASE ADD LOGFILE GROUP 2 ('I:\ora_log\KMSMESQ1\rdo1\REDO02A.LOG', 'H:\ora_dump\KMSMESQ1\rdo2\REDO02B.LOG') SIZE 200M;

    ALTER DATABASE DROP LOGFILE GROUP 3;
    ALTER DATABASE ADD LOGFILE GROUP 3 ('I:\ora_log\KMSMESQ1\rdo1\REDO03A.LOG', 'H:\ora_dump\KMSMESQ1\rdo2\REDO03B.LOG') SIZE 200M;

    반응형

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

    V$SQL BIND CAPTURE  (0) 2012.03.08
    SQL 실행 계획 확인방법  (0) 2012.01.10
    SHARED POOL SIZE의 계산방법  (0) 2011.11.23
    OWI를 활용한 shared pool 진단 및 튜닝  (0) 2011.11.23
    Oracle Session별 Trace 생성 방법  (0) 2011.10.21
    Posted by [PineTree]