MERCADOS FINANCIEROS

viernes, 7 de febrero de 2014

AUDITORIA UNIFICADA DBMS_AUDIT_MGMT CONFIGURACION Y MANTENIMIENTO COMPLETO

Auditing Enhancements (DBMS_AUDIT_MGMT) in Oracle Database 11g Release 2

Oracle 11g Release 1 turned on auditng by default for the first time. Oracle 11g Release 2 now allows better management of the audit trail using the DBMS_AUDIT_MGMT package.
Note. This package has also been backported to previous versions down to 10g Release 2. See Oracle Support Note 731908.1.
Related articles.

Moving the Database Audit Trail to a Different Tablespace

The SET_AUDIT_TRAIL_LOCATION procedure allows you to alter the location of the standard and/or fine-grained database audit trail. It does not currently allow the alteration of the OS audit trail, although the documentation suggests this may happen in future. The procedure accepts two parameters.
  • AUDIT_TRAIL_TYPE: They type of audit trail that is to be moved.
  • AUDIT_TRAIL_LOCATION_VALUE: The tablespace the audit trail tables should be moved to.
The AUDIT_TRAIL_TYPE parameter is specified using one of three constants.
  • DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD: Standard audit trail (AUD$).
  • DBMS_AUDIT_MGMT.AUDIT_TRAIL_FGA_STD: Fine-grained audit trail (FGA_LOG$).
  • DBMS_AUDIT_MGMT.AUDIT_TRAIL_DB_STD: Both standard and fine-grained audit trails.
Let's see this in action. First check the current location of the audit trail tables.
CONN / AS SYSDBA

SELECT table_name, tablespace_name
FROM   dba_tables
WHERE  table_name IN ('AUD$', 'FGA_LOG$')
ORDER BY table_name;

TABLE_NAME                     TABLESPACE_NAME
------------------------------ ------------------------------
AUD$                           SYSTEM
FGA_LOG$                       SYSTEM

SQL>
Next, create a new tablespace to hold the audit trail.
CREATE TABLESPACE audit_aux
  DATAFILE '/u01/app/oracle/oradata/DB11G/audit_aux01.dbf'
  SIZE 1M AUTOEXTEND ON NEXT 1M;
Then we move the standard audit trail to the new tablespace.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_location(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD,
    audit_trail_location_value => 'AUDIT_AUX');
END;
/



BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_location(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_FGA_STD,
    audit_trail_location_value => 'AUDITORIA');
END;
/

PL/SQL procedure successfully completed.

SQL>

-- Check locations.
SELECT table_name, tablespace_name
FROM   dba_tables
WHERE  table_name IN ('AUD$', 'FGA_LOG$')
ORDER BY table_name;

TABLE_NAME                     TABLESPACE_NAME
------------------------------ ------------------------------
AUD$                           AUDIT_AUX
FGA_LOG$                       SYSTEM

SQL>
Next we move the fine-grained audit trail.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_location(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_FGA_STD,
    audit_trail_location_value => 'AUDIT_AUX');
END;
/

PL/SQL procedure successfully completed.

SQL>

-- Check locations.
SELECT table_name, tablespace_name
FROM   dba_tables
WHERE  table_name IN ('AUD$', 'FGA_LOG$')
ORDER BY table_name;

TABLE_NAME                     TABLESPACE_NAME
------------------------------ ------------------------------
AUD$                           AUDIT_AUX
FGA_LOG$                       AUDIT_AUX

SQL>
Finally, we move them both back to their original location in a single step.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_location(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_DB_STD,
    audit_trail_location_value => 'SYSTEM');
END;
/

PL/SQL procedure successfully completed.

SQL>

-- Check locations.
SELECT table_name, tablespace_name
FROM   dba_tables
WHERE  table_name IN ('AUD$', 'FGA_LOG$')
ORDER BY table_name;

TABLE_NAME                     TABLESPACE_NAME
------------------------------ ------------------------------
AUD$                           SYSTEM
FGA_LOG$                       SYSTEM

SQL>
The AUDIT_AUX tablespace is no longer used so we can drop it.
DROP TABLESPACE audit_aux;
The time it takes to move the audit trail tables depends on the amount of data currently in the audit trail tables, and the resources available on your system.

Controlling the Size and Age of the OS Audit Trail

The SET_AUDIT_TRAIL_PROPERTY procedure allows you to set the maximum size and/or age of the OS audit trail files. The procedure can set parameters for several purposes, but I will restrict the discussion to only those relevant to this section. A full list of the constants available can be found here.
The procedure accepts three parameters.
  • AUDIT_TRAIL_TYPE: The type of audit trail to be modified (AUDIT_TRAIL_OS, AUDIT_TRAIL_XML or AUDIT_TRAIL_FILES).
  • AUDIT_TRAIL_PROPERTY: The name of the property to be set (OS_FILE_MAX_SIZE or OS_FILE_MAX_AGE).
  • AUDIT_TRAIL_PROPERTY_VALUE: The required value for the property.
To check the current settings query the DBA_AUDIT_MGMT_CONFIG_PARAMS view.
COLUMN parameter_name FORMAT A30
COLUMN parameter_value FORMAT A20
COLUMN audit_trail FORMAT A20

SELECT *
FROM   dba_audit_mgmt_config_params
WHERE  parameter_name LIKE 'AUDIT FILE MAX%';

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
AUDIT FILE MAX SIZE            10000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             5                    XML AUDIT TRAIL

SQL>
These defaults mean that OS and XML audit trail files will grow to a maximum of 10,000Kb, at which point a new file will be created. In addition, files older than 5 days will not be written to any more, even if they are below the maximum file size. Instead, a new file will be created and written to. Here are some examples of changing the settings.
-- Set the Maximum size of OS audit files to 15,000Kb.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_property(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_OS,
    audit_trail_property       => DBMS_AUDIT_MGMT.OS_FILE_MAX_SIZE,
    audit_trail_property_value => 15000);
END;
/

SELECT *
FROM   dba_audit_mgmt_config_params
WHERE  parameter_name LIKE 'AUDIT FILE MAX%';

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
AUDIT FILE MAX SIZE            15000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             5                    XML AUDIT TRAIL

SQL>


-- Set the Maximum age of XML audit files to 10 days.
BEGIN
  DBMS_AUDIT_MGMT.set_audit_trail_property(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_XML,
    audit_trail_property       => DBMS_AUDIT_MGMT.OS_FILE_MAX_AGE,
    audit_trail_property_value => 10);
END;
/

SELECT *
FROM   dba_audit_mgmt_config_params
WHERE  parameter_name LIKE 'AUDIT FILE MAX%';

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
AUDIT FILE MAX SIZE            15000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             10                   XML AUDIT TRAIL

SQL>
The CLEAR_AUDIT_TRAIL_PROPERTY procedure can be used to remove the size and age restrictions, or reset them to the default values. Setting the USE_DEFAULT_VALUES parameter value to FALSE removes the restrictions, while setting it to TRUE returns the restriction to the default value.
-- Reset the max size default values for both OS and XML audit file.
BEGIN
  DBMS_AUDIT_MGMT.clear_audit_trail_property(
   audit_trail_type     => DBMS_AUDIT_MGMT.AUDIT_TRAIL_FILES,
   audit_trail_property => DBMS_AUDIT_MGMT.OS_FILE_MAX_SIZE,
   use_default_values   => TRUE );
END;
/

SELECT *
FROM   dba_audit_mgmt_config_params
WHERE  parameter_name LIKE 'AUDIT FILE MAX%';

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
AUDIT FILE MAX SIZE            10000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             10                   XML AUDIT TRAIL

SQL>

-- Remove the max age restriction for both OS and XML audit file.
BEGIN
  DBMS_AUDIT_MGMT.clear_audit_trail_property(
   audit_trail_type     => DBMS_AUDIT_MGMT.AUDIT_TRAIL_FILES,
   audit_trail_property => DBMS_AUDIT_MGMT.OS_FILE_MAX_AGE,
   use_default_values   => FALSE );
END;
/

SELECT *
FROM   dba_audit_mgmt_config_params
WHERE  parameter_name LIKE 'AUDIT FILE MAX%';

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
AUDIT FILE MAX SIZE            10000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             NOT SET              OS AUDIT TRAIL
AUDIT FILE MAX AGE             NOT SET              XML AUDIT TRAIL

SQL>

-- Reset the max age default values for both OS and XML audit file.
BEGIN
  DBMS_AUDIT_MGMT.clear_audit_trail_property(
   audit_trail_type     => DBMS_AUDIT_MGMT.AUDIT_TRAIL_FILES,
   audit_trail_property => DBMS_AUDIT_MGMT.OS_FILE_MAX_AGE,
   use_default_values   => TRUE );
END;
/

SELECT *
FROM   dba_audit_mgmt_config_params
WHERE  parameter_name LIKE 'AUDIT FILE MAX%';

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
AUDIT FILE MAX SIZE            10000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             5                    XML AUDIT TRAIL

SQL>

Purging Audit Trail Records

As with previous versions, you can manually delete records from the AUD$ and FGA_LOG$ tables and manually delete OS audit files from the file system, but DBMS_AUDIT_MGMT package gives you some new and safer mechanisms for maintaining the audit trail.
Note. If you are using Oracle Audit Vault, use that to manage your audit trail, not this functionality.

Initializing the Management Infrastructure

Before you can purge the database audit trail you must perform a one-time initialization of the audit management infrastructure. This is done using the INIT_CLEANUP procedure. The procedure accepts two parameters.
  • AUDIT_TRAIL_TYPE: The audit trail to be initialized (Constants).
  • DEFAULT_CLEANUP_INTERVAL: The default interval in hours, after which the cleanup procedure should be called again (1-999).
