miércoles, 16 de julio de 2014

Visual Studio 2010 Express y Oracle Database

Un programa escirto en C++ y complicado en Visual Studio 2010 Express que se conecta a una base de datos Oracle. La infreaestructura

1.- Visual Studio 2010 Express

Ya que mi OS es un Windows 7 de 64 bit me permitio conocer que el Visual Studio 2010 Express crea por defecto solo ejecutables de 32 bit .

Pense, no hay problema uso las librerias de 32 bit, pero al ejecutar mi programa simpre obtenia el siguiente error:

0xc000007b

 En mi investigacion encontre lo siguiente:

"The error code means that the executable image header isn't good (for whatever reason). So... compiled 64 bits and try to run under 32 bits, or defective harddisk would be two possibilities"

"I think that you trying to use 64-bit DLL with 32-bit application (or vice versa)".

"Mainly these native errors are created due too using x32 bit libraries on x64 systems and vice versa or by not configuring your project settings correctly."

En forma de una equacion podria decir que:

 Windows7 (64-bit) + Visual Studio 2010 Express (32-bit) + OCI (32-bit) = 0xc000007b

Cambiar solo la version del OCI a 64-bit no cambio el resultado.

Windows7 (64-bit) + Visual Studio 2010 Express (32-bit) + OCI (64-bit) = 0xc000007b

Fue necesario alterar entonces la otra variable de nuestra equacion.

Compiling a 64-bit Application in Microsoft Visual Studio Express 2010  

Sin embargo, se presento otro error. La instalacion fallaba con el error:

Action start 10:38:35: INSTALL. Action start 10:38:35: DDSE_CA_Uninstall_InstallExecuteSequenceStarts_amd64. 07/16/14 10:38:35 DDSet_Status: LANGID: 1033 07/16/14 10:38:35 DDSet_Entry: ImmediateDispatch: DDSE_CA_Uninstall_InstallExecuteSequenceStarts entry 07/16/14 10:38:35 DDSet_Error: Patch Hooks: Missing required property 'ProductFamily': Setup cannot continue. 07/16/14 10:38:35 DDSet_Warning: Setup failed while calling 'getDLLName'. System error: Cannot create a file when that file already exists. 

Para esto la soucion fue desistalar toda las versiones superiores a 10.0.30319 del Microsoft Visual C++ 2010 x64 Redistributable

"Had a similar problem which turned out to be that the SDK 7.1 does NOT install if you have a newer vcredist_x86.exe than version 10.0.30319 of Visual C++ 2010 x86 Redistributable... I had 10.0.30419 installed... removed it through control panel "remove programs" and then the SDK 7.1 installed." 


Una vez solventado el tema del compilador nuestra ecuacion quedo de la siguiente forma, con un nuevo error:

Windows7 (64-bit) + Visual Studio 2010 Express (64-bit) + OCI (64-bit) = Exception: ORA-24960: the attribute OCI_ATTR_USERNAME is greater than the maxim um allowable length of 255

Para evitar inconsistencias con las librerias cambiela version del cliente OCI a de 12c a 11.2.0.4.
Oracle C++ Call Interface - Downloads

Pero apesar de esto el problema seguia siendo el mismo.

Windows7 (64-bit) + Visual Studio 2010 Express (64-bit) + OCI (64-bit) = Exception: ORA-24960: the attribute OCI_ATTR_USERNAME is greater than the maxim um allowable length of 255

Fue entonces cuando encontre este comenatrio:

carefully , if you are in debug model , use the oraocci10d.lib, not the oraocci10.lib

La soucion fue usar la libreria oraocci10d.lib ya que - segun lo que puedo entender ya que no sou expreto en VS2010- mi Visual Studio 2010 Express esta en modo Debug.

2.- El programa

#include "stdafx.h"
#include
#include  
using namespace std;

namespace oc = oracle::occi;

int main()
{
   try
   {
      // setup
      oc::Environment* env = oc::Environment::createEnvironment(); // 1
 oc::Connection* conn = env->createConnection("SYSTEM", "Oracle4U#", "TEMPFIN"); //2
      oc::Statement* stmt = conn->createStatement("select sysdate from dual"); // 3

      // execution
      oc::ResultSet* res = stmt->executeQuery(); // 4
      while(res->next()) // 5
         //std::cout << res->getString(1) << ' ' << res->getString(2) << ' ' << res->getInt(3) << std::endl;
 std::cout << res->getString(1)  << std::endl;

      // cleanup
      stmt->closeResultSet(res); // 6
      conn->terminateStatement(stmt);
      env->terminateConnection(conn);
      oc::Environment::terminateEnvironment(env);
   }
   catch(const oc::SQLException& e) // 7
   {
      std::cout << "Exception: " << e.what() << std::endl;
   }

   system("pause");
}

 El programa original lo puedes ecnontrar en este link.

3.- Configuracion del VS2010 Express

project -> properties -> C/C++ -> General -> C:\Users\pwjxm51\Downloads\oci11\64\instantclient_11_2\sdk\include; project -> properties -> Linker -> General -> C:\Users\pwjxm51\Downloads\oci11\64\instantclient_11_2\sdk\lib\msvc; C:\Users\pwjxm51\Downloads\oci11\64\instantclient_11_2\sdk\lib\msvc\vc9 project -> properties -> Linker -> Input -> oraocci11d.lib; project -> properties -> Debugging -> C:\Users\pwjxm51\Downloads\oci11\64\instantclient_11_2\sdk\lib\msvc\vc9 

 Finalmente todo funciono y el resultado fue: 

 C:\>Test1.exe 
16-JUL-14 Press any key to continue . . .

miércoles, 14 de mayo de 2014

C/C++ y Oracle Database

Un simple ejemplo de un programa escirto en C++ que se conecta a una base de datos Oracle.

#include <iostream>
#include <occi.h>

using namespace oracle::occi;
using namespace std;

int main()
{
  Environment *env;
  Connection *con;

  try
  {
    env = Environment::createEnvironment (Environment::DEFAULT);
    {
      con = env->createConnection ("user51","ora123");
      Statement *stmt = con->createStatement("SELECT * FROM DUAL");
      ResultSet *rs=stmt->executeQuery();
      rs->next();
      string empname=rs->getString(1);

      cout << "Hello Word! of C++ and Oracle database " << empname << endl;

      con->terminateStatement(stmt);
      env->terminateConnection (con);
    }
    Environment::terminateEnvironment(env);
  }
  catch (SQLException e)
  {
    cout << "Exception thrown" << endl;
    cout << "Error number: " << e.getErrorCode() << endl;
    cout << e.getMessage() << endl;
  }
  return 0;
}

