Sunday, June 14, 2009

Restore table drop by mistake

If there is table drop by mistake

1. Performing the incomplete recovery manually

Bring all offline datafiles online

SQL> select name,status from v$datafile ;

SQL>shutdown immediate ;

Perform complete close backup ,by copying the database file to another location this
backup must be taken before performing incomplete recovery .

SQL>startup mount;

SQL>alter session set NLS_DATE_FORMAT=’DD-MON-YYYY HH24:MI:SS’ ; this is optional

SQL>recover database until time ’07-DES-2008 10:00:00’ ;

SQL>alter database open resetlogs ;

Now you can see the deleted table,,,,,,

2. Incomplete recovery using RMAN
The set until command can take one of the following forms

• SET UNTIL TIME ‘DD MON YYYY HH:MI:SS’
• SET UNTIL LOG SEQUENCE n
• SET UNTIL SCN n

Using The LogMiner utility to determine the SCN(system change number)
The logminer utility used to analyze redo log files ,and the following steps describe how you can read the contents of redo log file

SQL>alter system set UTL_FILE_DIR=’c:\LOGMINIER’ SCOPE=SPFILE ;

SQL>SHUTDOWN IMMEDIATE ;

SQL>STARTUP ;

Create directory called LOGMINIER in c:\ drive

SQL>EXECUTE DBMS_LOGMINR_D.BUILD(‘LOGDICT.ORA’,’C:\LOGMINER’) ;

To see the log files

SQL>select member from v$logfile

MEMBER
D:\ORACLE\ORADATA\BOSST\REDO01.LOG
D:\ORACLE\ORADATA\BOSST\REDO02.LOG
D:\ORACLE\ORADATA\BOSST\REDO03.LOG
D:\ORACLE\ORADATA\BOSST\REDO04.LOG