Note. The documentation seems to be incorrect about 2 points.
  1. It claims that initializing the database audit trails move the AUD$ and FGA_LOG$ tables from the SYSTEM tablespace to the SYSAUX tablespace, unless they have already been moved out of the SYSTEM tablespace. This doesn't seem to be the case as the example below will show. Even though it doesn't happen automatically, it makes sense to move the audit tables into the SYSAUX tablespace or their own dedicated tablespace.
  2. It claims it is not necessary to initialize the OS audit trails, yet in the example below you can clearly see the default cleanup intervals being set by the initialization process.
The following code checks the current parameter settings, initializes the audit management infrastructure for all audit trails with a default interval of 12 hours and rechecks the settings.
COLUMN parameter_name FORMAT A30
COLUMN parameter_value FORMAT A20
COLUMN audit_trail FORMAT A20

SELECT * FROM dba_audit_mgmt_config_params;

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
DB AUDIT TABLESPACE            SYSTEM               STANDARD AUDIT TRAIL
DB AUDIT TABLESPACE            SYSTEM               FGA AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             5                    XML AUDIT TRAIL
DB AUDIT CLEAN BATCH SIZE      10000                STANDARD AUDIT TRAIL
DB AUDIT CLEAN BATCH SIZE      10000                FGA AUDIT TRAIL
OS FILE CLEAN BATCH SIZE       1000                 OS AUDIT TRAIL
OS FILE CLEAN BATCH SIZE       1000                 XML AUDIT TRAIL

SQL>

BEGIN
  DBMS_AUDIT_MGMT.init_cleanup(
    audit_trail_type         => DBMS_AUDIT_MGMT.AUDIT_TRAIL_ALL,
    default_cleanup_interval => 12 /* hours */);
END;
/

PL/SQL procedure successfully completed.

SQL>

SELECT * FROM dba_audit_mgmt_config_params;

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
DB AUDIT TABLESPACE            SYSTEM               STANDARD AUDIT TRAIL
DB AUDIT TABLESPACE            SYSTEM               FGA AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                OS AUDIT TRAIL
AUDIT FILE MAX SIZE            10000                XML AUDIT TRAIL
AUDIT FILE MAX AGE             5                    OS AUDIT TRAIL
AUDIT FILE MAX AGE             5                    XML AUDIT TRAIL
DB AUDIT CLEAN BATCH SIZE      10000                STANDARD AUDIT TRAIL
DB AUDIT CLEAN BATCH SIZE      10000                FGA AUDIT TRAIL
OS FILE CLEAN BATCH SIZE       1000                 OS AUDIT TRAIL
OS FILE CLEAN BATCH SIZE       1000                 XML AUDIT TRAIL
DEFAULT CLEAN UP INTERVAL      12                   OS AUDIT TRAIL

PARAMETER_NAME                 PARAMETER_VALUE      AUDIT_TRAIL
------------------------------ -------------------- --------------------
DEFAULT CLEAN UP INTERVAL      12                   STANDARD AUDIT TRAIL
DEFAULT CLEAN UP INTERVAL      12                   FGA AUDIT TRAIL
DEFAULT CLEAN UP INTERVAL      12                   XML AUDIT TRAIL
Notice that the 'DB AUDIT TABLESPACE' for the database audit trails are unchanged and the 'DEFAULT CLEAN UP INTERVAL' for all four audit trails has been set.
The current initialization status of a specific audit trail can be checked using the IS_CLEANUP_INITIALIZED.
SET SERVEROUTPUT ON
BEGIN
  IF DBMS_AUDIT_MGMT.is_cleanup_initialized(DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD) THEN
    DBMS_OUTPUT.put_line('YES');
  ELSE
    DBMS_OUTPUT.put_line('NO');
  END IF;
END;
/
YES

PL/SQL procedure successfully completed.

SQL>
To deconfigure the audit management infrastructure run the DEINIT_CLEANUP procedure.
BEGIN
  DBMS_AUDIT_MGMT.deinit_cleanup(
    audit_trail_type         => DBMS_AUDIT_MGMT.AUDIT_TRAIL_ALL);
END;
/

Timestamp Management

The next thing to consider before purging the audit trail is how much data you wish to purge. The DBMS_AUDIT_MGMT package allows us to purge all the records, or all the records older than a specific timestamp. The timestamp in question is specified individually for each audit trail using the SET_LAST_ARCHIVE_TIMESTAMP procedure, which accepts three parameters.
  • AUDIT_TRAIL_TYPE: The audit trail whose timestamp is to be set (Constants). Only individual audit trails are valid, not the constants that specify multiples.
  • LAST_ARCHIVE_TIME: Records or files older than this time will be deleted.
  • RAC_INSTANCE_NUMBER: Optionally specify the RAC node for OS audit trails. If unset it assumes the current instance.
The following code specifies a timestamp of 5 days ago for the standard database audit trail. The setting is then checked by querying the DBA_AUDIT_MGMT_LAST_ARCH_TS view.
BEGIN
  DBMS_AUDIT_MGMT.set_last_archive_timestamp(
    audit_trail_type  => DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD,
    last_archive_time => SYSTIMESTAMP-5);
END;
/

COLUMN audit_trail FORMAT A20
COLUMN last_archive_ts FORMAT A40

SELECT * FROM dba_audit_mgmt_last_arch_ts;

AUDIT_TRAIL          RAC_INSTANCE LAST_ARCHIVE_TS
-------------------- ------------ ----------------------------------------
STANDARD AUDIT TRAIL            0 13-DEC-09 01.57.54.000000 PM +00:00

SQL>
The timestamps for each audit trail can be cleared to allow a complete purge using the CLEAR_LAST_ARCHIVE_TIMESTAMP procedure.
BEGIN
  DBMS_AUDIT_MGMT.clear_last_archive_timestamp(
    audit_trail_type     =>  DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD);
END;
/

Manual Purge

The CLEAN_AUDIT_TRAIL procedure is the basic mechanism for manually purging the audit trail. It accepts two parameters.
  • AUDIT_TRAIL_TYPE: The audit trail to be purged (Constants).
  • USE_LAST_ARCH_TIMESTAMP: Set to FALSE to purge all records/files, or TRUE to only purge records/files older than the timestamp specified for the audit trail.
The following code queries the last archive timestamp and total number of audit records, deletes standard database audit records older than the last archive timestamp, then returns the number of records again.
SELECT * FROM dba_audit_mgmt_last_arch_ts;

AUDIT_TRAIL          RAC_INSTANCE LAST_ARCHIVE_TS
-------------------- ------------ ----------------------------------------
STANDARD AUDIT TRAIL            0 13-DEC-09 01.57.54.000000 PM +00:00

SQL>

SELECT COUNT(*) FROM aud$;

  COUNT(*)
----------
      2438

SQL> 

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

PL/SQL procedure successfully completed.

SELECT COUNT(*) FROM aud$;

  COUNT(*)
----------
        76

SQL>

Automated Purging

The CREATE_PURGE_JOB procedure allows you to schedule a job to call the CLEAN_AUDIT_TRAIL procedure. When creating a purge job you can specify 4 parameters.
  • AUDIT_TRAIL_TYPE: The audit trail to be purged by the scheduled job (Constants).
  • AUDIT_TRAIL_PURGE_INTERVAL: The interval in hours between purges.
  • AUDIT_TRAIL_PURGE_NAME: A name for the purge job.
  • USE_LAST_ARCH_TIMESTAMP: Set to FALSE to purge all records/files, or TRUE to only purge records/files older than the timestamp specified for the audit trail.
The following code schedules a purge of all audit trails every 24 hours. The resulting job is visible in the DBA_SCHEDULER_JOBS view.
BEGIN
  DBMS_AUDIT_MGMT.create_purge_job(
    audit_trail_type           => DBMS_AUDIT_MGMT.AUDIT_TRAIL_ALL,
    audit_trail_purge_interval => 24 /* hours */,  
    audit_trail_purge_name     => 'PURGE_ALL_AUDIT_TRAILS',
    use_last_arch_timestamp    => TRUE);
END;
/

PL/SQL procedure successfully completed.

SQL>

SELECT job_action
FROM   dba_scheduler_jobs
WHERE  job_name = 'PURGE_ALL_AUDIT_TRAILS';

JOB_ACTION
--------------------------------------------------------------------------------
BEGIN DBMS_AUDIT_MGMT.CLEAN_AUDIT_TRAIL(15, TRUE);  END;

SQL>
The job can be disabled and enabled using the SET_PURGE_JOB_STATUS procedure.
BEGIN
  DBMS_AUDIT_MGMT.set_purge_job_status(
    audit_trail_purge_name   => 'PURGE_ALL_AUDIT_TRAILS',
    audit_trail_status_value => DBMS_AUDIT_MGMT.PURGE_JOB_DISABLE);

  DBMS_AUDIT_MGMT.set_purge_job_status(
    audit_trail_purge_name   => 'PURGE_ALL_AUDIT_TRAILS',
    audit_trail_status_value => DBMS_AUDIT_MGMT.PURGE_JOB_ENABLE);
END;
/
The interval of the purge job can be altered using the SET_PURGE_JOB_INTERVAL procedure.
BEGIN
  DBMS_AUDIT_MGMT.SET_PURGE_JOB_INTERVAL(
    audit_trail_purge_name     => 'PURGE_ALL_AUDIT_TRAILS',
    audit_trail_interval_value => 48);