Y aqui esta la forma de compilarlo.

g++ -I $ORACLE_HOME/rdbms/public -L $ORACLE_HOME/lib -lclntsh -locci helloword.cpp -o helloword.out

martes, 15 de abril de 2014

Flashback Data Archive (FBDA)

EL FBDA es un nuevo tipo de objecto que permite almacenar por largo tiempo la indormacion en la base de datos sin comprometer el espacio utilziado.

1) Creamos un tablespace especial para esta funcion.

SQL> create tablespace tbs1 datafile '+DATA2' size 10M;

Tablespace created.

2) Creamos el flashback archive asociandolo al tablespace que hemos designado para esta tarea.

SQL> create flashback archive fla1 tablespace tbs1 retention 5 MONTH;

Flashback archive created.

3) Esta funcionalidad puede ser utilizada en tablas nuevas o tablas que ya existan en nuestra base de datos.

SQL> alter table juanudo.test flashback archive fla1;

Table altered.

4) Iniciamos una serie de operaciones para mostrat la funcionalidad.

SQL> select count(*) from juanudo.test;

  COUNT(*)
----------
        14

SQL> insert into juanudo.test select * from juanudo.test;

14 rows created.

SQL> commit;

Commit complete.

SQL> select count(*) from juanudo.test;

  COUNT(*)
----------
        28

SQL> truncate table juanudo.test;

Table truncated.

SQL>  select count(*) from juanudo.test;

  COUNT(*)
----------
         0
         
SQL> select to_char(sysdate,'DD-MM-YY HH24:MI:SS') from dual;

