jeudi 15 février 2018

Suivre les activités du backup RMAN


Voici quelques requêtes bien utiles pour suivre les activités les activités d'un job de backup  RMAN :


Select   sid,   start_time,   totalwork  sofar,  (sofar/totalwork) * 100 pct_done
from   v$session_longops
where
   totalwork > sofar
AND    opname NOT LIKE '%aggregate%'
AND    opname like 'RMAN%';


Select    sid,    spid,    client_info,    event,    seconds_in_wait,    p1, p2, p3
 from    v$process p,    v$session s
 where    p.addr = s.paddr
 and    client_info like 'rman channel=%';

Pour suivre le status d’un job de backup avec RMAN :

REM RMAN Progress
alter session set nls_date_format='dd/mm/yy hh24:mi:ss'
/
select SID, START_TIME,TOTALWORK, sofar, (sofar/totalwork) * 100 done,
sysdate + TIME_REMAINING/3600/24 end_at
from v$session_longops
where totalwork > sofar
AND opname NOT LIKE '%aggregate%'
AND opname like 'RMAN%'
/

REM RMAN wiats
set lines 120
column sid format 9999
column spid format 99999
column client_info format a25
column event format a30
column secs format 9999
SELECT SID, SPID, CLIENT_INFO, event, seconds_in_wait secs, p1, p2, p3
  FROM V$PROCESS p, V$SESSION s
  WHERE p.ADDR = s.PADDR
  and CLIENT_INFO like 'rman channel=%'
/
This script by Osama Mustafa will monitor the progress of a running RMAN job:


Une autre requête pour suivre l’avancement d’un job de backup RMAN :

select    to_char(start_time,'DD-MON-YY HH24:MI') "BACKUP STARTED",
   sofar,
   totalwork,
   elapsed_seconds/60 "ELAPSE (Min)",
   round(sofar/totalwork*100,2) "Complete%"
from    sys.v_$session_longops
where  compnam = 'dbms_backup_restore';

mercredi 14 février 2018

Requête ASM pour suivre l'opération du rebalance


 select INST_ID, GROUP_NUMBER, OPERATION, PASS, STATE, ACTUAL, EST_MINUTES, EST_RATE  from  gv$asm_operation where state = 'RUN'

actuellement : 
   INST_ID GROUP_NUMBER OPERATION       PASS                        STATE            ACTUAL EST_MINUTES   EST_RATE
---------- ------------ --------------- --------------------------- ------------ ---------- ----------- ----------
         2            1 REBAL           REBALANCE                   RUN                   4         288       5476

Normalement le ESt_MINUTES doit baisser, une fois le rebalance est fini il n'y aura aucune ligne 

Les sessions avec des LOCKs

Requête pour avoir des infos sur les sessions qui lock :