END;
/
Purge jobs are removed using the DROP_PURGE_JOB procedure.
BEGIN
  DBMS_AUDIT_MGMT.drop_purge_job(
     audit_trail_purge_name     => 'PURGE_ALL_AUDIT_TRAILS');
END;
/
There are two things to note about the automated functionality.
  1. If purge jobs use the last archived timestamp and you do not manually move this timestamp forward, the job will run and have nothing to purge. You should reset the timestamp using DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP when you have made an archive of the audit information, that way your audit information is secure and the job can purge the excess data.
  2. The purge job functionality is simply a wrapper over the DBMS_SCHEDULER package to make automating purge jobs easier.
If you want the purge job to maintain an audit trail of a specific number of days, the easiest way to accomplish this is to define a job to set the last archive time automatically. The following job resets the last archive time on a daily basis, keeping the last archive time 90 days in the past.
BEGIN
  DBMS_SCHEDULER.create_job (
    job_name        => 'audit_last_archive_time',
    job_type        => 'PLSQL_BLOCK',
    job_action      => 'BEGIN 
                          DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP(DBMS_AUDIT_MGMT.AUDIT_TRAIL_AUD_STD, TRUNC(SYSTIMESTAMP)-90);
                          DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP(DBMS_AUDIT_MGMT.AUDIT_TRAIL_FGA_STD, TRUNC(SYSTIMESTAMP)-90);
                          DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP(DBMS_AUDIT_MGMT.AUDIT_TRAIL_OS, TRUNC(SYSTIMESTAMP)-90);
                          DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP(DBMS_AUDIT_MGMT.AUDIT_TRAIL_XML, TRUNC(SYSTIMESTAMP)-90);
                        END;',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'freq=daily; byhour=0; byminute=0; bysecond=0;',
    end_date        => NULL,
    enabled         => TRUE,
    comments        => 'Automatically set audit last archive time.');
END;
/

jueves, 6 de febrero de 2014

Capacidad Almacenamiento y Conversiones

En Noviembre de 2000 apareció un nuevo standard.


NameSymbolBefore the standardizationAfter the standardization
bitb1 bit=1 bit1bit=1 bit
byteB1B=8 bit1B=8 bit
kilobitkbit / kb1 kbit= 1024 bit1kBit=1000 bit
KibibitKiBit1KiBit= 1024 bit
kilobytekB1kB=1024 B = Byte1kB=1000 Byte
kibibyteKiB1KiB=1024 Byte
megabitMBit / Mb1 MBit=1024 KBit1 MBit=1000 kBit
mebibitMiBit / Mib1Mib=1024 KiBit
megabyteMB1MB=1024 kB1MB=1000 kB
MebibyteMiBit / MiB1MiB=1024 KiB
gigabitGBit / 1GBit=1024 MBit1GBit=1000 MBit
gibibitGiBit / Gib1Gib=1024 MiBit
gigabyteGB1GB= 1024 MB1GB=1000 MB
gibibyteGiB1GiB=1024 MiB
terabyteTB1TB =1024 GB1TB=1000 GB
tebibyteTiB1TiB=1024 GiB
petabytePB1PB=1024 TB1PB=1000 TB
pebibytePiB1PiB=1024 TiB
exabyteEB1EB= 1024 PB1EB=1000 PB
exbibyteEiB1EiB=1024 PiB
zettabyteZB1ZB=1024 EB1ZB=1000 EB
zebibyteZiB1ZiB=1024 EiB
yottabyteYB1YB=1024 ZB1YB=1000 ZB
yobibyteYiB1YiB=1024 ZiB



El nuevo Standard IEC
bitbit0 or 1
byteB8 bits
kibibitKibit1024 bits
kilobitkbit1000 bits
kibibyte (binary)KiB1024 bytes
kilobyte (decimal)kB1000 bytes
megabitMbit1000 kilobits
mebibyte (binary)MiB1024 kibibytes
megabyte (decimal)MB1000 kilobytes
gigabitGbit1000 megabits
gibibyte (binary)GiB1024 mebibytes
gigabyte (decimal)GB1000 megabytes
terabitTbit1000 gigabits
tebibyte (binary)TiB1024 gibibytes
terabyte (decimal)TB1000 gigabytes
petabitPbit1000 terabits
pebibyte (binary)PiB1024 tebibytes
petabyte (decimal)PB1000 terabytes
exabitEbit1000 petabits
exbibyte (binary)EiB1024 pebibytes
exabyte (decimal)EB1000 petabytes

viernes, 24 de enero de 2014

RECUPERACION OBJETOS TABLESPACE

SELECT OWNER, NAME, TABLESPACE_NAME,
       TO_CHAR(CREATION_TIME, 'YYYY-MM-DD:HH24:MI:SS')
       FROM TS_PITR_OBJECTS_TO_BE_DROPPED
WHERE TABLESPACE_NAME IN ('USERS','TOOLS')
AND CREATION_TIME > TO_DATE('02-NOV-02:07:03:11','YY-MON-DD:HH24:MI:SS')
ORDER BY TABLESPACE_NAME, CREATION_TIME;

This example returns the users and tools tablespaces to the end of log sequence number 1300, and stores the auxiliary instance files (including auxiliary set datafiles) in the destination /disk1/auxdest:
RMAN> RECOVER TABLESPACE users, tools 
     UNTIL LOGSEQ 1300 THREAD 1
      AUXILIARY DESTINATION '/disk1/auxdest';
RECUPERAR TABLAS CON RMAN
The following RECOVER command recovers the EMP and DEPT tables.
RECOVER TABLE SCOTT.EMP, SCOTT.DEPT
    UNTIL TIME 'SYSDATE-1'
    AUXILIARY DESTINATION '/tmp/oracle/recover'
    DATAPUMP DESTINATION '/tmp/recover/dumpfiles'
    DUMP FILE 'emp_dept_exp_dump.dat'
    NOTABLEIMPORT;
RECOVER TABLE SH.SALES:SALES_1998, SH.SALES:SALES_1999
    UNTIL SEQUENCE 354
    AUXILIARY DESTINATION '/tmp/oracle/recover'
    REMAP TABLE 'SH'.'SALES':'SALES_1998':'HISTORIC_SALES_1998',
              'SH'.'SALES':'SALES_1999':'HISTORIC_SALES_1999'
    REMAP TABLESPACE 'SALES_TS':'SALES_PRE_2000_TS';


RMAN> recover table ludovico.reco until scn 803916 auxiliary destination '/tmp/recover';

jueves, 16 de enero de 2014

install flash_player

rpm -ivh http://linuxdownload.adobe.com/adobe-release/adobe-release-x86_64-1.0-1.noarch.rpm

rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-adobe-linux

rpm -ivh http://linuxdownload.adobe.com/adobe-release/adobe-release-i386-1.0-1.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-adobe-linux

yum check-update

yum install flash-plugin nspluginwrapper alsa-plugins-pulseaudio libcurl

martes, 14 de enero de 2014

Oracle Database 11g Patch Security 11.2.0.3 Update Octubre 2013


Check your OPatch Versión

[oracle@server1 16902043]$ /u01/app/oracle/product/11.2.0/db_ee_2/OPatch/opatch version
OPatch Version: 11.2.0.3.4

[oracle@server1 16902043]$ $ORACLE_HOME/OPatch/opatch apply
Oracle Interim Patch Installer version 11.2.0.3.4
Copyright (c) 2012, Oracle Corporation.  All rights reserved.

Oracle Home       : /u01/app/oracle/product/11.2.0/db_ee_1
Central Inventory : /u01/app/oraInventory
   from           : /u01/app/oracle/product/11.2.0/db_ee_1/oraInst.loc
OPatch version    : 11.2.0.3.4
OUI version       : 11.2.0.3.0
Log file location : /u01/app/oracle/product/11.2.0/db_ee_1/cfgtoollogs/opatch/opatch2013-10-27_10-09-47AM_1.log

Verifying environment and performing prerequisite checks...
OPatch continues with these patches:   16902043  

Do you want to proceed? [y|n]
y
User Responded with: Y
All checks passed.
Provide your email address to be informed of security issues, install and
initiate Oracle Configuration Manager. Easier for you if you use your My
Oracle Support Email address/User Name.
Visit http://www.oracle.com/support/policies.html for details.
Email address/User Name: 

You have not provided an email address for notification of security issues.
Do you wish to remain uninformed of security issues ([Y]es, [N]o) [N]:  y

This node is part of an Oracle Real Application Cluster.
Remote nodes: 'server2' 
Local node: 'server1'
Please shutdown Oracle instances running out of this ORACLE_HOME on the local system.
(Oracle Home = '/u01/app/oracle/product/11.2.0/db_ee_1')

Is the local system ready for patching? [y|n]
y
User Responded with: Y
Backing up files...
Applying sub-patch '16902043' to OH '/u01/app/oracle/product/11.2.0/db_ee_1'
ApplySession: Optional component(s) [ oracle.idm.oid, 11.2.0.3.0 ]  not present in the Oracle Home or a higher version is found.

Patching component oracle.ldap.rsf, 11.2.0.3.0...

Patching component oracle.ldap.rsf.ic, 11.2.0.3.0...

Patching component oracle.owb.rsf, 11.2.0.3.0...

Patching component oracle.rdbms, 11.2.0.3.0...

Patching component oracle.rdbms.rsf, 11.2.0.3.0...

Patching component oracle.sysman.console.db, 11.2.0.3.0...

Verifying the update...

Patching in rolling mode.