TO_CHAR(SYSDATE,'
-----------------
15-04-14 08:12:48


SQL> select count(*) from juanudo.test as of timestamp to_timestamp(sysdate-1,'DD-MM-YY HH24:MI:SS');

  COUNT(*)
----------
        14

SQL> select count(*) from juanudo.test as of timestamp to_timestamp('15-04-14 08:12:48','DD-MM-YY HH24:MI:SS');

  COUNT(*)
----------
         0

SQL> select count(*) from juanudo.test as of timestamp to_timestamp('15-04-14 08:11:00','DD-MM-YY HH24:MI:SS');

  COUNT(*)
----------
        14


SQL> select count(*) from juanudo.test as of timestamp to_timestamp('15-04-14 08:11:38','DD-MM-YY HH24:MI:SS');

  COUNT(*)
----------
        28

SQL> insert into juanudo.test select * from juanudo.test as of timestamp to_timestamp('15-04-14 08:11:30','DD-MM-YY HH24:MI:SS');

14 rows created.

SQL> commit;


SQL> select * from dba_flashback_archive_tables

TABLE_NAME      OWNER_NAME                     FLASHBACK_ARCHI ARCHIVE_TABLE_NAME                                    STATUS
--------------- ------------------------------ --------------- ----------------------------------------------------- -------------
TEST            JUANUDO                        FLA1            SYS_FBA_HIST_82471                                    ENABLED

El objecto FBAD no puede ser modificado directamente

SQL> delete from JUANUDO.SYS_FBA_HIST_82471;
delete from JUANUDO.SYS_FBA_HIST_82471
                    *
ERROR at line 1:
ORA-55622: DML, ALTER and CREATE UNIQUE INDEX operations are not allowed on table "JUANUDO"."SYS_FBA_HIST_82471"


SQL> alter table JUANUDO.SYS_FBA_HIST_82471 add x char;
alter table JUANUDO.SYS_FBA_HIST_82471 add x char
*
ERROR at line 1:
ORA-55622: DML, ALTER and CREATE UNIQUE INDEX operations are not allowed on table "JUANUDO"."SYS_FBA_HIST_82471"

Es necesario desasociar el control de la base de datos sobre el objecto para poder modificarlo

SQL> EXEC DBMS_FLASHBACK_ARCHIVE.DISASSOCIATE_FBA('juanudo','test');

PL/SQL procedure successfully completed.

SQL> alter table JUANUDO.SYS_FBA_HIST_82471 add x char;

Table altered.

Si el FBDA sufre alguna modificacion resultando el objecto diferente a la estructura de la tabla original la base de datos no permite asociar el objevto.

SQL> EXEC DBMS_FLASHBACK_ARCHIVE.REASSOCIATE_FBA('juanudo','test');
BEGIN DBMS_FLASHBACK_ARCHIVE.REASSOCIATE_FBA('juanudo','test'); END;

*
ERROR at line 1:
ORA-55636: Flashback Data Archive enabled table "JUANUDO"."TEST" has different definition from its history table
ORA-06512: at "SYS.DBMS_FLASHBACK_ARCHIVE", line 17
ORA-06512: at line 1


SQL>  EXEC DBMS_FLASHBACK_ARCHIVE.DISASSOCIATE_FBA('juanudo','test');

PL/SQL procedure successfully completed.

Hay que igualar ambos objectos

SQL>  alter table JUANUDO.SYS_FBA_HIST_82471 drop column x;

Table altered.

SQL>  EXEC DBMS_FLASHBACK_ARCHIVE.REASSOCIATE_FBA('juanudo','test');

PL/SQL procedure successfully completed.

lunes, 14 de abril de 2014

Data Recovery Advisor - (ADR)


El ADR es una nueva funcionalidad de RMAN que permite, entre otras cosas, realizar operaciones de recovery de manera automática. Básicamente el ADR corresponde a estos nuevos comandos en RMAN:

LIST FAILURE
ADVISE FAILURE
REPAIR FAILURE
CHANGE FAILURE

Para este primer caso vemos como se usan los dos primeros comandos:

RMAN>  LIST FAILURE;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
402        HIGH     OPEN      03-DEC-13     Data file +DATA/orcl10/datafile/test.256.830614885 cannot be accessed because of an ASM Failure
302        HIGH     OPEN      04-NOV-13     Data file +DATA/orcl10/datafile/test.256.830614261 cannot be accessed because of an ASM Failure
262        HIGH     OPEN      04-NOV-13     Data file +DATA/orcl10/datafile/test.256.830613347 cannot be accessed because of an ASM Failure
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline
42         HIGH     OPEN      04-NOV-13     One or more non-system datafiles are missing

RMAN> ADVISE FAILURE;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
402        HIGH     OPEN      03-DEC-13     Data file +DATA/orcl10/datafile/test.256.830614885 cannot be accessed because of an ASM Failure
302        HIGH     OPEN      04-NOV-13     Data file +DATA/orcl10/datafile/test.256.830614261 cannot be accessed because of an ASM Failure
262        HIGH     OPEN      04-NOV-13     Data file +DATA/orcl10/datafile/test.256.830613347 cannot be accessed because of an ASM Failure
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline
42         HIGH     OPEN      04-NOV-13     One or more non-system datafiles are missing

analyzing automatic repair options; this may take some time
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=38 device type=DISK
analyzing automatic repair options complete

Not all specified failures can currently be repaired.
The following failures must be repaired before advise for others can be given.

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
402        HIGH     OPEN      03-DEC-13     Data file +DATA/orcl10/datafile/test.256.830614885 cannot be accessed because of an ASM Failure
302        HIGH     OPEN      04-NOV-13     Data file +DATA/orcl10/datafile/test.256.830614261 cannot be accessed because of an ASM Failure
262        HIGH     OPEN      04-NOV-13     Data file +DATA/orcl10/datafile/test.256.830613347 cannot be accessed because of an ASM Failure

Mandatory Manual Actions
========================
1. Ensure that ASM instance is up
2. Ensure that ASM disk group is mounted
3. Contact Oracle Support Services if the preceding recommendations cannot be used, or if they do not fix the failures selected for repair

Optional Manual Actions
=======================
no manual actions available

Automated Repair Options
========================
no automatic repair options available

RMAN> REPAIR FAILURE PREVIEW;

RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of repair command at 04/14/2014 08:46:22
RMAN-06953: no automatic repairs were listed by ADVISE FAILURE

Este error hace referencia a que no se ha encontrado ninguna opción para reparar. Por lo que por ahora solo probaremos la otra opción CHANGE para cerrar uno de los incidentes:


RMAN> change failure 402 closed;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
402        LOW      OPEN      03-DEC-13     Data file +DATA/orcl10/datafile/test.256.830614885 cannot be accessed because of an ASM Failure

Do you really want to change the above failures (enter YES or NO)? YES
closed 1 failures

Sin embargo, hay otras opciones que nos permite tomar acciones tempranas como validar tanto la base de datos como los backup generados por RMAN:

RMAN> validate database;

Starting validate at 14-APR-14
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=59 device type=DISK
channel ORA_DISK_1: starting validation of datafile
channel ORA_DISK_1: specifying datafile(s) for validation
input datafile file number=00001 name=/u02/app/oracle/oradata/orcl10/system01.dbf
input datafile file number=00006 name=+DATA1/orcl10/datafile/tbs_asm.256.840539557
input datafile file number=00002 name=/u02/app/oracle/oradata/orcl10/undotbs01.dbf
input datafile file number=00003 name=/u02/app/oracle/oradata/orcl10/sysaux01.dbf

channel ORA_DISK_1: validation complete, elapsed time: 00:07:56
List of Datafiles
=================
File Status Marked Corrupt Empty Blocks Blocks Examined High SCN
---- ------ -------------- ------------ --------------- ----------
1    OK     0              18126        96093           2181031
  File Name: /u02/app/oracle/oradata/orcl10/system01.dbf
  Block Type Blocks Failing Blocks Processed
  ---------- -------------- ----------------
  Data       0              58909
  Index      0              14760
  Other      0              4205

File Status Marked Corrupt Empty Blocks Blocks Examined High SCN
---- ------ -------------- ------------ --------------- ----------
2    OK     0              0            77440           2181062
  File Name: /u02/app/oracle/oradata/orcl10/undotbs01.dbf
  Block Type Blocks Failing Blocks Processed
  ---------- -------------- ----------------
  Data       0              0
  Index      0              0
  Other      0              77440

File Status Marked Corrupt Empty Blocks Blocks Examined High SCN
---- ------ -------------- ------------ --------------- ----------
3    OK     0              22986        64080           2181298
  File Name: /u02/app/oracle/oradata/orcl10/sysaux01.dbf
  Block Type Blocks Failing Blocks Processed
  ---------- -------------- ----------------
  Data       0              10378
  Index      0              7906
  Other      0              22730

File Status Marked Corrupt Empty Blocks Blocks Examined High SCN
---- ------ -------------- ------------ --------------- ----------
6    OK     0              1150         1280            2081262
  File Name: +DATA1/orcl10/datafile/tbs_asm.256.840539557
  Block Type Blocks Failing Blocks Processed
  ---------- -------------- ----------------
  Data       0              0
  Index      0              0
  Other      0              130

channel ORA_DISK_1: starting validation of datafile
channel ORA_DISK_1: specifying datafile(s) for validation
input datafile file number=00004 name=/u02/app/oracle/oradata/orcl10/users01.dbf
channel ORA_DISK_1: validation complete, elapsed time: 00:00:03
List of Datafiles
=================
File Status Marked Corrupt Empty Blocks Blocks Examined High SCN
---- ------ -------------- ------------ --------------- ----------
4    OK     0              8904         12640           2134137
  File Name: /u02/app/oracle/oradata/orcl10/users01.dbf
  Block Type Blocks Failing Blocks Processed
  ---------- -------------- ----------------
  Data       0              2452
  Index      0              1025
  Other      0              259

channel ORA_DISK_1: starting validation of datafile
channel ORA_DISK_1: specifying datafile(s) for validation
including current control file for validation
including current SPFILE in backup set
channel ORA_DISK_1: validation complete, elapsed time: 00:00:01
List of Control File and SPFILE
===============================
File Type    Status Blocks Failing Blocks Examined
------------ ------ -------------- ---------------
SPFILE       OK     0              2
Control File OK     0              624
Finished validate at 14-APR-14

Para este primer ejercicio vamos a simular la pérdida de un datafile:


1) Primero debemos estar plenamente seguros de que contamos con el backup adecuado.

RMAN> backup tablespace users;

Starting backup at 14-APR-14
using channel ORA_DISK_1
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00004 name=/u02/app/oracle/oradata/orcl10/users01.dbf
channel ORA_DISK_1: starting piece 1 at 14-APR-14
channel ORA_DISK_1: finished piece 1 at 14-APR-14
piece handle=/u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1 tag=TAG20140414T091547 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:01
Finished backup at 14-APR-14

Starting Control File and SPFILE Autobackup at 14-APR-14
piece handle=/u01/app/oracle/product/11.2.0.2/dbs/c-4037562677-20140414-01 comment=NONE
Finished Control File and SPFILE Autobackup at 14-APR-14

RMAN> shutdown immediate

database closed
database dismounted
Oracle instance shut down

RMAN> exit

