viernes, 25 de septiembre de 2015

Creating Encrypted RMAN Backups and Recovery

NOTA: VALIDAR EL DEFAULT DEL ALGORITH ENCRYPTION

PARA CAMBIAR.

RMAN> CONFIGURE ENCRYPTION ALGORITHM 'AES192';

RMAN> CONFIGURE ENCRYPTION ALGORITHM 'AES256';


RMAN> CONFIGURE ENCRYPTION ALGORITHM 'AES128';

old RMAN configuration parameters:
CONFIGURE ENCRYPTION ALGORITHM 'AES192';
new RMAN configuration parameters:
CONFIGURE ENCRYPTION ALGORITHM 'AES128';
new RMAN configuration parameters are successfully stored

RMAN>  CONFIGURE ENCRYPTION ALGORITHM clear;

old RMAN configuration parameters:

CONFIGURE ENCRYPTION ALGORITHM 'AES128';
RMAN configuration parameters are successfully reset to default value

RMAN> 

new RMAN configuration parameters:
CONFIGURE ENCRYPTION ALGORITHM 'AES192';
new RMAN configuration parameters are successfully stored

RMAN> CONFIGURE ENCRYPTION ALGORITHM CLEAR;

old RMAN configuration parameters:
CONFIGURE ENCRYPTION ALGORITHM 'AES192';
RMAN configuration parameters are successfully reset to default value

Creating Encrypted RMAN Backups and Recovery

It is very simple to restore the database created by RMAN using simple commands.  If someone has stolen the  backup of the database, they can easily restore it and steal all our data, too.  To prevent that from happening, encrypt the backup that has been made. By querying the v$rman_encryption_algorithms view, a list of RMAN encryption algorithms can be obtained:
SQL>
set line 200

select
algorithm_id, algorithm_name, algorithm_description, is_default
from
v$rman_encryption_algorithms;

ALGORITHM_ID ALGORITHM_NAME  ALGORITHM_DESCRIPTION        IS_DEFAULT
------------   -----------   ------------------------     ----------
1              AES128                 AES 128-bit key     YES
2              AES192                 AES 192-bit key     NO
3              AES256                 AES 256-bit key     NO
SQL>
There are three forms of encryption in Oracle 10g: transparent, password and dual mode.
  • To use transparent mode encryption, Oracle Encryption Wallet should be used.
  • To use password mode, a password should be provide by the DBA which will be used in encryption.
  • By using dual mode encryption, both above mentioned modes will be used.
In the following example, we will show how to use password mode to encrypt our backup. Use the set encryption on command and the password using the identified by command, and encrypt the backup that is taken in this session.   Use the only keyword at the end to use only password encryption.  If the keyword only is missed, RMAN uses dual mode encryption and demands the presence of Oracle Encryption Wallet, too.

    RMAN> set encryption algorithm 'AES192';

RMAN> set encryption on identified by 'oracle' only;
Backup the users tablespace:
RMAN>; backup tablespace users;
Now try to restore it:
RMAN> restore tablespace users;
ORA-19913: unable to decrypt backup
ORA-28365: wallet is not open
As this shows, it is impossible to restore already encrypted backup without using the password.  In this situation, if someone has stolen our backup, they will not be able to restore it and steal our data, too, without providing the correct password. Now provide the password and restore the backup:
RMAN> set decryption identified by 'oracle';
RMAN> restore tablespace users;

RMAN> recover database;
Using the password, tablespace is restored successfully.  If we provide a wrong password, it will not restore the backup:
RMAN> set decryption identified by 'wrong'; #wrong password
RMAN> restore tablespace users;
ORA-19913: unable to decrypt backup
ORA-28365: wallet is not open
RMAN>
By default, RMAN uses the AES 128-bit key algorithm for encryption.  The algorithm can be easily changed using the configure encryption algorithm command as follows:
RMAN> show encryption algorithm;
RMAN configuration parameters are:
configure encryption algorithm 'AES128'; #default

RMAN> configure encryption algorithm 'AES256';
new RMAN configuration parameters:
configure encryption algorithm 'AES256';
new RMAN configuration parameters are successfully stored