The node 'server2' will be patched next.

Please shutdown Oracle instances running out of this ORACLE_HOME on 'server2'.
(Oracle Home = '/u01/app/oracle/product/11.2.0/db_ee_1')

Is the node ready for patching? [y|n]
y
User Responded with: Y
Updating nodes 'server2' 
   Apply-related files are:
     FP = "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/copy_files.txt"
     DP = "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/copy_dirs.txt"
     MP = "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/make_cmds.txt"
     RC = "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/remote_cmds.txt"

Instantiating the file "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/copy_files.txt.instantiated" by replacing $ORACLE_HOME in "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/copy_files.txt" with actual path.
Propagating files to remote nodes...
Instantiating the file "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/copy_dirs.txt.instantiated" by replacing $ORACLE_HOME in "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/copy_dirs.txt" with actual path.
Propagating directories to remote nodes...
Instantiating the file "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/make_cmds.txt.instantiated" by replacing $ORACLE_HOME in "/u01/app/oracle/product/11.2.0/db_ee_1/.patch_storage/NApply/2013-10-27_10-09-47AM/rac/make_cmds.txt" with actual path.
Running command on remote node 'server2': 
cd /u01/app/oracle/product/11.2.0/db_ee_1/rdbms/lib; /usr/bin/make -f ins_rdbms.mk irenamedg ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_ee_1 || echo REMOTE_MAKE_FAILED::>&2 

Running command on remote node 'server2': 
cd /u01/app/oracle/product/11.2.0/db_ee_1/rdbms/lib; /usr/bin/make -f ins_rdbms.mk ioracle ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_ee_1 || echo REMOTE_MAKE_FAILED::>&2 

Running command on remote node 'server2': 
cd /u01/app/oracle/product/11.2.0/db_ee_1/rdbms/lib; /usr/bin/make -f ins_rdbms.mk client_sharedlib ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_ee_1 || echo REMOTE_MAKE_FAILED::>&2 

Running command on remote node 'server2': 
cd /u01/app/oracle/product/11.2.0/db_ee_1/network/lib; /usr/bin/make -f ins_net_client.mk client_sharedlib ORACLE_HOME=/u01/app/oracle/product/11.2.0/db_ee_1 || echo REMOTE_MAKE_FAILED::>&2 

RC file not exist.  There are no commands to be run on the remote nodes.

The node 'server2' has been patched.  You can restart Oracle instances on it.

Composite patch 16902043 successfully applied.
Log file location: /u01/app/oracle/product/11.2.0/db_ee_1/cfgtoollogs/opatch/opatch2013-10-27_10-09-47AM_1.log

OPatch succeeded.
If you have done all above without any error you need upgrade you database itself. To do this load the catbundle.sql in your database.
[oracle@server1 db_ee_1]$ cd $ORACLE_HOME/rdbms/admin
[oracle@server1 admin]$ sqlplus / as sysdba

SQL*Plus: Release 11.2.0.3.0 Production on Sun Oct 27 10:52:49 2013

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

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options

SQL> @catbundle psu apply

Check the Logfile ($ORACLE_HOME/cfgtoollogs/catbundle/catbundle_PSU_DB11EE_APPLY_.log for any erros.
If you have also a RMAN catalog running remember to update it also.
As always, comments are welcome.

lunes, 23 de diciembre de 2013

DataGuard 11G Physical Standby Oracle Base

Data Guard Physical Standby Setup in Oracle Database 11g Release 2

Data Guard is the name for Oracle's standby database solution, used for disaster recovery and high availability. This article contains an updated version of the 9i physical standby setup method posted here.
Related articles.

Assumptions

  • You have two servers (physical or VMs) with an operating system and Oracle installed on them. In this case I've used Oracle Linux 5.6 and Oracle Database 11.2.0.2.
  • The primary server has a running instance.
  • The standby server has a software only installation.

Primary Server Setup

Logging

Check that the primary database is in archivelog mode.
SELECT log_mode FROM v$database;

LOG_MODE
------------
NOARCHIVELOG

SQL>
If it is noarchivelog mode, switch is to archivelog mode.
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE ARCHIVELOG;
ALTER DATABASE OPEN;
Enabled forced logging by issuing the following command.
ALTER DATABASE FORCE LOGGING;

Initialization Parameters

Check the setting for the DB_NAME and DB_UNIQUE_NAME parameters. In this case they are both set to "DB11G" on the primary database.
SQL> show parameter db_name

NAME         TYPE  VALUE
------------------------------------ ----------- ------------------------------
db_name         string  DB11G

SQL> show parameter db_unique_name

NAME         TYPE  VALUE
------------------------------------ ----------- ------------------------------
db_unique_name        string  DB11G

SQL>
The DB_NAME of the standby database will be the same as that of the primary, but it must have a different DB_UNIQUE_NAME value. The DB_UNIQUE_NAME values of the primary and standby database should be used in the DG_CONFIG setting of the LOG_ARCHIVE_CONFIG parameter. For this example, the standby database will have the value "DB11G_STBY".
ALTER SYSTEM SET LOG_ARCHIVE_CONFIG='DG_CONFIG=(DB11G,DB11G_STBY)';
Set suitable remote archive log destinations. In this case I'm using the fast recovery area for the local location, but you could specify an location explicitly if you prefer. Notice the SERVICE and the DB_UNIQUE_NAME for the remote location reference the standby location.
ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='SERVICE=db11g_stby NOAFFIRM ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=DB11G_STBY';
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;
The LOG_ARCHIVE_FORMAT and LOG_ARCHIVE_MAX_PROCESSES parameters must be set to appropriate values and the REMOTE_LOGIN_PASSWORDFILE must be set to exclusive.
ALTER SYSTEM SET LOG_ARCHIVE_FORMAT='%t_%s_%r.arc' SCOPE=SPFILE;
ALTER SYSTEM SET LOG_ARCHIVE_MAX_PROCESSES=30;
ALTER SYSTEM SET REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE SCOPE=SPFILE;
In addition to the previous setting, it is recommended to make sure the primary is ready to switch roles to become a standby. For that to work properly we need to set the following parameters. Adjust the *_CONVERT parameters to account for your filename and path differences between the servers.
ALTER SYSTEM SET FAL_SERVER=DB11G_STBY;
--ALTER SYSTEM SET DB_FILE_NAME_CONVERT='DB11G_STBY','DB11G' SCOPE=SPFILE;
--ALTER SYSTEM SET LOG_FILE_NAME_CONVERT='DB11G_STBY','DB11G'  SCOPE=SPFILE;
ALTER SYSTEM SET STANDBY_FILE_MANAGEMENT=AUTO;
Remember, some of the parameters are not modifiable, so the database will need to be restarted before they take effect.

Service Setup

Entries for the primary and standby databases are needed in the "$ORACLE_HOME/network/admin/tnsnames.ora" files on both servers. You can create these using the Network Configuration Utility (netca) or manually. The following entries were used during this setup.
DB11G =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dga1)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = DB11G.WORLD)
    )
  )

DB11G_STBY =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dga2)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = DB11G.WORLD)
    )
  )

Backup Primary Database

If you are planning to use an active duplicate to create the standby database, then this step is unnecessary. For a backup-based duplicate, or a manual restore, take a backup of the primary database.
$ rman target=/

RMAN> BACKUP DATABASE PLUS ARCHIVELOG;

Create Standby Controlfile and PFILE

Create a controlfile for the standby database by issuing the following command on the primary database.
ALTER DATABASE CREATE STANDBY CONTROLFILE AS '/tmp/db11g_stby.ctl';
Create a parameter file for the standby database.
CREATE PFILE='/tmp/initDB11G_stby.ora' FROM SPFILE;
Amend the PFILE making the entries relevant for the standby database. I'm making a replica of the original server, so in my case I only had to amend the following parameters.
*.db_unique_name='DB11G_STBY'
*.fal_server='DB11G'
*.log_archive_dest_2='SERVICE=db11g ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=DB11G'

Standby Server Setup (Manual)

Copy Files

Create the necessary directories on the standby server.
$ mkdir -p /u01/app/oracle/oradata/DB11G
$ mkdir -p /u01/app/oracle/fast_recovery_area/DB11G
$ mkdir -p /u01/app/oracle/admin/DB11G/adump
Copy the files from the primary to the standby server.
$ # Standby controlfile to all locations.
$ scp oracle@ol5-112-dga1:/tmp/db11g_stby.ctl /u01/app/oracle/oradata/DB11G/control01.ctl
$ cp /u01/app/oracle/oradata/DB11G/control01.ctl /u01/app/oracle/fast_recovery_area/DB11G/control02.ctl

$ # Archivelogs and backups
$ scp -r oracle@ol5-112-dga1:/u01/app/oracle/fast_recovery_area/DB11G/archivelog /u01/app/oracle/fast_recovery_area/DB11G
$ scp -r oracle@ol5-112-dga1:/u01/app/oracle/fast_recovery_area/DB11G/backupset /u01/app/oracle/fast_recovery_area/DB11G

$ # Parameter file.
$ scp oracle@ol5-112-dga1:/tmp/initDB11G_stby.ora /tmp/initDB11G_stby.ora

$ # Remote login password file.
$ scp oracle@ol5-112-dga1:$ORACLE_HOME/dbs/orapwDB11G $ORACLE_HOME/dbs
Notice, the backups were copied across to the standby server as part of the FRA copy. If your backups are not held within the FRA, you must make sure you copy them to the standby server and make them available from the same path as used on the primary server.

Start Listener