2) Simulamos la pérdida del datafile

Recovery Manager complete.
[ora11@nodo1 ~]$ mv /u02/app/oracle/oradata/orcl10/users01.dbf /u02/app/oracle/oradata/orcl10/users01.old
[ora11@nodo1 ~]$ rman target /

Recovery Manager: Release 11.2.0.2.0 - Production on Mon Apr 14 09:16:42 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database (not started)

RMAN> startup

Oracle instance started
database mounted
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of startup command at 04/14/2014 09:17:01
ORA-01157: cannot identify/lock data file 4 - see DBWR trace file
ORA-01110: data file 4: '/u02/app/oracle/oradata/orcl10/users01.dbf'

3) En este caso empezamos a usar la nueva funcionalidad del RMAN (ADR):

RMAN> list failure;

using target database control file instead of recovery catalog
List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
42         HIGH     OPEN      04-NOV-13     One or more non-system datafiles are missing
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

RMAN> advise failure;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
42         HIGH     OPEN      04-NOV-13     One or more non-system datafiles are missing
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

analyzing automatic repair options; this may take some time
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=22 device type=DISK
analyzing automatic repair options complete

Mandatory Manual Actions
========================
no manual actions available

Optional Manual Actions
=======================
1. If file /u02/app/oracle/oradata/orcl10/users01.dbf was unintentionally renamed or moved, restore it
2. An automatic repair was generated for some of the failures selected for repair.  A database state change is required to repair the following failures.
3. Open the database to validate and get repair advice for failure 137: Datafile 7: '+DGNM11GASM/orcl10/datafile/test.257.830609941' is offline

Automated Repair Options
========================
Option Repair Description
------ ------------------
1      Restore and recover datafile 4
  Strategy: The repair includes complete media recovery with no data loss
  Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_2930074363.hm

La opcion de preview nos permite conocer los scripts que se van a ejecutar:

RMAN> REPAIR FAILURE PREVIEW;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_2930074363.hm

contents of repair script:
   # restore and recover datafile
   restore datafile 4;
   recover datafile 4;
   sql 'alter database datafile 4 online';

RMAN> REPAIR FAILURE;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_2930074363.hm

contents of repair script:
   # restore and recover datafile
   restore datafile 4;
   recover datafile 4;
   sql 'alter database datafile 4 online';

Do you really want to execute the above repair (enter YES or NO)? YES
executing repair script

Starting restore at 14-APR-14
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00004 to /u02/app/oracle/oradata/orcl10/users01.dbf
channel ORA_DISK_1: reading from backup piece /u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1
channel ORA_DISK_1: piece handle=/u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1 tag=TAG20140414T091547
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:01
Finished restore at 14-APR-14

Starting recover at 14-APR-14
using channel ORA_DISK_1

starting media recovery
media recovery complete, elapsed time: 00:00:00

Finished recover at 14-APR-14

sql statement: alter database datafile 4 online
repair failure complete

RMAN> shutdown immediate

database dismounted
Oracle instance shut down

RMAN> startup

connected to target database (not started)
Oracle instance started
database mounted
database opened

Total System Global Area     431038464 bytes

Fixed Size                     1344672 bytes
Variable Size                322964320 bytes
Database Buffers             100663296 bytes
Redo Buffers                   6066176 bytes

Para el segundo caso veremos como funciona esta nueva caracteristica para el caso de la corrupcion en un bloque de datos pertenecioentes a una tabla.

1) Identificamos el segmento con el que vamos a trabajar.

SQL>  select header_file, header_block from dba_segments where segment_name='EMP' and owner='SCOTT';

HEADER_FILE HEADER_BLOCK
----------- ------------
          6          131

2) Da#amos el segmento con el comando dd

[ora11@nodo1 ~]$ dd of=/u02/app/oracle/oradata/orcl10/users01.dbf bs=8192 conv=notrunc seek=131 << EOF
> CORRUPT corrupt CORRUPT corrupt CORRUPT corrupt CORRUPT corrupt CORRUPT CORRUPT CORRUPT CORRUPT corrupt corrupt
> EOF
0+1 records in
0+1 records out
112 bytes (112 B) copied, 0.000127676 seconds, 877 kB/s

3) Detenemos la base de datos

SQL> shutdown immediate
ORA-01122: database file 4 failed verification check
ORA-01110: data file 4: '/u02/app/oracle/oradata/orcl10/users01.dbf'
ORA-01210: data file header is media corrupt


4) Iniciamos la operaciones de recovery

[ora11@nodo1 ~]$ rman target /

Recovery Manager: Release 11.2.0.2.0 - Production on Mon Apr 14 09:43:37 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database (not started)

RMAN> startup

Oracle instance started
database mounted
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of startup command at 04/14/2014 09:43:52
ORA-01157: cannot identify/lock data file 4 - see DBWR trace file
ORA-01110: data file 4: '/u02/app/oracle/oradata/orcl10/users01.dbf'

RMAN> list failure;

using target database control file instead of recovery catalog
List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
11725      HIGH     OPEN      14-APR-14     One or more non-system datafiles are corrupt
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

RMAN> advise failure;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
11725      HIGH     OPEN      14-APR-14     One or more non-system datafiles are corrupt
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

analyzing automatic repair options; this may take some time
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=18 device type=DISK
analyzing automatic repair options complete

Mandatory Manual Actions
========================
no manual actions available

Optional Manual Actions
=======================
1. An automatic repair was generated for some of the failures selected for repair.  A database state change is required to repair the following failures.
2. Open the database to validate and get repair advice for failure 137: Datafile 7: '+DGNM11GASM/orcl10/datafile/test.257.830609941' is offline

Automated Repair Options
========================
Option Repair Description
------ ------------------
1      Restore and recover datafile 4
  Strategy: The repair includes complete media recovery with no data loss
  Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_38285761.hm

RMAN> repair failure;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_38285761.hm

contents of repair script:
   # restore and recover datafile
   restore datafile 4;
   recover datafile 4;
   sql 'alter database datafile 4 online';

Do you really want to execute the above repair (enter YES or NO)? YES
executing repair script

Starting restore at 14-APR-14
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00004 to /u02/app/oracle/oradata/orcl10/users01.dbf
channel ORA_DISK_1: reading from backup piece /u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1
channel ORA_DISK_1: piece handle=/u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1 tag=TAG20140414T091547
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:03
Finished restore at 14-APR-14

Starting recover at 14-APR-14
using channel ORA_DISK_1

starting media recovery
media recovery complete, elapsed time: 00:00:00

Finished recover at 14-APR-14