select blocking_session,blocked_session,script from
( select distinct
s1.username || '@' || s1.machine || ' ( INST=' || s1.inst_id || ' SID=' || s1.sid || ' ET=' || s1.last_call_et || 'sn. STATUS=' || s1.status || ' EVENT=' || s1.event || ' ACTION= ' || s1.action || ' PROGRAM=' || s1.program || ' MODULE=' || s1.module || ')' blocking_session,
s2.username || '@' || s2.machine || ' ( INST=' || s2.inst_id || ' SID=' || s2.sid || ' ET=' || s2.last_call_et || 'sn. STATUS=' || s2.status || ' EVENT=' || s2.event || ' ACTION= ' || s2.action || ' PROGRAM=' || s2.program || ' MODULE=' || s2.module || ')' blocked_session,
decode(s1.type,'USER','alter system kill session ''' || s1.sid || ',' || s1.serial# || ',@' || s1.inst_id || ''' immediate;' ,null, s2.LAST_CALL_ET/60)
script ,
count(*) over (partition by s1.inst_id,s1.sid) blocked_cnt
from gv$lock l1, gv$session s1, gv$lock l2, gv$session s2
where s1.sid=l1.sid and s2.sid=l2.sid
and s1.inst_id=l1.inst_id and s2.inst_id=l2.inst_id
and l1.block > 0 and l2.request > 0
and l1.id1 = l2.id1 and l1.id2 = l2.id2 )
order by blocked_cnt desc;


select LAST_CALL_ET/60 , blocking_session,blocked_session,script from
( select distinct s2.LAST_CALL_ET,
s1.username || '@' || s1.machine || ' ( INST=' || s1.inst_id || ' SID=' || s1.sid || ' ET=' || s1.last_call_et || 'sn. STATUS=' || s1.status || ' EVENT=' || s1.event || ' ACTION= ' || s1.action || ' PROGRAM=' || s1.program || ' MODULE=' || s1.module || ')' blocking_session,
s2.username || '@' || s2.machine || ' ( INST=' || s2.inst_id || ' SID=' || s2.sid || ' ET=' || s2.last_call_et || 'sn. STATUS=' || s2.status || ' EVENT=' || s2.event || ' ACTION= ' || s2.action || ' PROGRAM=' || s2.program || ' MODULE=' || s2.module || ')' blocked_session,
decode(s1.type,'USER','alter system kill session ''' || s1.sid || ',' || s1.serial# || ',@' || s1.inst_id || ''' immediate;' ,null )
script ,
count(*) over (partition by s1.inst_id,s1.sid) blocked_cnt
from gv$lock l1, gv$session s1, gv$lock l2, gv$session s2
where s1.sid=l1.sid and s2.sid=l2.sid
and s1.inst_id=l1.inst_id and s2.inst_id=l2.inst_id
and l1.block > 0 and l2.request > 0
and l1.id1 = l2.id1 and l1.id2 = l2.id2 )
order by blocked_cnt desc;

mardi 26 décembre 2017

Automatically and Manual Purging Alert Log and Trace files with Automatic Diagnostic Repository Command Interpreter (ADRCI)

Sometimes we are facing with space related issues due to the huge number of trace file generation. Automatic purging can help us in this situations if set short retention time for trace files.

adrci> show homes
ADR Homes:
diag/tnslsnr/GMCLIMODA01N2PLP/listener_scan2
diag/tnslsnr/GMCLIMODA01N2PLP/asmnet1lsnr_asm
diag/tnslsnr/GMCLIMODA01N2PLP/mgmtlsnr
diag/tnslsnr/GMCLIMODA01N2PLP/asmnet2lsnr_asm
diag/tnslsnr/GMCLIMODA01N2PLP/listener_scan1
diag/tnslsnr/GMCLIMODA01N2PLP/listener
diag/apx/+apx/+APX2
diag/crs/gmclimoda01n2plp/crs
diag/crs/172/crs
diag/asm/+asm/+ASM2
diag/rdbms/_mgmtdb/-MGMTDB

adrci>

adrci> set homepath diag/tnslsnr/GMCLIMODA01N2PLP/asmnet1lsnr_asm
adrci> show control

ADR Home = /u01/app/grid/diag/tnslsnr/GMCLIMODA01N2PLP/asmnet1lsnr_asm:
*************************************************************************
ADRID                SHORTP_POLICY        LONGP_POLICY         LAST_MOD_TIME                            LAST_AUTOPRG_TIME                        LAST_MANUPRG_TIME                        ADRDIR_VERSION       ADRSCHM_VERSION      ADRSCHMV_SUMMARY     ADRALERT_VERSION     CREATE_TIME
-------------------- -------------------- -------------------- ---------------------------------------- ---------------------------------------- ---------------------------------------- -------------------- -------------------- -------------------- -------------------- ----------------------------------------
2978292604           720                  8760                 2015-08-13 16:48:09.227855 +02:00                                                 2017-12-24 05:00:02.312601 +01:00        1                    2                    82                   1                    2015-08-13 16:48:09.227855 +02:00
1 rows fetched

adrci>

adrci> select SHORTP_POLICY,LONGP_POLICY from ADR_CONTROL;

ADR Home = /u01/app/oracle/diag/rdbms/db12c_stby/db12c_stby:
*************************************************************************
SHORTP_POLICY        LONGP_POLICY         
-------------------- -------------------- 
720                  8760                
1 rows fetched
  1. By default retention is 720 hours for short policy and 8760 hours for long policy.
    Short policy include the following files :(Trace files, Core dump files, Packaging information)
    Long policy include the following files:(Incident information, Incident dumps, Alert logs)
  2. To change the retention policy :
adrci> set control (SHORTP_POLICY=120); -- 5 days

adrci> set control (LONGP_POLICY=720); -- 1 week


--check changes

adrci> select SHORTP_POLICY,LONGP_POLICY,LAST_AUTOPRG_TIME,LAST_MANUPRG_TIME from ADR_CONTROL; 

ADR Home = /u01/app/oracle/diag/rdbms/db12c_stby/db12c_stby:
*************************************************************************
SHORTP_POLICY LONGP_POLICY LAST_AUTOPRG_TIME LAST_MANUPRG_TIME 
-------------------- -------------------- ---------------------------------------- ---------------------------------------- 
120 720 2016-07-07 23:27:37.789953 +05:00 2016-07-16 22:37:52.700123 +05:00 
1 rows fetched

adrci> 


purger l'alert log d'une base on line :
dans l'exemple ici la taille de l'alert log est de 4G :
cat alert_oibko121.log |gzip > alert_oibko121.log.20180129.gz; echo > alert_oibko121.log


résultat :
4.0K    alert_oibko121.log
53M     alert_oibko121.log.20180129.gz
24K     oibko121_cjq0_11163.trc

lundi 27 novembre 2017

SCRIPT pour retrouver les infos d'un user : mot de passe et droit

set echo off;
set feedback off;
set heading off;
set verify off;
set linesize 1000
set pagesize 0
set long 20000
set longchunksize 20000
set autoprint on
variable x clob

execute dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'SQLTERMINATOR', true);
execute  dbms_metadata.set_transform_param (dbms_metadata.session_transform, 'PRETTY', true);

SELECT DBMS_METADATA.GET_DDL('USER','${_USERNAME}') FROM dual;

declare
no_grant exception;
pragma exception_init( no_grant, -31608 );
begin
:x := dbms_metadata.get_granted_ddl( 'ROLE_GRANT','${_USERNAME}') || ';';
exception
when no_grant then :x := '-- no role grants';
end;
/

declare
no_grant exception;
pragma exception_init( no_grant, -31608 );
begin
:x := dbms_metadata.get_granted_ddl( 'DEFAULT_ROLE','${_USERNAME}');
exception
when no_grant then :x := '-- no default role';
end;
/

declare
no_grant exception;
pragma exception_init( no_grant, -31608 );
begin
:x := dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT','${_USERNAME}');
exception
when no_grant then :x := '-- no system grants';
end;
/

declare
no_grant exception;
pragma exception_init( no_grant, -31608 );
begin
:x := dbms_metadata.get_granted_ddl( 'OBJECT_GRANT','${_USERNAME}');
exception
when no_grant then :x := '-- no object grants';
end;
/

declare
no_grant exception;
pragma exception_init( no_grant, -31608 );
begin
:x := dbms_metadata.get_granted_ddl( 'TABLESPACE_QUOTA','${_USERNAME}');
exception
when no_grant then :x := '-- no tablespace quota';
end;
/

exit

jeudi 3 août 2017

Purge des stats sur les bases dans SYSAUX

Purge des stats sur les bases en 10g dans SYSAUX


select sum(bytes/1024/1024) Mb, segment_name,segment_type, tablespace_name
from dba_segments
where  tablespace_name = 'SYSAUX'
and segment_name like 'WRI$_OPTSTAT%'
and segment_type='TABLE'
group by segment_name,segment_type,tablespace_name order by 1 asc;

select sum(bytes/1024/1024) Mb, segment_name,segment_type,tablespace_name
from dba_segments
where  tablespace_name = 'SYSAUX'
and segment_name like '%OPT%'
and segment_type='INDEX'
group by segment_name,segment_type,tablespace_name
order by 1 asc;

Affichage de la retention des stats:
select dbms_stats.get_stats_history_retention from dual;

Passage de la retention des stats à 10 jours (par défaut 31):
exec dbms_stats.alter_stats_history_retention(10);

Date des stats les plus anciennes:
select dbms_stats.get_stats_history_availability from dual;

Requêtes SQL pour MOVE TABLE concernées:
select 'alter table '||segment_name||'  move tablespace SYSAUX;'
from dba_segments where tablespace_name = 'SYSAUX'
and segment_name like '%OPT%'
and segment_type='TABLE';

Requêtes SQL pour Rebuild Index concernés:
select 'alter index '||segment_name||'  rebuild online parallel (degree 4);'
from dba_segments
where tablespace_name = 'SYSAUX'
and segment_name like '%OPT%'
and segment_type='INDEX';

Vérif de l'état des index:

select  di.index_name,di.index_type,di.status  from  dba_indexes di where  di.tablespace_name = 'SYSAUX' and di.index_name like '%OPT%' order by 1 asc;


 SELECT t.OWNER "OWNER", t.TABLESPACE_NAME "TABLESPACE", SUM(ROUND(t.BLOCKS*p.value/1024/1024,2)) "SIZE (Mo)"
FROM DBA_SEGMENTS t, v$parameter p
WHERE t.TABLESPACE_NAME <> 'SYSTEM'
AND upper(p.name) = upper('db_block_size')
 GROUP BY t.OWNER, t.TABLESPACE_NAME

ORDER BY 3;

mercredi 15 juin 2016

Auditing Enhancements (Audit Policies and Unified Audit Trail) in Oracle Database 12c Release 1 (12.1)

Creating Audit Policies

Just like standard auditing that came before it, unified auditing can be used to create extremely complex auditing rules. The documentation for managing audit policies is very good, so rather than trying to duplicate that, I will just show some simple examples to give a flavour of the functionality.
An audit policy is made up of several distinct clauses, some of which are optional.
CREATE AUDIT POLICY policy_name
    { {privilege_audit_clause [action_audit_clause ] [role_audit_clause ]}
        | { action_audit_clause  [role_audit_clause ] } 
        | { role_audit_clause }
     }        
    [WHEN audit_condition EVALUATE PER {STATEMENT|SESSION|INSTANCE}] 
    [CONTAINER = {CURRENT | ALL}];
Examples of the usages are given in the sections below, but here is a quick summary of them.
  • privilege_audit_clause : Used to specify a list of system privileges to be audited.
  • action_audit_clause : Defines the actions that need to be audited. These can be standard_actions, like DELETE, or object-specific, like DELETE ON schema.table. They can also be component_actions that target specific features like data pump or SQL*Loader.
  • role_audit_clause : Specifies a list of roles. All system privileges granted via those roles are audited.
  • WHEN ... EVALUATE PER : Allows you to define an audit_condition to determine when the auditing should take place. The condition can be evaluated for eachSTATEMENT, SESSION or INSTANCE, depending on the level of granularity the condition requires.
  • CONTAINER : Determines if an audit policy is specific to an individual PDB (CURRENT) or common to all PDBs (ALL).
This might sound a little confusing, but if you've ever used database auditing in previous releases, it will quickly look quite familiar. The main thing to remember is rather than issuing the AUDIT/NOAUDIT commands directly, you create an audit policy containing the relevant pieces, then enable and disable it using the AUDIT/NOAUDIT commands.
Some of the following examples require these three test users.
CONN sys@pdb1 AS SYSDBA

CREATE USER test IDENTIFIED BY test QUOTA UNLIMITED ON users;
GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE TO test;

CREATE USER test2 IDENTIFIED BY test2 QUOTA UNLIMITED ON users;
GRANT CREATE SESSION TO test2;

CREATE USER test3 IDENTIFIED BY test3 QUOTA UNLIMITED ON users;
GRANT CREATE SESSION TO test3;
 In some cases the contents of the unified audit trail has been purged between tests to keep the output simple and specific to the functionality being tested.

Privilege Auditing

As the name suggests, privilege auditing allows you to audit the use of system privileges. The SYSTEM_PRIVILEGE_MAP view identifies the system privileges that can be audited.
SELECT name
FROM   system_privilege_map
ORDER BY name;

NAME
----------------------------------------
ADMINISTER ANY SQL TUNING SET
ADMINISTER DATABASE TRIGGER
.
.
.
UPDATE ANY TABLE
USE ANY SQL TRANSLATION PROFILE

237 rows selected.

SQL>
If we want to audit the creation of tables and sequences by the TEST user, we might do something like the following.
CONN sys@pdb1 AS SYSDBA

CREATE AUDIT POLICY test_audit_policy
  PRIVILEGES CREATE TABLE, CREATE SEQUENCE
  WHEN    'SYS_CONTEXT(''USERENV'', ''SESSION_USER'') = ''TEST'''
  EVALUATE PER SESSION
  CONTAINER = CURRENT;

AUDIT POLICY test_audit_policy;
Display the configuration of the policy.
SET LINESIZE 200
COLUMN audit_option FORMAT A15
COLUMN condition_eval_opt FORMAT A10
COLUMN audit_condition FORMAT A50

SELECT audit_option,
       condition_eval_opt,
       audit_condition
FROM   audit_unified_policies
WHERE  policy_name = 'TEST_AUDIT_POLICY';

AUDIT_OPTION    CONDITION_ AUDIT_CONDITION
--------------- ---------- --------------------------------------------------
CREATE SEQUENCE SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST'
CREATE TABLE    SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST'

SQL>
Connect to the TEST user and create some objects.
CONN test/test@pdb1

CREATE TABLE tab1 (id NUMBER);
CREATE SEQUENCE tab1_seq;
Check the audit trail. If you are in delayed-write mode, you may need to flush the audit trail before you can see the audit records.
CONN sys@pdb1 AS SYSDBA

-- You might need to flush the audit information before it is visible.
-- EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail;

COLUMN event_timestamp FORMAT A30
COLUMN dbusername FORMAT A10
COLUMN action_name FORMAT A20
COLUMN object_schema FORMAT A10
COLUMN object_name FORMAT A20

SELECT event_timestamp,
       dbusername,
       action_name,
       object_schema,
       object_name
FROM   unified_audit_trail
WHERE  dbusername = 'TEST'
ORDER BY event_timestamp;

EVENT_TIMESTAMP                DBUSERNAME ACTION_NAME          OBJECT_SCH OBJECT_NAME
------------------------------ ---------- -------------------- ---------- --------------------
27-JUN-2015 10:25:37.359596    TEST       CREATE TABLE         TEST       TAB1
27-JUN-2015 10:25:37.363989    TEST       CREATE SEQUENCE      TEST       TAB1_SEQ

SQL>
Disable the policy and drop it.
NOAUDIT POLICY test_audit_policy;

DROP AUDIT POLICY test_audit_policy;

Action Auditing

Actions against all objects, specific objects or even those actions performed by specific utilities can be audited quite easily in Oracle 12c.
Create some schema objects to audit and grant access to them to the second user.
CONN test/test@pdb1

DROP TABLE tab1 PURGE;
DROP SEQUENCE tab1_seq;
DROP TABLE tab2 PURGE;
DROP SEQUENCE tab2_seq;

CREATE TABLE tab1 (
  id NUMBER,
  CONSTRAINT tab1_pk PRIMARY KEY (id)
);

CREATE SEQUENCE tab1_seq;

CREATE TABLE tab2 (
  id NUMBER,
  CONSTRAINT tab2_pk PRIMARY KEY (id)
);

CREATE SEQUENCE tab2_seq;

GRANT SELECT, INSERT, UPDATE, DELETE ON tab1 TO test2;
GRANT SELECT ON tab1_seq TO test2;
GRANT SELECT, INSERT, UPDATE, DELETE ON tab2 TO test2;
GRANT SELECT ON tab2_seq TO test2;
Create and enable an audit policy that audits some actions against those objects, when performed by the TEST2 user.
CONN sys@pdb1 AS SYSDBA

CREATE AUDIT POLICY test_audit_policy
  ACTIONS DELETE ON test.tab1,
          INSERT ON test.tab1,
          UPDATE ON test.tab1,
          SELECT ON test.tab1_seq,
          ALL ON test.tab2,
          SELECT ON test.tab2_seq
  WHEN    'SYS_CONTEXT(''USERENV'', ''SESSION_USER'') = ''TEST2'''
  EVALUATE PER SESSION
  CONTAINER = CURRENT;

AUDIT POLICY test_audit_policy;
Display the configuration of the policy.
SET LINESIZE 200
COLUMN object_schema FORMAT A15
COLUMN object_name FORMAT A15
COLUMN object_type FORMAT A12
COLUMN audit_option FORMAT A15
COLUMN condition_eval_opt FORMAT A10
COLUMN audit_condition FORMAT A50

SELECT object_schema,
       object_name,
       object_type,
       audit_option,
       condition_eval_opt,
       audit_condition
FROM   audit_unified_policies
WHERE  policy_name = 'TEST_AUDIT_POLICY';


OBJECT_SCHEMA   OBJECT_NAME     OBJECT_TYPE  AUDIT_OPTION    CONDITION_ AUDIT_CONDITION
--------------- --------------- ------------ --------------- ---------- --------------------------------------------------
TEST            TAB1            TABLE        DELETE          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB1            TABLE        INSERT          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB1            TABLE        UPDATE          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB1_SEQ        SEQUENCE     SELECT          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB2            TABLE        ALL             SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB2_SEQ        SEQUENCE     SELECT          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'

SQL>
Perform some actions that won't match the policy condition.
CONN test/test@pdb1

INSERT INTO tab1 (id) VALUES (tab1_seq.NEXTVAL);
INSERT INTO tab2 (id) VALUES (tab2_seq.NEXTVAL);
COMMIT;
Perform some actions that will match the policy condition.
CONN test2/test2@pdb1

UPDATE test.tab1 SET id = test.tab1_seq.NEXTVAL;
UPDATE test.tab2 SET id = test.tab2_seq.NEXTVAL;
DELETE FROM test.tab1;
DELETE FROM test.tab2;
COMMIT;
Check the audit trail. If you are in delayed-write mode, you may need to flush the audit trail before you can see the audit records.
CONN sys@pdb1 AS SYSDBA

-- You might need to flush the audit information before it is visible.
-- EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail;

COLUMN event_timestamp FORMAT A30
COLUMN dbusername FORMAT A10
COLUMN action_name FORMAT A20
COLUMN object_schema FORMAT A10
COLUMN object_name FORMAT A20

SELECT event_timestamp,
       dbusername,
       action_name,
       object_schema,
       object_name
FROM   unified_audit_trail
WHERE  dbusername LIKE 'TEST%'
ORDER BY event_timestamp;

EVENT_TIMESTAMP                DBUSERNAME ACTION_NAME          OBJECT_SCH OBJECT_NAME
------------------------------ ---------- -------------------- ---------- --------------------
27-JUN-2015 10:41:40.070965    TEST2      SELECT               TEST       TAB1_SEQ
27-JUN-2015 10:41:40.071033    TEST2      UPDATE               TEST       TAB1
27-JUN-2015 10:41:40.073326    TEST2      SELECT               TEST       TAB2_SEQ
27-JUN-2015 10:41:40.073347    TEST2      UPDATE               TEST       TAB2
27-JUN-2015 10:41:40.074657    TEST2      DELETE               TEST       TAB1
27-JUN-2015 10:41:40.076132    TEST2      DELETE               TEST       TAB2

SQL>
Amend the audit policy and check the changes have been reflected in the configuration.
ALTER AUDIT POLICY test_audit_policy
  DROP ACTIONS ALL ON test.tab2,
               SELECT ON test.tab2_seq;

SET LINESIZE 200
COLUMN object_schema FORMAT A15
COLUMN object_name FORMAT A15
COLUMN object_type FORMAT A12
COLUMN audit_option FORMAT A15
COLUMN condition_eval_opt FORMAT A10
COLUMN audit_condition FORMAT A50

SELECT object_schema,
       object_name,
       object_type,
       audit_option,
       condition_eval_opt,
       audit_condition
FROM   audit_unified_policies
WHERE  policy_name = 'TEST_AUDIT_POLICY';

OBJECT_SCHEMA   OBJECT_NAME     OBJECT_TYPE  AUDIT_OPTION    CONDITION_ AUDIT_CONDITION
--------------- --------------- ------------ --------------- ---------- --------------------------------------------------
TEST            TAB1            TABLE        DELETE          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB1            TABLE        INSERT          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB1            TABLE        UPDATE          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'
TEST            TAB1_SEQ        SEQUENCE     SELECT          SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST2'

SQL>
Disable and drop the audit policy, then check the changes have been reflected in the configuration.
NOAUDIT POLICY test_audit_policy;

DROP AUDIT POLICY test_audit_policy;

SET LINESIZE 200
COLUMN object_schema FORMAT A15
COLUMN object_name FORMAT A15
COLUMN object_type FORMAT A12
COLUMN audit_option FORMAT A15
COLUMN condition_eval_opt FORMAT A10
COLUMN audit_condition FORMAT A50

SELECT object_schema,
       object_name,
       object_type,
       audit_option,
       condition_eval_opt,
       audit_condition
FROM   audit_unified_policies
WHERE  policy_name = 'TEST_AUDIT_POLICY';

no rows selected

SQL>
In the above examples the audit policies were object specific. We could have omitted the ON object-name part of the action to make it apply to all objects. If we wanted to audit all DML and queries issued by the TEST2 user, we might create a policy like the following.
CREATE AUDIT POLICY test_audit_policy
  ACTIONS DELETE, INSERT, UPDATE, SELECT
  WHEN    'SYS_CONTEXT(''USERENV'', ''SESSION_USER'') = ''TEST2'''
  EVALUATE PER SESSION
  CONTAINER = CURRENT;

--DROP AUDIT POLICY test_audit_policy;

Component Action Auditing

Rather than auditing actions on specific objects, you can instead audit actions relevant to specific functionality or utilities, such as Oracle Label Security (OLS), Real Application Security, Database Vault, Data Pump or SQL*Loader. There are two examples of component_action auditing linked below.
  • Auditing Data Pump Operations
  • Auditing SQL*Loader Direct Path Loads

Role Auditing

It is possible to audit all system privileges granted via a built-in or custom role using an audit policy.
Create a new role, then grant privileges on the TEST objects via the new role.
CONN sys@pdb1 AS SYSDBA

CREATE ROLE create_table_role;
GRANT CREATE TABLE TO create_table_role;

GRANT create_table_role TO test3;
Create an audit policy based on all the system privileges associated with the role. Enable the auditing policy and check the configuration.
CREATE AUDIT POLICY create_table_role_policy
  ROLES create_table_role
  WHEN    'SYS_CONTEXT(''USERENV'', ''SESSION_USER'') = ''TEST3'''
  EVALUATE PER SESSION
  CONTAINER = CURRENT;

AUDIT POLICY create_table_role_policy;

SET LINESIZE 200
COLUMN audit_option FORMAT A20
COLUMN condition_eval_opt FORMAT A10
COLUMN audit_condition FORMAT A50

SELECT audit_option,
       audit_option_type,
       condition_eval_opt,
       audit_condition
FROM   audit_unified_policies
WHERE  policy_name = 'CREATE_TABLE_ROLE_POLICY';

AUDIT_OPTION         AUDIT_OPTION_TYPE  CONDITION_ AUDIT_CONDITION
-------------------- ------------------ ---------- --------------------------------------------------
CREATE_TABLE_ROLE    ROLE PRIVILEGE     SESSION    SYS_CONTEXT('USERENV', 'SESSION_USER') = 'TEST3'

SQL>
Perform some actions that will match the policy condition.
CONN test3/test3@pdb1

CREATE TABLE tab1 (id NUMBER);
Check the audit trail. If you are in delayed-write mode, you may need to flush the audit trail before you can see the audit records.
CONN sys@pdb1 AS SYSDBA

-- You might need to flush the audit information before it is visible.
-- EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail;

COLUMN event_timestamp FORMAT A30
COLUMN dbusername FORMAT A10
COLUMN action_name FORMAT A20
COLUMN object_schema FORMAT A10
COLUMN object_name FORMAT A20

SELECT event_timestamp,
       dbusername,
       action_name,
       object_schema,
       object_name
FROM   unified_audit_trail
WHERE  dbusername = 'TEST3'
ORDER BY event_timestamp;

EVENT_TIMESTAMP                DBUSERNAME ACTION_NAME          OBJECT_SCH OBJECT_NAME
------------------------------ ---------- -------------------- ---------- --------------------
27-JUN-2015 10:48:40.744492    TEST3      CREATE TABLE         TEST3      TAB1

SQL>
Disable and drop the policy.
NOAUDIT POLICY create_table_role_policy;

DROP AUDIT POLICY create_table_role_policy;

Unified Audit Trail Administration

Administration of the unified audit trail can seem a little complicated at first, but there are a few things to keep in mind.
  • Unified auditing works by default, so you don't need to do anything to get started.
  • The default settings are OK. You will probably only have to focus on your specific audit policies.
  • Setting up an archival and purging process will need some thought, but you will probably only do this once in the lifetime of your database, so don't get scared off by this aspect of auditing.
With that said, the remaining parts of this article will explain how to perform some of the basic administration tasks.
 For brevity, I will avoid repetition of functionality explained in previous articles, but links will be provided.

Available By Default

The unified audit trail and audit policy functionality is available by default in all editions, but it can run in two modes. By default it runs in mixed mode, which means you can combine traditional auditing with unified auditing. The following query shows that "pure" unified auditing is not enabled, which means we are running in mixed mode.
SELECT value FROM v$option WHERE parameter = 'Unified Auditing';

VALUE
----------------------------------------------------------------
FALSE

SQL>
All the functionality of unified auditing is still available, but you may still need to consider the AUDIT_TRAIL parameter, as it still controls how the traditional auditing is performed.

Enable/Disable Pure Unified Auditing

Running in mixed mode is perfectly acceptable, but you can choose to switch to pure unified auditing, so the traditional auditing functionality is no longer available. This is done by relinking the Oracle binaries as follows.
sqlplus / as sysdba <<EOF
SHUTDOWN IMMEDIATE;
EXIT
EOF

cd $ORACLE_HOME/rdbms/lib
make -f ins_rdbms.mk uniaud_on ioracle

sqlplus / as sysdba <<EOF
STARTUP;
EXIT
EOF
After restarting, the banner will include the "Unified Auditing" option and we can see the unified auditing option is enabled.
$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.2.0 Production on Mon Jun 1 11:35:52 2015

Copyright (c) 1982, 2014, Oracle.  All rights reserved.


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics, Real Application Testing
and Unified Auditing options

SQL> SELECT value FROM v$option WHERE parameter = 'Unified Auditing';

VALUE
----------------------------------------------------------------
TRUE

SQL>
Switching back to mixed mode involves a relink again.
sqlplus / as sysdba <<EOF
SHUTDOWN IMMEDIATE;
EXIT
EOF

cd $ORACLE_HOME/rdbms/lib
make -f ins_rdbms.mk uniaud_off ioracle

sqlplus / as sysdba <<EOF
STARTUP;
EXIT
EOF
After restarting, the banner no longer includes the "Unified Auditing" option and we can see the unified auditing option is disabled.
$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.2.0 Production on Mon Jun 1 11:35:52 2015

Copyright (c) 1982, 2014, Oracle.  All rights reserved.


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL> SELECT value FROM v$option WHERE parameter = 'Unified Auditing';

VALUE
----------------------------------------------------------------
FALSE

SQL>
For Windows, the documentation suggests it is just a case of turning the services off and moving the relevant DLL. I've not tried this, so I can't guarantee it works.
Rem Enable
%ORACLE_HOME%/bin/orauniaud12.dll.dbl file to %ORACLE_HOME%/bin/orauniaud12.dll

Rem Disable
%ORACLE_HOME%/bin/orauniaud12.dll file to %ORACLE_HOME%/bin/orauniaud12.dll.dbl

Audit Trail Security

Maintenance of the audit trail and audit policies is limited to those users granted the AUDIT_ADMIN role.
The AUDIT_VIEWER role can be granted to users who need to view the audit information, but not manage the audit trail or audit policies.
Under unified auditing, users are no longer able to create auditing policies against their own objects. For backwards compatibility, this is still possible for traditional auditing. This is possibly a reason to move away from mixed-mode auditing.

Write Mode

For performance reasons unified auditing uses a queued-write mechanism, so audited actions are written to the SGA and periodically pushed out to disk. This can result in loss of audit records during an instance crash, since the records may not be pushed out to disk before the instance fails. If this represents a problem, the write mode can be altered to immediate-write, so the audit actions are pushed directly to disk, but this will result in auditing having a greater overhead. The following code shows how to switch between these two modes. In a multitenant environment, these setting are container-specific.
-- Switch to immediate-write.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_property(
    audit_trail_type           => DBMS_AUDIT_MGMT.audit_trail_unified,
    audit_trail_property       => DBMS_AUDIT_MGMT.audit_trail_write_mode, 
    audit_trail_property_value => DBMS_AUDIT_MGMT.audit_trail_immediate_write
  );
END;
/

-- Switched to queued-write.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_property(
    audit_trail_type           => DBMS_AUDIT_MGMT.audit_trail_unified,
    audit_trail_property       => DBMS_AUDIT_MGMT.audit_trail_write_mode, 
    audit_trail_property_value => DBMS_AUDIT_MGMT.audit_trail_queued_write
  );
END;
/
The size of the queue in the SGA is controlled by the UNIFIED_AUDIT_SGA_QUEUE_SIZE initialization parameter, which can be set to values between 1-30MB, with the default being 1MB. Each RAC instance can have a different value.
As a consequence of running in queued-write mode, in some cases, especially while testing or before maintenance, it may be necessary to flush audit records to the audit trail. This can be done using the FLUSH_UNIFIED_AUDIT_TRAIL procedure. It accepts the FLUSH_TYPE and CONTAINER parameters, which allow the following variations.
-- Flush records to audit trail for the current container in the current instance.
EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail;

EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail(flush_type => DBMS_AUDIT_MGMT.flush_current_instance);

EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail(container => DBMS_AUDIT_MGMT.container_current);

BEGIN
  DBMS_AUDIT_MGMT.flush_unified_audit_trail(
    flush_type => DBMS_AUDIT_MGMT.flush_current_instance,
    container  => DBMS_AUDIT_MGMT.container_current);
END;
/

-- Flush records to audit trail for all containers in the current instance.
-- Must be run from root container.
EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail(container => DBMS_AUDIT_MGMT.container_all);

BEGIN
  DBMS_AUDIT_MGMT.flush_unified_audit_trail(
    flush_type => DBMS_AUDIT_MGMT.flush_current_instance,
    container  => DBMS_AUDIT_MGMT.container_all);
END;
/

-- Flush records to audit trail for the all RAC instances. Current Container.
EXEC DBMS_AUDIT_MGMT.flush_unified_audit_trail(flush_type => DBMS_AUDIT_MGMT.flush_all_instances);

BEGIN
  DBMS_AUDIT_MGMT.flush_unified_audit_trail(
    flush_type => DBMS_AUDIT_MGMT.flush_all_instances,
    container  => DBMS_AUDIT_MGMT.container_current);
END;
/

-- Flush records to audit trail for the all RAC instances. All Containers.
-- Must be run from root container.
BEGIN
  DBMS_AUDIT_MGMT.flush_unified_audit_trail(
    flush_type => DBMS_AUDIT_MGMT.flush_all_instances,
    container  => DBMS_AUDIT_MGMT.container_all);
END;
/

Purging the Unified Audit Trail

Oracle 11g Release 2 introduced the DBMS_AUDIT_MGMT package to manage the audit trail. Oracle 12c uses the same functionality to archive and purge the unified audit trail, described here, with the addition of constants to identify the unified audit trail. For mixed mode auditing environments, remember to manage both the conventional audit trails as well as the unified audit trail.
The following example shows how to set the last archived time for the unified audit trail and manually purge audit records older than that time. Remember to archive records before purging them if you need to store them long term.
-- Set the last archive timestamp.
BEGIN
  DBMS_AUDIT_MGMT.set_last_archive_timestamp(
    audit_trail_type     => DBMS_AUDIT_MGMT.audit_trail_unified,
    last_archive_time    => SYSTIMESTAMP-5,
    --rac_instance_number  =>  1,
    container            => DBMS_AUDIT_MGMT.container_current
  );
END;
/

-- Check the new setting.
COLUMN audit_trail FORMAT A20
COLUMN last_archive_ts FORMAT A40

SELECT audit_trail,
       last_archive_ts
FROM   dba_audit_mgmt_last_arch_ts;

AUDIT_TRAIL          LAST_ARCHIVE_TS
-------------------- ----------------------------------------
UNIFIED AUDIT TRAIL  10-JUN-15 13.48.14.000000 +00:00

SQL>

-- Manually purge the audit trail to the last archive timestamp.
SELECT COUNT(*) FROM unified_audit_trail;

  COUNT(*)
----------
        49

SQL>

BEGIN
  DBMS_AUDIT_MGMT.clean_audit_trail(
   audit_trail_type        => DBMS_AUDIT_MGMT.audit_trail_unified,
   use_last_arch_timestamp => TRUE);
END;
/

SELECT COUNT(*) FROM unified_audit_trail;

  COUNT(*)
----------
         4

SQL>
You can automate purging by creating a purge job