Make sure the listener is started on the standby server.
$ lsnrctl start

Restore Backup

Create the SPFILE form the amended PFILE.
$ export ORACLE_SID=DB11G
$ sqlplus / as sysdba

SQL> CREATE SPFILE FROM PFILE='/tmp/initDB11G_stby.ora';
Restore the backup files.
$ export ORACLE_SID=DB11G
$ rman target=/

RMAN> STARTUP MOUNT;
RMAN> RESTORE DATABASE;

Create Redo Logs

Create online redo logs for the standby. It's a good idea to match the configuration of the primary server.
ALTER SYSTEM SET STANDBY_FILE_MANAGEMENT=MANUAL;
ALTER DATABASE ADD LOGFILE ('/u01/app/oracle/oradata/DB11G/online_redo01.log') SIZE 50M;
ALTER DATABASE ADD LOGFILE ('/u01/app/oracle/oradata/DB11G/online_redo02.log') SIZE 50M;
ALTER DATABASE ADD LOGFILE ('/u01/app/oracle/oradata/DB11G/online_redo03.log') SIZE 50M;
ALTER SYSTEM SET STANDBY_FILE_MANAGEMENT=AUTO;
In addition to the online redo logs, you should create standby redo logs on both the standby and the primary database (in case of switchovers). The standby redo logs should be at least as big as the largest online redo log and there should be one extra group per thread compared the online redo logs. In my case, the following is standby redo logs must be created on both servers.
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo01.log') SIZE 50M;
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo02.log') SIZE 50M;
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo03.log') SIZE 50M;
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo04.log') SIZE 50M;
Once this is complete, we can start the apply process.

Standby Server Setup (DUPLICATE)

Copy Files

Create the necessary directories on the standby server.
$ mkdir -p /u01/app/oracle/oradata/DB11G
$ mkdir -p /u01/app/oracle/fast_recovery_area/DB11G
$ mkdir -p /u01/app/oracle/admin/DB11G/adump
Copy the files from the primary to the standby server.
$ # Standby controlfile to all locations.
$ scp oracle@ol5-112-dga1:/tmp/db11g_stby.ctl /u01/app/oracle/oradata/DB11G/control01.ctl
$ cp /u01/app/oracle/oradata/DB11G/control01.ctl /u01/app/oracle/fast_recovery_area/DB11G/control02.ctl

$ # Parameter file.
$ scp oracle@ol5-112-dga1:/tmp/initDB11G_stby.ora /tmp/initDB11G_stby.ora

$ # Remote login password file.
$ scp oracle@ol5-112-dga1:$ORACLE_HOME/dbs/orapwDB11G $ORACLE_HOME/dbs

Start Listener

When using active duplicate, the standby server requires static listener configuration in a "listener.ora" file. In this case I used the following configuration.
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = DB11G.WORLD)
      (ORACLE_HOME = /u01/app/oracle/product/11.2.0/db_1)
      (SID_NAME = DB11G)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = ol5-112-dga2.localdomain)(PORT = 1521))
    )
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

ADR_BASE_LISTENER = /u01/app/oracle
Make sure the listener is started on the standby server.
$ lsnrctl start

Create Standby Redo Logs on Primary Server

The DUPLICATE command automatically creates the standby redo logs on the standby. To make sure the primary database is configured for switchover, we must create the standby redo logs on the primary server.
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo01.log') SIZE 50M;
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo02.log') SIZE 50M;
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo03.log') SIZE 50M;
ALTER DATABASE ADD STANDBY LOGFILE ('/u01/app/oracle/oradata/DB11G/standby_redo04.log') SIZE 50M;

Create Standby Using DUPLICATE

Start the auxillary instance on the standby server by starting it using the temporary "init.ora" file.
$ export ORACLE_SID=DB11G
$ sqlplus / as sysdba

SQL> STARTUP NOMOUNT PFILE='/tmp/initDB11G_stby.ora';
Connect to RMAN, specifying a full connect string for both the TARGET and AUXILLARY instances. DO not attempt to use OS authentication.
$ rman TARGET sys/password@DB11G AUXILIARY sys/password@DB11G_STBY
Now issue the following DUPLICATE command.
DUPLICATE TARGET DATABASE
  FOR STANDBY
  FROM ACTIVE DATABASE
  DORECOVER
  SPFILE
    SET db_unique_name='DB11G_STBY' COMMENT 'Is standby'
    SET LOG_ARCHIVE_DEST_2='SERVICE=db11g ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=DB11G'
    SET FAL_SERVER='DB11G' COMMENT 'Is primary'
  NOFILENAMECHECK;
A brief explanation of the individual clauses is shown below.
  • FOR STANDBY: This tells the DUPLICATE command is to be used for a standby, so it will not force a DBID change.
  • FROM ACTIVE DATABASE: The DUPLICATE will be created directly from the source datafile, without an additional backup step.
  • DORECOVER: The DUPLICATE will include the recovery step, bringing the standby up to the current point in time.
  • SPFILE: Allows us to reset values in the spfile when it is copied from the source server.
  • NOFILENAMECHECK: Destination file locations are not checked.
Once the command is complete, we can start the apply process.

Start Apply Process

Start the apply process on standby server.
# Foreground redo apply. Session never returns until cancel. 
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE;

# Background redo apply. Control is returned to the session once the apply process is started.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
If you need to cancel the apply process, issue the following command.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
If you prefer, you can set a delay between the arrival of the archived redo log and it being applied on the standby server using the following commands.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DELAY 30 DISCONNECT FROM SESSION;

ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE NODELAY DISCONNECT FROM SESSION;
Provided you have configured standby redo logs, you can start real-time apply using the following command.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE;

Test Log Transport

On the primary server, check the latest archived redo log and force a log switch.
ALTER SESSION SET nls_date_format='DD-MON-YYYY HH24:MI:SS';

SELECT sequence#, first_time, next_time
FROM   v$archived_log
ORDER BY sequence#;

ALTER SYSTEM SWITCH LOGFILE;
Check the new archived redo log has arrived at the standby server and been applied.
ALTER SESSION SET nls_date_format='DD-MON-YYYY HH24:MI:SS';

SELECT sequence#, first_time, next_time, applied
FROM   v$archived_log
ORDER BY sequence#;

Protection Mode

There are three protection modes for the primary database:
  • Maximum Availability: Transactions on the primary do not commit until redo information has been written to the online redo log and the standby redo logs of at least one standby location. If no standby location is available, it acts in the same manner as maximum performance mode until a standby becomes available again.
  • Maximum Performance: Transactions on the primary commit as soon as redo information has been written to the online redo log. Transfer of redo information to the standby server is asynchronous, so it does not impact on performance of the primary.
  • Maximum Protection: Transactions on the primary do not commit until redo information has been written to the online redo log and the standby redo logs of at least one standby location. If not suitable standby location is available, the primary database shuts down.
By default, for a newly created standby database, the primary database is in maximum performance mode.
SELECT protection_mode FROM v$database;

PROTECTION_MODE
--------------------
MAXIMUM PERFORMANCE

SQL>
The mode can be switched using the following commands. Note the alterations in the redo transport attributes.
-- Maximum Availability.
ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='SERVICE=db11g_stby AFFIRM SYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=DB11G_STBY';
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE AVAILABILITY;

-- Maximum Performance.
ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='SERVICE=db11g_stby NOAFFIRM ASYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=DB11G_STBY';
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PERFORMANCE;

-- Maximum Protection.
ALTER SYSTEM SET LOG_ARCHIVE_DEST_2='SERVICE=db11g_stby AFFIRM SYNC VALID_FOR=(ONLINE_LOGFILES,PRIMARY_ROLE) DB_UNIQUE_NAME=DB11G_STBY';
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PROTECTION;
ALTER DATABASE OPEN;

Database Switchover

A database can be in one of two mutually exclusive modes (primary or standby). These roles can be altered at runtime without loss of data or resetting of redo logs. This process is known as a Switchover and can be performed using the following statements.
-- Convert primary database to standby
CONNECT / AS SYSDBA
ALTER DATABASE COMMIT TO SWITCHOVER TO STANDBY;

-- Shutdown primary database
SHUTDOWN IMMEDIATE;

-- Mount old primary database as standby database
STARTUP NOMOUNT;
ALTER DATABASE MOUNT STANDBY DATABASE;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
On the original standby database issue the following commands.
-- Convert standby database to primary
CONNECT / AS SYSDBA
ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY;

-- Shutdown standby database
SHUTDOWN IMMEDIATE;

-- Open old standby database as primary
STARTUP;
Once this is complete, test the log transport as before. If everything is working fine, switch the primary database back to the original server by doing another switchover. This is known as a switchback.

Failover

If the primary database is not available the standby database can be activated as a primary database using the following statements.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;
ALTER DATABASE ACTIVATE STANDBY DATABASE;
Since the standby database is now the primary database it should be backed up immediately.
The original primary database can now be configured as a standby. If Flashback Database was enabled on the primary database, then this can be done relatively easily (shown here). If not, the whole setup process must be followed, but this time using the original primary server as the standby.

Flashback Database

It was already mentioned in the previous section, but it is worth drawing your attention to Flashback Database once more. Although a switchover/switchback is safe for both the primary and standby database, a failover renders the original primary database useless for converting to a standby database. If flashback database is not enabled, the original primary must be scrapped and recreated as a standby database.
An alternative is to enable flashback database on the primary (and the standby if desired) so in the event of a failover, the primary can be flashed back to the time before the failover and quickly converted to a standby database. That process is shown here.

Read-Only Standby and Active Data Guard