RMAN> show encryption algorithm;
RMAN configuration parameters are:
configure encryption algorithm 'AES256';
Again, anytime this configuration is cleared, the encryption algorithmcan be returned to its default value as follows:
RMAN> configure encryption algorithm clear;

old RMAN configuration parameters:
configure encryption algorithm 'AES256';
RMAN configuration parameters are successfully reset to default value

RMAN> show encryption algorithm;
RMAN configuration parameters are:
configure encryption algorithm 'AES128'; # default
RMAN>
To use Oracle Encryption Wallet, we need to configure RMAN to perform an encrypted backup of any tablespace or whole database automatically.  For this, use the configure encryption for command.  In the following example, we configure RMAN to create an encrypted backup of the database, and exclude users tablespace from encryption:
RMAN> show all;
RMAN configuration parameters are:
configure encryption for database off; # default
configure encryption algorithm 'AES128'; # default

RMAN> configure encryption for database on;
new RMAN configuration parameters:
configure encryption for database on;
new RMAN configuration parameters are successfully stored

RMAN> configure encryption for tablespace users off;
tablespace users will not be encrypted in future backup sets
new RMAN configuration parameters are successfully stored

RMAN> show all;
RMAN configuration parameters are:
configure encryption for database on;
configure encryption algorithm 'AES128'; # default
configure encryption for tablespace 'users' off;
To return back to default value, clear the encryption configuration parameter:
RMAN> configure encryption for database clear;
old RMAN configuration parameters:
configure encryption for database on;
RMAN configuration parameters are successfully reset to default value 

RMAN> configure encryption for tablespace users clear;
tablespace users will default to database encryption configuration
old RMAN configuration parameters are successfully deleted

RMAN> show all;
RMAN configuration parameters are:
configure encryption for database off; # default


jueves, 24 de septiembre de 2015

CAMBIAR REDUNDANCY +ASM

Change ASM disk group from normal redundancy to external redundancy


Hello,
1
When the disk group was created with normal redundancy, the only way to change is to drop the disk group and recreate a new one.
1) shutdown database
shutdown immediate;
2) startup in mount mode
startup mount;
3) make database full backup, archivelog backup, spfile backup and controlfile backup
RMAN> backup device type disk format '/u02/backup/backup/database_backup%U' database;

RMAN> backup device type disk format '/u02/backup/backup/archivelog%U' archivelog all;

SQL>  create pfile='/u02/backup/initorcl.ora' from spfile;

SQL>  alter database backup controlfile to '/u02/backup/control.ctl';
4) shutdown database;
shutdown immediate;
5) login as sysasm and drop disk group
[oracle@oel6 backup]$ . oraenv
ORACLE_SID = [orcl] ? +ASM
sqlplus / as sysasm

SQL> drop diskgroup DISKS including contents;

SQL> shutdown immedaite;

SQL> startup nomount;
6) run asmca and create new disk group with external redundancy
2
SQL> select status from v$instance;
STATUS
————
STARTED
7) ASM instance is already started, now we must restore database and all related files.
[oracle@oel6]$ . oraenv
ORACLE_SID = [+ASM] ? orcl
sqlplus / as sysdba

SQL> startup nomount pfile='/u02/backup/initorcl.ora';

SQL> create spfile='+DISKS' from pfile='/u02/backup/initorcl.ora';

SQL> !rman target /

RMAN> restore controlfile from '/u02/backup/control.ctl';

RMAN> alter database mount;

RMAN> restore database;

RMAN> recover database;