sql statement: alter database datafile 4 online
repair failure complete

RMAN> exit

Una vez termina la operacion, es necesario "abrir" la base de datos.

[ora11@nodo1 ~]$ sqlplus "/as sysdba"

SQL*Plus: Release 11.2.0.2.0 Production on Mon Apr 14 09:44:30 2014

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


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

SQL> select * from SCOTT.EMP;
select * from SCOTT.EMP
                         *
ERROR at line 1:
ORA-01219: database not open: queries allowed on fixed tables/views only


SQL> alter database open;

Database altered.

SQL> select * from SCOTT.EMP;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
      7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
      7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
      7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
      7839 KING       PRESIDENT            17-NOV-81       5000                    10
      7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
      7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
      7900 JAMES      CLERK           7698 03-DEC-81        950                    30
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
      7934 MILLER     CLERK           7782 23-JAN-82       1300                    10

Pero este ejmeplo solo es posible porque se reinicio la base de datos, vemos un ejemplo donde no la reiniciamos.

1) Identificamos el segmento con el que vamos a trabajar.

SQL>  select header_file, header_block from dba_segments where segment_name='EMP' and owner='SCOTT';

HEADER_FILE HEADER_BLOCK
----------- ------------
          6          131

2) Da#amos el segmento con el comando dd

[ora11@nodo1 ~]$ dd of=/u02/app/oracle/oradata/orcl10/users01.dbf bs=8192 conv=notrunc seek=131 << EOF
> CORRUPT corrupt CORRUPT corrupt CORRUPT corrupt CORRUPT corrupt CORRUPT CORRUPT CORRUPT CORRUPT corrupt corrupt
> EOF
0+1 records in
0+1 records out
112 bytes (112 B) copied, 0.000127676 seconds, 877 kB/s

3) Vaciamos la memoria de la base de datos

SQL> alter system flush shared_pool;

System altered.

SQL>  alter system flush buffer_cache;

System altered.

SQL> select * from SCOTT.EMP;
select * from SCOTT.EMP
                    *
ERROR at line 1:
ORA-01578: ORACLE data block corrupted (file # 4, block # 27)
ORA-01110: data file 4: '/u02/app/oracle/oradata/orcl10/users01.dbf'

4) Iniciamos la operacion de recovery

RMAN> list failure;

using target database control file instead of recovery catalog
List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
11852      HIGH     OPEN      14-APR-14     Datafile 4: '/u02/app/oracle/oradata/orcl10/users01.dbf' contains one or more corrupt blocks
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

RMAN> advise failure;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
11852      HIGH     OPEN      14-APR-14     Datafile 4: '/u02/app/oracle/oradata/orcl10/users01.dbf' contains one or more corrupt blocks
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

analyzing automatic repair options; this may take some time
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=49 device type=DISK
analyzing automatic repair options complete

Mandatory Manual Actions
========================
1. Please contact Oracle Support Services to resolve failure 137: Datafile 7: '+DGNM11GASM/orcl10/datafile/test.257.830609941' is offline

Optional Manual Actions
=======================
no manual actions available

Automated Repair Options
========================
Option Repair Description
------ ------------------
1      Recover multiple corrupt blocks in datafile 4
  Strategy: The repair includes complete media recovery with no data loss
  Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_1411271822.hm

RMAN> repair failure;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_1411271822.hm

contents of repair script:
   # block media recovery for multiple blocks
   recover datafile 4 block 131;

Do you really want to execute the above repair (enter YES or NO)? YES
executing repair script

Starting recover at 14-APR-14
using channel ORA_DISK_1

channel ORA_DISK_1: restoring block(s)
channel ORA_DISK_1: specifying block(s) to restore from backup set
restoring blocks of datafile 00004
channel ORA_DISK_1: reading from backup piece /u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1
channel ORA_DISK_1: piece handle=/u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1 tag=TAG20140414T091547
channel ORA_DISK_1: restored block(s) from backup piece 1
channel ORA_DISK_1: block restore complete, elapsed time: 00:00:01

starting media recovery
media recovery complete, elapsed time: 00:00:01

Finished recover at 14-APR-14
repair failure complete

RMAN> exit


Recovery Manager complete.

5) Verificamos que la tabla exista

[ora11@nodo1 ~]$ sqlplus "/as sysdba"

SQL*Plus: Release 11.2.0.2.0 Production on Mon Apr 14 09:44:30 2014

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


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

SQL> select * from SCOTT.EMP;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
      7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
      7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
      7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
      7839 KING       PRESIDENT            17-NOV-81       5000                    10
      7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
      7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
      7900 JAMES      CLERK           7698 03-DEC-81        950                    30
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
      7934 MILLER     CLERK           7782 23-JAN-82       1300                    10
      
Una forma interesante de valida el o los datafiles donde resice la tabla es con el uso del comando dbv

En el caso de del datafile users01.dbf este seria la salida cada vez que ada#amos el segmento EMP

[ora11@nodo1 ~]$ dbv file=/u02/app/oracle/oradata/orcl10/users01.dbf

DBVERIFY: Release 11.2.0.2.0 - Production on Mon Apr 14 10:03:35 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

DBVERIFY - Verification starting : FILE = /u02/app/oracle/oradata/orcl10/users01.dbf
Page 131 is marked corrupt
Corrupt block relative dba: 0x0100001b (file 4, block 131)
Bad header found during dbv:
Data in bad block:
 type: 67 format: 7 rdba: 0x0a545055
 last change scn: 0x000a.3b464f45 seq: 0x3 flg: 0x04
 spare1: 0x52 spare2: 0x52 spare3: 0x0
 consistency value in tail: 0xccf42303
 check value in block header: 0x62fd
 computed block checksum: 0x5cd0

DBVERIFY - Verification complete

Total Pages Examined         : 12640
Total Pages Processed (Data) : 2383
Total Pages Failing   (Data) : 0
Total Pages Processed (Index): 1025
Total Pages Failing   (Index): 0
Total Pages Processed (Other): 6207
Total Pages Processed (Seg)  : 0
Total Pages Failing   (Seg)  : 0
Total Pages Empty            : 3024
Total Pages Marked Corrupt   : 1
Total Pages Influx           : 0
Total Pages Encrypted        : 0
Highest block SCN            : 2134137 (0.2134137)

Otra forma de saber sie xisten segmentos corructos es con la vista v$database_block_corruption;

Nuevamente, al momento de da#ar el datafile 

SQL>  select * from SCOTT.EMP;
 select * from SCOTT.EMP
                     *