Once a standby database is configured, it can be opened in read-only mode to allow query access. This is often used to offload reporting to the standby server, thereby freeing up resources on the primary server. When open in read-only mode, archive log shipping continues, but managed recovery is stopped, so the standby database becomes increasingly out of date until managed recovery is resumed.
To switch the standby database into read-only mode, do the following.
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE OPEN READ ONLY;
To resume managed recovery, do the following.
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
In 11g, Oracle introduced the Active Data Guard feature. This allows the standby database to be open in read-only mode, but still apply redo information. This means a standby can be available for querying, yet still be up to date. There are licensing implications for this feature, but the following commands show how active data guard can be enabled.
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE OPEN READ ONLY;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
Since managed recovery continues with active data guard, there is no need to switch back to managed recovery from read-only mode in this case.

Snapshot Standby

Introduced in 11g, snapshot standby allows the standby database to be opened in read-write mode. When switched back into standby mode, all changes made whilst in read-write mode are lost. This is achieved using flashback database, but the standby database does not need to have flashback database explicitly enabled to take advantage of this feature, thought it works just the same if it is.
If you are using RAC, turn off all but one of the RAC instances. Make sure the instance is in MOUNT mode.
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
Make sure managed recovery is disabled.
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
Convert the standby to a snapshot standby. The following example queries the V$DATABASE view to show that flashback database is not enabled prior to the conversion operation.
SELECT flashback_on FROM v$database;

FLASHBACK_ON
------------------
NO

ALTER DATABASE CONVERT TO SNAPSHOT STANDBY;
ALTER DATABASE OPEN;
SELECT flashback_on FROM v$database;

FLASHBACK_ON
------------------
RESTORE POINT ONLY

SQL>
You can now do treat the standby like any read-write database.
To convert it back to the physical standby, losing all the changes made since the conversion to snapshot standby, issue the following commands.
SHUTDOWN IMMEDIATE;
STARTUP MOUNT;
ALTER DATABASE CONVERT TO PHYSICAL STANDBY;
SHUTDOWN IMMEDIATE;
STARTUP NOMOUNT;
ALTER DATABASE MOUNT STANDBY DATABASE;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT;
SELECT flashback_on FROM v$database;

FLASHBACK_ON
------------------
NO

SQL>
The standby is once again in managed recovery and archivelog shipping is resumed. Notice that flashback database is still not enabled.
For more information see:

martes, 17 de diciembre de 2013

Insufficient Memory Target Errors

 

4.3.2 Insufficient Memory Target Errors

On Linux systems, if the operating system /dev/shm mount size is too small for the Oracle system global area (SGA) and program global area (PGA), then you encounter the following error:
ORA-00845: MEMORY_TARGET not supported on this system. 
The cause of this error is an insufficient /dev/shm allocation. The total memory size of the SGA and PGA, which sets the initialization parameter MEMORY_TARGET or MEMORY_MAX_TARGET, cannot be greater than the shared memory file system (/dev/shm) on your operating system.
Background
Automatic Memory Management (AMM) has been updated in Oracle ASM 11g Release 2. It manages both the SGA and PGA together. It is managed by the Memory Manager Process (MMAN). In this release, note the following changes to AMM:
  • It uses MEMORY_TARGET instead of SGA_TARGET
  • It uses MEMORY_MAX_TARGET instead of SGA_MAX_SIZE (defaults to MEMORY_TARGET)
  • It uses memory allocated by /dev/shm
If the value of max_target is set to a value greater than the allocation for the /dev/shm size, then you may encounter the error ORA-00845: MEMORY_TARGET not supported on this system.
Note:
An ORA-00845 error can also occur if /dev/shm is not properly mounted. To rule out this possibility, run the command df -k to ensure that /dev/shm is mounted. For example:
$ df -k 
 
Filesystem 1K-blocks Used Available Use% Mounted on 
shmfs 6291456 832356 5459100 14% /dev/shm
Solution
Increase the /dev/shm mountpoint size.
For example:
# mount -t tmpfs shmfs -o size=2g /dev/shm
To make this change persistent across system restarts, add an entry in /etc/fstab similar to the following:
shmfs /dev/shm tmpfs size=2g 0

jueves, 21 de noviembre de 2013

Expresiones Regulares

http://www.oracle.com/technetwork/es/articles/sql/expresiones-regulares-base-de-datos-1569340-esa.HTML


REGEXP_LIKECondición que se puede utilizar en la cláusula WHERE de una sentencia SQL SELECT y que permite retornar aquellas filas que coinciden con el patrón especificado en una expresión regular.
REGEXP_COUNTFunción que permite contar el número de veces que un patrón aparece en una cadena de caracteres.
REGEXP_INSTRFunción que permite determinar la posición de inicio de un patrón específico en una cadena de caracteres.
REGEXP_REPLACEFunción que permite hacer búsqueda y reemplazo en una cadena de caracteres utilizando expresiones regulares para la búsqueda.
REGEXP_SUBSTRFunción para extraer de una cadena una subcadena de caracteres que coincidan con un patrón especificado en una expresión regular.

El patron de telefonos es este:

'([A-Z0-9]*\-*\.*\_*\@*\#*\s*)(.*)(\s*TELEFONO[E|FO|NO|AX|(\s)]*\s*(\-)*(\_)*(\.)*(\:)*[A-Z0-9]*\s*([\d]{1,7}\-*\s*[\d]{2,4}\-*\s*([\d]{2,6})*\-*\s*([\d]{2,7})*[Y]*))+(.*)([A-Z0-9]*\-*\.*\_*\@*\#*\s*)'
 
El patron de mail es este:  
'((\w.*)\s+)*(.+\s*@.+\.[A-Za-z]+)(.*)*
 

Prólogo
Históricamente Oracle había ofrecido prestaciones muy básicas para el uso de expresiones regulares y la manipulación de cadenas de caracteres. Aquellos desarrolladores que necesitaban hacer uso de expresiones regulares se veían prácticamente obligados a extraer los datos de la base para manipular las cadenas de caracteres en capas intermedias de la aplicación. A partir de la versión 10g, con la introducción de las llamadas funciones REGEXP (REGular EXPressions), Oracle nos ofrece una batería de sofisticadas y potentes herramientas nativas que permiten al desarrollador centralizar el procesamiento intensivo de cadenas de caracteres dentro de la base de datos Oracle y con los lenguajes SQL y PL/SQL.
Tabla de Contenidos
¿Qué son las Expresiones Regulares?
Antes de introducirnos bien en el mundo de las expresiones regulares es necesario que le perdamos un poco el miedo. Lo más común es que un ser humano huya desesperadamente cuando se encuentra por primera vez con una expresión regular como la siguiente:
^Ab*[0-8]\*(ha|ve)n$

Sin embargo, un buen manejo de las expresiones regulares es algo tan poderoso que vale la pena que nos tomemos un tiempo para aprender a utilizarlas. Además, saber manejar expresiones regulares nos servirá no solamente en el mundo de las bases de datos Oracle; las podremos usar también en otros lenguajes de programación como Perl, Java, .Net, Php y Unix Shell Scripting, entre otros.
La idea de este documento es hacer una introducción al tema de manera práctica, comenzando con ejemplos sencillos para luego ir aumentando la complejidad.
Comenzamos entonces definiendo a una expresión regular como una cadena de caracteres que definen un patrón de búsqueda. En una expresión regular encontramos literales y metacaracteres. Los literales se leen al pie de la letra. Los metacaracteres son caracteres que tienen un significado especial.
Tomemos por ejemplo la siguiente expresión regular:
[n|p]ata

Los metacaracteres son los corchetes y el símbolo pipe (|). El resto son literales.
Los corchetes agrupan a varios caracteres en un solo caracter.
El símbolo pipe indica un símbolo u otro; es decir la 'n' o la 'p'.
Luego, la expresión regular:
[n|p]ata

Coincide con las cadenas:
nata
pata

Seguramente el lector se preguntará cómo determinar qué elementos de una expresión regular son literales y qué elementos son metacaracteres. Más adelante encontrará la respuesta. Sigamos.
¿Para qué sirven las Expresiones Regulares?
En una base de datos Oracle existen diversos escenarios en que la implementación de expresiones regulares constituye una herramienta de gran utilidad:
  • Búsqueda de texto. Las expresiones regulares nos permiten hacer búsquedas complejas de cadenas de caracteres dentro de las columnas de nuestras tablas.
  • Formateo de datos. Podemos modificar los datos proyectados en las sentencias SELECT, invirtiendo palabras, agregando o quitando caracteres, etc.
  • Definición de constraints. A fin de forzar el contenido de una columna para que se ajuste a un formato determinado: casilla de correo, número telefónico, etc.
  • Manipulación de datos. Por ejemplo, regularizando datos en procesos de migración desde aplicaciones legacy y aplicando reglas de búsqueda y reemplazo (Search & Replace).
Entendiendo las Expresiones Regulares
Como se había dicho anteriormente, en una expresión regular encontramos literales y metacaracteres. Al analizar una expresión regular, lo primero que tenemos que hacer es determinar qué elementos son literales y qué elementos son metacaracteres (también llamados operadores). Existe una larga lista de metacaracteres soportados por Oracle. No es la intención estudiarlos a todos en este documento. A continuación iremos viendo algunos.
El metacaracter punto (.)
El metacaracter punto coincide con cualquier carácter. Por ejemplo, en la expresión regular
ca.a