unable to find archived log
archived log thread=1 sequence=8
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of recover command at 09/25/2013 12:11:31
RMAN-06054: media recovery requesting unknown archived log for thread 1 with sequence 8 and starting SCN of 21904164
While recovery it will give an error for archive log missing, this is expected we need to open the database with resetlogs as
RMAN> alter database open resetlogs;
8)
for using correct spfile:
ASMCMD> cp '/u0/app/oracle/product/11.2.0/dbhome_1/dbs/spfileorcl.ora' '+DISKS/ORCL/spfileorcl.ora' 
delete spfile from file system
rm -rf /u0/app/oracle/product/11.2.0/dbhome_1/dbs/spfileorcl.ora
edit /u0/app/oracle/product/11.2.0/dbhome_1/dbs/initorcl.ora, which must contains link to our spfile in disk group.
*.SPFILE='+DISKS/orcl/spfileorcl.ora'
3
that’s all.

jueves, 17 de septiembre de 2015

Guia Basica RMAN

Guía Básica de RMAN (actualizada)


Conexión a RMAN

La forma más simple de conectarse a RMAN es la siguiente (con el usuario oracle):
$ rman target /

Recovery Manager: Release 10.2.0.1.0 - Production on Wed Mar 8 13:16:22 2006

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

connected to target database: LCBDPROD (DBID=2582320114)

RMAN>
Si queremos que nuestras actividades se registren en un archivo log:
$ rman target / log /ruta/archivo.log [append]

Parámetros de configuración de RMAN

RMAN viene configurado con una serie de parámetros predefinidos, mismos que podemos ver con el comando show:
RMAN> show all ;
using target database control file instead of recovery catalog
RMAN configuration parameters are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/oracle/10.2.0/dbs_1/dbs/snapcf_LCBDPROD1.f'; 
 # default

Respaldos incrementales

Un respaldo incremental consta de dos niveles: 0 (respaldo completo de la base de datos y que sirve de base a los respaldos incrementales) y 1 (respaldos incrementales en los que solamente se respaldan los bloques que han cambiado desde el último respaldo). Adicionalmente, es posible “actualizar” el respaldo de nivel 0 con los cambios del respaldo de nivel 1. Un respaldo de este tipo se haría de la siguiente forma:
Paso 1. Respaldo completo (nivel 0):
RMAN> backup incremental level 0 tag ‘INC_L0’ database ;
Paso 2: Primer respaldo incremental (nivel 1):
RMAN> backup incremental level 1 for recover of copy tag ‘INC_L0’ database ;
Paso 3: Aplicar el respaldo incremental al respaldo de nivel 0, es decir, aplicar los cambios en los bloques al respaldo base.
RMAN> recover copy of database with tag ‘INC_L0’ ;
Para que el desempeño del respaldo incremental sea óptimo, es necesario habilitar la opción llamada block change tracking, que es un archivo que lleva el registro de los bloques que van cambiado desde el último respaldo. Si no está habilitado, RMAN tiene que leer todos los bloques de la base de datos para determinar cual respaldar, haciendo el respaldo tan caro como un full backup. Para habilitar block change tracking:
SQL> ALTER DATABASE ENABLE BLOCK CHANGE TRACKING ;
El archivo de tracking se genera automáticamente en el área de flashback.

Respaldo de los respaldos

Si los respaldos se están haciendo en flashback recovery area, es conveniente respaldar también esta área que se encuentra en disco.
RMAN> backup recovery area ;
Esto respalda todos los archivos de recuperación en flashback recovery area: full backups, copies, incrementals, respaldos de controlfiles, y archivelogs. No se respaldan block change tracking files, controfiles actuales ni redo logs. El único destino válido para estos respaldos es cinta.

Políticas de retención

Las políticas de retención nos ayudan a determinar qué respaldos todavía son necesarios y cuáles ya no debido a que han quedado obsoletos por un respaldo más reciente. Hay dos tipos de políticas de retención y son mutuamente excluyentes: redundancy y recovery window.
  • Redundancy: determina cuantas copias de un archivo se necesitan antes de considerar una copia obsoleta. Si la redundancia es 1, cada que se respalde un archivo (copia), todas las copias anteriores son obsoletas. REDUNDANCY=1 es la política de retención por default.
  • Recovery Window: determina el tiempo que debe ser retenido un archivo antes de ser obsoleto.