ERROR at line 1:
ORA-01578: ORACLE data block corrupted (file # 4, block # 27)
ORA-01110: data file 4: '/u02/app/oracle/oradata/orcl10/users01.dbf'

Podemos usar la vista

SQL> select * from v$database_block_corruption;

     FILE#     BLOCK#     BLOCKS CORRUPTION_CHANGE# CORRUPTIO
---------- ---------- ---------- ------------------ ---------
         4         131          1                  0 CORRUPT


Pero todo esto ejemplo se ejecuto sobre un datafile "nomral" cual es el esenario para un datafile en ASM?

Para ello creamos una copia de la table que inicialmente usamos en una nueva table que recide en un tablespace con datafiles en ASM

SQL> create table juanudo.test tablespace TBS_ASM as select * from scott.emp;

Table created.

SQL>  select segment_name from dba_segments where tablespace_name='TBS_ASM';

SEGMENT_NAME
---------------------------------------------------------------------------------
TEST

SQL> select header_file, header_block from dba_segments where segment_name='TEST' and owner='JUANUDO';

HEADER_FILE HEADER_BLOCK
----------- ------------
          6          130

SQL> select * from JUANUDO.TEST;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
      7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
      7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
      7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
      7839 KING       PRESIDENT            17-NOV-81       5000                    10
      7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
      7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
      7900 JAMES      CLERK           7698 03-DEC-81        950                    30
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
      7934 MILLER     CLERK           7782 23-JAN-82       1300                    10

Verificamos donde esta nuestro nuevo segmento

SQL> select header_file, header_block from dba_segments where segment_name='TEST' and owner='JUANUDO';

HEADER_FILE HEADER_BLOCK
----------- ------------
          6          138
          
Intentamos da#ar el segmento como en el ejemplo anterior

[ora11@nodo1 ~]$ dd of=+DATA1/orcl10/datafile/tbs_asm.256.840539557 bs=8192 conv=notrunc seek=138 << EOF
> CORRUPT
> EOF
dd: opening `+DATA1/orcl10/datafile/tbs_asm.256.840539557': No such file or directory

Pero esta vez, ya que el datafile esta en ASM no podemos acceder a el directamente con el commando dd

Para esto hay que relizar algunas operaciones con el RMAN

1) Sacar del ASM una copia del (o los) datafiles asociados al tablespace

[ora11@nodo1 ~]$ rman target /

Recovery Manager: Release 11.2.0.2.0 - Production on Mon Apr 14 11:00:23 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: ORCL10 (DBID=4037562677)

RMAN> BACKUP AS COPY DATAFILE 6 FORMAT '/home/ora11/asm%f';

Starting backup at 14-APR-14
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=45 device type=DISK
channel ORA_DISK_1: starting datafile copy
input datafile file number=00006 name=+DATA1/orcl10/datafile/tbs_asm.256.840539557
output file name=/home/ora11/asm6 tag=TAG20140414T110100 RECID=1 STAMP=844858862
channel ORA_DISK_1: datafile copy complete, elapsed time: 00:00:01
Finished backup at 14-APR-14

Starting Control File and SPFILE Autobackup at 14-APR-14
piece handle=/u01/app/oracle/product/11.2.0.2/dbs/c-4037562677-20140414-06 comment=NONE
Finished Control File and SPFILE Autobackup at 14-APR-14

RMAN> exit

Recovery Manager complete.
[ora11@nodo1 ~]$ pwd
/home/ora11
[ora11@nodo1 ~]$ ls -lrt
total 30748
drwxr-x--- 3 ora11 oinstall     4096 Oct 21 09:32 oradiag_ora11
-rw-r--r-- 1 ora11 oinstall       92 Oct 21 14:48 dbua.log
drwxr-xr-x 2 ora11 oinstall     4096 Oct 22 08:12 Desktop
-rw-r--r-- 1 ora11 oinstall 20879989 Oct 22 09:08 upgrade.log
-rw-r----- 1 ora11 oinstall    21125 Oct 23 11:16 sqlnet.log
-rw-r--r-- 1 ora11 oinstall    12138 Nov  4 13:50 asm_data_backup
-rw-r--r-- 1 ora11 oinstall    12138 Nov  4 13:57 asm_data_backup2
drwxr-xr-x 4 ora11 oinstall     4096 Dec  4 10:31 test_capture
drwxr-xr-x 9 ora11 oinstall     4096 Dec  4 11:21 replay_capture
-rw-r----- 1 ora11 dba      10493952 Apr 14 11:01 asm6

Da#amos el segmento de la table en la copia

[ora11@nodo1 ~]$ dd of=asm6 bs=8192 conv=notrunc seek=138 << EOF
> CORRUPT
> EOF
0+1 records in
0+1 records out
8 bytes (8 B) copied, 0.000919285 seconds, 8.7 kB/s

Utilizamos el dbv para asegurarnos de que el segmento esta da#ado


[ora11@nodo1 ~]$ dbv file=/home/ora11/asm6 USERID=sys/oracle

DBVERIFY: Release 11.2.0.2.0 - Production on Mon Apr 14 11:03:22 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

DBVERIFY - Verification starting : FILE = /home/ora11/asm6
Page 138 is marked corrupt
Corrupt block relative dba: 0x0180008a (file 6, block 138)
Bad header found during dbv:
Data in bad block:
 type: 67 format: 7 rdba: 0x0a545055
 last change scn: 0x0000.002200f4 seq: 0x1 flg: 0x04
 spare1: 0x52 spare2: 0x52 spare3: 0x0
 consistency value in tail: 0x00f42301
 check value in block header: 0xe98f
 computed block checksum: 0xe439



DBVERIFY - Verification complete

Total Pages Examined         : 1280
Total Pages Processed (Data) : 2
Total Pages Failing   (Data) : 0
Total Pages Processed (Index): 0
Total Pages Failing   (Index): 0
Total Pages Processed (Other): 131
Total Pages Processed (Seg)  : 1
Total Pages Failing   (Seg)  : 0
Total Pages Empty            : 1145
Total Pages Marked Corrupt   : 1
Total Pages Influx           : 0
Total Pages Encrypted        : 0
Highest block SCN            : 2228582 (0.2228582)

Colocamos el datafile en modo offline y realizamos un proceso de restore y recover desde la copia que da#amos

SQL> alter database datafile 6 offline;

Database altered.

SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options
[ora11@nodo1 ~]$ rman target /

Recovery Manager: Release 11.2.0.2.0 - Production on Mon Apr 14 11:03:46 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: ORCL10 (DBID=4037562677)

RMAN> RUN
{
SET MAXCORRUPT FOR DATAFILE 6 TO 2;
RESTORE DATAFILE 6 FROM TAG 'TAG20140414T110100';
RECOVER DATAFILE 6;
}2> 3> 4> 5> 6>

executing command: SET MAX CORRUPT
using target database control file instead of recovery catalog

Starting restore at 14-APR-14
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=47 device type=DISK

channel ORA_DISK_1: restoring datafile 00006
input datafile copy RECID=1 STAMP=844858862 file name=/home/ora11/asm6
destination for restore of datafile 00006: +DATA1/orcl10/datafile/tbs_asm.256.840539557
channel ORA_DISK_1: copied datafile copy of datafile 00006
output file name=+DATA1/orcl10/datafile/tbs_asm.256.840539557 RECID=0 STAMP=0
Finished restore at 14-APR-14

Starting recover at 14-APR-14
using channel ORA_DISK_1

starting media recovery
media recovery complete, elapsed time: 00:00:01

Finished recover at 14-APR-14

RMAN> sql ' alter database datafile 6 online';

sql statement:  alter database datafile 6 online

RMAN> exit

Verificamos si nustro segmento de prueba esta da#ando

SQL> select * from v$database_block_corruption;

     FILE#     BLOCK#     BLOCKS CORRUPTION_CHANGE# CORRUPTIO
---------- ---------- ---------- ------------------ ---------
         6        138          1                  0 CORRUPT

Y comprovamos que el datafile 6 esta en ASM

select file_id,file_name from dba_data_files

   FILE_ID FILE_NAME
---------- --------------------------------------------------
         4 /u02/app/oracle/oradata/orcl10/users01.dbf
         3 /u02/app/oracle/oradata/orcl10/sysaux01.dbf
         2 /u02/app/oracle/oradata/orcl10/undotbs01.dbf
         1 /u02/app/oracle/oradata/orcl10/system01.dbf
         6 +DATA1/orcl10/datafile/tbs_asm.256.840539557
         
Posterior a esto, el procedimiento basicamente es el mismo


1) Tratamos de acceder a la tabla:

SQL> select * from juanudo.test;
select * from juanudo.test
                      *
ERROR at line 1:
ORA-01578: ORACLE data block corrupted (file # 6, block # 138)
ORA-01110: data file 6: '+DATA1/orcl10/datafile/tbs_asm.256.840539557'

2) Iniciamos el proceso de recover y resotre con el ADR

SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options
[ora11@nodo1 ~]$ rman target /

Recovery Manager: Release 11.2.0.2.0 - Production on Mon Apr 14 11:08:57 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database: ORCL10 (DBID=4037562677)

RMAN> list failure;

using target database control file instead of recovery catalog
List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
12187      HIGH     OPEN      14-APR-14     Datafile 6: '+DATA1/orcl10/datafile/tbs_asm.256.840539557' contains one or more corrupt blocks
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

RMAN> advise failure;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
12187      HIGH     OPEN      14-APR-14     Datafile 6: '+DATA1/orcl10/datafile/tbs_asm.256.840539557' contains one or more corrupt blocks
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

analyzing automatic repair options; this may take some time
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=47 device type=DISK
analyzing automatic repair options complete

Mandatory Manual Actions
========================
1. Please contact Oracle Support Services to resolve failure 137: Datafile 7: '+DGNM11GASM/orcl10/datafile/test.257.830609941' is offline

Optional Manual Actions
=======================
no manual actions available

Automated Repair Options
========================
Option Repair Description
------ ------------------
1      Perform block media recovery of block 138 in file 6
  Strategy: The repair includes complete media recovery with no data loss
  Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_1120464266.hm

RMAN> repaire failure preview;

RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-00558: error encountered while parsing input commands
RMAN-01009: syntax error: found "identifier": expecting one of: "advise, allocate, alter, backup, @, catalog, change, configure, connect, convert, copy, create, crosscheck, delete, drop, duplicate, exit, flashback, grant, host, import, list, mount, open, print, quit, recover, register, release, repair, replace, report, reset, restore, resync, revoke, run, send, set, show, shutdown, spool, sql, startup, switch, transport, unregister, upgrade, validate, {, "
RMAN-01008: the bad identifier was: repaire
RMAN-01007: at line 1 column 1 file: standard input

RMAN> repair failure preview;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_1120464266.hm

contents of repair script:
   # block media recovery
   recover datafile 6 block 138;

RMAN> list faiulre;

Pero esta vez no vamos a reparar el segmento, solo utilizamos la opcion preview para validar los comandos de RMAN que el ADR va a utlizar.


Una vez que ya tenemos dos ejercicios, la perdida de un datafile y la corrupcion de un segemto, que pasa si esos dos escenarios se dan simulteneamente?


1) Nuevamente da#amos el datafile

[ora11@nodo1 ~]$ mv /u02/app/oracle/oradata/orcl10/users01.dbf /u02/app/oracle/oradata/orcl10/users01.old
[ora11@nodo1 ~]$ exit
exit

2) Reiniciamos la base de datos

SQL> shutdown abort
ORACLE instance shut down.
SQL> exit
Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - Production
With the Partitioning, Automatic Storage Management, OLAP, Data Mining
and Real Application Testing options

3) Nos conectamos en el RMAN

[ora11@nodo1 ~]$ rman target /

Recovery Manager: Release 11.2.0.2.0 - Production on Mon Apr 14 11:10:55 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

connected to target database (not started)

RMAN> startup

Oracle instance started
database mounted
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of startup command at 04/14/2014 11:11:10
ORA-01157: cannot identify/lock data file 4 - see DBWR trace file
ORA-01110: data file 4: '/u02/app/oracle/oradata/orcl10/users01.dbf'

RMAN> list failure;

using target database control file instead of recovery catalog
List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
42         HIGH     OPEN      14-APR-14     One or more non-system datafiles are missing
12187      HIGH     OPEN      14-APR-14     Datafile 6: '+DATA1/orcl10/datafile/tbs_asm.256.840539557' contains one or more corrupt blocks
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

RMAN> advise failure;

List of Database Failures
=========================

Failure ID Priority Status    Time Detected Summary
---------- -------- --------- ------------- -------
42         HIGH     OPEN      14-APR-14     One or more non-system datafiles are missing
12187      HIGH     OPEN      14-APR-14     Datafile 6: '+DATA1/orcl10/datafile/tbs_asm.256.840539557' contains one or more corrupt blocks
122        HIGH     OPEN      04-NOV-13     One or more non-system datafiles are offline

analyzing automatic repair options; this may take some time
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=19 device type=DISK
analyzing automatic repair options complete

Mandatory Manual Actions
========================
no manual actions available

Optional Manual Actions
=======================
1. If file /u02/app/oracle/oradata/orcl10/users01.dbf was unintentionally renamed or moved, restore it
2. An automatic repair was generated for some of the failures selected for repair.  A database state change is required to repair the following failures.
3. Open the database to validate and get repair advice for failure 137: Datafile 7: '+DGNM11GASM/orcl10/datafile/test.257.830609941' is offline

Automated Repair Options
========================
Option Repair Description
------ ------------------
1      Restore and recover datafile 4; Perform block media recovery of block 138 in file 6
  Strategy: The repair includes complete media recovery with no data loss
  Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_2211559917.hm

RMAN> repair failure preview;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_2211559917.hm

contents of repair script:
   # restore and recover datafile
   restore datafile 4;
   recover datafile 4;
   sql 'alter database datafile 4 online';
   # block media recovery
   recover datafile 6 block 138;

Para este casi el ADR muestra los dos operaciones que tiene que relaizar el RMAN para reparar el segmento da#ado y el datafile perdido, ordenado las operaciones con mayor importancia para que
la base de datos pueda estar disponible.

RMAN> repair failure;

Strategy: The repair includes complete media recovery with no data loss
Repair script: /u01/app/oracle/diag/rdbms/orcl10/orcl10/hm/reco_2211559917.hm

contents of repair script:
   # restore and recover datafile
   restore datafile 4;
   recover datafile 4;
   sql 'alter database datafile 4 online';
   # block media recovery
   recover datafile 6 block 138;

Do you really want to execute the above repair (enter YES or NO)? YES
executing repair script

Starting restore at 14-APR-14
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00004 to /u02/app/oracle/oradata/orcl10/users01.dbf
channel ORA_DISK_1: reading from backup piece /u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1
channel ORA_DISK_1: piece handle=/u01/app/oracle/product/11.2.0.2/dbs/0ep5mra4_1_1 tag=TAG20140414T091547
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:03
Finished restore at 14-APR-14

Starting recover at 14-APR-14
using channel ORA_DISK_1

starting media recovery

archived log for thread 1 with sequence 178 is already on disk as file /u01/app/oracle/product/11.2.0.2/dbs/arch1_178_829568439.dbf
archived log for thread 1 with sequence 179 is already on disk as file /u01/app/oracle/product/11.2.0.2/dbs/arch1_179_829568439.dbf
archived log for thread 1 with sequence 180 is already on disk as file /u01/app/oracle/product/11.2.0.2/dbs/arch1_180_829568439.dbf
archived log for thread 1 with sequence 181 is already on disk as file /u01/app/oracle/product/11.2.0.2/dbs/arch1_181_829568439.dbf
archived log for thread 1 with sequence 182 is already on disk as file /u01/app/oracle/product/11.2.0.2/dbs/arch1_182_829568439.dbf
archived log for thread 1 with sequence 183 is already on disk as file /u01/app/oracle/product/11.2.0.2/dbs/arch1_183_829568439.dbf
archived log file name=/u01/app/oracle/product/11.2.0.2/dbs/arch1_178_829568439.dbf thread=1 sequence=178
archived log file name=/u01/app/oracle/product/11.2.0.2/dbs/arch1_179_829568439.dbf thread=1 sequence=179
archived log file name=/u01/app/oracle/product/11.2.0.2/dbs/arch1_180_829568439.dbf thread=1 sequence=180
archived log file name=/u01/app/oracle/product/11.2.0.2/dbs/arch1_181_829568439.dbf thread=1 sequence=181
media recovery complete, elapsed time: 00:00:00
Finished recover at 14-APR-14

sql statement: alter database datafile 4 online

Starting recover at 14-APR-14
using channel ORA_DISK_1

channel ORA_DISK_1: restoring block(s) from datafile copy /home/ora11/asm6
failover to previous backup

channel ORA_DISK_1: restoring block(s)
channel ORA_DISK_1: specifying block(s) to restore from backup set
restoring blocks of datafile 00006
channel ORA_DISK_1: reading from backup piece /u01/app/oracle/product/11.2.0.2/dbs/12p5mvvc_1_1
channel ORA_DISK_1: piece handle=/u01/app/oracle/product/11.2.0.2/dbs/12p5mvvc_1_1 tag=TAG20140414T103524
channel ORA_DISK_1: restored block(s) from backup piece 1
channel ORA_DISK_1: block restore complete, elapsed time: 00:00:00

starting media recovery
media recovery complete, elapsed time: 00:00:01

Finished recover at 14-APR-14
repair failure complete

Finalmente abrimos la base de datos

RMAN> alter database open;

database opened

RMAN> exit

Y verificams del SQL*Plus la tabla que recide en el tablespace de ASM

SQL> select * from JUANUDO.TEST;

     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
      7654 MARTIN     SALESMAN        7698 28-SEP-81       1250       1400         30
      7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    30
      7782 CLARK      MANAGER         7839 09-JUN-81       2450                    10
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    20
      7839 KING       PRESIDENT            17-NOV-81       5000                    10
      7844 TURNER     SALESMAN        7698 08-SEP-81       1500          0         30
      7876 ADAMS      CLERK           7788 23-MAY-87       1100                    20
      7900 JAMES      CLERK           7698 03-DEC-81        950                    30
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    20
      7934 MILLER     CLERK           7782 23-JAN-82       1300                    10


NOTA: Aun que no podemos acceder al datafile ASM directamente con el comando dd si podemos usar el commando dbv sobre datafiles ASM

[ora11@nodo1 ~]$ dbv file=+DATA1/orcl10/datafile/tbs_asm.256.840539557 USERID=sys/oracle

DBVERIFY: Release 11.2.0.2.0 - Production on Mon Apr 14 10:41:22 2014

Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

DBVERIFY - Verification starting : FILE = +DATA1/orcl10/datafile/tbs_asm.256.840539557


DBVERIFY - Verification complete

Total Pages Examined         : 1280
Total Pages Processed (Data) : 2
Total Pages Failing   (Data) : 0
Total Pages Processed (Index): 0
Total Pages Failing   (Index): 0
Total Pages Processed (Other): 133
Total Pages Processed (Seg)  : 0
Total Pages Failing   (Seg)  : 0
Total Pages Empty            : 1145
Total Pages Marked Corrupt   : 0
Total Pages Influx           : 0
Total Pages Encrypted        : 0
Highest block SCN            : 0 (0.0)