Para que una cadena de caracteres coincida con dicho patrón:
- Debe estar el literal 'c'.
- Le debe seguir el literal 'a'
- Le debe seguir un y solamente un carácter cualquiera.
- Le debe seguir el literal 'a'
En la expresión regular encontramos 3 literales y el metacaracter punto. Analicemos las siguientes cadenas y veamos cuales coinciden con el patrón buscado y cuáles no.
Cadena¿Coincide?Análisis
casaSiCoinciden los literales y en la posición del operador punto aparece sólo un carácter
canaSiCoinciden los literales y en la posición del operador punto aparece sólo un carácter
caraSiCoinciden los literales y en la posición del operador punto aparece sólo un carácter
cantaNoEn la posición del punto aparece más de un carácter
palaNoEl literal 'p' en la primer posición no respeta el literal ´c´ definido en la expresión regular

El metacaracter suma (+)
El metacaracter suma coincide con una o más ocurrencias de la subexpresión que lo precede. Por ejemplo, analicemos la expresión regular
cas+a

Para que una cadena de caracteres coincida con dicho patrón:
- Debe estar el carácter 'c'
- Le debe seguir el carácter 'a'
- Le debe seguir una o mas ocurrencias del carácter 's'
- Le debe seguir el carácter 'a'
Vemos nuevamente tres literales y el metacaracter Suma. Busquemos el patrón en las siguientes cadenas y veamos las coincidencias.
Cadena¿Coincide?Análisis
cassa
cassssa
cassssssssa
SiEl símbolo más (+) es precedido por la subexpresión "s". Por lo tanto todas las cadenas que tienen una o más "s" en a partir de la tercer posición y respetan el resto de los literales, coinciden con el patrón representado en la expresión regular.
CaaNoEl patrón definido requiere al menos una ‘s’ en la tercer posición
LasaNoNo respeta todos los literales de la expresión regular
TassaNoNo respeta todos los literales de la expresión regular

El metacaracter asterisco (*)
Coincide con cero o más ocurrencias de la subexpresión que le precede al asterisco. Analicemos la expresión:
cas*a

Para que una cadena de caracteres coincida con dicho patrón:
- Debe estar el carácter 'c' - Le debe seguir el carácter 'a' - Le debe seguir cero o mas ocurrencias del carácter 's'. Es decir que el carácter 's' puede o no estar. - Le debe seguir el carácter 'a'
Analicemos qué pasa con las mismas cadenas de caracteres del ejemplo anterior:
Cadena¿Coincide?Análisis
Casa
cassssa
cassssssssa
SiEl símbolo asterisco (*) es precedido por la subexpresión "s". Por lo tanto todas las cadenas que tienen cero o más "s" a partir de la tercera posición y respetan el resto de los literales, coinciden con el patrón representado en la expresión regular.
caaSiEl patrón acepta la no existencia del carácter 's' en la tercera posición.
lasaNoNo respeta todos los literales de la expresión regular
tassaNoNo respeta todos los literales de la expresión regular

El metacaracter [char...]
Coincide con una sola ocurrencia de alguno de los caracteres de la lista entre corchetes. En la lista, todos los caracteres son tomados como literales excepto algunos caracteres que son interpretados como metacaracteres. Aquí nos limitaremos a mencionar el metacaracter '-' para representar rangos de caracteres. Analicemos la siguiente expresión regular:
ca[snt]a

Para que una cadena de caracteres coincida con dicho patrón:
- Debe estar el carácter 'c'
- Le debe seguir el carácter 'a'
- Le debe seguir uno y solamente uno de los siguientes caracteres: 's', 'n' o 't'.
- Le debe seguir el carácter 'a'
Cadena¿Coincide?Análisis
casaSiCoinciden los literales y en la posición del operador aparece sólo un carácter y es de los de la lista
canaSiCoinciden los literales y en la posición del operador aparece sólo un carácter y es de los de la lista
cataSiCoinciden los literales y en la posición del operador aparece sólo un carácter y es de los de la lista
caraNoEn la posición del operador aparece un solo carácter pero no está en la lista
cantaNoSi bien en la posición del operador aparecen literales de la lista; son más de uno
pasaNoNo respeta el primer literal de la lista

Como se dijo anteriormente, en la lista se puede utilizar el metacaracter rango '-'. Haciendo uso de este metacaracter la siguiente lista de caracteres:
[123456789]

Podemos expresarla como
[1-9]

Y la siguiente lista de caracteres
[abcdef]

Podemos expresarla como
[a-f]

Analicemos ahora la siguiente expresión regular:
a[3-7][f-i]9

Para que una cadena coincida con el patrón:
- Debe tener el literal 'a'
- Le debe seguir un numero de 3 a 7. Es decir: 3, 4, 5, 6 ó 7.
- Le debe seguir una letra de la f a la i. Es decir 'f', 'g', 'h' o 'i'
- Le debe seguir el numero 9
Cadena¿Coincide?Análisis
a3h9SiCoinciden los literales y en la posición de los operadores aparecen literales incluidos en los rangos especificados en el patrón de la expresión regular.
a33f9NoEn la posición del primer operador aparece más de un caracter
a3z9NoLa 'z' no está incluida en el rango del segundo operador

El metacaracter [^char...]
El sombrerito (^) que precede a la lista indica que los literales que le siguen no deben estar en la cadena de caracteres para que se produzca una coincidencia. Veamos,
ca[^snt]a

Para que una cadena de caracteres coincida con dicho patrón:
- Debe estar el carácter 'c'
- Le debe seguir el carácter 'a'
- Le debe seguir uno y solamente un carácter que no sea ni 's' ni 'n' ni 't'.
- Le debe seguir el carácter 'a'
Cadena¿Coincide?Análisis
casaNoCoinciden los literales y en la posición del operador aparece un carácter de los negados en la lista
canaNoCoinciden los literales y en la posición del operador aparece un carácter de los negados en la lista
cataNoCoinciden los literales y en la posición del operador aparece un carácter de los negados en la lista
caraSiCoinciden los literales y en la poscion del operador aparece un carácter que no está en la lista de literales negados.
cantaNoEn la posición del operador aparece más de un valor
paraNoNo respeta el primer literal de la lista

El metacaracter subexpresión (expr)
Considera a toda la expresión entre paréntesis como una unidad. La expresión puede ser una simple cadena de literales o una expresión compleja conteniendo otros metacaracteres. Analicemos la siguiente expresión regular
chau(hola)*chau

Ahora el asterisco precede a la expresión
hola

El asterisco indica que la expresión
hola

Puede aparecer cero ó más veces
Cadena¿Coincide?Análisis
chauchauSiCoinciden los literales y la expresión 'hola' aparece cero veces
chauholachauSiCoinciden los literales y la expresión 'hola' aparece una vez, es decir cero o más veces.
chauholaholachauSiCoinciden los literales y la expresión 'hola' aparece dos veces, es decir cero o más veces.
holachauNoNo aparecen el literal chau' que precede al ‘hola’
chauNoNo aparece el literal 'chau' que precede al ‘hola’

El metacaracter de anclaje de principio de línea (^)
Coincide con el principio de línea y el operador está representado con el caracter sombrerito (^). En la expresión regular
^hola

Los literales que componen la palabra 'hola' deben estar al inicio de la línea para que se produzca la coincidencia con el patrón expresado.
Cadena¿Coincide?Análisis
holaSiLos literales que componen la palabra 'hola' están al inicio de la línea
chauholaNoLa línea no comienza con los literales que conforman la palabra 'hola'
holachauSiLos literales que componen la palabra 'hola' están al inicio de la línea
holaholaSiLos literales que componen la palabra 'hola' están al inicio de la línea

El metacaracter de anclaje de fin de línea ($)
Coincide con el final de línea y el operador está representado con el carácter pesos ($). En la expresión regular
hola$

Los literales que componen la palabra 'hola' deben estar al final de la línea para que se produzca la coincidencia con el patrón expresado.
Cadena¿Coincide?Análisis
HolaSiLos literales que componen la palabra 'hola' están al final de la línea
chauholaSiLa línea finaliza con los literales que conforman la palabra 'hola'
holachauNoLos literales que componen la palabra 'hola' no están al final de la línea
holaholaSiLos literales que componen la palabra 'hola' están al final de la línea

El metacaracter de escape (\)
Precediendo a un metacaracter con el símbolo de escape, el metacaracter será interpretado como un literal. El doble carácter de escape (\\) permite considerar al carácter de escape como literal.
En la expresión regular
hola\*

Cadena¿Coincide?Análisis
holaNoFalta el literal '*' que sigue literal 'a'
Hola*SiCoinciden todos los literales
hol*NoFaltan los literales 'a' y ‘*’

Construyendo Expresiones Regulares complejas
Hasta aquí hemos visto algunos de los metacaracteres que se usan con más frecuencia. Combinando varios de estos metacaracteres en una sola expresión regular, podemos hacer construcciones más complejas y muy poderosas. Analicemos la siguiente expresión regular en la que encontramos varios metacaracteres
^hola[0-9]*chau[^a]+$

Hagamos un desglose de la expresión regular:
^holaAl principio de la línea debe estar la palabra 'hola'
[0-9]*Luego de la palabra 'hola' deben aparecer cero o mas dígitos del 0 al 9
chauLuego debe aparecer el literal 'chau'
[^a]+$La línea debe continuar hasta el final con uno o más caracteres distintos de 'a'