SQL>EXECUTE DBMS_LOGMINR.ADD_LOGFILE(LOGFILENAME=>’D:\ORACLE\ORADATA\BOSST\REDO01.LOG’ ,OPTIONS => DBMS_LOGMNR.NEW) ;
SQL>EXECUTE DBMS_LOGMINR.ADD_LOGFILE(LOGFILENAME=>'D:\ORACLE\ORADATA\BOSST\REDO02.LOG’ ,OPTIONS => DBMS_LOGMNR.ADDFILE) ; etc…

Next start the mining process using DBMS_LOGMNR.START_LOGMNR procedure .The DDL_DICT_TRACKING option that mean you will track DDL command In the redo log file

SQL> DBMS_LOGMNR.START_LOGMNR(OPTIONS=>DBMS_LOGMNR .DDL_DICT_TRACKING) ;

SQL>select SCN ,SQL_REDO FROM V$LOGMNR_CONTENTS WHERE SEG_NAME =’TABLE NAME’;

Now you can get the SCN , and after that you can stop the mining session by
executing this command

SQL>EXECUTE DBMS_LOGMNR.END_LOGMNR ;

SQL> select file# ,status from v$datafile ;

If there is any file offline you must bring them online by this command

SQL>ALTER DATABASE DATAFILE ONLINE;

Shutdown database and perform complete backup

Connect to RMAN and to the target database

RMAN>STARTUP MOUNT
RMAN>RUN{
ALLOCATE CHANNEL C1 TYPE DISK ;
SET UNTIL SCN 8767887 ;
RESTORE DATABASE;
RECOVER DATABASE ;
ALTER DATABASE OPEN RESETLOGS;
}
Now you can see the dropped table

Tuesday, June 9, 2009

Changing Oracle Database Character Set to Arabic

SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER SYSTEM ENABLE RESTRICTED SESSION;
ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;
ALTER SYSTEM SET AQ_TM_PROCESSES=0;
ALTER DATABASE OPEN;
ALTER DATABASE CHARACTER SET INTERNAL_USE AR8MSWIN1256;
SHUTDOWN IMMEDIATE;
STARTUP;

Sunday, May 31, 2009

Change Serial Number for Windows XP

If you need to change Serial Number (Product Key) for Windows XP for various reasons (maybe you find that your key is pirated and want to enter a new ok one) follow next steps:

1.Click on Start and then Run.
2.In the text box in the Run window, type regedit and click OK. This will open the Registry Editor program.
3.Locate the HKEY_LOCAL_MACHINE folder under My Computer and click on the (+) sign next the folder name to expand the folder.
4.Continue to expand folders until you reach the HKEY_LOCAL_MACHINE\Software\Microsoft\WindowsNT\Current Version\WPAEvents registry key.
5.Click on the WPAEvents folder.
6.In the results that appear in the window on the right, locate OOBETimer.
7.Right-click on the OOBETimer entry and choose Modify from the resulting menu.
8.Change at least one digit in the Value data text box and click OK. This will deactivate Windows XP.
9.Click on Start and then Run.
10.In the text box in the Run window, type the following command and click OK.
%systemroot%\system32\oobe\msoobe.exe /a

11.When the Windows Product Activation window appears, choose Yes, I want to telephone a customer service representative to activate Windows and then click Next.
12.Click Change Product Key.
13.Type your new, valid Windows XP product key in the New key text boxes and then click Update.
14.If you’re taken back to the previous screen and prompted, choose Remind me later.
15.Restart your PC.
16.Repeat steps 9 and 10 to verify that Windows is activated. You receive the following message:Windows is already activated. Click OK to exit.
17.Click OK.

Tuesday, May 19, 2009

Delete Archive Log Files From RMAN

to list all avilable archive log file
from this command we will able to know the sequence of the archive log file
from RMAN>list archivelog all;

from RMAN>DELETE ARCHIVELOG SEQUENCE between SEQ... AND SEQ...n ;

Wednesday, May 13, 2009

Oracle Statspack Survival Guide



Oracle Statspack Survival Guide
________________________________________
Overview
STATSPACK is a performance diagnosis tool, available since Oracle8i. STATSPACK can be considered BSTAT/ESTAT's successor, incorporating many new features. STATSPACK is a diagnosis tool for instance-wide performance problems; it also supports application tuning activities by providing data which identifies high-load SQL statements. STATSPACK can be used both proactively to monitor the changing load on a system, and also reactively to investigate a performance problem.
Remember to set timed_statistics to true for your instance. Setting this parameter provides timing data which is invaluable for performance tuning.
The «more is better» approach is not always better!
The single most common misuse of STATSPACK is the «more is better» approach. Often STATSPACK reports spans hours or even days. The times between the snapshots (the collection points) should, in general, be measured in minutes, not hours and never days.
The STATSPACK reports we like are from 1 5-minute intervals during a busy or peak time, when the performance is at its worst. That provides a very focused look at what was going wrong at that exact moment in time. The problem with a very large STATSPACK snapshot window, where the time between the two snapshots is measured in hours, is that the events that caused serious performance issues for 20 minutes during peak processing don't look so bad when they're spread out over an 8-hour window. It's also true with STATSPACK that measuring things over too long of a period tends to level them out over time. Nothing will stand out and strike you as being wrong. So, when taking snapshots, schedule them about 15 to 30 minutes (maximum) apart. You might wait 3 or 4 hours between these two observations, but you should always do them in pairs and within minutes of each other.
«Having a history of the good times is just as important as having a history of the bad; you need both»
Another common mistake with STATSPACK is to gather snapshots only when there is a problem. That is fine to a point, but how much better would it be to have a STATSPACK report from when things were going good to compare it with when things are bad. A simple STATSPACK report that shows a tremendous increase in physical 1/0 activity or table scans (long tables) could help you track down that missing index. Or, if you see your soft parse percentage value went from 99% to 70%, you know that someone introduced a new feature into the system that isn't using bind variables (and is killing you). Having a history of the good times is just as important as having a history of the bad; you need both.
Architecture
To fully understand the STATSPACK architecture, we have to look at the basic nature of the STATSPACK utility. The STATSPACK utility is an outgrowth of the Oracle UTLBSTAT and UTLESTAT utilities, which have been used with Oracle since the very earliest versions.
UTLBSTAT - UTLESTAT
The BSTAT-ESTAT utilities capture information directly from the Oracle's in-memory structures and then compare the information from two snapshots in order to produce an elapsed-time report showing the activity of the database. If we look inside utlbstat.sql and utlestat.sql, we see the SQL that samples directly from the view: V$SYSSTAT;
insert into stats$begin_stats select * from v$sysstat;
insert into stats$end_stats select * from v$sysstat;

STATSPACK
When a snapshot is executed, the STATSPACK software will sample from the RAM in-memory structures inside the SGA and transfer the values into the corresponding STATSPACK tables. These values are then available for comparing with other snapshots.

Note that in most cases, there is a direct correspondence between the v$ view in the SGA and the corresponding STATSPACK table. For example, we see that the stats$sysstat table is similar to the v$sysstat view.
SQL> desc v$sysstat;
Name Null? Type
----------------------------------------- -------- -----------------------
STATISTIC# NUMBER
NAME VARCHAR2(64)
CLASS NUMBER
VALUE NUMBER
STAT_ID NUMBER

SQL> desc stats$sysstat;
Name Null? Type
----------------------------------------- -------- -----------------------
SNAP_ID NOT NULL NUMBER
DBID NOT NULL NUMBER
INSTANCE_NUMBER NOT NULL NUMBER
STATISTIC# NOT NULL NUMBER
NAME NOT NULL VARCHAR2(64)
VALUE NUMBER
It is critical to your understanding of the STATSPACK utility that you realize the information captured by a STATSPACK snapshot is accumulated values. The information from the V$VIEWS collects database information at startup time and continues to add the values until the instance is shutdown. In order to get a meaningful elapsed-time report, you must run a STATSPACK report that compares two snapshots as shown above. It is critical to understand that a report will be invalid if the database is shut down between snapshots. This is because all of the accumulated values will be reset, causing the second snapshot to have smaller values than the first snapshot.
Installing and Configuring STATSPACK
Create PERFSTAT Tablespace
The STATSPACK utility requires an isolated tablespace to obtain all of the objects and data. For uniformity, it is suggested that the tablespace be called PERFSTAT, the same name as the schema owner for the STATSPACK tables. It is important to closely watch the STATSPACK data to ensure that the stats$sql_summary table is not taking an inordinate amount of space.
SQL> CREATE TABLESPACE perfstat
DATAFILE '/u01/oracle/db/AKI1_perfstat.dbf' SIZE 1000M REUSE
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 512K
SEGMENT SPACE MANAGEMENT AUTO
PERMANENT
ONLINE;
Run the Create Scripts
Now that the tablespace exists, we can begin the installation process of the STATSPACK software. Note that you must have performed the following before attempting to install STATSPACK.
Run catdbsyn.sql as SYS
Run dbmspool.sql as SYS
$ cd $ORACLE_HOME/rdbms/admin
$ sqlplus "/ as sysdba"
SQL> start spcreate.sql
Choose the PERFSTAT user's password
-----------------------------------
Not specifying a password will result in the installation FAILING

Enter value for perfstat_password: perfstat
Choose the Default tablespace for the PERFSTAT user
---------------------------------------------------
Below is the list of online tablespaces in this database which can
store user data. Specifying the SYSTEM tablespace for the user's
default tablespace will result in the installation FAILING, as
using SYSTEM for performance data is not supported.

Choose the PERFSTAT users's default tablespace. This is the tablespace
in which the STATSPACK tables and indexes will be created.

TABLESPACE_NAME CONTENTS STATSPACK DEFAULT TABLESPACE
------------------------------ --------- ----------------------------
PERFSTAT PERMANENT
SYSAUX PERMANENT *
USERS PERMANENT

Pressing will result in STATSPACK's recommended default
tablespace (identified by *) being used.

Enter value for default_tablespace: PERFSTAT
Choose the Temporary tablespace for the PERFSTAT user
-----------------------------------------------------
Below is the list of online tablespaces in this database which can
store temporary data (e.g. for sort workareas). Specifying the SYSTEM
tablespace for the user's temporary tablespace will result in the
installation FAILING, as using SYSTEM for workareas is not supported.

Choose the PERFSTAT user's Temporary tablespace.

TABLESPACE_NAME CONTENTS DB DEFAULT TEMP TABLESPACE
------------------------------ --------- --------------------------
TEMP TEMPORARY *

Pressing will result in the database's default Temporary
tablespace (identified by *) being used.

Enter value for temporary_tablespace: TEMP
.....
.....
Creating Package STATSPACK...

Package created.

No errors.
Creating Package Body STATSPACK...

Package body created.

No errors.

NOTE:
SPCPKG complete. Please check spcpkg.lis for any errors.
Check the Logfiles: spcpkg.lis, spctab.lis, spcusr.lis
Adjusting the STATSPACK Collection Level
STATSPACK has two types of collection options, level and threshold. The level parameter controls the type of data collected from Oracle, while the threshold parameter acts as a filter for the collection of SQL statements into the stats$sql_summary table.
SQL> SELECT * FROM stats$level_description ORDER BY snap_level;
Level 0 This level captures general statistics, including rollback segment, row cache, SGA, system events, background events, session events, system statistics, wait statistics, lock statistics, and Latch information.
Level 5 This level includes capturing high resource usage SQL Statements, along with all data captured by lower levels.
Level 6 This level includes capturing SQL plan and SQL plan usage information for high resource usage SQL Statements, along with all data captured by lower levels.
Level 7 This level captures segment level statistics, including logical and physical reads, row lock, itl and buffer busy waits, along with all data captured by lower levels.
Level 10 This level includes capturing Child Latch statistics, along with all data captured by lower levels.
You can change the default level of a snapshot with the statspack.snap function. The i_modify_parameter => 'true' changes the level permanent for all snapshots in the future.
SQL> exec statspack.snap(i_snap_level => 6, i_modify_parameter => 'true');
Create, View and Delete Snapshots
sqlplus perfstat/perfstat
SQL> exec statspack.snap;
SQL> select name,snap_id,to_char(snap_time,'DD.MM.YYYY:HH24:MI:SS')
"Date/Time" from stats$snapshot,v$database;

NAME SNAP_ID Date/Time
--------- ---------- -------------------
AKI1 4 14.11.2004:10:56:01
AKI1 1 13.11.2004:08:48:47
AKI1 2 13.11.2004:09:00:01
AKI1 3 13.11.2004:09:01:48
SQL> @?/rdbms/admin/sppurge;
Enter the Lower and Upper Snapshot ID
Create the Report
sqlplus perfstat/perfstat
SQL> @?/rdbms/admin/spreport.sql
Statspack at a Glance
What if you have this long STATSPACK report and you want to figure out if everything is running smoothly? Here, we will review what we look for in the report, section by section. We will use an actual STATSPACK report from our own Oracle 10g system.
Statspack Report Header
STATSPACK report for

DB Name DB Id Instance Inst Num Release RAC Host
------------ ----------- ------------ -------- ----------- --- ----------------
AKI1 2006521736 AKI1 1 10.1.0.2.0 NO akira

Snap Id Snap Time Sessions Curs/Sess Comment
--------- ------------------ -------- --------- -------------------
Begin Snap: 5 14-Nov-04 11:18:00 15 14.3
End Snap: 6 14-Nov-04 11:33:00 15 10.2
Elapsed: 15.00 (mins)
Cache Sizes (end)
~~~~~~~~~~~~~~~~~
Buffer Cache: 24M Std Block Size: 4K
Shared Pool Size: 764M Log Buffer: 1,000K
Note that this section may appear slightly different depending on your version of Oracle. For example, the Curs/Sess column, which shows the number of open cursors per session, is new with Oracle9i (an 8i Statspack report would not show this data).
Here, the item we are most interested in is the elapsed time. We want that to be large enough to be meaningful, but small enough to be relevant (15 to 30 minutes is OK). If we use longer times, we begin to lose the needle in the haystack.
Statspack Load Profile
Load Profile
~~~~~~~~~~~~ Per Second Per Transaction
--------------- ---------------
Redo size: 425,649.84 16,600,343.64
Logical reads: 1,679.69 65,508.00
Block changes: 2,546.17 99,300.45
Physical reads: 77.81 3,034.55
Physical writes: 78.35 3,055.64
User calls: 0.24 9.55
Parses: 2.90 113.00
Hard parses: 0.16 6.27
Sorts: 0.76 29.82
Logons: 0.01 0.36
Executes: 4.55 177.64
Transactions: 0.03

% Blocks changed per Read: 151.59 Recursive Call %: 99.56
Rollback per transaction %: 0.00 Rows per Sort: 65.61
Here, we are interested in a variety of things, but if we are looking at a "health check", three items are important:
The Hard parses (we want very few of them)
Executes (how many statements we are executing per second / transaction)
Transactions (how many transactions per second we process).
This gives an overall view of the load on the server. In this case, we are looking at a very good hard parse number and a fairly light system load (1 - 4 transactions per second is low).
Statspack Instance Efficiency Percentage
Next, we move onto the Instance Efficiency Percentages section, which includes perhaps the only ratios we look at in any detail:
Instance Efficiency Percentages (Target 100%)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Buffer Nowait %: 100.00 Redo NoWait %: 99.99
Buffer Hit %: 95.39 In-memory Sort %: 100.00
Library Hit %: 99.42 Soft Parse %: 94.45
Execute to Parse %: 36.39 Latch Hit %: 100.00
Parse CPU to Parse Elapsd %: 59.15 % Non-Parse CPU: 99.31

Shared Pool Statistics Begin End
------ ------
Memory Usage %: 10.28 10.45
% SQL with executions>1: 70.10 71.08
% Memory for SQL w/exec>1: 44.52 44.70
The three in bold are the most important: Library Hit, Soft Parse % and Execute to Parse. All of these have to do with how well the shared pool is being utilized. Time after time, we find this to be the area of greatest payback, where we can achieve some real gains in performance.
Here, in this report, we are quite pleased with the Library Hit and the Soft Parse % values. If the library Hit ratio was low, it could be indicative of a shared pool that is too small, or just as likely, that the system did not make correct use of bind variables in the application. It would be an indicator to look at issues such as those.
OLTP System
The Soft Parse % value is one of the most important (if not the only important) ratio in the database. For a typical OLTP system, it should be as near to 100% as possible. You quite simply do not hard parse after the database has been up for a while in your typical transactional / general-purpose database. The way you achieve that is with bind variables. In a regular system like this, we are doing many executions per second, and hard parsing is something to be avoided.
Data Warehouse
In a data warehouse, we would like to generally see the Soft Parse ratio lower. We don't necessarily want to use bind variables in a data warehouse. This is because they typically use materialized views, histograms, and other things that are easily thwarted by bind variables. In a data warehouse, we may have many seconds between executions, so hard parsing is not evil; in fact, it is good in those environments.
The moral of this is ...
... to look at these ratios and look at how the system operates. Then, using that knowledge, determine if the ratio is okay given the conditions. If we just said that the execute-to-parse ratio for your system should be 95% or better, that would be unachievable in many web-based systems. If you have a routine that will be executed many times to generate a page, you should definitely parse once per page and execute it over and over, closing the cursor if necessary before your connection is returned to the connection pool.
Statspack Top 5 Timed Events
Moving on, we get to the Top 5 Timed Events section (in Oracle9i Release 2 and later) or Top 5 Wait Events (in Oracle9i Release 1 and earlier).
Top 5 Timed Events
~~~~~~~~~~~~~~~~~~ % Total
Event Waits Time (s) Call Time
-------------------------------------------- ------------ ----------- ---------
CPU time 122 91.65
db file sequential read 1,571 2 1.61
db file scattered read 1,174 2 1.59
log file sequential read 342 2 1.39
control file parallel write 450 2 1.39
-------------------------------------------------------------
Wait Events DB/Inst: AKI1/AKI1 Snaps: 5-6

-> s - second
-> cs - centisecond - 100th of a second
-> ms - millisecond - 1000th of a second
-> us - microsecond - 1000000th of a second
-> ordered by wait time desc, waits desc (idle events last)
This section is among the most important and relevant sections in the Statspack report. Here is where you find out what events (typically wait events) are consuming the most time. In Oracle9i Release 2, this section is renamed and includes a new event: CPU time.
CPU time is not really a wait event (hence, the new name), but rather the sum of the CPU used by this session, or the amount of CPU time used during the snapshot window. In a heavily loaded system, if the CPU time event is the biggest event, that could point to some CPU-intensive processing (for example, forcing the use of an index when a full scan should have been used), which could be the cause of the bottleneck.

Db file sequential read - This wait event will be generated while waiting for writes to TEMP space generally (direct loads, Parallel DML (PDML) such as parallel updates. You may tune the PGA AGGREGATE TARGET parameter to reduce waits on sequential reads.

Db file scattered read - Next is the db file scattered read wait value. That generally happens during a full scan of a table. You can use the Statspack report to help identify the query in question and fix it.
SQL ordered by Gets
Here you will find the most CPU-Time consuming SQL statements
SQL ordered by Gets DB/Inst: AKI1/AKI1 Snaps: 5-6
-> Resources reported for PL/SQL code includes the resources used by all SQL
statements called by the code.
-> End Buffer Gets Threshold: 10000 Total Buffer Gets: 720,588
-> Captured SQL accounts for 3.1% of Total Buffer Gets
-> SQL reported below exceeded 1.0% of Total Buffer Gets

CPU Elapsd Old
Buffer Gets Executions Gets per Exec %Total Time (s) Time (s) Hash Value
--------------- ------------ -------------- ------ -------- --------- ----------
16,926 1 16,926.0 2.3 2.36 3.46 1279400914
Module: SQL*Plus
create table test as select * from all_objects
Tablespace IO Stats
Tablespace
------------------------------
Av Av Av Av Buffer Av Buf
Reads Reads/s Rd(ms) Blks/Rd Writes Writes/s Waits Wt(ms)
-------------- ------- ------ ------- ------------ -------- ---------- ------
TAB 1,643 4 1.0 19.2 16,811 39 0 0.0
UNDO 166 0 0.5 1.0 5,948 14 0 0.0
SYSTEM 813 2 2.5 1.6 167 0 0 0.0
STATSPACK 146 0 0.3 1.1 277 1 0 0.0
SYSAUX 18 0 0.0 1.0 29 0 0 0.0
IDX 18 0 0.0 1.0 18 0 0 0.0
USER 18 0 0.0 1.0 18 0 0 0.0
-------------------------------------------------------------
Rollback Segment Stats
->A high value for "Pct Waits" suggests more rollback segments may be required
->RBS stats may not be accurate between begin and end snaps when using Auto Undo
managment, as RBS may be dynamically created and dropped as needed

Trans Table Pct Undo Bytes
RBS No Gets Waits Written Wraps Shrinks Extends
------ -------------- ------- --------------- -------- -------- --------
0 8.0 0.00 0 0 0 0
1 3,923.0 0.00 14,812,586 15 0 14
2 5,092.0 0.00 19,408,996 19 0 19
3 295.0 0.00 586,760 1 0 0
4 1,312.0 0.00 4,986,920 5 0 5
5 9.0 0.00 0 0 0 0
6 9.0 0.00 0 0 0 0
7 9.0 0.00 0 0 0 0
8 9.0 0.00 0 0 0 0
9 9.0 0.00 0 0 0 0
10 9.0 0.00 0 0 0 0
-------------------------------------------------------------
Rollback Segment Storage
->Optimal Size should be larger than Avg Active

RBS No Segment Size Avg Active Optimal Size Maximum Size
------ --------------- --------------- --------------- ---------------
0 364,544 0 364,544
1 17,952,768 8,343,482 17,952,768
2 25,292,800 11,854,857 25,292,800
3 4,321,280 617,292 6,418,432
4 8,515,584 1,566,623 8,515,584
5 126,976 0 126,976
6 126,976 0 126,976
7 126,976 0 126,976
8 126,976 0 126,976
9 126,976 0 126,976
10 126,976 0 126,976
-------------------------------------------------------------
Generate Execution Plan for given SQL statement
If you have identified one or more problematic SQL statement, you may want to check the execution plan. Remember the "Old Hash Value" from the report above (1279400914), then execute the scrip to generate the execution plan.
sqlplus perfstat/perfstat
SQL> @?/rdbms/admin/sprepsql.sql
Enter the Hash Value, in this example: 1279400914
SQL Text
~~~~~~~~
create table test as select * from all_objects

Known Optimizer Plan(s) for this Old Hash Value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows all known Optimizer Plans for this database instance, and the Snap Id's
they were first found in the shared pool. A Plan Hash Value will appear
multiple times if the cost has changed
-> ordered by Snap Id

First First Plan
Snap Id Snap Time Hash Value Cost
--------- --------------- ------------ ----------
6 14 Nov 04 11:26 1386862634 52

Plans in shared pool between Begin and End Snap Ids
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows the Execution Plans found in the shared pool between the begin and end
snapshots specified. The values for Rows, Bytes and Cost shown below are those
which existed at the time the first-ever snapshot captured this plan - these
values often change over time, and so may not be indicative of current values
-> Rows indicates Cardinality, PHV is Plan Hash Value
-> ordered by Plan Hash Value

--------------------------------------------------------------------------------
| Operation | PHV/Object Name | Rows | Bytes| Cost |
--------------------------------------------------------------------------------
|CREATE TABLE STATEMENT |----- 1386862634 ----| | | 52 |
|LOAD AS SELECT | | | | |
| VIEW | | 1K| 216K| 44 |
| FILTER | | | | |
| HASH JOIN | | 1K| 151K| 38 |
| TABLE ACCESS FULL |USER$ | 29 | 464 | 2 |
| TABLE ACCESS FULL |OBJ$ | 3K| 249K| 35 |
| TABLE ACCESS BY INDEX ROWID |IND$ | 1 | 7 | 2 |
| INDEX UNIQUE SCAN |I_IND1 | 1 | | 1 |
| NESTED LOOPS | | 5 | 115 | 16 |
| INDEX RANGE SCAN |I_OBJAUTH1 | 1 | 10 | 2 |
| FIXED TABLE FULL |X$KZSRO | 5 | 65 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| FIXED TABLE FULL |X$KZSPR | 1 | 26 | 14 |
| VIEW | | 1 | 13 | 2 |
| FAST DUAL | | 1 | | 2 |
--------------------------------------------------------------------------------
Resolving Your Wait Events
The following are 10 of the most common causes for wait events, along with explanations and potential solutions:
1. DB File Scattered Read
This generally indicates waits related to full table scans. As full table scans are pulled into memory, they rarely fall into contiguous buffers but instead are scattered throughout the buffer cache. A large number here indicates that your table may have missing or suppressed indexes. Although it may be more efficient in your situation to perform a full table scan than an index scan, check to ensure that full table scans are necessary when you see these waits. Try to cache small tables to avoid reading them in over and over again, since a full table scan is put at the cold end of the LRU (Least Recently Used) list.
2. DB File Sequential Read
This event generally indicates a single block read (an index read, for example). A large number of waits here could indicate poor joining orders of tables, or unselective indexing. It is normal for this number to be large for a high-transaction, well-tuned system, but it can indicate problems in some circumstances. You should correlate this wait statistic with other known issues within the Statspack report, such as inefficient SQL. Check to ensure that index scans are necessary, and check join orders for multiple table joins. The DB_CACHE_SIZE will also be a determining factor in how often these waits show up. Problematic hash-area joins should show up in the PGA memory, but they're also memory hogs that could cause high wait numbers for sequential reads. They can also show up as direct path read/write waits.
3. Free Buffer
This indicates your system is waiting for a buffer in memory, because none is currently available. Waits in this category may indicate that you need to increase the DB_BUFFER_CACHE, if all your SQL is tuned. Free buffer waits could also indicate that unselective SQL is causing data to flood the buffer cache with index blocks, leaving none for this particular statement that is waiting for the system to process. This normally indicates that there is a substantial amount of DML (insert/update/delete) being done and that the Database Writer (DBWR) is not writing quickly enough; the buffer cache could be full of multiple versions of the same buffer, causing great inefficiency. To address this, you may want to consider accelerating incremental checkpointing, using more DBWR processes, or increasing the number of physical disks.
4. Buffer Busy
This is a wait for a buffer that is being used in an unshareable way or is being read into the buffer cache. Buffer busy waits should not be greater than 1 percent. Check the Buffer Wait Statistics section (or V$WAITSTAT) to find out if the wait is on a segment header. If this is the case, increase the freelist groups or increase the pctused to pctfree gap. If the wait is on an undo header, you can address this by adding rollback segments; if it's on an undo block, you need to reduce the data density on the table driving this consistent read or increase the DB_CACHE_SIZE. If the wait is on a data block, you can move data to another block to avoid this hot block, increase the freelists on the table, or use Locally Managed Tablespaces (LMTs). If it's on an index block, you should rebuild the index, partition the index, or use a reverse key index. To prevent buffer busy waits related to data blocks, you can also use a smaller block size: fewer records fall within a single block in this case, so it's not as "hot." When a DML (insert/update/ delete) occurs, Oracle Database writes information into the block, including all users who are "interested" in the state of the block (Interested Transaction List, ITL). To decrease waits in this area, you can increase the initrans, which will create the space in the block to allow multiple ITL slots. You can also increase the pctfree on the table where this block exists (this writes the ITL information up to the number specified by maxtrans, when there are not enough slots built with the initrans that is specified).
5. Latch Free
Latches are low-level queuing mechanisms (they're accurately referred to as mutual exclusion mechanisms) used to protect shared memory structures in the system global area (SGA). Latches are like locks on memory that are very quickly obtained and released. Latches are used to prevent concurrent access to a shared memory structure. If the latch is not available, a latch free miss is recorded. Most latch problems are related to the failure to use bind variables (library cache latch), redo generation issues (redo allocation latch), buffer cache contention issues (cache buffers LRU chain), and hot blocks in the buffer cache (cache buffers chain). There are also latch waits related to bugs; check MetaLink for bug reports if you suspect this is the case. When latch miss ratios are greater than 0.5 percent, you should investigate the issue.
6. Enqueue
An enqueue is a lock that protects a shared resource. Locks protect shared resources, such as data in a record, to prevent two people from updating the same data at the same time. An enqueue includes a queuing mechanism, which is FIFO (first in, first out). Note that Oracle's latching mechanism is not FIFO. Enqueue waits usually point to the ST enqueue, the HW enqueue, the TX4 enqueue, and the TM enqueue. The ST enqueue is used for space management and allocation for dictionary-managed tablespaces. Use LMTs, or try to preallocate extents or at least make the next extent larger for problematic dictionary-managed tablespaces. HW enqueues are used with the high-water mark of a segment; manually allocating the extents can circumvent this wait. TX4s are the most common enqueue waits. TX4 enqueue waits are usually the result of one of three issues. The first issue is duplicates in a unique index; you need to commit/rollback to free the enqueue. The second is multiple updates to the same bitmap index fragment. Since a single bitmap fragment may contain multiple rowids, you need to issue a commit or rollback to free the enqueue when multiple users are trying to update the same fragment. The third and most likely issue is when multiple users are updating the same block. If there are no free ITL slots, a block-level lock could occur. You can easily avoid this scenario by increasing the initrans and/or maxtrans to allow multiple ITL slots and/or by increasing the pctfree on the table. Finally, TM enqueues occur during DML to prevent DDL to the affected object. If you have foreign keys, be sure to index them to avoid this general locking issue.
7. Log Buffer Space
This wait occurs because you are writing the log buffer faster than LGWR can write it to the redo logs, or because log switches are too slow. To address this problem, increase the size of the log files, or increase the size of the log buffer, or get faster disks to write to. You might even consider using solid-state disks, for their high speed.
8. Log File Switch
All commit requests are waiting for "logfile switch (archiving needed)" or "logfile switch (Checkpoint. Incomplete)." Ensure that the archive disk is not full or slow. DBWR may be too slow because of I/O. You may need to add more or larger redo logs, and you may potentially need to add database writers if the DBWR is the problem.
9. Log File Sync
When a user commits or rolls back data, the LGWR flushes the session's redo from the log buffer to the redo logs. The log file sync process must wait for this to successfully complete. To reduce wait events here, try to commit more records (try to commit a batch of 50 instead of one at a time, for example). Put redo logs on a faster disk, or alternate redo logs on different physical disks, to reduce the archiving effect on LGWR. Don't use RAID 5, since it is very slow for applications that write a lot; potentially consider using file system direct I/O or raw devices, which are very fast at writing information.
10. Idle Event.
There are several idle wait events listed after the output; you can ignore them. Idle events are generally listed at the bottom of each section and include such things as SQL*Net message to/from client and other background-related timings. Idle events are listed in the stats$idle_event table.
Remove STATSPACK from the Database
After a STATSPACK session you want to remove the STATSPACK tables.
sqlplus "/ as sysdba"
SQL> @?/rdbms/admin/spdrop.sql
SQL> DROP TABLESPACE perfstat INCLUDING CONTENTS AND DATAFILES;

Thursday, April 30, 2009

أسوأ أيام الأمة: سقوط بغداد في قبضة التتار

حينما فشلت المساعي بين القائد المغولي هولاكو خان، والخليفة العباسي المستعصم، بمنع الحرب وتجنب المواجهة، عقد هولاكو النية على احتلال بغداد عاصمة الخلافة الإسلامية، فأعطى أوامره بانتقال جيوش جرماجون وبايجو نوبان من معاقلهما في آسيا الصغرى، وأن تسير على ميمنة الجيوش الزاحفة على بغداد إلى الموصل عن طريق أربيل، ثم تعبر جسر الموصل وتعسكر في الجانب الغربي من بغداد، حتى إذا جاءت الجيوش من المشرق تخرج إليها من هذه الناحية، ويزحف على رأس الجناح الأيسر كل من كيتوبوقا، وقدسون، وترك إيلكا ـ كبار قادة هولاكو ـ من حدود إيران باتجاه بغداد مباشرة.

أما هولاكو نفسه فقد كان على رأس قلب الجيش، وتحرك في أوائل المحرم سنة 655هـ الموافق 18 يناير 1258م نحو نهر دجلة، ومر هولاكو في طريقه على مدينة كرمنشاة فدمرها على طريقة المغول التقليدية، وتعمد هولاكو بهذا التدمير البربري إلقاء الرعب في النفوس، ورسالة إنذار للبغداديين بسوء المصير المنتظر.

عسكر قلب الجيش على شاطئ نهر حلوان في التاسع من شهر ذي الحجة، وأقاموا هناك حتى الثاني والعشرين منه، حتى يتمكن جيش كيتو بوقا من إنجاز مهامه، والوصول إلى مواقعه المتفق عليها في الوقت المحدد، كما تمكنت عدة فرق أخرى من عبور نهر دجلة في الوقت المقرر.

في ذلك الوقت كان مجاهد الدواتدار القائد العام لجيش الخليفة معسكرا بجنوده بين بعقوبة وباجسري، ولما سمعوا بقدوم المغول إلى الضفة الأخرى عبروا نهر دجلة واشتبكوا في قتال شرس مع المغول في حدود الأنبار على باب قصر المنصور، على بعد تسعة أميال من بغداد.

في تلك النواحي كان يوجد نهر عليه سد كبير فتحه المغول، فغمرت المياه كل الصحراء الواقعة خلف جيش الخليفة، وفي فجر يوم الخميس من المحرم دهم المغول الجيش المحاصر بين مائين، وأوقعوا به هزيمة منكرة، بلغ عدد القتلى فيها اثنا عشر ألف مسلم، فضلا عمن غرق أو قضى نحبه في الوحل.

فر قائد جيش الخليفة مع عدد قليل من جنوده، وعادوا إلى بغداد، كما هرب البعض إلى المدن الأخرى مثل الحلة والكوفة، وفي يوم الثلاثاء منتصف المحرم تقدم قادة الجيش المغولي بوقا تيمور وبايجو وسونجاق، تقدموا إلى بغداد واستولوا على الجانب الغربي منها، ونزلوا في ضواحي المدينة على شواطىء نهر دجلة، وفي الوقت نفسه وصل بوقا نويان من ناحية صرصر، وتحرك هولاكو من خانقين حيث كان معسكرا، وواصل سيره نحو بغداد حتى نزل في الجهة الشرقية منها، ثم تدفقت بعد ذلك باقي الجيوش كالنمل والجراد من كل جهة وناحية، فحاصروها من جميع أطرافها حتى أصبحوا حولها كسور بشري.

وفي صباح يوم 22 من المحرم 656هـ الموافق 30 يناير 1258م، أعطيت الأوامر لقادة الميدان باقتحام المدينة من جميع الجهات، فقام المغول بشن هجوم كاسح على أسوار بغداد، استخدموا فيه المنجانيق على نطاق واسع، وأحدث ثقل الحجارة وقوة اندفاعها ثغرات كبيرة في برج العجمي ـ أحد أكبر الأبراج بسور بغداد ـ ورافق هذا الهجوم الوحشي قرع الطبول وصراخ المغول المرعب وصيحاتهم الحادة، فانهارت أعصاب الخليفة، وعندئذ أرسل إلى هولاكو يخبره بموافقته على جميع شروطه للتسليم، فرد هولاكو على رسل الخليفة: هذه الشروط طلبتها وأنا على باب همدان، أما الآن فأنا على باب بغداد.

وفي يوم الجمعة 26 من المحرم إنهار برج العجمي، فانطلق المغول كالإعصار يجرفون كل حي في طريقهم، وفي يوم الاثنين 28 منه تسلق بعضهم السور عنوة، وأخلوا الأسوار من جند الخليفة، وما كان المساء يحل حتى تسلم المغول جميع الأسوار الشرقية.

على إثر ذلك أمر هولاكو بإقامة جسر في أعلى بغداد وفي أسفلها، وإعداد السفن ونصب المنجانيق، وكان بوقا تيمور قد رابط مع عشرة آلاف جندي على طريق المدائن والبصرة ليصد كل من يحاول الهرب بالسفن، ولما حمي وطيس القتال داخل بغداد، وضاق الحال بالمسلمين، أراد الدواتدار أن يركب سفينة ويهرب، لكن جنود المغول أفشلوا هروبه وأعادوه مهزوما مكسورا.

وفي ليلة الثلاثاء التاسع والعشرين من المحرم، خرج من بغداد للقاء هولاكو أبوالفضل عبدالرحمن بن الخليفة المستعصم، يرافقه جماعة من كبار رجال الدولة، ومعهم أموال طائلة وهدايا ثمينة لم تقبل منهم، وفي اليوم التالي خرج بن الخليفة الأكبر مع جماعة من المقربين للشفاعة فلم يجدوا آذانا صاغية.

أخيرا أرسل هولاكو برسالة قصيرة للخليفة يقول فيها: إن الرأي للخليفة، فله أن يخرج أو لايخرج، وسيكون جيش المغول مقيما على الأسوار إلى أن يخرج سليمان شاة والدواتدار، وفي يوم الخميس خرج الرجلان لمقابلة هولاكو، ولكنه أعادهما مرة أخرى ليخرجا أتباعهما، وكل ما يخصهما، بحجة أنهم سينفون إلى مصر والشام، وخرج معهما جند بغداد وكثير من السكان، وكانوا خلقا لا يحصى، مؤملين أن يجدوا طريقا للخلاص، بيد أن أملهم قد خاب، فقد قتلهم المغول بلا رحمة.

وفي يوم الجمعة الثامن من صفر قتل مجاهد الدواتدار وسليمان شاة وجميع أتباعهم وأشياعهم، وأرسلت رؤوس الثلاثة على يد الملك الصالح بن بدر الدين لؤلؤ إلى الموصل، وكان بدر الدين صديقا لسليمان شاة فبكى، ولكنه علق رؤوسهم خوفا على حياته.


المشهد الأخير

ثم حلت الفاجعة الكبرى، في يوم عد على أنه من أسود الأيام في تاريخ الأمة الإسلامية، يوم الأحد 14 من صفر سنة 656 هـ الموافق 10 فبراير سنة 1258م، إذ خرج الخليفة المستعصم من بغداد ومعه أبناؤه الثلاثة أبوالفضل عبدالرحمن، وأبوالعباس أحمد، وأبوالمناقب مبارك، يرافقهم ثلاثة آلاف من السادات والأئمة، والقضاة والأكابر والأعيان، لتسليم أنفسهم وعاصمة الخلافة الإسلامية بلا قيد ولا شرط، ورافق هذا الخروج الجماعي للاستسلام الذليل، صراخ وندب وصياح من النساء، وارتفعت أكف عشرات الآلاف من المسلمين في وقت واحد تتضرع إلى الله أن يرفع عنهم الغمة، في جو قاتم مشحون بالرعب والدماء ورائحة الموت.

استقبل هولاكو الخليفة استقبالا لا ينم عن غضب منه، بل سأله بأسلوب مهذب عن صحته، وكلمه بالحسنى، وطلب منه أن يأمر بخروج كل سكان المدينة من منازلهم ومخابئهم حتى يحصوهم، فخالت على الخليفة الخدعة، وأذعن لطلبه، وخرج المنادون في كل أحياء بغداد ليعلنوا على المسلمين، أن كل من يود إنقاذ حياته وصيانة ماله وعرضه، فليخرج من المدينة، ويسلم ما في حوزته من سلاح للمغول.. ووقع الناس في بلبلة كبيرة، فمنهم من صدق وسلم سلاحه، ومنهم من ارتاب من سلامة الأوامر وصحتها، فاحتفظ واعتصم بداره وبقي بجانب عائلته.

نصب المغول خياما على امتداد نهر دجله لاستلام السلاح، وجاء المسلمون جماعات يسلمون سلاحهم، وكل من دخل خيمة لتسليم سلاحه خرج من الناحية الأخرى جثة هامدة، وأدرك الأهالي أن الفخ المنصوب لهم، وأن المغول يذبحونهم كقطعان الغنم، ويرمون بجثثهم في مجار مائية متفرعة من نهر دجلة، فانتشر الخبر بسرعة، وعاد الناس للاختفاء عنهم.

وفي يوم الأربعاء 17 من صفر 656 هـ الموافق 13 فبراير 1258م، أعطيت الأوامر بإباحة المدينة بالكامل، وتم توزيع قادة المغول والضباط وفرق الجيش على أحياء ودروب بغداد، يفعلون فيها مايشاءون، فاجتاح المغول المدينة بلا أية ضوابط، فقتلوا الرجال والأطفال، وهتكوا أعراض النساء، وبقروا بطون الحوامل، وقتلوا كل حي رأوه، ولم يسلم منهم إلا من اختفى منهم في باطن الأرض، أو تصنع الموت ونام بين الجثث المقتولة !!.

ولم يقف الأمر عند هذا فقط، بل راحوا يخربون مباني المدينة، فهدموا جامع الخليفة، ومشهد الإمام موسى الكاظم، ونبشوا قبور الخلفاء في الرصافة، ودمروا المساجد ليستولوا على الذهب المزينة به قبابها، وهدموا القصور بعد أن استولوا على كل ما فيها من تحف نادرة ومجوهرات، ، ثم أضرموا النار في المدينة لتأتي على الأخضر واليابس فيها.


رواية شاهد عيان


من بين شهود العيان الذين كتبت لهم النجاة من هذا اليوم الرهيب، عبدالمؤمن مغني الخليفة المستعصم ونديمه، قال في روايته عن هذا اليوم:

طلب هولاكو من رؤساء البلد أن يقسموا دروب بغداد ومحالها وبيوت ذوي يسارها على أمراء دولته فقسموها، وجعلوا كل محلة أو محلتين أو سوقين باسم أمير كبير، فوقع الدرب الذي أسكنه في حصة أمير مقدم عشرة آلاف فارس اسمه “بانوانوين”، وكان هولاكو قد رسم لبعض الأمراء أن يقتل ويأسر وينهب مدة ثلاثة أيام، ولبعضهم يوم حسب طبقتهم، فلما دخل الأمراء إلى بغداد ، فأول درب جاء إليه الدرب الذي أنا ساكنه، وكان قد اجتمع عندي كثير من ذوي اليسار، واجتمع عندي نحو خمسين جوقة من أعيان المغاني من ذوي المال والجمال، فوقف بانوانوين على باب الدرب، وهو مدبس بالأخشاب والتراب، فطوقوا الباب وقالوا:

● افتحوا لنا الباب وادخلوا في الطاعة ولكم الأمان، وإلا حرقنا الباب وقتلناكم

● قلت: السمع والطاعة

ففتحت الباب وخرجت إليه وحدي وعليّ ثياب وسخة، وأنا أنتظر الموت، فقبلت الأرض بين يديه، فقال للترجمان: إذا أردتم السلامة من الموت فاحملوا لنا كذا وكذا، وطلب شيئا كثيرا، فقبلت الأرض مرة ثانية، وقلت: كل ما طلب الأمير يحضر، وقد صار كل ما في الدرب بحكمك، فمر جيوشك ينهبون باقي الدروب المعينة، وأنزل حتى أضيفك ومن تريد من خواصك، فأجمع لك ماطلبت.

فشاور أصحابه ونزل في نحو ثلاثين رجلا، فأتيت به إلى داري، وفرشت له الفرش الخليفية الفاخرة، والسور المطرزة بالزركش، وأحضرت له في الحال أطعمة، مقليات ومشويات وحلوى، فلما فرغ من الأكل عملت له مجلسا ملوكيا، وأحضرت له الأواني المذهبة من الزجاج، وأواني فضة فيها شراب مروق، فلما دارت الأقداح وسكر قليلا، اخترت عشر جوق كلهم نساء، كل جوقة تغني بملهاة غير ملهاة أختها، وأمرتهم فغنوا كلهم، فارتج المجلس وطرب، وانبسطت نفسه، وضم واحدة من المغنيات أعجبته، فواقعها في المجلس ونحن نشاهده.

وتم يومه في غاية الحسن، فلما كان وقت العصر، حضر أصحابه بالنهب والسبايا، فقدمت له ولأصحابه الذين كانوا معه تحفا جليلة من أواني الذهب والفضة، ومن الأقمشة الفاخرة، واعتذرت له على التقصير، وقلت له جئتني على غفلة، لكن غدا أعمل للأمير دعوة أحسن من هذه، فركب وقبلت ركابه، ولما رجعت جمعت أهل الدرب من أهل اليسار وقلت لهم انظروا لأنفسكم هذا الرجل غدا عندي وبعد غد وكل يوم، أريد أضعاف المتقدم، فجمعوا لي من بينهم ما يساوي خمسين ألف دينار من أنواع الذهب والأقمشة الفاخرة والسلاح.

فلما طلعت الشمس إلا وقد جاءني ومعه نساؤه، فرأى ما أذهله، فقدمت له ولنسائه من الذخائر والنقد ما قيمته عشرون ألف دينار، وقدمت له في اليوم الثالث لآلىء نفيسة وجواهر ثمينة وبغلة جميلة، وقدمت لجميع من معه، وقلت له هذا الدرب قد صار بحكمك، فإن تصدقت على أهله بأرواحهم، فقال من أول يوم وهبتهم أرواحهم، وما حدثتني نفسي بقتلهم ولا سبيهم، لكن أنت تجهز معي قبل كل شيء إلى حضرة الخان، فقد ذكرتك عنده، وقدمت له شيئا من المستظرفات التي قدمتها لي، فأعجبته فرسم بحضورك.

ويواصل مغني الخليفة ونديمه شهادته فيقول:

دخل هولاكو بغداد لمشاهدة قصر الخليفة، فأعجب ببنائه وهندسته والسجاد العجمي الذي يكسو جدرانه، ثم أشار بإحضار الخليفة المستعصم، فجيء به مكبلا بالسلاسل شاحب اللون حزين، فقال له هولاكو ساخرا: إنك الآن مضيف ونحن الضيوف، فهيا أحضر ما يليق بنا، ومن فرط الخوف صدق الخليفة هذا الكلام, وبلغ من الدهشة درجة لم يعد يعرف أين وضع مفاتيح الخزائن، فأمر بكسر الأقفال وأخرج منها ألفي ثوب، وعشرة آلاف دينار، ونفائس ومرصعات وعددا من الجواهر، قدمها جميعا إلى هولاكو الذي لم يعر تلك الأشياء التفاتا، ومنحها كلها للأمراء والحاضرين، ثم قال للخليفة: إن هذه الأموال التي تملكها على الأرض ظاهرة، وهي ملك عبيدنا، لكن أذكر ما تملكه من الدفائن وأين توجد؟

عندئذ اعترف الخليفة بوجود حوض مملوء بالذهب في ساحة القصر، فحفروا الأرض حتى وجدوه، وكان بالفعل مملوء بالجواهر المؤلفة من الإبريز والذهب والفضة والألماس والأحجار الكريمة، مما أدخره العباسيون من خزائن قصر بغداد وجمعوها خلال خمسة قرون، وكانت كل قطعة منها تزن مائة مثقال.

700 زوجة وسرية للخليفة!!

في يوم الجمعة 19 صفر أصدر هولاكو أوامره بإحصاء نساء الخليفة، فعدوا سبعمائة زوجة وسرية وألف خادمة، فلما اطلع الخليفة على تعداد نسائه جاء إلى هولاكو متضرعا وقال له: مٌن علىَ بأهلي حرمي اللاتي لم تطلع عليهن الشمس والقمر، فأخرج الخليفة مائة امرأة من أقاربه والمحببات إليه، وألحق هولاكو ما استرعين نظره بحريمه، ثم وزع الباقي على الأمراء وقادة جيشه.

وبعدما تم قتل ما يقرب من ثمانمائة ألف نفس في بغداد، وتخريب آلاف المباني والقصور، صدرت الأوامر بالكف عن القتل، فخرج من تحت الأرض من كان مختبئا كأنهم موتى، حتى أنكر بعضهم بعضا، ووجدوا أرض بغداد مخضبة بالدم، مليئة بجثث القتلى، وهواؤها فاسدا عفنا من رائحة الجثث المترممة ولم تجد من يدفنها، وانتشرت الأوبئة والأمراض من جراء ذلك، حتى أن هولاكو نفسه غادر بغداد هربا من رائحتها إلى قرية وقف، وهناك استدعى الخليفة العباسي الذي يأس من إنقاذ حياته، ولذلك استأذن هولاكو في الذهاب إلى الحمام ليجدد اغتساله، فأمر هولاكو بأن يصحبه خمسة من المغول، لكن الخليفة رفض قائلا: أنا لا أريد أن أذهب بصحبة خمسة من الزبانية، وفي مساء نفس اليوم 24 صفر 656 هـ الموافق 20 فبراير سنة 1258 م ، قتل الخليفة وكان عمره 46 سنة، وابنه الأكبر أبوالعباس أحمد وعمره كان 25 سنة، وابنه الأوسط أبوالفضل عبدالرحمن وكان عمره 23 سنة، وأسر ولده الأصغر مبارك، وأسرت إخواته الثلاث فاطمة وخديجة ومريم، وقتل خمسة من الخدم كانوا في معية الخليفة، وقتلوا كل من وجدوه حيا من العباسيين، وتم أسر ما يقرب من ألف بكر من نساء دار الخلافة، وفي يوم الجمعة 23 من ربيع الأول رحل هولاكو عن بغداد قاصدا معسكره في خانقين، حيث أرسل لأخيه منكوبان كثيرا من الغنائم والأموال التي نهبت من بغداد.

يقول ابن كثير: اختلف الناس في عدد من قتل ببغداد من المسلمين في هذه الواقعة، فمنهم من قال ثمانمائة ألف، ومنهم من قال ألف ألف وثمانمائة ألف، وقيل بلغ القتلى ألفي ألف نفس، وقال: كانت جثث القتلى في الطرقات كأنها التلول، وقد سقط عليها المطر، فتغيرت صورهم، وأنتنت من جيفهم البلد، وتغير الهواء، فحصل بسببه الوباء الشديد، حتى تعدى وسرى في الهواء إلى بلاد الشام، فمات خلق كثير من تغير الجو وفساد الريح، فاجتمع من بقي على الوباء والغلاء والفناء، والطعن والطاعون، فإنا لله وإنا إليه راجعون
مصطفى سنجر

Thursday, April 23, 2009

How We Can Started Database in EXCLUSIVE mode

A database is started in EXCLUSIVE mode by default. Therefore, the
ORA-01102 error is misleading and may have occurred due to one of the
following reasons:

- there is still an "sgadef.dbf" file in the "ORACLE_HOME/dbs"
directory
- the processes for Oracle (pmon, smon, lgwr and dbwr) still exist
- shared memory segments and semaphores still exist even though the
database has been shutdown
- there is a "ORACLE_HOME/dbs/lk" file

The "lk" and "sgadef.dbf" files are used for locking shared memory.
It seems that even though no memory is allocated, Oracle thinks memory is
still locked. By removing the "sgadef" and "lk" files you remove any knowledge
oracle has of shared memory that is in use. Now the database can start.

POSSIBLE SOLUTION:
Verify that the database was shutdown cleanly by doing the following:

1. Verify that there is not a "sgadef.dbf" file in the directory
"ORACLE_HOME/dbs".

% ls $ORACLE_HOME/dbs/sgadef.dbf

If this file does exist, remove it.

% rm $ORACLE_HOME/dbs/sgadef.dbf

2. Verify that there are no background processes owned by "oracle"

% ps -ef | grep ora_ | grep $ORACLE_SID

If background processes exist, remove them by using the Unix
command "kill". For example:

% kill -9

3. Verify that no shared memory segments and semaphores that are owned
by "oracle" still exist

% ipcs -b

If there are shared memory segments and semaphores owned by "oracle",
remove the shared memory segments

% ipcrm -m

and remove the semaphores

% ipcrm -s

NOTE: The example shown above assumes that you only have one
database on this machine. If you have more than one
database, you will need to shutdown all other databases
before proceeding with Step 4.

4. Verify that the "$ORACLE_HOME/dbs/lk" file does not exist

5. Startup the instance

Tuesday, April 21, 2009

My Skills

1-Good understanding of the Oracle database, related utilities and tools
2-Good understanding of the underlying operating system
3-Good knowledge of the physical database design
4-Ability to perform both Oracle and operating system performance tuning and monitoring
5-Knowledge of ALL Oracle backup and recovery scenarios
6-Good knowledge of Oracle security management
7-Good knowledge of how Oracle acquires and manages resources
8-Good knowledge Oracle data integrity
9-Sound knowledge of the implemented application systems
10-Experience in code migration, database change management and data management through the various stages of the development life cycle
11-Sound knowledge of both database and system performance tuning
12-Sound communication skills with management, development teams, vendors and systems administrators
13-Provide a strategic database direction for the organisation
14-Ability to handle multiple projects and deadlines
15-Sound understanding of the business

My Roles and Responsibilities

The job of the DBA seems to be everything that everyone else either doesn't want to do, or doesn't have the ability to do. DBAs get the enviable task of figuring out all of the things no one else can figure out. More seriously though, here is a list of typical DBA responsibilities:

1-Installation, configuration and upgrading of Oracle server software and related products
2-Evaluate Oracle features and Oracle related products
3-Establish and maintain sound backup and recovery policies and procedures
4-Take care of the Database design and implementation
5-Implement and maintain database security (create and maintain users and roles, assign privileges)
6-Perform database tuning and performance monitoring
7-Perform application tuning and performance monitoring
8-Setup and maintain documentation and standards
9-Plan growth and changes (capacity planning)
10-Work as part of a team and provide 7x24 support when required
11-Perform general technical trouble shooting and give consultation to development teams
12-Interface with Oracle Corporation for technical support.
13-Patch Management and Version Control

Wednesday, April 8, 2009

Add New File System In Linux

1-Identify device
fdisk -l
2-Partition device
fdisk /dev/sdb
mkdir /u02
3-Make filesystem
mkfs.ext3 -c /dev/sdb
4-Mount new filesystem
mount -t ext2 /dev/sdb /u02
5-Create entry in /etc/fstab
vi /etc/fstab
add
/dev/sdb /u02 ext3 defaults 0 0

Add Swap Space In Linux

1-Determine the size of the new swap file and multiple by 1024 to determine the block size. For example, the block size of a 1024 MB (1G) swap file is 1048576.

At a shell prompt as root, type the following command with count being equal to the desired block size:

dd if=/dev/zero of=/swapfile bs=1024 count=1048576


2-Setup the swap file with the command:

mkswap /swapfile


3-To enable the swap file immediately but not automatically at boot time:

swapon /swapfile


4-To enable it at boot time, edit /etc/fstab to include:

/swapfile swap swap defaults 0 0


The next time the system boots(or type mount -a ), it will enable the new swap file.

5-After adding the new swap file and enabling it, make sure it is enabled by viewing the output of the command cat /proc/swaps or free.

Oracle Database Administration Fundamentals I and II


check log files

To chack many log files for backup in linux use this command:

grep -il unsuccessfully *.LOG > unsuccessfull_backups.txt

Tuesday, April 7, 2009

RMAN backup

1:create user
SQL> create user rman identified by rman ;
SQL> alter user rman default tablespace tools temporary tablespace temp ;
SQL> alter user rman quota unlimited on tools ;
SQL> grant connect,resource,recovery_catalog_owner to rman ;
SQL> exit ;

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

2:login to rman and create cataloge schema
$ rman catalog rman/rman
RMAN> create catalog tablespace tools ;
RMAN> exit ;

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

3:put database in archive log

sqlplus login as sysdba

SQL>select log_mode from v$database ;
select name from v$database;
SQL> shutdown immediate ;
SQL> startup mount ;
SQL>alter database archivelog ;
SQL>alter database open ;
SQL>select log_mode from v$database ;

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

4:register the database in the catalog
$ rman catalog rman/rman target sys/sys
RMAN>register database;
============================================================================
5:create script to make backup
RMAN> create script daily_backup{
backup database plus archivelog;
delete noprompt obsolete;
}


============================================================================
RMAN configuration parameters are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1;
CONFIGURE BACKUP OPTIMIZATION ON;
CONFIGURE DEFAULT DEVICE TYPE TO DISK;
CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/home/backup/%F';
CONFIGURE DEVICE TYPE DISK PARALLELISM 1;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1;
CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT '/home/backup/RMAN_%d_S_%s_P_%p_T_%t' MAXPIECESIZE 2 G;
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO 'F:\RMANBACKUP\SNCFSULAPP1.ORA';

RMAN>
CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT 'f:\RmanBackup\backup_db_%d_S_%s_P_%p_T_%t' MAXPIECESIZE 2 G;
CONFIGURE CHANNEL 2 DEVICE TYPE DISK FORMAT 'f:\RmanBackup\backup_db_%d_S_%s_P_%p_T_%t' MAXPIECESIZE 2 G;
================================================================================
7: execute script to backup
RMAN> run {execute script daily_backup;}

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

Complete Restore / Recover Example

1/create folder in any directory for exampel d:\backupdatabase
change the configration of rman
rman catalog rman/rman target sys/sys
RMAN>CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO 'd:\backupdatabase\%F';
RMAN>CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT 'd:\backupdatabase\backup_db_%d_S_%s_P_%p_T_%t';
RMAN>CONFIGURE SNAPSHOT CONTROLFILE NAME TO 'd:\backupdatabase\SNCFORCL.ORA';
exit;
2/connect to sql
sql> sys/sys as sysdba
shutdown immediate
startup nomount
exit;

3/connect to rman
rman target sys/sys
RMAN>set dbid=1134214906 {this is the id of your database}
RMAN>set controlfile autobackup format for device type disk to 'D:\backup\%F'
RMAN>restore controlfile from autobackup;
RMAN>mount database;
RMAN>restore database;
RMAN>recover database;
RMAN>alter database open resetlogs;
RMAN>exit;
rman catalog rman/rman target sys/sys
RMAN>reset database;
exit;

create batch file
rman catalog rman/rman target sys/sys @d:\cmdfile.txt
create text file in d:\ name cmdfile and write in it rman command

set controlfile autobackup format for device type disk to 'D:\backup\%F'


RMAN>Friday backup
run {
backup incremental level 0 database ;
sql 'alter system archive log current';
backup archivelog all delete input;
delete noprompt obsolete;
}
RMAN>Daily backup
run {
backup incremental level 1 database ;
sql 'alter system archive log current';
backup archivelog all delete input ;
delete noprompt obsolete;
}
RMAN>MONDAY
run {
backup incremental level 2 database ;
sql 'alter system archive log current';
backup archivelog all delete input;
delete noprompt obsolete;
}
RMAN>Wed backup
run {
backup incremental level 2cumulative database ;
sql 'alter system archive log current';
backup archivelog all delete input;
delete noprompt obsolete;
}

ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp


Check whether backup pieces, proxy copies, or disk copies still exist.

CROSSCHECK BACKUP;
CROSSCHECK COPY;
CROSSCHECK backup of database;
CROSSCHECK backup of controlfile;
CROSSCHECK archivelog all;

uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
List the backups and copies recorded in the repository.


LIST BACKUP;
RMAN> LIST BACKUP OF DATABASE;
RMAN> LIST BACKUP SUMMARY;
RMAN> LIST INCARNATION;
RMAN> LIST BACKUP BY FILE;
RMAN> LIST COPY OF DATABASE ARCHIVELOG ALL;
RMAN> LIST COPY OF DATAFILE 1, 2, 3;
RMAN> LIST BACKUP OF DATAFILE 11 SUMMARY;
RMAN> LIST BACKUP OF ARCHIVELOG FROM SEQUENCE 1437;
RMAN> LIST CONTROLFILECOPY "/tmp/cntrlfile.copy";
RMAN> LIST BACKUPSET OF DATAFILE 1;


[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[

list incarnation of database;
reset database to incarnation Your_KEY;
reset database;


////////////////////////////////////////////////////////
ALTER SYSTEM ARCHIVE LOG START;







In AIX and Linux

rman target rman/*****@SID rcvcat rman/****@CAT_SID

run
{
allocate channel t1 type 'sbt_tape' parms 'ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo.opt)' CONNECT 'rman/*****@SID1';
allocate channel t2 type 'sbt_tape' parms 'ENV=(TDPO_OPTFILE=/usr/tivoli/tsm/client/oracle/bin64/tdpo.opt)' CONNECT 'rman/*****@SID2';
backup format "%d_full_%s_%p" filesperset 5 database;
sql "alter system archive log current";
backup format "%d_arch_%s_%p" filesperset 20 (archivelog all delete input);
release channel t1;
release channel t2;
}


delete noprompt obsolete;

Audit In Oracle

Introduction
This article will introduce the reader to the basics of auditing an Oracle database. Oracle's RDBMS is a functionally rich product and there are a number of auditing alternatives available to the reader. Because auditing Oracle is such a huge subject, doing all of it justice would take an entire book, so this paper will cover the basics of why, when and how to conduct an audit. It will also use a couple of good example cases to illustrate how useful Oracle audit can be to an organization.
The Issues
There are a number of basic issues that should be considered when contemplating using Oracle's auditing features. These are as follows:

• Why is audit needed in Oracle?
Is this a strange question? Well, lots of companies don't actually use the internal audit features of Oracle. Or, when they do use them, they are so overwhelmed with choice, they turn on everything for good measure, then realise there is far too much output to read and digest so they quickly turn it all off again. It is quite common to use firewalls, intrusion detection systems (IDS) and other security tools to determine if the network or operating system is being misused or abused. So why not audit what users are doing to the "crown jewels" of an organization, the data. Oracle audit can help detect unauthorized access and internal abuse of the data held in the database.

• When should Oracle users be audited?
A simple basic set of audit actions should be active all the time. The ideal minimum is to capture user access, use of system privileges and changes to the database schema structure. This basic set will not show attempted access to specific data that shouldn't be accessed; however, it will give a reasonably simple overview of "incorrect" access and use of privileges. If an employee is suspected of inappropriate actions or if an attack has been suspected then more detailed audit can be turned on for specific tables. From a data management point of view, auditing data changes for all tables in the database is not really practical and could also affect performance. Monitoring data change access on critical tables (such as salaries in a HR database) should be considered.

• How can Oracle users be audited?
The standard audit commands allow all system privileges to be audited along with access at the object level to any table or view on the database for select, delete, insert or update. Audit can be run for either successful or unsuccessful attempts or both. It can be for each individual user or for all users and it can also be done at the session level or access level. At action level a single record is created per action and at session level one record is created for all audit actions per session.

• What are the performance and complexity issues?
Audit is generally perceived to be complex and slow. The reason for this is usually ignorance. If many or all options are turned on, then the resultant audit trail produced can be large and difficult to interpret and manage. Furthermore, if audit is used on all tables and views in the database, then this can have an effect on performance. Every time an action performed is auditable a record is written to the database; clearly the more audit is used, the more records will be written to the system tablespace purely for audit. In some cases double the amount of access to the database can be performed: the original write and the audit record being written.
The watchword here is simplicity and caution. Use only the audit that is needed to give an overall view of what is happening and for detailed monitoring of critical data and objects. The simpler the audit trail set-up, the more likely it is that the data will be analyzed and be of some use. It is important to define what actions or abuses are being checked for so that simple reports can be written to filter the audit trail for these actions. A default installation of Oracle has audit turned off by default and Oracle does not come with any standard default audit settings or reports to analyse any audit trail produced. These reasons, and the fact that there are many options available are, in my opinion, why audit is perceived to be complex.
The standard audit commands do not allow audit to be performed at row level. It is also not possible to audit the actions of privileged users such as SYS and "as sysdba" until Oracle 9iR2.
Oracles Audit Facilities
The task of auditing an Oracle database does not have to be limited only to the audit commands; other techniques can be employed as well. Here are some of the main methods that can be used to audit an Oracle database:

• Oracle audit
This is really the subject of this paper. All privileges that can be granted to a user or role within the database can be audited. This includes read, write and delete access on objects at the table level. For more detailed audit, the database triggers need to be employed.

• System triggers
These were introduced with Oracle and allow the writing of database triggers that fire when system events take place. These include start- up and shutdown of the database, log-on and log-off attempts, and creation, altering and dropping of schema objects. With the aid of autonomous transactions, these allow a log to be written for the above system events.

• Update, delete, and insert triggers
This is the second line of defence in trying to understand users' actions at a more detailed row level. Database triggers need to be written to capture changes at the column and row level. It is possible to write complete rows of data before and after the change being made to a log table in the database. The use of this type of logging is very resource intensive, as many extra records are written and stored. The one failing with this method is that read access cannot be captured with normal database triggers.

• Fine-grained audit
Fine-grained audit solves the problem of capturing read access. This feature is also based on internal triggers that fire when any piece of SQL is parsed. This is very efficient, as the SQL is parsed once for audit and execution. The feature uses predicates that are defined and tested each time the relevant object is accessed. Fine-grained audit is managed by a PL/SQL package called DBMS_FGA. A PL/SQL procedure is executed every time a "match" is made with the predicate. This method allows the audit to be performed down to the row and column level and to also for read statements. Readers should be forewarned that use of this feature requires programming skills.

• System logs
Oracle generates many log files and many of them can provide useful information to assist in auditing the database. One good example is the alert log used by the database to record start-up and shutdown as well as any structural changes such as adding a datafile to the database.
This paper is going to explore only the standard built-in audit commands. The other options will be left for future articles.
Some Examples
Because of the myriad of possibilities, auditing an Oracle database can be a daunting task. In order to try and simplify the discussion of what can be done, we will discuss a couple of simple examples that we will explore and work through.

• Auditing database access
This is a fundamental check to find out who accesses the database, from where and when. Log-on failures can be captured as well as log- ons at strange (anomolous) times of the day.

• Auditing changes to the database structure
In a production database, no user should ever change the schema structure. DBAs should make changes for upgrades at specific times; any other changes should be regarded as suspicious. Watching for structural changes can turn up indicators of incorrect use of the database.
A third simple example that could have been employed here is to audit any use of system privileges. However, this example is left to the reader to explore.
The final group of audit commands that can be employed is to audit any data changes to objects themselves. Unfortunately, as the requirements are very application and installation specific, this is beyond the scope of this paper.
Audit within Oracle is broken into three areas: statement auditing such as CREATE TABLE or CREATE SESSION, privilege auditing such as ALTER USER, and object level auditing such as SELECT TABLE.
Basic Configuration
The audit trail can be either written to the database or to the operating system. Writing the audit trail to the operating system is, in some senses, more secure but the implementation is not available on all platforms and is platform specific. In this article we will concentrate on using the database to store the audit trail.
Audit is turned on for writing to the database by adding the following line to the init.ora file. A symbolic link to it can usually be found in $ORACLE_HOME/dbs
audit_trail = db
The database now needs to be restarted. A simple check will show that audit is indeed now turned on.
SQL> select name,value from v$parameter
where name like 'audit%';

NAME VALUE
------------------------------ ------------------------------
audit_trail DB
audit_file_dest ?/rdbms/audit

No audit actions are captured yet until audit actions are defined; that is, except for privileged access to the database, starting and stopping of the database, and structural changes such as adding a datafile. These are logged to operating system files in $ORACLE_HOME/rdbms/audit unless audit_file_dest is redefined in the init.ora file. On Windows these events appear in the Event Viewer. To check if any privilege or statement audit actions are enabled, do the following:

SQL> select * from dba_stmt_audit_opts
union
select * from dba_priv_audit_opts;

no rows selected


To find out what objects are being audited, query the view dba_obj_audit_opts.
The Worked Examples
Let us now work through our two example cases and see what can be learned. First, turn on audit for the access attempts to the database:
SQL> audit create session;

Audit succeeded.

The above command will capture access by all users by access and whether successful or unsuccessful. The default for this command is by access.
Note: The format of all audit commands from the Oracle documentation is as follows:
audit {statement_option|privilege_option} [by user] [by
{session|access}] [ whenever {successful|unsuccessful}]
Only the statement_option or privilege_option part is mandatory. The other clauses are optional and enabling them allows audit be more specific.
For a user to define audit statements, the privilege "AUDIT SYSTEM" needs to have been granted first. The users that have this privilege can be checked as follows:
SQL> select *
from dba_sys_privs
where privilege like '%AUDIT%';

GRANTEE PRIVILEGE ADM
------------------------------ ---------------------------------------- ---
CTXSYS AUDIT ANY NO
CTXSYS AUDIT SYSTEM NO
DBA AUDIT ANY YES
DBA AUDIT SYSTEM YES
IMP_FULL_DATABASE AUDIT ANY NO
MDSYS AUDIT ANY YES
MDSYS AUDIT SYSTEM YES
WKSYS AUDIT ANY NO
WKSYS AUDIT SYSTEM NO

9 rows selected.


The above results are for a 9i database, the default users MDSYS, CTXSYS and WKSYS would likely be good targets for attackers, as any audit actions could be turned off as one of these users to hide any actions undertaken.
Now that audit will capture all access attempts, we need to wait for some users to log in to do work. So while they do that, let's set up the audit to capture alterations to the schema. For the sake of brevity, in this example, not all schema object changes will be captured. Changes to tables, indexes, clusters, views, sequences, procedures, triggers, libraries and many more can be captured. In this example, audit will be enabled on an example set. Turning on the audit can be performed as a two-stage process, generate the audit commands and then run them as follows:
set head off
set feed off
set pages 0
spool aud.lis
select 'audit '||name||';'
from system_privilege_map
where (name like 'CREATE%TABLE%'
or name like 'CREATE%INDEX%'
or name like 'CREATE%CLUSTER%'
or name like 'CREATE%SEQUENCE%'
or name like 'CREATE%PROCEDURE%'
or name like 'CREATE%TRIGGER%'
or name like 'CREATE%LIBRARY%')
union
select 'audit '||name||';'
from system_privilege_map
where (name like 'ALTER%TABLE%'
or name like 'ALTER%INDEX%'
or name like 'ALTER%CLUSTER%'
or name like 'ALTER%SEQUENCE%'
or name like 'ALTER%PROCEDURE%'
or name like 'ALTER%TRIGGER%'
or name like 'ALTER%LIBRARY%')
union
select 'audit '||name||';'
from system_privilege_map
where (name like 'DROP%TABLE%'
or name like 'DROP%INDEX%'
or name like 'DROP%CLUSTER%'
or name like 'DROP%SEQUENCE%'
or name like 'DROP%PROCEDURE%'
or name like 'DROP%TRIGGER%'
or name like 'DROP%LIBRARY%')
union
select 'audit '||name||';'
from system_privilege_map
where (name like 'EXECUTE%INDEX%'
or name like 'EXECUTE%PROCEDURE%'
or name like 'EXECUTE%LIBRARY%')
/
spool off
@@aud.lis
This will generate a set of audit commands that can be captured to a spool file, which is then run to enable the audit commands.
Another solution would be to audit the actual permissions granted to users by generating the audit commands from the database view dba_sys_privs. While this may seem to be a better solution and potentially involve less audit commands, it would not allow for the case when new permissions are granted to users. In this case, audit would also need to be enabled at the time the privileges are granted.
Now that all of the sample audit is now enabled, the settings can be viewed with this SQL:
select audit_option,success,failure
from dba_stmt_audit_opts
union
select privilege,success,failure
from dba_priv_audit_opts
SQL> /

AUDIT_OPTION SUCCESS FAILURE
---------------------------------------- ---------- ----------
ALTER ANY CLUSTER BY ACCESS BY ACCESS
ALTER ANY INDEX BY ACCESS BY ACCESS
ALTER ANY INDEXTYPE BY ACCESS BY ACCESS
ALTER ANY LIBRARY BY ACCESS BY ACCESS

EXECUTE ANY LIBRARY BY SESSION BY SESSION
EXECUTE ANY PROCEDURE BY SESSION BY SESSION

38 rows selected.

Every time a user attempts anything in the database where audit is enabled the Oracle kernel checks to see if an audit record should be created or updated (in the case or a session record) and generates the record in a table owned by the SYS user called AUD$. This table is, by default, located in the SYSTEM tablespace. This in itself can cause problems with potential denial of service attacks. If the SYSTEM tablespace fills up, the database will hang.
The AUD$ table is rare, as it is the only SYS owned table from which Oracle allows records to be deleted. If the audit trail is turned on and written to the database, then the numbers of records in this table need to be monitored carefully to ensure it doesn't grow too fast and fill the system tablespace. A purging strategy needs to be adopted to keep the size of the table in check and, if needed, to archive off audit trail records for future reference. One tactic could be to copy the records to summary tables that allow specific checks for abuse to be performed offline. These summary tables can be in a separate database for added security. Once copied, sys.aud$ can be truncated.
SYS.AUD$ can be moved to a different tablespace other than SYSTEM but check with Oracle support first, as this action is no longer supported.
Only users who have been granted specific access to SYS.AUD$ can access the table to read, alter or delete from it. This is usually just the user SYS or any user who has had permissions. There are two specific roles that allow access to SYS.AUD$ for select and delete, these are DELETE_CATALOG_ROLE and SELECT_CATALOG_ROLE. These roles should not be granted to general users.
Back to the examples, our users have been logging on and working throughout the day and created some audit records. These audit records can be viewed in a number of ways:
• By selecting from SYS.AUD$ - This is the raw audit trail
• By selecting from dba_audit_trail - This is a DBA view showing the raw audit trail.
• By selecting from dba_audit_session - This view shows just log-on and log-off actions.
A simple piece of SQL can show details of the connection attempts:
SQL> get check_create_session
--
-- check_create_session.sql
--
col username for a15
col terminal for a6
col timestamp for a15
col logoff_time for a15
col action_name for a8
col returncode for 9999
select username,
terminal,
action_name,
to_char(timestamp,'DDMMYYYY:HHMISS') timestamp,
to_char(logoff_time,'DDMMYYYY:HHMISS') logoff_time,
returncode
from dba_audit_session

USERNAME TERMIN ACTION_N TIMESTAMP LOGOFF_TIME RETURNCODE
--------------- ------ -------- --------------- --------------- ----------
SYS pts/1 LOGOFF 09042003:051046 09042003:051641 0
ZULIA pts/1 LOGON 09042003:051641 1017
SYS pts/1 LOGOFF 09042003:051649 09042003:053032 0
SYS pts/2 LOGOFF 09042003:052622 09042003:053408 0
ZULIA pts/1 LOGON 09042003:053032 1017

There are a number of simple abuses that can be checked for in the area of user access to the database. As examples for this paper we will look at the following:

• Failed log-on attempts
This can indicate fat fingers or attackers' attempts to gain unauthorized access the database. The following SQL highlights this:
SQL> select count(*),username,terminal,to_char(timestamp,'DD-MON-YYYY')
from dba_audit_session
where returncode<>0
group by username,terminal,to_char(timestamp,'DD-MON-YYYY');

COUNT(*) USERNAME TERMIN TO_CHAR(TIM
---------- --------------- ------ -----------
1 BILL pts/3 09-APR-2003
3 FRED pts/3 09-APR-2003
4 ZULIA pts/1 09-APR-2003


This shows two possible abuses, the first is the user Zulia attempting to log on and failing four times on the same day. This could be a forgotten password or it could be someone trying to guess his or her password. A change to the SQL as follows gives a bit more detail:
SQL> select count(*),username,terminal,to_char(timestamp,'DD-MON-YYYY'),returncode
from dba_audit_session
group by username,terminal,to_char(timestamp,'DD-MON-YYYY'),returncode;

COUNT(*) USERNAME TERMIN TO_CHAR(TIM RETURNCODE
---------- --------------- ------ ----------- ----------
1 BILL pts/3 09-APR-2003 1017
1 EMIL pts/1 09-APR-2003 0
1 EMIL pts/2 09-APR-2003 0
1 EMIL pts/3 09-APR-2003 0
1 EMIL pts/4 09-APR-2003 0
3 FRED pts/3 09-APR-2003 1017
3 SYS pts/1 09-APR-2003 0
1 SYS pts/2 09-APR-2003 0
1 SYSTEM pts/5 09-APR-2003 0
4 ZULIA pts/1 09-APR-2003 1017
1 ZULIA pts/1 09-APR-2003 0

11 rows selected.

This reveals that the user successfully logged on on the same terminal on the same day. A number of failed log-ons should be agreed as part of these checks and the above SQL run every day. Those users with failure numbers above the threshold should be investigated.

• Attempts to access the database with non-existent users
One interesting extension to the above SQL is to find attempts to log in where the user doesn't exist. An audit record is still created in this case. The following SQL illustrates:

SQL>select username,terminal,to_char(timestamp,'DD-MON-YYYY HH24:MI:SS')
from dba_audit_session
where returncode<>0
and not exists (select 'x'
from dba_users
where dba_users.username=dba_audit_session.username)


USERNAME TERMIN TO_CHAR(TIMESTAMP,'D
--------------- ------ --------------------
FRED pts/3 09-APR-2003 17:31:47
FRED pts/3 09-APR-2003 17:32:02
FRED pts/3 09-APR-2003 17:32:15
BILL pts/3 09-APR-2003 17:33:01


This is probably abuse. All attempts to log on with a user that doesn't exist should be checked each day and investigated.
• Attempts to access the database at unusual hours
Checks should be made for any attempts to access the database outside of working hours. These accesses could be genuine overtime work or maintenance but they could just as easily be unauthorized access attempts and should be checked as follows:
SQL> select username,
terminal,
action_name,
returncode,
to_char(timestamp,'DD-MON-YYYY HH24:MI:SS'),
to_char(logoff_time,'DD-MON-YYYY HH24:MI:SS')
from dba_audit_session
where to_date(to_char(timestamp,'HH24:MI:SS'),'HH24:MI:SS') <
to_date('08:00:00','HH24:MI:SS')
or to_date(to_char(timestamp,'HH24:MI:SS'),'HH24:MI:SS') >
to_date('19:30:00','HH24:MI:SS')


USERNAME TERMIN ACTION_N RETURNCODE TO_CHAR(TIMESTAMP,'D TO_CHAR(LOGOFF_TIME,
---------- ------ -------- ---------- -------------------- --------------------
SYS pts/1 LOGOFF 0 09-APR-2003 20:10:46 09-APR-2003 20:16:41
SYSTEM pts/5 LOGOFF 0 09-APR-2003 21:49:20 09-APR-2003 21:49:50
ZULIA pts/5 LOGON 0 09-APR-2003 21:49:50
EMIL APOLLO LOGON 0 09-APR-2003 22:49:12


The above SQL shows any connections before 8:00 AM and after 7:30 PM. Any connections, particularly those made by privileged users such as SYS and SYSTEM, should be investigated. Particular attention can be made to the location from which the access was made. For instance, if privileged access is made from machines that are not in the administrator department, the administrator needs to find out why.

• Check for users sharing database accounts
The following SQL looks for users who are potentially sharing database accounts:
SQL> select count(distinct(terminal)),username
from dba_audit_session
having count(distinct(terminal))>1
group by username


COUNT(DISTINCT(TERMINAL)) USERNAME
------------------------- ----------
4 EMIL
3 SYS
3 ZULIA

This shows that three users have accessed their accounts from more than one location. A further check could be to add a time component to see if they are accessed simultaneously and also to restrict the check per day. The above SQL gives some idea of the potential without complicating it too much. Again, these accounts and users should be investigated.

• Multiple access attempts for different users from the same terminal
The final example checks to find where multiple database accounts have been used from the same terminal. The SQL is again simple and could be extended to group by day and also to print out the users per terminal. This is a simple test to illustrate the abuse idea:
SQL> select count(distinct(username)),terminal
from dba_audit_session
having count(distinct(username))>1
group by terminal


COUNT(DISTINCT(USERNAME)) TERMIN
------------------------- ------
3 pts/1
2 pts/2
3 pts/3
3 pts/5


This could indicate someone trying to gain access by trying many accounts and passwords, or it could indicate legitimate users sharing accounts for certain aspects of their work. In either case, the admin should investigate further.
There are, of course, many other scenarios that could indicate possible abuses. Checking for those is as simple as the cases depicted above. It will be left to the reader to experiment. Let me know what you find useful.
The second example case that audit actions were set for is to detect changes made to the database schema. This could include new objects being added or attempts to change existing objects within the database.
A simple piece of SQL will show any audit trail items that relate to objects being created or changed as follows:
col username for a8
col priv_used for a16
col obj_name for a22
col timestamp for a17
col returncode for 9999
select username,
priv_used,
obj_name,
to_char(timestamp,'DD-MON-YYYY HH24:MI') timestamp,
returncode
from dba_audit_trail
where priv_used is not null
and priv_used<>'CREATE SESSION'

SQL> @check_obj.sql

ZULIA CREATE TABLE STEAL_SALARY 09-APR-2003 20:07 0
PETE CREATE PROCEDURE HACK 09-APR-2003 20:42 0

This simple example shows that the user ZULIA has created a table and the user PETE has been writing PL/SQL procedures. Any changes such as this that are found should be investigated in a production database. Many more specific abuses can be checked for in relation to object and schema changes but, in general, no user should be able to alter the database schema in a production database. As a result, the check can remain pretty simple.
Protecting the Database Against These Abuses
The two examples given are just two of many possible scenarios that could be detected using Oracle's auditing facilities. Turning on and managing audit is one of the first steps to securing the database. Using audit should be part of an overall organization security plan and policy that includes Oracle. The database should be audited regularly for misconfiguration or known vulnerabilities that could allow security breaches to take place.
Because of its complex nature and vast number of different ways it can be used and configured, the best approach to securing Oracle will always be to follow the principle of least privilege. Once the database is part of the overall security plan and is configured correctly and checked regularly, then auditing it should be considered an important part of the strategy.
In general, do not grant any privileges to general users in a production database, remove most of the PUBLIC privileges and delete or lock and change the passwords of any default accounts. Ensure that users obey password policies and that the password management features of Oracle are employed.
It is important that the audit actions are planned from a performance and usability point of view and that the audit trail is managed. It is also important that the audit trail data is understood in terms of detecting abuse.
The author's recent book by the SANS Institute "Oracle security step- by-step - A survival guide for Oracle security" gives excellent guidelines on how to configure Oracle securely.


example:::::\

SQL> SHOW PARAMETER AUDIT
SQL> ALTER SYSTEM SET audit_trail=db SCOPE=SPFILE;
SQL> SHUTDOWN immediate;
SQL> startup;




First we create a new user called AUDIT_TEST.

SQL> CREATE USER audit_test IDENTIFIED BY audit_test
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp
QUOTA UNLIMITED ON users;

GRANT connect TO audit_test;
GRANT create table, create procedure TO audit_test;


Next we audit all operations by the AUDIT_TEST user.

CONNECT sys/password AS SYSDBA

AUDIT ALL BY user_name BY ACCESS;
AUDIT SELECT TABLE, UPDATE TABLE, INSERT TABLE, DELETE TABLE BY user_name BY ACCESS;
AUDIT EXECUTE PROCEDURE BY audit_test BY ACCESS;

Next, we perform some operations that will be audited.

CONN audit_test/password

CREATE TABLE test_tab (id NUMBER);

INSERT INTO test_tab (id) VALUES (1);
UPDATE test_tab SET id = id;
SELECT * FROM test_tab;
DELETE FROM test_tab;

DROP TABLE test_tab;In the next section we will look at how we view the contents of the audit trail.


COLUMN username FORMAT A10
COLUMN owner FORMAT A10
COLUMN obj_name FORMAT A10
COLUMN extended_timestamp FORMAT A35

SELECT username,
extended_timestamp,
owner,
obj_name,
action_name
FROM dba_audit_trail
WHERE owner = 'AUDIT_TEST'
ORDER BY timestamp;


AUDIT INSERT, UPDATE, DELETE ON sys.aud$ BY ACCESS;



select OS_USERNAME, USERNAME, USERHOST, TERMINAL, TIMESTAMP,
OWNER, OBJ_NAME, ACTION_NAME, NEW_OWNER, NEW_NAME,
SES_ACTIONS, COMMENT_TEXT, SESSIONID, ENTRYID, STATEMENTID,
RETURNCODE, PRIV_USED, CLIENT_ID, SESSION_CPU,
EXTENDED_TIMESTAMP, PROXY_SESSIONID, GLOBAL_UID, INSTANCE_NUMBER,
OS_PROCESS, TRANSACTIONID, SCN, SQL_BIND, SQL_TEXT
from dba_audit_trail
where ACTION_NAME like '%INSERT%'