Para cambiar la política de retención:
RMAN> configure retention policy to redundancy X ;
ó
RMAN> configure retention policy to recovery window of X days ;
Con nuestra política definida, podemos revisar los respaldos que ya son obsoletos:
RMAN> report obsolete ;
Y borrarlos si determinamos que ya no son necesarios:
RMAN> delete obsolete ; <-- borrar="" nos="" pregunta="" queremos="" realmente="" rman="" si=""> delete force noprompt obsolete ; <-- borra="" confirmaci="" n.="" pre="" sin="">Oracle automáticamente borrará respaldos obsoletos si flashback recovery area comienza a tener problemas de espacio.

Configuración de cintas

RMAN no puede escribir directamente a cintas, por lo que es necesario configurar una librería que generalmente es proporcionada por el fabricante de la unidad de respaldo a cinta. En versiones anteriores de RMAN dicha librería se configuraba en $ORACLE_HOME/lib, sin embargo, en 10g Oracle recomienda que se especifique la librería directamente:
RMAN> configure channel device type sbt
2> parms= ‘SBT_LIBRARY=/path/librería’ ;

Reporte de operaciones

Podemos usar los comandos LIST y REPORT para generar reportes de actividades realizadas con RMAN:
list backup summary;
list backup by datafile;
list backup of database;
list backup of archivelog all;
list backup of controlfile;
report obsolete ;
report need backup ;

Scripts

Archivos de comandos: Un archivo de comandos es un archivo de texto conteniendo comandos RMAN, y que puede ser llamado de la siguiente forma:
RMAN> @/ruta/script.txt 
ó 
$ rman target / @/ruta/script.txt
Comando RUN: El comando RUN agrupa comandos de RMAN para ser ejecutados como uno solo. Si uno de los comandos falla, el resto ya no es ejecutado.
RUN {
 BACKUP ARCHIVELOG ALL DELETE ALL INPUT;
 BACKUP INCREMENTAL LEVEL 0 TAG mon_bkup DATABASE;
}

Casos de recuperación

Se puede ejecutar el comando RESTORE … VALIDATE para confirmar que una operación puede ser ejecutada correctamente. RMAN automáticamente decide qué archivos son necesarios para la recuperación y verifica que sean utilizables.
RMAN> restore database validate ;
Caso 1. Recuperación completa de la base de datos cuando se tiene el archivo de control y la base de datos está montada:
RMAN> restore database ;
RMAN> recover database ;
Caso 2. Se tiene la situación del caso 1 pero se desea recuperar a un punto pasado en el tiempo:
RMAN> run {set until time = ’04-MAR-06 12:00:00’;
2> restore database ;
3> recover database ;
4> }
Caso 3. Recuperación de un datafile
Identificar el número de datafile:
SQL> select file#, name from v$datafile ;

Poner offline el datafile, ya sea desde SQL*Plus o desde RMAN:
RMAN> sql ‘alter database datafile 8 offline’ ;

Recuperar el datafile:
RMAN> run {restore datafile 8 ;
2> recover datafile 8 ;
3> sql ‘alter database datafile 8 online’ ;
4> }
Caso 4. Recuperación de un tablespace.
RMAN> run {sql ‘alter tablespace users offline’ ;
2> restore tablespace users ;
3> recover tablespace users ;
4> sql ‘alter tablespace users online’ ;
5> }
El comando run es para correr las instrucciones en modo script, pero también pueden ser ejecutadas una por una:
RMAN> sql ‘alter tablespace users offline’ ;
RMAN> restore tablespace users ;
RMAN> recover tablespace users ;
RMAN> sql ‘alter tablespace users online’ ;
Caso 5. Recuperación de bloques corruptos RMAN es la herramienta ideal para recuperación de bloques corruptos (ORA-1578). El error nos dice cuál es el bloque corrupto:
ORA-1578: ORACLE data block corrupted (file # 7, block # 1234)
Mismos que también podemos consultar en la vista v$database_block_corruption. Para recuperar todos los bloques corruptos:
RMAN> blockrecover corruption list ;
O podemos recuperar bloques individuales:
RMAN> blockrecover datafile 7 block 1234[, datafile 10 block 3265, ...] ;