Busquemos el patrón en algunas cadenas de caracteres
Cadena¿Coincide?Análisis
hola123chaubSiComienza con el texto 'hola'. Le siguen varios dígitos entre 0 y 9. Le sigue el literal 'chau' y finaliza con al menos una letra distinta de 'a'.
holachaucSiComienza con el texto 'hola'. No aparecen dígitos del 0 al 9 (el asterisco indica que esto es aceptado para que haya coincidencia). Luego aparece el literal 'chau' y se finaliza con una letra distinta de 'a'
hola0chauaNoFinaliza con una ‘a’

Uso de las Expresiones Regulares en Oracle
Hasta aquí hemos visto un poco de teoría y algunos ejemplos prácticos para conocer y aprender un poco acerca de las expresiones regulares. Pero, ¿cómo podemos hacer uso de este conocimiento adquirido en una base de datos Oracle?
A partir de la versión 10g Oracle nos ofrece un grupo de nuevas funciones y condiciones para poder manejar expresiones regulares en el lenguaje SQL:
REGEXP_LIKECondición que se puede utilizar en la cláusula WHERE de una sentencia SQL SELECT y que permite retornar aquellas filas que coinciden con el patrón especificado en una expresión regular.
REGEXP_COUNTFunción que permite contar el número de veces que un patrón aparece en una cadena de caracteres.
REGEXP_INSTRFunción que permite determinar la posición de inicio de un patrón específico en una cadena de caracteres.
REGEXP_REPLACEFunción que permite hacer búsqueda y reemplazo en una cadena de caracteres utilizando expresiones regulares para la búsqueda.
REGEXP_SUBSTRFunción para extraer de una cadena una subcadena de caracteres que coincidan con un patrón especificado en una expresión regular.

Veamos algunos ejemplos de implementación de estas condiciones y funciones combinadas con el uso de expresiones regulares.
La condición REGEXP_LIKE es similar a la condición LIKE pero, a diferencia del LIKE, utiliza patrones basados en expresiones regulares para la búsqueda de coincidencias en las cadenas de caracteres analizadas.
En el siguiente ejemplo, vemos una tabla de empleados cuyos nombres fueron migrados de un sistema legacy. En muchos casos el nombre ha quedado separado del apellido por varios espacios en blanco:
SQL> select nombre from empleados;
 
NOMBRE
----------------------------------------
Fernando         Garcia
Marcelo  Burgos
       Marcelo         Ochoa
Gerardo     Tezza
Clarisa Maman Orfali
Rodolfo  Pajuelo Quispe
 
6 rows selected.

El único caso de un solo espacio entre el nombre y el apellido es el de Clarisa Maman Orfali. Veamos cómo podemos construir un query que detecte aquellas filas en que haya dos o más espacios separando nombres de apellidos.
SQL> select nombre
  2  from empleados
  3  where regexp_like(nombre, '[ ][ ][ ]*');
 
NOMBRE
----------------------------------------
Fernando         Garcia
Marcelo  Burgos
       Marcelo         Ochoa
Gerardo     Tezza
Rodolfo  Pajuelo Quispe

Corrijamos esta situación dejando un solo blanco de separación en donde hay dos o más espacios en blanco.
SQL> update empleados
  2  set nombre = regexp_replace(nombre, '[ ][ ][ ]*', ' ')
  3  where regexp_count(nombre, '[ ][ ][ ]*') > 0;
 
5 rows updated.

Veamos cómo quedo la tabla luego de la corrección
SQL> select nombre from empleados;
 
NOMBRE
----------------------------------------
Fernando Garcia
Marcelo Burgos
 Marcelo Ochoa
Gerardo Tezza
Clarisa Maman Orfali
Rodolfo Pajuelo Quispe
 
6 rows selected.

Bastante bien. Salvo el caso de Marcelo Ochoa, en donde nos quedó un espacio en blanco al principio de la línea. Eliminemos entonces los espacios en blanco que están al principio de la línea.
SQL> update empleados
  2  set nombre = regexp_replace(nombre, '^ ')
  3  where regexp_count(nombre, '^ ') > 0
  4  /
 
1 row updated.
 
SQL> select nombre from empleados;
 
NOMBRE
----------------------------------------
Fernando Garcia
Marcelo Burgos
Marcelo Ochoa
Gerardo Tezza
Clarisa Maman Orfali
Rodolfo Pajuelo Quispe
 
6 rows selected.

En este otro ejemplo vemos una tabla de impuestos en la que almacenamos un código de identificación tributaria numérico y que debe respetar el siguiente formato:
99-99999999-99 
 
SQL> select cuit from impuestos;
 
CUIT
-------------
20-20198123-9
10-43112345-8
1-22123987-9
8883838382
aa-75212456-x

Busquemos aquellos códigos que no están respetando el formato requerido:
select cuit
from impuestos
where not regexp_like (cuit, '[0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9]')
 
CUIT
-------------
1-22123987-9
8883838382
aa-75212456-x

A fin de evitar que la tabla siga admitiendo códigos que no respetan el formato, podemos crear una constraint que fuerce el ingreso de códigos que respeten el formato.
alter table impuestos
add constraint c_cuit
check (regexp_like(cuit,'[0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9]'))
enable novalidate
/
Table altered.

Veamos qué ocurre al ingresar nuevas filas a la table de impuestos
SQL> insert into impuestos (cuit) values ('20-17979866-2');
 
1 row created.
 
SQL> insert into impuestos (cuit) values ('1x-17979866-2');
insert into impuestos (cuit) values ('1x-17979866-2')
*
ERROR at line 1:
ORA-02290: check constraint (SYS.C_CUIT) violated
 
 
SQL> insert into impuestos values ('12888122812');
insert into impuestos values ('12888122812')
*
ERROR at line 1:
ORA-02290: check constraint (SYS.C_CUIT) violated

Profundizando el conocimiento y uso de las expresiones regulares en Oracle
Hemos visto varios ejemplos para demostrar el potencial y utilidad que nos ofrecen las expresiones regulares en las bases de datos Oracle. Existen muchos más metacaracteres que no hemos mencionado aquí. Las funciones tampoco las hemos visto en profundidad; hay más argumentos para hacer búsquedas que ignoren mayúsculas y minúsculas, etc. Para seguir profundizando el tema, aquí dejamos algunos links de interés:
Using Regular Expressions in Database Applications
Oracle® Database Advanced Application Developer's Guide
11g Release 2 (11.2)
Part Number E25518-04
http://docs.oracle.com/cd/E11882_01/appdev.112/e25518/adfns_regexp.htm#ADFNS1003
Introducing Oracle Regular
Expressions
An Oracle White Paper
Author: Peter Linsley
http://www.oracle.com/technetwork/database/focus-areas/application-development/twp-regular-expressions-133133.pdf
Regular-Expressions.info
The Premier website about Regular Expressions
http://www.regular-expressions.info/

martes, 19 de noviembre de 2013

configuracion fstab /dev/shm

tmpfs                   /dev/shm                tmpfs   defaults,size=3G 0 0

martes, 5 de noviembre de 2013

CAMBIAR PASSWORD ASM

1. How to create asmsnmp user
——————————————-

First Check which all users are present for ASM >>

SQL> select * from v$pwfile_users;
no rows selected

OR

ASMCMD> lspwusr
Username sysdba sysoper sysasm 
This shows no user are present

A) Create a password file if not already present
$orapwd file=/u01/app/11.2.0/grid/dbs/orapw+ASM password=


++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Remember below important point about password file in ASM
If there are two nodes with +ASM1 running on node 1 and +ASM2 running on node2.
– Pre 11gR2 –
Password file on Node1: orapw+ASM1
Password file on Node2: orapw+ASM2
– 11gR2 –
Password file on Node1: orapw+ASM
Password file on Node2: orapw+ASM
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


B) Copy the password file to other nodes
$ scp orapw+ASM :/u01/app/11.2.0/grid/dbs/

copy the password files to other nodes if you have more than 2 nodes in the RAC.

C) create user and give sysdba privileges

SQL>create user asmsnmp identified by ;
SQL> grant sysdba to asmsnmp;


Check again for users in ASM  >>

SQL> select * from v$pwfile_users;
 
USERNAME              SYSDB                SYSOP             SYSAS
——————————————————————————————————————— —– —– —————————————————————————————————————–
SYS                    TRUE                TRUE                 TRUE
ASMSNMP                TRUE                FALSE                FALSE

SQL> show parameter pass
NAME                                   TYPE                            VALUE
———————————— —————————————————————————————– ——————————————————————————————————
remote_login_passwordfile             string                          EXCLUSIVE

The ASM instance parameter “REMOTE_LOGIN_PASSWORDFILE” has to be set to EXCLUSIVE or you will get an ORA-01999 error.

Also you can check  user detials from asmcmd

ASMCMD> lspwusr
Username        sysdba         sysoper       sysasm
SYS             TRUE           TRUE          FALSE
ASMSNMP         TRUE           FALSE         FALSE



How to Change password for ASMSNMP
——————————————————–
ASMCMD> lspwusr
Username  sysdba sysoper sysasm
SYS       TRUE   TRUE     TRUE
ASMSNMP   TRUE   FALSE    FALSE

ASMCMD> orapwusr --modify --password ASMSNMP
Enter password: *******
(give new password and press enter)
orapwusr attempts to update passwords on all nodes in a cluster. The command requires the SYSASM privilege to run. A user logged in as SYSDBA cannot change its password using this command.

Test new asmsnmp password >>
————————–
$ sqlplus asmsnmp/asmsnmp as sysdba
SQL*Plus: Release 11.2.0.3.0 Production on Wed Feb 6 12:57:30 2013
Copyright (c) 1982, 2011, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 – 64bit Production
With the Real Application Clusters and Automatic Storage Management options
SQL>