MERCADOS FINANCIEROS

martes, 22 de septiembre de 2009

RMAN Backups

Types of Files That RMAN Can Back Up
RMAN lets you back up all the files you’d need for a database recovery, such as the following:
• Datafiles
• Control files
• Archived redo logs
• Image copies of datafiles and control files, including those made by RMAN
• Backup pieces that contain RMAN backups

RMAN> backup as backupset database;

The following command shows how to specify a tape device as the backup destination
and specify that the backup be made as a backup set:

RMAN> backup as backupset device type sbt database;

To make image copies of the database, use the as copy clause instead, as shown here:

RMAN> backup as copy database;


RMAN> backup database format= '/u01/backup_%U ';

ASM

RMAN> backup
database
format '+dgroup1';

Backing Up the Control File

RMAN> configure controlfile autobackup on;

From here on out, RMAN will create a backup of the control file (as well as the server
parameter file) whenever you perform any backup with RMAN or make structural database
changes.
If you prefer not to configure automatic control file backups, you can use the backup command’s
current controlfile clause to perform a manual backup of the current control file, as
shown here:

RMAN> backup current controlfile;
You also have the option to manually include the control file with any other backup that
you make. You do that by adding the include current controlfile option to any backup command.

For example, you can back up the control file as part of a tablespace backup operation:

RMAN> backup tablespace users include current controlfile;

Backing Up the Server Parameter File

RMAN> backup spfile;

Starting backup at 22-SEP-09
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: sid=2757 devtype=DISK
allocated channel: ORA_DISK_2
channel ORA_DISK_2: sid=3576 devtype=DISK
channel ORA_DISK_1: starting full datafile backupset
channel ORA_DISK_1: specifying datafile(s) in backupset
including current SPFILE in backupset
channel ORA_DISK_1: starting piece 1 at 22-SEP-09
channel ORA_DISK_1: finished piece 1 at 22-SEP-09
piece handle=/u02/app/oracle/flash_recovery_area/LETODB/backupset/2009_09_22/o1_mf_nnsnf_TAG20090922T151400_5cld0b3z_.bkp tag=TAG20090922T151400 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:03
Finished backup at 22-SEP-09

Starting Control File and SPFILE Autobackup at 22-SEP-09
piece handle=/u02/backup/letodb/c-3814852239-20090922-03 comment=NONE
Finished Control File and SPFILE Autobackup at 22-SEP-09

RMAN>

Backing Up Datafiles

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

RMAN> backup datafile 1,2,3,4
format '/u01/app/oracle/rman/%d_%U.bus';

RMAN> backup as copy datafile '/ora01/testdb/system01.dbf'
format '/oraback/system01.bk';

Backing Up Tablespaces

RMAN> backup tablespace users, tools;

RMAN> backup tablespace system format '/ora01/prod1/%d_%U.bus';

RMAN> backup as copy tablespace users;

RMAN> backup incremental level 1 tablespace example;

Making a Whole-Database Backup


RMAN> backup database;

RMAN> backup database;
RMAN> SQL "alter system archive log current";

RMAN> backup archivelog all;

RMAN> backup device type sbt
archivelog like '/disk%arc%'
delete all input;

RMAN> backup archivelog
from time "sysdate-15" until time "sysdate-7";

RMAN> backup archivelog sequence 99
delete input;

RMAN> backup archivelog sequence between 99 and 199 thread 1
delete input;

Backing Up Everything

RMAN> configure controlfile autobackup on;

Then you can issue the backup database plus archivelog command to back up the
database along with the archived redo logs:

RMAN> backup database plus archivelog;

RMAN> list backup by file;

RMAN> backup database
2> include current controlfile;

Backing Up Flash Recovery Files

RMAN> backup recovery area;

The previous command will back up recovery files that were created not only in the
current flash recovery area but also in all previous flash recovery area locations.
If you want to back up the recovery files located in all locations, not merely the flash
recovery area, use the following command instead after configuring a tape backup channel:

RMAN> backup recovery files;

RMAN> backup incremental level 1 datafile 5;


Performing Incremental Backups


Differential Incremental Backups
A differential incremental backup is an incremental backup of all data blocks that changed
subsequently to a level 0 or a level 1 backup. RMAN first looks for a level 1 backup and, in its
absence, looks for a level 0 backup and backs up all changes since that level 0 backup. Here’s
an example of a differential incremental level 0 backup:

RMAN> backup incremental level 0 database;

Incremental level 0 backups can be made as image copies or backup sets.
Here’s how you’d perform a level 1 differential incremental backup that backs up the data
blocks changed since the most recent level 0 or, if there’s no level 0 backup, a level 1 backup:

RMAN> backup incremental level 1 database;

Cumulative Incremental Backups
A cumulative incremental backup is an incremental backup of all data blocks that changed
subsequently to the most recent level 0 incremental backup. The following command shows
how to make a cumulative incremental backup of a database:

RMAN> backup incremental level 1 cumulative database;

RMAN> backup incremental level 1 database;


You can’t use an incremental backup directly during a database restore operation since it’s
only a complement to a full backup and can’t be “restored.” It’s only to provide a faster recovery
time (faster mean time to recovery, or MTTR). The following example serves to
demonstrate this point:
RMAN> run
{
restore datafile 7;
recover datafile 7;
}

Reducing Incremental Backup Time

1. First, make sure the db_create_file_dest parameter is set. If it isn’t, set it using the
alter system command, as shown in this example:
SQL> alter system set
db_create_file_dest='/u01/app/oracle/dfiles'
scope= both;

2. Enable block change tracking by using the following alter database statement:
SQL> alter database enable block change tracking;
Database altered.

If you want, you can create the block changing file in a location you specify, as shown here:

SQL> alter database enable block change tracking using file
'/u05/app/oracle/change_track.txt';
Database altered.

You can disable block change tracking by using the following command:

SQL> alter database disable block change tracking;

The V$BLOCK_CHANGE_TRACKING view shows whether change tracking is enabled as
well as other things such as the change tracking filename.
If you need to move the change tracking file, use the following procedure:

1. Determine the current location of the change tracking file with the following command:
SQL> select filename from v$block_change_tracking;

2. Shut down the database.

3. Move the change tracking file to the new location using the following command:

$ mv /u05/app/oracle/change_trck.f /u10/app/oracle/change_track.f

4. Start up the database in mount mode:

SQL> startup mount

5. Use the alter database rename file command to rename the change tracking file in
the Oracle database:

SQL> alter database rename file
'/u05/app/oracle/change_track.f' to
'/u10/app/oracle/change_track.f';

6. Open the database:

SQL> alter database open;


If you can’t shut down the database for some reason, you have to first disable change
tracking and then reenable it after you rename the change tracking file, as shown here:

SQL> alter database disable block change tracking;

SQL> alter database enable block change tracking using file
'/u10/app/oracle/change_track.f';

Creating Multiple Backup Sets


RMAN> backup
copies 2
database
format '/u01/app/oracle/backup/db_%U',
'/u02/app/oracle/backupdb_%U';

run
{
allocate channel c1 device type sbt;
parms 'env=(ob_device_1=testtape1,ob_device_2=testtape2)';
set backup copies = 2;
backup database plus archivelog;
}

RMAN> run {
allocate channel d1 type disk;
set backup copies = 2;
backup
as backupset
datafile 12
format '+BACKUP',
'+BACKUP';
release channel d1;
}

Making Copies of Backup Sets

RMAN> backup device type sbt
backupset
completed before 'sysdate-30'


Making Copies of Image Copy Backups

You want to make copies of image copy backups you’ve already made using RMAN.

RMAN> backup as copy copy of database;
RMAN> backup as backupset copy of tablespace users;
RMAN> backup as backupset copy of datafile 4;

RMAN> backup as copy
copy of datafile 2,3
from tag 'weekly_copy'
format '/backup/datafile%f_Database%d';

RMAN> backup as copy
copy of database
from tag "test";

Making Tape Copies of Disk-Based Image Copies

RMAN> backup device type sbt datafilecopy '/u05/app/oracle/system01.dbf';

RMAN> backup datafilecopy from tag whole_tag;

RMAN> backup as backupset
device type sbt_tape
tag "monthly_backup"
copy of database;

Excluding a Tablespace from a Backup

RMAN> show exclude;
RMAN configuration parameters are:
RMAN configuration has no stored or default parameters
RMAN>

RMAN> configure exclude for tablespace users;

RMAN> configure exclude for tablespace users clear;

RMAN will back
up all tablespaces, including those tablespaces that you expressly excluded from the backup
earlier with a configure exclude command. Here’s how you use the noexclude option as part
of a backup database command:

RMAN> backup database noexclude;

Skipping Read-Only,Offline, or Inaccessible Files

RMAN> backup database
skip inaccessible
skip readonly
skip offline;

Encrypting RMAN Backups

SQL> alter system set encryption key identified by "sammyy11";
System altered.

RMAN> configure encryption for database on;

RMAN> backup database;

RMAN> set encryption on identified by only;

RMAN> configure encryption for database off;

RMAN> configure encryption for tablespace example on;

RMAN> configure encryption for tablespace example off;

Making a Compressed Backup

RMAN> backup
as compressed backupset
database plus archivelog;

Parallelizing Backups

run
{
allocate channel ch1 device type sbt
parms 'env=(ob_device_1=testtape1)';
allocate channel ch2 device type sbt
parms 'env=(ob_device_2=testtape12';
backup
database channel ch1
archivelog all channel ch2;
}


run
{
allocate channel d1 device type disk format '/u01/%d_backups/%U';
allocate channel d2 device type disk format '/u02/%d_backups/%U';
allocate channel d3 device type disk format '/u03/%d_backups/%U';
allocate channel d4 device type disk format '/u04/%d_backups/%U';
backup database;
}

RMAN> configure device type disk parallelism 4;

RMAN> configure device type sbt parallelism 3;

RMAN> configure device type sbt clear;

Making Faster Backups of Large Files


$ rman target sys/@target_db

{allocate channel c1 device type sbt
parms 'env=(ob_device_1=testtape1)';
allocate channel c1 device type sbt
parms 'env=(ob_device_2=testtape2)';
allocate channel c1 device type sbt
parms 'env=(ob_device_3=testtape3)';

RMAN> backup
section size 150m
tablespace system;

RMAN> exit

The section_size column in both the V$BACKUP_DATAFILE and RC_BACKUP_DATAFILE
views shows the number of blocks in each section of a multisection backup. If you haven’t
performed any multisection backups, the section_size column would have a zero value. The
V$BACKUP_SET and RC_BACKUP_SET views tell you which backups or multisection backups.
The following example shows a query on the V$BACKUP_DATAFILE view:

SQL> select pieces, multi_section from V$BACKUP_SET;
PIECES MUL
------ --------
1 NO
2 YES
7 YES
4 NO

Specifying Backup Windows

RMAN> backup duration 6:00
database;

You can use the duration clause along with other clauses to control what happens when a
backup fails to complete within the specified time interval. By default, RMAN reports an error
when the backup is interrupted because of the end of the backup interval. If your backup command
is part of a run block, that run block will also terminate immediately. By using the
optional clause partial, you can suppress the RMAN error reports and instead have RMAN
merely report which datafiles it couldn’t back up because of a lack of time. Here’s an example:

RMAN> backup duration 6:00 partial
database

In addition to not issuing any error messages, the partial clause also lets the other commands
within a run block continue to execute after the termination of a backup when the
window of time for backups expires. You can also use the duration clause along with one of
two other options to control the speed of the backup. To perform the backup in the shortest
time possible, specify the minimize time option, as shown here:


RMAN> backup
duration 6:00 partial
minimize time
database
filesperset 1;

On the other hand, if you think that the backup may not go over the backup window,
you can reduce the overhead imposed by the backup with the minimize load option with the
duration clause, as shown here:

RMAN> backup
duration 6:00 partial
minimize load
database
filesperset 1 ;

Reusing RMAN Backup Files

You can use the reuse option with your backup commands to enable RMAN to overwrite existing
backups, as shown in the following example:

RMAN> backup reuse database;

Retaining Backups for a Long Time

Use the keep option with the backup command to retain backups beyond what’s mandated by
the retention polices that you’ve configured. In the following example, the keep until time
clause tells RMAN to retain the backup for a period of six months:

run
{
backup database
tag quarterly
keep until time 'sysdate+180'
restore point 2007Q1;
}

You may sometimes need to retain a given backup forever. As long as you’re using a recovery
catalog, you can simply use the keep forever option during a backup command to exempt
a backup copy from any retention policies:

run
{
backup database
tag quarterly
keep forever
restore point Y2007Q1;
}

One of the common uses of archival backups is to use them for creating a test database on
a different server. Since you won’t need the backups after you create the test database from the
backups, you can set the keep parameter to sysdate+1, meaning that the backup will become
obsolete a day after the backup is made, regardless of your backup retention policy. Here’s an
example:



run
{
backup database
tag quarterly
keep until time 'sysdate+1';
restore point Y2007Q1
}

RMAN> backup database keep forever tag 'semi_annual_bkp';
RMAN> change backup tag 'semi_annual_bkp' unavailable;

Backing Up Only Those Files Previously Not Backed Up

RMAN> backup database not backed up;


Restarting Backups After a Crash

Problem

The RMAN backup process fails midway through a database backup, say, because of a database

instance crash or because of the unavailability of some datafiles. You want to resume the
backup but save time by backing up only those parts of the database that failed to be backed
up the first time.

Solution
Use the restartable backup feature to back up only those files that failed to be backed up the
first time around. Use the not backed up since time clause of the backup command to restart a backup after it partially completes. If the time you specify for the since time clause is a more
recent time than the backup completion time, RMAN backs up the database file.
Here’s an example that shows how to restart an RMAN backup that failed midway through
a nightly backup. You discover the backup failure in the morning and decide to back up only
those parts of the database that weren’t backed up by RMAN before the backup failed. Simply
run the following backup command to achieve your goal.

RMAN> backup not backed up since time 'sysdate-1'
database plus archivelog;

Updating Image Copies

You want to update image copies to keep them current without having to perform lengthy
image copy backups of entire datafiles.

run {
recover copy of database
with tag 'incr_update';
backup
incremental level 1 for recover of copy with tag 'incr_update'
database;
}


RMAN> run
2> {
3> recover copy of database
4> with tag 'incr_update';
5> backup
6> incremental level 1
7> for recover of copy with tag 'incr_update'
8> database;
9> }

RMAN Creating a High-Availability Recovery Catalog

Creating a High-Availability Recovery Catalog
Problem
You have registered a large number of databases in a single recovery catalog and want to
ensure that the recovery catalog is always available to perform backup and recovery tasks.
That is, you want a high-availability solution for the RMAN recovery catalog.
Solution
The solution is to maintain multiple, redundant recovery catalogs. If you’re using the recovery
catalog to manage the backup and recovery tasks for a large number of production databases,
maintaining high availability becomes critical. You can ensure high availability of the recovery
catalog just as you would any other Oracle database—by using a standby recovery catalog
instance. In the case of recovery catalogs, however, you really don’t use a special standby database
for the alternate recovery catalog instance—you simply maintain a secondary recovery
catalog that can take over from the primary recovery catalog in the event disaster strikes.

Here’s a simple outline of the strategy for using a standby recovery catalog:
1. Create a secondary recovery catalog in a separate Oracle database.
2. Register all databases—all that you have registered in your primary catalog—in the
secondary recovery catalog.
3. The primary recovery catalog is synchronized automatically during the normal backups
of the target databases.
4. Synchronize the secondary recovery catalog manually with the resync catalog command
after connecting to each of the target databases registered in the catalog.
5. Switch to the secondary catalog as the primary recovery catalog when necessary after
resynchronizing it first. Switching to the secondary catalog is as easy as can be. Simply
connect to that catalog instead of to the primary one. The secondary catalog will be
now your primary catalog.
How It Works
It’s important to synchronize the secondary recovery catalog manually on a frequent basis so
the catalog remains current. This way, when you are forced to fall back on the secondary catalog,
it’ll have all the backup metadata you need.
You must back up the secondary recovery catalog database just as you would the primary
catalog database to provide high availability.

Using the Recovery Catalog

Creating the Recovery Catalog Owner

Follow these steps to create the recovery catalog owner:

1. Using SQL*Plus, connect as the user sys to the database where you want to create the
recovery catalog. For example:

SQL> connect sys/oracle@catdb as sysdba

2. Create a default tablespace for the RMAN recovery catalog owner you’re about to create.

Otherwise, the system tablespace may be used by default to hold the recovery
catalog structures, and it’s not a smart idea to let that happen. This example creates a
tablespace named cattbs:

SQL> create tablespace cattbs
datafile '/u10/oradata/catdb/cattbs_01.dbf' size 500M;
Tablespace created.

SQL>
3. Create the recovery catalog owner. This example creates a user named rman to own the
catalog:

SQL> create user rman identified by rman
temporary tablespace temp
default tablespace cattbs
quota unlimited on cattbs;
User created.

SQL>
The default tablespace of the recovery catalog owner in this example is the cattbs
tablespace created in the previous step.

4. Once you create the recovery catalog owner, you must grant that user the
recovery_catalog_owner privilege in order for that user to have the authority to work
with the recovery catalog you’ll create in the next step. This recovery catalog owner is
named rman, so grant the recovery_catalog_owner privilege to that user:

SQL> grant recovery_catalog_owner to rman;
SQL> exit;

Creating the Recovery Catalog
Once you’ve created the recovery catalog schema, your next step is to create the recovery catalog.
You must connect to the recovery catalog, but not to a target database, when you do this.
Here are the steps you must follow to create the recovery catalog:

1. Connect to the RMAN catalog database by starting up the RMAN client and using the
connect catalog command. You must connect as the recovery catalog owner you created
in the previous section.

RMAN> connect catalog rman/cat@catdb
connected to recovery catalog database

RMAN>
2. Using the create catalog command, create the recovery catalog. RMAN will create the
recovery catalog in the default tablespace of the recovery catalog owner. For example:

RMAN> create catalog;
recovery catalog created
RMAN>

Granting Restricted Access


SQL> create user virtual1 identified by virtual1
2 temporary tablespace temp
3 default tablespace vp_users
4 quota unlimited on vp_users;
User created.

Grant the new user the recovery_catalog_owner role, just as you do when you create a
base recovery catalog:

SQL> grant recovery_catalog_owner to virtual1;
Grant succeeded.

Connect to the recovery catalog database as the base recovery catalog owner, and grant

the new user virtual1 restricted access (virtual private catalog access) to just one database,
orcl11, from the base recovery catalog. You grant the catalog for database
privilege to the new user in order to do this:

$ rman
Recovery Manager: Release 11.1.0.1.0 - Beta on Sun Apr 8 13:19:30 2
Copyright (c) 1982, 2005, Oracle. All rights reserved.

RMAN> connect catalog rman/rman@nick
connected to recovery catalog database

RMAN> grant catalog for database orcl11 to virtual1;
Grant succeeded.

Now that the virtual private catalog owner has the catalog for database privilege, that
user can log in to the base recovery catalog and create the virtual private catalog:

RMAN> connect catalog virtual1/virtual1@nick
connected to recovery catalog database

RMAN> create virtual catalog;
found eligible base catalog owned by RMAN
created virtual catalog against base catalog owned by RMAN

RMAN> list incarnation;


The catalog for database privilege shown here grants the virtual catalog user access to a
database already registered in the base recovery catalog:

RMAN> connect catalog rman/rman@catdb

RMAN> grant catalog for database prod1 to virtual1;

By granting the register database privilege as shown in the following example, you grant
a user the ability to register new databases in the virtual private catalog and, implicitly, in the
base recovery catalog as well:

RMAN> connect catalog rman/rman@catdb

RMAN> grant register database to virtual1;

RMAN> revoke catalog for database prod1 from virtual1;

RMAN> revoke all privileges from virtual1;


If you’re using an Oracle 10.2 or older release of RMAN, you must perform the following

steps in order to use a virtual private catalog. Connect to the base recovery catalog as the virtual
catalog owner, and execute the create_virtual_catalog procedure as shown here:

SQL> execute base_catalog_owner.dbms_rcvcat.create_virtual_catalog;

Connecting to the Catalog from the Command Line

$ rman target / catalog rman/rman@catalog_db

$ rman target sys/power@target_db catalog rman/rman@cat10g


Connecting to the Catalog from the RMAN Prompt

RMAN> connect target /

You can then use Oracle Net authentication to connect to the recovery catalog:

RMAN> connect catalog rman/rman@cat10g

RMAN> register database;
RMAN> unregister database;
RMAN> unregister database POWER;

RMAN> run
{
set dbid 1234567899;
unregister database POWER;
}

Cataloging Older Files

RMAN> catalog datafilecopy '/u01/app/oracle/users01.dbf';
cataloged datafile copy
datafile copy filename=/u01/app/oracle/users01.dbf recid=2 stamp=604202000

RMAN> catalog backuppiece '/disk1/backups/backup_820.bkp';

Cataloging Sets of Files

RMAN> catalog start with '/disk1/arch_logs/';

RMAN> catalog recovery area;

Updating the Recovery Catalog

RMAN> resync catalog;

Dropping the Recovery Catalog

RMAN> connect catalog rman/rman@catdb
Connected to recovery catalog database

RMAN> drop catalog;

Merging Recovery Catalogs

RMAN> connect catalog rman/rman@eleven
RMAN> import catalog rman10/rman10@tenner;

RMAN> import catalog rman10/rman10@tenner dbid = 123456, 123457;

RMAN> import catalog rman10/rman10@tenner db_name = testdb, mydb;

If you don’t want RMAN to unregister the databases
from the source catalog after importing the metadata for the databases registered in that
catalog, issue the following import catalog command, with the no unregister option:

RMAN> import catalog rman10/rman10@tenner no unregister;

Moving the Recovery Catalog to Another Database

RMAN> connect catalog rman/rman@target_db
RMAN> import catalog rman10/rman10@source_db;

Viewing Backup Information

SQL> connect / as sysdba
SQL> select DBID from v$database;
DBID
--------
6325412

connect rman/cat@catdb

RC_STORED_SCRIPT: This view lists information about RMAN scripts stored in the recovery
catalog.

RC_UNUSABLE_BACKUPFILE_DETAILS: This view shows the unusable backup files
recorded in the recovery catalog.

RC_RMAN_STATUS: This view is similar to the V$RMAN_STATUS view and shows the status
of all RMAN operations. This view doesn’t contain information about any operations
that are currently executing.

RC_RMAN_CONFIGURATION: This view provides information about persistent configuration
settings.

RC_DATAFILE: This view shows all datafiles registered in the recovery catalog.

RC_DATABASE: This view shows the databases registered in the recovery catalog.

RC_ARCHIVED_LOG: This view provides historical information on both archived as well
as unarchived redo logs.


Uncataloging RMAN Records

RMAN> change controlfilecopy '/u01/app/oracle/rman/backup/control01.ctl' uncatalog;
RMAN> change datafilecopy '/u01/app/oracle/rman/backup/users01.ctl' uncatalog;

Using a Release 11.x Client with Older Catalogs
RMAN> upgrade catalog;

RMAN Configuration Enviroment

-bash-3.00$ rman target /

Recovery Manager: Release 10.2.0.4.0 - Production on Tue Sep 22 11:20:06 2009

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

connected to target database: LETODB (DBID=3814852239)

RMAN> show all;

using target database control file instead of recovery catalog
RMAN configuration parameters are:
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 5 DAYS;
CONFIGURE BACKUP OPTIMIZATION ON;
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/u02/backup/letodb/%F';
CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO BACKUPSET PARALLELISM 2;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE CHANNEL DEVICE TYPE DISK MAXPIECESIZE 4 G;
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 '/u01/app/oracle/product/10.2.0/dbs/snapcf_letodb.f'; # default

RMAN>

Shows the archivelog deletion policy.

RMAN> show archivelog deletion policy;

RMAN configuration parameters are:
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default

Shows the number of archivelog backup copies.

RMAN> show archivelog backup copies;

RMAN configuration parameters are:
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default

Shows the auxiliary database information.

RMAN> show auxname;

RMAN configuration parameters are:
RMAN configuration has no stored or default parameters

Shows whether optimization is on or off.

RMAN> show backup optimization;

RMAN configuration parameters are:
CONFIGURE BACKUP OPTIMIZATION ON;

Shows how the normal channel and auxiliary
channel are configured.

RMAN> show channel;

RMAN configuration parameters are:
CONFIGURE CHANNEL DEVICE TYPE DISK MAXPIECESIZE 4 G;


RMAN> show controlfile autobackup;

RMAN configuration parameters are:
CONFIGURE CONTROLFILE AUTOBACKUP ON;

Shows the format of the autobackup control file.


RMAN> show controlfile autobackup format;

RMAN configuration parameters are:
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '/u02/backup/letodb/%F';

Shows the number of datafile backup copies being
kept

RMAN> show datafile backup copies;

RMAN configuration parameters are:
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default

Shows the default type (disk or tape).


RMAN> show default device type;

RMAN configuration parameters are:
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default


Shows policy for datafile and control file backups
and copies that RMAN marks as obsolete.

RMAN> show retention policy;

RMAN configuration parameters are:
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 5 DAYS;


Shows the encryption algorithm currently in use.


RMAN> show encryption algorithm;

RMAN configuration parameters are:
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default

RMAN> show encryption for database;

RMAN configuration parameters are:
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default

RMAN> show encryption for tablespace;

RMAN configuration parameters are:
RMAN configuration has no stored or default parameters

Shows the tablespaces excluded from the backup.


RMAN> show exclude;

RMAN configuration parameters are:
RMAN configuration has no stored or default parameters

Shows the maximum size for backup sets. The
default is unlimited.

RMAN> show maxsetsize;

RMAN configuration parameters are:
CONFIGURE MAXSETSIZE TO UNLIMITED; # default


Shows the policy for datafile and control file
backups and copies that RMAN marks as obsolete.


RMAN configuration parameters are:
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 5 DAYS;


Shows the snapshot control filename.


RMAN> show snapshot controlfile name;

RMAN configuration parameters are:
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/10.2.0/dbs/snapcf_letodb.f'; # default

Shows the compression algorithm in force. The
default is the ZLIB algorithm.

select * from v$rman_configuration;

CONF# NAME VALUE
---------- ------------------------------ ------------------------
1 RETENTION POLICY TO REDUNDANCY 3
2 BACKUP OPTIMIZATION ON
3 DEFAULT DEVICE TYPE TO sbt_tape
4 CONTROLFILE AUTOBACKUP ON
5 DEVICE TYPE DISK PARALLELISM 2
5 rows selected.

run
{
configure retention policy to 1 redundancy 2;
configure backup optimization off;
configure default device type to disk;
configure controlfile autobackup on;
configure controlfile autobackup format for device type disk to
'/proj/11/backup/%F';
configure device type disk parallelism 2;
configure datafile backup copies for device type disk to 1;
configure archivelog backup copies for device type disk to 1;
configure maxsetsize to unlimited;
configure snapshot controlfile name to '/proj/11/backup/snapf_prod11.f';
}

Restoring Default Parameter Settings

RMAN> configure backup optimization clear;
RMAN> configure retention policy clear;
RMAN> configure channel device type sbt maxpiecesize 100m clear;
RMAN> configure channel device type sbt clear;

Enabling and Disabling Automatic Control File Backups

RMAN> configure controlfile autobackup on;

RMAN> configure controlfile autobackup clear;

Specifying the Autobackup Control File Directory
and Filename


RMAN> configure controlfile autobackup format
for device type disk to 'c:\rback\prod1\autobackup\controlfile_%F';

RMAN> configure controlfile autobackup format for device type disk clear;

You can also configure the autobackup to back up the control file to an automatic storage

management (ASM) disk group, as shown in the following example:

RMAN> configure controlfile autobackup
for device type disk to '+dgroup1/%F';

Specifying the Snapshot Control Filename and Location

RMAN> configure snapshot controlfile name to 'c:\rback\prod1\snct.ctl';

RMAN> configure snapshot controlfile name clear;

RMAN> show snapshot controlfile name;

using target database control file instead of recovery catalog
RMAN configuration parameters are:
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oracle/product/10.2.0/dbs/snapcf_letodb.f'; # default


Specifying the Retention Period for RMAN History

SQL> show parameter control_file_record_keep_time;

NAME TYPE
------------------------------------ --------------------------------
VALUE
------------------------------
control_file_record_keep_time integer 7


SQL> alter system set control_file_record_keep_time=15;
System altered.


view provides information about the control file record sections.

select * from V$CONTROLFILE_RECORD_SECTION

Configuring the Default Device Type

RMAN> configure default device type to sbt;

You can use the clear option to return the default device type to disk again:

RMAN> configure default device type clear;

You can also explicitly reset the default device type to disk, as shown here:

RMAN> configure default device type to disk;

Once you configure the default device type to disk, all backups will be made to disk.

RMAN> backup device type sbt database;

RMAN> backup device type disk database;


RMAN> configure channel device type
sbt parms='sbt_library=/mediavendor/lib/libobk.so
env=(nsr_server=tape_svr,nsr_client=oracleclnt,
nsr_group=ora_tapes)';

RMAN> configure default device type to sbt;

RMAN> backup archivelog all;

RMAN> backup device type disk database;

Solution
The default backup type in RMAN, whether you’re backing up to disk or to tape, is a backup set.

You can change the default backup type to an image copy by using the following command:

RMAN> configure device type disk backup type to copy;
You can revert to the original setting of backup set backup type by using either of the following
two commands:

RMAN> configure device type disk clear;

RMAN> configure device type disk backup type to backupset;

Making Compressed Backup Sets the Default


RMAN> configure device type disk backup type to compressed backupset;
using target database control file instead of recovery catalog
new RMAN configuration parameters:
CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COMPRESSED BACKUPSET PARALLELISM 1;
new RMAN configuration parameters are successfully stored
RMAN>


RMAN> show compression algorithm;
RMAN configuration parameters are:
CONFIGURE COMPRESSION ALGORITHM 'ZLIB'; # default


Configuring Multiple Backup Copies

RMAN> configure datafile backup copies for device type disk to 2;
RMAN> configure datafile backup copies for device type sbt to 2;

if you want to place one copy of a backup set in three different locations on disk, you
would configure RMAN as follows:


RMAN> show datafile backup copies;

using target database control file instead of recovery catalog
RMAN configuration parameters are:
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default

RMAN> show datafile backup copies;

using target database control file instead of recovery catalog
RMAN configuration parameters are:
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default

RMAN> show archivelog backup copies;

RMAN configuration parameters are:
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default

RMAN> configure channel device type disk format '/save1/%U','/save2/%U','save3/%U';


Skipping Previously Backed Up Files

RMAN> configure backup optimization on;

You can turn off backup optimization during a particular RMAN session and force RMAN
to back up a file regardless of whether it’s identical to a previously backed up file by specifying
the force option with your backup command, as shown here:

RMAN> backup database force;

RMAN> configure backup optimization off;

RMAN> backup database;
Starting backup at 09-NOV-06
using channel ORA_DISK_2
using channel ORA_DISK_1
using channel ORA_DISK_3
skipping datafile 1; already backed up 2 time(s)
skipping datafile 1; already backed up 2 time(s)
skipping datafile 1; already backed up 2 time(s)
skipping datafile 1; already backed up 2 time(s)


RMAN> backup device type sbt copies 3 archivelog all;

RMAN> configure backup optimization on;

RMAN> backup device type sbt copies 2 archivelog all;

Specifying Backup Piece Filenames

RMAN> backup tablespace users format = '/tmp/users_%u%p%c';


FORMATOS BACKUP

Type of File Meaning of %U
Datafile data-D-%d_id-%I_TS-%N_FNO-%f_%u
Archived log arch-D_%d-id-%I_S-%e_T-%h_A-%a_%u
Control file cf-D_%d-id-%I_%u

Tagging RMAN Backups

RMAN> backup copies 1 datafile 5 tag test_bkp;

RMAN> backup as copy tag users_bkp tablespace users;

Configuring Automatic Channels

RMAN> configure default device type to sbt;

RMAN> configure device type sbt parallelism 3;

RMAN> backup device type sbt database plus archivelog;

RMAN> configure channel device type disk
maxpiecesize 1g;


RMAN> configure channel 1 device type disk format '/disk1/%U';

RMAN> configure channel 2 device type disk format '/disk2/%U';

RMAN> configure channel 3 device type disk format '/disk3/%U';

You use the clear option with the configure command to clear any automatic channel
settings. You must use a separate configure ... clear command to set the configuration back
to its default value. Here are some examples:

RMAN> configure default device type clear; # reverts to the default
device type (DISK)

RMAN> configure channel device type sbt clear; # erases all
options that were set for the sbt channel

RMAN> configure channel 1 device type disk clear; # erases
configuration values set specifically for channel 1.

RMAN> configure channel device type disk format '+dgroup1';

Manually Allocating RMAN Channels


run
{
allocate channel c1 device type sbt;
backup database plus archivelog
release channel c1;
}


Allocating an RMAN Maintenance Channel


RMAN> allocate channel for maintenance device type sbt;
RMAN> delete backup of database completed before 'sysdate-30';

Backup Retention Policy Based on a Recovery Window

RMAN> configure retention policy to recovery window of 7 days;

Configuring an Archived Redo Log Deletion Policy


RMAN> configure archivelog deletion policy to
2> backed up 2 times to sbt;
new RMAN configuration parameters:
CONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 2 TIMES TO 'SBT_TAPE';
new RMAN configuration parameters are successfully stored

Limiting the Size of Individual Backup Pieces


RMAN> configure channel device type disk maxpiecesize = 1g;
RMAN> backup as backupset tablespace users;


RMAN> CONFIGURE CHANNEL DEVICE TYPE ‘SBT_TAPE’ clear;

RMAN> CONFIGURE CHANNEL DEVICE TYPE 'SBT_TAPE' clear;

old RMAN configuration parameters:
CONFIGURE CHANNEL DEVICE TYPE 'SBT_TAPE' MAXPIECESIZE 8 G;
old RMAN configuration parameters are successfully deleted

Using RMAN

Starting the RMAN Client

$ $ORACLE_HOME/bin/rman

RMAN-related records in the target database’s control file are overwritten after seven days, but

you can control the length of retention by setting a higher value for the initialization parameter


control_file_record_keep_time.

SQL> show parameter control_file_record_keep_time;

NAME TYPE
------------------------------------ --------------------------------
VALUE
------------------------------
control_file_record_keep_time integer
7

Problem
You’d like to start working with RMAN and issue the various RMAN commands to back up
your database and to manage those backups.

Solution
RMAN uses a free-form command language. Each RMAN command statement starts with a
keyword, is followed by specific arguments, and ends with a semicolon. A command can be
one line or multiple lines. For example, the following single-line command initiates a backup
of the target database:


RMAN> backup database;


RMAN> backup database
2> include current
3> controlfile
4> ;


You can add comments to your RMAN commands, which makes it easy to follow the logic
of your RMAN commands when you use several of them inside a command file (we discuss
RMAN command files later in this chapter). Each comment must be preceded by the # sign


# this command will be run daily
backup incremental level 1
for recover of copy # uses incrementally updated backups
database;

Problem
You want to save the output of an RMAN session to a text file.

Solution

how to use the spool command:

spool log to '/tmp/rman/backuplog.f';
backup datafile 1;
spool log off;

spool log to '/tmp/rman/backuplog.f' append.

Problem
You want to log the output of RMAN commands you issue in command-line mode.

Solution

If you want RMAN to log all its output when you use RMAN from the operating system command
line, just add the keyword log to the command line, and supply the name of the log file
to use. For example:

$ rman target / cmdfile commandfile1.rcv log /u01/app/oracle/outfile.txt
$ rman target / cmdfile commandfile2.rcv log /u01/app/oracle/outfile.txt append

connect to your target database from the RMAN prompt.

RMAN> connect target /
Connected to target database: POWER (DBID=922224687)

And here’s an example showing how to log in using a database username and password
that are authenticated against the password file:
$ rman

Recovery Manager: Release 11.1.0.1.0 - Beta on Mon Apr 2 08:31:11 2007
Copyright (c) 1982, 2005, Oracle. All rights reserved.

RMAN> connect target sys/password@power

$ orapwd
Usage: orapwd file= password= entries= force=
ignorecase= nosysdba=
where

file - name of password file (required),
password - password for SYS (required),
entries - maximum number of distinct DBA (required),
force - whether to overwrite existing file (optional),
ignorecase - passwords are case-insensitive (optional),
nosysdba - whether to shut out the SYSDBA logon (optional Database Vault only).

Example

$ orapwd file=mydb_pwd password=sammyy1 entries=20

remote_login_passwordfile = 'EXCLUSIVE'

Executing Operating System Commands from Within RMAN

In the following example, we use the host command to list all files ending with dbf, after
backing up a datafile from the RMAN prompt:

RMAN> shutdown immediate;
RMAN> startup mount;
RMAN> backup datafile '/u01/app/oracle/oradata/targ/system01.dbf'
format '/tmp/system01.dbf';
RMAN> host 'ls -l /tmp/*dbf';
RMAN> alter database open;

The following example uses the host command with no parameters to temporarily escape
to the operating system level during an interactive RMAN session:

RMAN> backup datafile 3 format '/u01/app/oracle/oradata/targ_db/dbs01.cpy';
RMAN> host;

$ ls $ORACLE_HOME/oradata/dbs01.cpy
/net/oracle/oradata/dbs01.cpy
$ exit
RMAN>

CRON DE RMAN


#!/bin/ksh
1 export ORACLE_SID=$1
2 rman target / catalog rman/rman@rcat > ${LOGFILE} <<- EOF
3 sql 'alter system archive log current';
4 change archivelog all crosscheck;
5 allocate channel for maintenance type disk;
6 delete noprompt expired archivelog all;
7 run {
8 allocate channel ch1 type disk format
9 '${BACKUP_DIR}/%d_level${LEVEL}_${TIMESTAMP}_%s_U%U.bak';
10 set limit channel ch1 kbytes=2000000;
11 backup incremental level ${LEVEL} (database);
12 release channel ch1;
13 resync catalog;
14 }
15 EOF

you can invoke RMAN from the command line to execute those files. For example, suppose

you have a file called full_backup.rman consisting of the following run block:

run {
allocate channel d1 type disk;
backup full database format '/export/rman/rman_%n_%T_%s_%p.bus';
}

You can then invoke RMAN from the operating system command line to execute this file
as follows:

$ rman target / @full_backup.rman

$ rman target / cmdfile commandfile.rcv

$ rman target / cmdfile /oracle/dbs/cmd/commandfile.rcv

$ rman target / @commandfile.rcv


Creating Dynamic Command Files

1. Create the RMAN command file that uses two substitution variables:
#backup.cmd

connect target sys/@prod1
run {
backup database
tag &1
format &2
}
exit;

The command file shown here will back up the database using two substitution variables
(&1 and &2), one for the backup tag and the other for the string value in the
format specification.

2. Create the shell script to run the backup command file you created in step 1:
#!/bin/tcsh
# script name: nightly_backup.sh

set tag=$argv(1)
set format=$argv[2]

rman @backup.cmd using $tag $format

3. Now that you have created a dynamic shell script, you can specify the arguments for
the tag and format variables on the command line, thus being able to modify them for
different jobs. Here’s an example:

$ nightly_backup.sh longterm_backup back0420


Connecting to an Auxiliary Database


$ rman auxiliary sys/@aux

You can also start the RMAN client first and then connect to the auxiliary instance from

the RMAN prompt, as shown in this example:
$ rman

RMAN> connect auxiliary sys/@aux

RMAN> connect target sys/@trgt
RMAN> connect catalog rman/@catalog
RMAN> connect auxiliary sys/@aux

The following example shows how you can connect to all three types of database in one
go from the operating system command line:
% rman target sys/oracle@trgt catalog rman/cat@catalog auxiliary sys/aux@aux


Executing Multiple RMAN Commands As a Single Unit

run
{
allocate channel t1 device type disk format '/disk1/%U';
allocate channel t2 device type disk format '/disk2/%U';
backup database;
}


Here’s one more example, this time showing how you use the set command to temporarily
change the value of a parameter within a run block. Let’s say you configured datafile copies
to three using the following command:

RMAN> configure datafile backup copies for device type sbt to 3;

You can override the default of three copies by using the following run block, where the
set command sets the number of backup copies to only two. You’ll thus get two copies of each
datafile and archived log that’s part of the backup.
run
{
allocate channel dev1 device type sbt;
set backup copies = 2;
backup datafile 1,2,3,4,5;
backup archivelog all;
}


RMAN commands dealing with configuration and environmental settings within a run
block.

For example, you can’t use the following commands from within a run block:

connect, configure, create catalog, drop catalog, upgrade catalog
create script, delete script, replace script, list, report

RMAN> SQL 'alter system archive log all';

run
{
SQL "alter tablespace tools offline immediate";
restore tablespace tools;
recover tablespace tools;
SQL "alter tablespace tools online";
}

RMAN> connect target /
RMAN> connect catalog rman/rman@catdb
RMAN> startup nomount;
RMAN> restore controlfile;
RMAN> alter database mount;
RMAN> recover database;
RMAN> alter database open resetlogs;

set DBID 1296234570;

RMAN> startup dba pfile=/tmp/initprod1.ora;

Checking the Syntax of RMAN Commands

$. /rman checksyntax
Recovery Manager: Release 11.1.0.1.0 - Beta on Mon Apr 2 08:31:11 2007


RMAN> shutdown immediate;
RMAN> startup mount;
RMAN> backup database;
RMAN> alter database open;


-bash-3.00$ rman checksyntax

Recovery Manager: Release 10.2.0.4.0 - Production on Tue Sep 22 10:59:59 2009

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

RMAN> backup database;

The command has no syntax errors

RMAN>


Identifying RMAN Server Sessions

$ ps –ef | grep rman



RMAN> drop database;
Database name is "NINA" and DBID is 922224687.

RMAN will require a confirmation from you that you really do want to drop the database.
Respond with yes, if that’s what you intend to do:

Do you really want to drop the database (enter YES or NO)? yes
Database dropped.

RMAN> drop database including backups;
Note how RMAN



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

lunes, 21 de septiembre de 2009

RMAN Using the Flash Recovery Area

1. Disable the parameters log_archive_dest and log_archive_duplex_dest, if they are set
in the database. You can do that by issuing the following commands:

SQL> alter system set log_archive_duplex_dest = '';
SQL> alter system set log_archive_dest = '';

2. Log on as a user with the sysdba role (such as the user sys) in preparation to create the
flash recovery area:

sqlplus / as sysdba (if logged in as the Oracle software owner)
sqlplus sys/ as sysdba

3. Issue the following commands to size and create the flash recovery area:

SQL> alter system set db_recovery_size = 4G;
SQL> alter system set db_recovery_dest = '/home/oracle/flasharea';

SQL>show parameter log_archive_dest


SQL> alter database open;
alter database open
*
ERROR at line 1:
ORA-38760: This database instance failed to turn on flashback database

Solution 1: Increase Space

You can increase the size of the flashback area dynamically. To increase it to, say, 10GB, you
would issue the following:

SQL> alter system set db_recovery_file_dest_size = 10G;

Solution 2: Remove Restore Points

SQL> select name, storage_size
2* from v$restore_point;
NAME STORAGE_SIZE
------------------------- ------------
RP0 207028224
RP1 0
RP2 915701760
PRE_TEST1 0
POST_TEST1 0
GOOD_ONE 0
QA_GOLD 0

SQL> drop restore point rp2;
Restore point dropped.

Solution 3: Disable Flashback
If solutions 1 and 2 fail or are not applicable, you may want to disable flashback in the database
temporarily. First shut down the database (if not down already):

SQL> shutdown immediate
Database closed.
Database dismounted.
ORACLE instance shut down.
Then start the database in mount mode:

SQL> startup mount
ORACLE instance started.
Total System Global Area 167772160 bytes
Fixed Size 1218316 bytes
Variable Size 67111156 bytes
Database Buffers 96468992 bytes
Redo Buffers 2973696 bytes
Database mounted.
Then disable flashback in the database:

SQL> alter database flashback off;
Database altered.

RMAN> delete noprompt backup of database;
RMAN> delete noprompt copy of database;

SQL> create restore point rp1;
SQL> flashback database to rp1;
SQL> create guaranteed restore point rp1;

Checking Space Usage in the FRA

SQL>select * from v$recovery_file_dest;

SQL> select * from v$flash_recovery_area_usage;

SQL> select
file_type,
space_used*percent_space_used/100/1024/1024 used,
space_reclaimable*percent_space_reclaimable/100/1024/1024 reclaimable,
frau.number_of_files
from v$recovery_file_dest rfd, v$flash_recovery_area_usage frau;

RMAN> backup as copy tablespace users;

Starting backup at 10-OCT-06
allocated channel: ORA_DISK_1
channel ORA_DISK_1: sid=146 devtype=DISK
channel ORA_DISK_1: starting datafile copy
input datafile fno=00004 name=/home/oracle/oradata/PRODB2/USERS.dbf
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03009: failure of backup command on ORA_DISK_1 channel at 10/10/2006 00:08:53
ORA-19809: limit exceeded for recovery files
ORA-19804: cannot reclaim 5242880 bytes disk space from 1073741824 limit
Note the error ORA-19804: cannot reclaim 5242880 bytes disk space from 1073741824
limit. To reclaim space from the flash recovery area at this time, you have to delete the redundant
backups yourself. For example:

RMAN> report obsolete;
RMAN retention policy will be applied to the command
RMAN retention policy is set to redundancy 1
Report of obsolete backups and copies
Type Key Completion Time Filename/Handle
-------------------- ------ ------------------ --------------------
Archive Log 5442 08-OCT-06
/home/oracle/oracle/product/10.2.0/db_1/flash_recovery_area/PRODB2/archivelog/➥
2006_10_08/o1_mf_1_40_2lmkv9mo_.arc
Datafile Copy 5461 27-SEP-06 /home/oracle/orabackup/Copy_data➥
D-PRODB2_I-3053038066_TS-SYSTEM_FNO-1_5ehubk8h
Datafile Copy 5462 27-SEP-06 /home/oracle/orabackup/Copy_data➥
D-PRODB2_I-3053038066_TS-UNDOTBS1_FNO-2_5hhubkbs
Datafile Copy 5463 27-SEP-06 /home/oracle/orabackup/Copy_data➥
D-PRODB2_I-3053038066_TS-SYSAUX_FNO-3_5fhubka9
Datafile Copy 5464 27-SEP-06 /home/oracle/orabackup/Copy_data➥
_D-PRODB2_I-3053038066_TS-USERS_FNO-4_5ihubkbv
Datafile Copy 5465 27-SEP-06 /home/oracle/orabackup/Copy_data➥
_D-PRODB2_I-3053038066_TS-EXAMPLE_FNO-5_5ghubkbc
To create even more space in the flash recovery area, you may want to remove the old
backups. The RMAN command delete obsolete does the trick:

RMAN> delete obsolete ;
RMAN retention policy will be applied to the command
RMAN retention policy is set to redundancy 1
using channel ORA_DISK_1


RMAN> delete noprompt obsolete;

Now that the backup piece is in the right directory, you must tell RMAN. First you need

to remove the identity of the backup piece from the RMAN repository using a process
generally known as uncataloging:

RMAN> change backuppiece
'/home/oracle/flasharea/PRODB2/backupset/2006_11_10➥
/o1_mf_nnndf_TAG20061110T175734_2ob0yzgp_.bkp' uncatalog;
uncataloged backuppiece
backup piece handle=/home/oracle/flasharea/PRODB2/backupset/2006_11_10/➥
o1_mf_nnndf_TA G20061110T175734_2ob0yzgp_.bkp recid=153 stamp=606160655
Uncataloged 1 objects

4. Then catalog the piece again with the correct file:

RMAN> catalog backuppiece
'/home/oracle/flasharea/PROD2/backupset/2006_11_10/o1_mf_n➥
nndf_TA G20061110T175734_2ob0yzgp_.bkp';

Sending Image Copies to the FRA

RMAN> backup as copy database;

Deleting Backup Sets from the FRA

rman target=/

Recovery Manager: Release 10.2.0.1.0 - Production on Wed Nov 8 00:20:58 2006
Copyright (c) 1982, 2005, Oracle. All rights reserved.
connected to target database: PRODB2 (DBID=3053038066)

RMAN> list backupset;

List of Backup Sets
===================
BS Key Type LV Size Device Type Elapsed Time Completion Time
------- ---- -- ---------- ----------- ------------ ---------------
157 Full 7.14M DISK 00:00:01 14-OCT-06
BP Key: 151 Status: AVAILABLE Compressed: NO Tag:➥
TAG20061014T233415
Piece Name: /home/oracle/flasharea/PRODB2/autobackup/2006_10_14/➥
o1_mf_n_6038
48055_2m3c1r1s_.bkp
Control File Included: Ckp SCN: 1909037 Ckp time: 14-OCT-06

2. Now, to delete a backup set, let’s say number 157, issue a delete backupset command:

RMAN> delete backupset 157;

RMAN> list archivelog all;

2. To delete the archived log sequences 78 and 79, you can use the following commands:

RMAN> delete archivelog from logseq=78 until logseq=79;

RMAN Using the Flash Recovery Area

1. Disable the parameters log_archive_dest and log_archive_duplex_dest, if they are set
in the database. You can do that by issuing the following commands:

SQL> alter system set log_archive_duplex_dest = '';
SQL> alter system set log_archive_dest = '';

2. Log on as a user with the sysdba role (such as the user sys) in preparation to create the
flash recovery area:

sqlplus / as sysdba (if logged in as the Oracle software owner)
sqlplus sys/ as sysdba

3. Issue the following commands to size and create the flash recovery area:

SQL> alter system set db_recovery_size = 4G;
SQL> alter system set db_recovery_dest = '/home/oracle/flasharea';

RMAN Examples Recover

$ mv /ora01/BRDSTN/users01.dbf /ora01/BRDSTN/users.bk
Once the datafile has been renamed, attempt to start your database as follows:

RMAN> connect target /
RMAN> startup

You should see a message similar to the following:
RMAN-03002: failure of startup command at 10/19/2006 16:13:07
ORA-01157: cannot identify/lock data file 4 - see DBWR trace file
ORA-01110: data file 4: 'C:\ORA01\BRDSTN\USERS01.DBF'


RMAN> connect target /
RMAN> startup mount;
RMAN> restore database;

You’ll see several lines of output as RMAN tells you what it is restoring. It should look
something like the following:
Starting restore at 19-OCT-06
allocated channel: ORA_DISK_1
channel ORA_DISK_1: sid=156 devtype=DISK
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
restoring datafile 00001 to C:\ORA01\BRDSTN\SYSTEM01.DBF
restoring datafile 00002 to C:\ORA01\BRDSTN\UNDOTBS01.DBF
restoring datafile 00003 to C:\ORA01\BRDSTN\SYSAUX01.DBF
restoring datafile 00004 to C:\ORA01\BRDSTN\USERS01.DBF
Next recover your database as follows:
RMAN> recover database;
You should see a message similar to this:
Starting recover at 19-OCT-06
using channel ORA_DISK_1
starting media recovery
media recovery complete, elapsed time: 00:00:07
Finished recover at 19-OCT-06
You can now open your database for use with the alter database open command:

RMAN> alter database open;

Reinstating a Damaged Datafile from an Image Copy
Problem



RMAN> report schema;

RMAN> list copy of datafile 5;

Take the damaged datafile offline, if not offline already:

RMAN> sql 'alter database datafile 5 offline';

Now, instruct the database to make the copy of the file in the flash recovery area, the
production datafile:

RMAN> switch datafile 5 to copy;

RMAN> recover datafile 5;

Bring the recovered datafile online:

RMAN> sql 'alter database datafile 5 online';

Backing Up the FRA to Tape

RMAN> run {
2> allocate channel c1 type sbt_tape;
3> backup recovery area;
4> };

SQL> select sum(bytes)/1024/1024
2 from dba_data_files;

Purging statistics from the SYSAUX tablespace

set linesize 120
set pagesize 100

SELECT * FROM V$SYSAUX_OCCUPANTS;

COLUMN "Item" FORMAT A25
COLUMN "Space Used (GB)" FORMAT 999.99
COLUMN "Schema" FORMAT A25
COLUMN "Move Procedure" FORMAT A40

SELECT occupant_name "Item",
space_usage_kbytes/1048576 "Space Used (GB)",
schema_name "Schema",
move_procedure "Move Procedure"
FROM v$sysaux_occupants
ORDER BY 1
/

select snap_interval, retention
from dba_hist_wr_control
/

select OCCUPANT_NAME,SCHEMA_NAME,SPACE_USAGE_KBYTES from V$sysaux_occupants;
/
SELECT
snap_id, begin_interval_time, end_interval_time
FROM
SYS.WRM$_SNAPSHOT
WHERE
snap_id = ( SELECT MIN (snap_id) FROM SYS.WRM$_SNAPSHOT)
UNION
SELECT
snap_id, begin_interval_time, end_interval_time
FROM
SYS.WRM$_SNAPSHOT
WHERE
snap_id = ( SELECT MAX (snap_id) FROM SYS.WRM$_SNAPSHOT)
/

SNAP_ID BEGIN_INTERVAL_TIME END_INTERVAL_TIME
---------- --------------------------------------------------------------------------- ---------------------------------------------------------------------------
15720 11-08-2008 19:00:25.442 11-08-2008 20:00:40.792
24219 21-09-2009 10:00:19.262 21-09-2009 11:00:41.262

BEGIN
dbms_workload_repository.drop_snapshot_range(low_snap_id => 7556, high_snap_id=>15000);
END;
/


select dbms_stats.get_stats_history_retention from dual;

Set retention of old stats to 10 days

exec dbms_stats.alter_stats_history_retention(10);

Purge stats older than 10 days (best to do this in stages if there is a lot of data (sysdate-30,sydate-25 etc)

exec DBMS_STATS.PURGE_STATS(SYSDATE-10);

Show available stats that have not been purged

SQL> select dbms_stats.get_stats_history_availability from dual;

GET_STATS_HISTORY_AVAILABILITY
---------------------------------------------------------------------------
26-08-2008 19:38:08.580380000 -05:00

Show how big the tables are and rebuild after stats have been purged

col Mb form 9,999,999
col SEGMENT_NAME form a40
col SEGMENT_TYPE form a6

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

MB SEGMENT_NAME SEGMEN
---------- ---------------------------------------- ------
0 WRI$_OPTSTAT_OPR TABLE
0 WRI$_OPTSTAT_AUX_HISTORY TABLE
88 WRI$_OPTSTAT_TAB_HISTORY TABLE
126 WRI$_OPTSTAT_IND_HISTORY TABLE
158 WRI$_OPTSTAT_HISTGRM_HISTORY TABLE
4,482 WRI$_OPTSTAT_HISTHEAD_HISTORY TABLEShow how big the indexes are ready for a rebuild after stats have been purged


col Mb form 9,999,999
col SEGMENT_NAME form a40
col SEGMENT_TYPE form a6
set lines 120
select sum(bytes/1024/1024) Mb, segment_name,segment_type from dba_segments
where tablespace_name = 'SYSAUX'
and segment_name like '%OPT%'
and segment_type='INDEX'
group by segment_name,segment_type order by 1 asc
/

MB SEGMENT_NAME SEGMEN
---------- ---------------------------------------- ------
0 WRH$_OPTIMIZER_ENV_PK INDEX
0 I_WRI$_OPTSTAT_OPR_STIME INDEX
0 I_WRI$_OPTSTAT_AUX_ST INDEX
88 I_WRI$_OPTSTAT_TAB_ST INDEX
105 I_WRI$_OPTSTAT_IND_ST INDEX
105 I_WRI$_OPTSTAT_H_ST INDEX
195 I_WRI$_OPTSTAT_TAB_OBJ#_ST INDEX
213 I_WRI$_OPTSTAT_H_OBJ#_ICOL#_ST INDEX
214 I_WRI$_OPTSTAT_IND_OBJ#_ST INDEX
2,055 I_WRI$_OPTSTAT_HH_ST INDEX
3,883 I_WRI$_OPTSTAT_HH_OBJ_ICOL_ST INDEX


Note that you cannot enable row movement and shrink the tables as the indexes are function based

alter table WRI$_OPTSTAT_IND_HISTORY enable row movement;
alter table WRI$_OPTSTAT_IND_HISTORY shrink space;


select 'alter table '||segment_name||' move tablespace SYSAUX;' from dba_segments where tablespace_name = 'SYSAUX'
and segment_name like '%OPT%' and segment_type='TABLE'

Run the rebuild table commands – note that this does cause any gather_stats jobs to fail

alter table WRI$_OPTSTAT_TAB_HISTORY move tablespace sysaux;
alter table WRI$_OPTSTAT_IND_HISTORY move tablespace sysaux;
alter table WRI$_OPTSTAT_HISTHEAD_HISTORY move tablespace sysaux;
alter table WRI$_OPTSTAT_HISTGRM_HISTORY move tablespace sysaux;
alter table WRI$_OPTSTAT_AUX_HISTORY move tablespace sysaux;
alter table WRI$_OPTSTAT_OPR move tablespace sysaux;
alter table WRH$_OPTIMIZER_ENV move tablespace sysaux;Script to generate rebuild statements

select 'alter index '||segment_name||' rebuild online parallel (degree 14);' from dba_segments where tablespace_name = 'SYSAUX'
and segment_name like '%OPT%' and segment_type='INDEX'

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


SQL>
INDEX_NAME INDEX_TYPE STATUS
------------------------------ --------------------------- --------
I_WRI$_OPTSTAT_AUX_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_HH_OBJ_ICOL_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_HH_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_H_OBJ#_ICOL#_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_H_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_IND_OBJ#_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_IND_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_OPR_STIME FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_TAB_OBJ#_ST FUNCTION-BASED NORMAL VALID
I_WRI$_OPTSTAT_TAB_ST FUNCTION-BASED NORMAL VALID
WRH$_OPTIMIZER_ENV_PK NORMAL VALID

Finally lets see what space has been saved with a retention date of 1 day and a gather schema stats for the SYSASDM schema

exec dbms_stats.alter_stats_history_retention(1);

select dbms_stats.get_stats_history_retention from dual;

MB SEGMENT_NAME SEGMEN
---------- ---------------------------------------- ------
0 WRI$_OPTSTAT_OPR TABLE
0 WRI$_OPTSTAT_AUX_HISTORY TABLE
3 WRI$_OPTSTAT_TAB_HISTORY TABLE
4 WRI$_OPTSTAT_IND_HISTORY TABLE
8 WRI$_OPTSTAT_HISTGRM_HISTORY TABLE
104 WRI$_OPTSTAT_HISTHEAD_HISTORY TABLE

MB SEGMENT_NAME SEGMEN
---------- ---------------------------------------- ------
0 WRH$_OPTIMIZER_ENV_PK INDEX
0 I_WRI$_OPTSTAT_OPR_STIME INDEX
0 I_WRI$_OPTSTAT_AUX_ST INDEX
2 I_WRI$_OPTSTAT_IND_ST INDEX
2 I_WRI$_OPTSTAT_TAB_ST INDEX
3 I_WRI$_OPTSTAT_TAB_OBJ#_ST INDEX
4 I_WRI$_OPTSTAT_IND_OBJ#_ST INDEX
5 I_WRI$_OPTSTAT_H_ST INDEX
9 I_WRI$_OPTSTAT_H_OBJ#_ICOL#_ST INDEX
41 I_WRI$_OPTSTAT_HH_ST INDEX
96 I_WRI$_OPTSTAT_HH_OBJ_ICOL_ST INDEX

Snapshots. Config en DBA_HIST_WR_CONTROL. Ej de cambio a intervalo de 30días cada
30min (expresado en minutos y si intervalo=0 no se calculan más snapshots):


SELECT snap_id, startup_time, begin_interval_time, end_interval_time
FROM dba_hist_snapshot
ORDER BY 1,2

– DBMS_WORKLOAD_REPOSITORY.modify_snapshot_settings(43200,30);
– DBMS_WORKLOAD_REPOSITORY.drop_snapshot_range (22, 32); Borra
rango

• Baselines. Pareja de snapshots (q ya no se borrarán).

Speed up ‘removal’ of old AWR reports

removing the entries takes ages and fails on undo errors … Metalink note Doc ID: 852028.1 states that I can safely remove the AWR metadata tables and recreate them.

SQL> connect / as sysdba
SQL> @?/rdbms/admin/catnoawr.sql
SQL> @?/rdbms/admin/catawrtb.sql


– DBMS_WORKLOAD_REPOSITORY.create_baseline (210, 220, 'batch baseline'); Snapshots
inicial y final, y nombre para el baseline

– DBMS_WORKLOAD_REPOSITORY.drop_baseline ( 'batch baseline', 'FALSE); Si
TRUE, borra los snaphosts asociados

• Informes AWR en $ORACLE_HOME/rdbms/admin (con salida en HTML o TEXTO):
– awrrpt.sql, pedirá formato salida (text o html), los snapshots inicial y final, y el nombre
del fichero del informe. Existe awrrpti.sql q permite seleccionar una instancia.
– awrsqrpt.sql, muestra estadísticas de una sentencia SQL para un rango de snapshots.
– awrddrpt.sql, compara atributos detallados de rendimiento y valores de configuración
entre dos períodos de tiempo.

viernes, 18 de septiembre de 2009

Oracle Multi-master Replication

Oracle Multi-master Replication

I’ll start with a high-level view of multi-master replication and introduce some basic concepts. Multi-master replication is such a complex topic that I can’t fully address every issue about it in this space. However, I hope you’ll be happy with a conceptual explanation of the mechanisms.

In a nutshell, multi-master replication is nothing more than a coordinated set of updateable snapshots. By “updateable,” I mean that the snapshot allows the FOR UPDATE clause in the snapshot definition. To illustrate this concept, refer to the example below, where you’ll see that the snapshot is allowed to propagate updates back to the master table.

create snapshot
customer_updatable_snap
refresh fast start with sysdate
next sysdate + 1/24
for update
query rewrite
as
select * from customer@master_site;

Multi-master Conflicts and Resolutions

At first blush, multi-master replication may appear straightforward. However, there is a dark side to the process. Whenever a snapshot has the ability to send updates to other “master” tables, you always run the risk of update conflicts. So what’s the best way to avoid and/or resolve those conflicts? Let’s start the lesson by reviewing multi-master conflict avoidance. Then we’ll dive head-first into the details of procedural replication, so we can see how it all fits together.

An update conflict occurs when one remote user overlays the updates made by a user on another database. Your multi-master replication model should detect and resolve conflicts. Unfortunately, detecting and resolving those conflicts can get extremely complex. Let’s start by looking at what conflicts can occur, and then we’ll look at mechanisms for resolving them.

Conflict Types
Here are the most common types of conflicts you’ll encounter with multi-master replication:

*
Uniqueness conflict — This conflict results from an attempt from two different sites to insert records with the same primary key. To avoid uniqueness conflicts, you can choose from three available options. Those three pre-built methods are called Append Site Name To Duplicate Value, Append Sequence To Duplicate Value, and Discard Duplicate Value.
*
Update conflict — This conflict is caused by simultaneous update operations on the same record.
*
Delete conflict — This type of conflict occurs when one transaction deletes a row that another transaction updates (before the delete is propagated).

Oracle provides several pre-written scripts to help in resolving conflicts. In the case of update conflicts, your only option is to write conflict-resolution routines, and deal with each conflict on a case-by-case basis. Fortunately, Oracle provides several pre-built methods for creating the routines. Click here for the details about Oracle conflict-resolution techniques.

Conflict Resolution Mechanisms
Here are the most common mechanisms at your disposal for resolving conflicts:

*
Latest Timestamp Value. With this simple technique, you apply updates as they are received. Based on timestamp value, the most recent updates overlays prior updates. This approach can result in situations where one user’s update gets overlaid by a more recent update.

*
Earliest Timestamp Value. This mechanism is the opposite of the latest timestamp value, in that the first update overlays subsequent updates. As you’d expect, not many shops use this method, but it is an option.

*
Minimum and Maximum Value. This mechanism may be used when the advanced replication facility detects a conflict with a column group. The advanced replication facility calls the minimum value conflict resolution method and then compares the new value from the originating site with the current value from the destination site for a designated column in the column group. You must designate that column when you select the minimum value conflict resolution method.

*
Additive and Average Value. When you’re dealing with replicated numeric values, this additive method adds a new value to the existing value using the following formula: (current value = current value + (new value - old value)). The average method averages the conflicting values into the existing value using the formula (current value = (current value + new value)/2).

*
Groups priority Value. Using this method, some groups have priority (a higher rank) over other groups. Therefore, the update associated with the highest-ranked group gets the update.

*
Site Priority Value. In this method, all master sites are NOT created equal. Some remote sites will have priority over other sites.

To illustrate how conflict resolution is defined, consider the example below. In this code, we execute dbms_repcat.add_update_resolution to direct Oracle to use the “latest timestamp” method for conflict resolution for updates to the EMP table.

execute dbms_repcat.add_update_resolution( -
sname => 'SCOTT', -
oname => 'EMP', -
column_group => 'EMP_COLGRP', -
sequence_no => 1, -
method => 'LATEST TIMESTAMP', -
parameter_column_name => 'EMPNO');

At this point, you should be starting to appreciate the complexity of conflict resolution in multi-master replication. Now let’s take a quick look at the techniques you can use to define procedural multi-master replication.


Implementing Procedural Multi-master Replication

Although Procedural multi-master replication is an extremely complex process, you can break down the basic steps for defining procedural replication into four phases:

*
Phase I: Pre-configuration. (Set-up Oracle parameters and catalog scripts.)
*
Phase II: Define the repadmin user and database links.
*
Phase III: Create master database and refresh groups.
*
Phase IV: Monitor the replication environment.

Let’s take a close look at each phase in turn.

Phase I: Pre-configuration Steps for Multi-master Replication

Before you’re ready to define a multi-master replication environment, there’s a short checklist you need to deal with up front. For every site that will be participating in the replication, you must check the values of these parameters:

1. Oracle parameters minimum settings

*
shared_pool_size=10m
*
global_names=true
*
job_queue_processes=4

To check those values, run this script on your database:

select
name,
value
from
v_$parameter
where
name in (
'job_queue_processes',
'global_names',
‘shared_pool_size’);

2. You also must be sure that the following dictionary scripts have been run from ORACLE_HOME/rdbms/admin. The catalog.sql was run when you created your instance, and the catproc.sql script is for the procedural option in Oracle.

*
catalog.sql
*
catproc.sql

Phase II: Set-up REPADMIN User and Database Links

The following illustrates some of the main steps you’ll follow in pre-creating the REPADMIN users and the required database links for multi-master replication. You should review these steps with great care.

REM Assign global name to the current DB
alter database rename global_name to PUBS.world;

REM Create public db link to the other master databases
create public database link NEWPUBS using 'newpubs';

REM Create replication administrator / propagator / receiver
create user
repadmin
identified by
repadmin
default tablespace
USER_DATA
temporary tablespace
TEMP
quota unlimited on
USER_DATA;

REM Grant privileges to the propagator, to propagate changes to remote
sites
execute dbms_defer_sys.register_propagator(username=>'REPADMIN');

REM Grant privileges to the receiver to apply deferred transactions
grant execute any procedure to repadmin;

REM Authorize the administrator to administer replication groups
execute dbms_repcat_admin.grant_admin_any_repgroup('REPADMIN');

REM Authorize the administrator to lock and comment tables
grant lock any table to repadmin;
grant comment any table to repadmin;

connect repadmin/repadmin

REM Create private db links for repadmin
create database link newpubs
connect to repadmin identified by repadmin;

REM Schedule job to push transactions to master sites
REM This will replicate every minute
execute dbms_defer_sys.schedule_push( -
destination => 'newpubs', -
interval => 'sysdate+1/24/60', -
next_date => sysdate+1/24/60, -
stop_on_error => FALSE, -
delay_seconds => 0, -
parallelism => 1);

REM Schedule job to delete successfully replicated transactions
execute dbms_defer_sys.schedule_purge( -
next_date => sysdate+1/24, -
interval => 'sysdate+1/24');

REM Test the database link
select global_name from global_name@newpubs;

Phase III: Create the Master Database and Refresh Groups

Once the repadmin user and the links are in place, you’re ready to define the replication. Again, this is an extremely complex process. However, the following script will provide you with the general steps to get the work done.

connect repadmin/repadmin



REM Create replication group for MASTERDEF site
execute dbms_repcat.create_master_repgroup('MYREPGRP');

REM Register objects within the group
execute dbms_repcat.create_master_repobject('SCOTT', -
'EMP', 'TABLE', gname=>'MYREPGRP');

execute dbms_repcat.make_column_group( -
sname => 'SCOTT', -
oname => 'EMP', -
column_group => 'EMP_COLGRP', -
list_of_column_names => 'EMPNO');

execute dbms_repcat.add_update_resolution( -
sname => 'SCOTT', -
oname => 'EMP', -
column_group => 'EMP_COLGRP', -
sequence_no => 1, -
method => 'LATEST TIMESTAMP', -
parameter_column_name => 'EMPNO');

REM Add master destination sites
execute
dbms_repcat.add_master_database( -
'MYREPGRP', -
'TD2.world');

REM Generate replication support for objects within the group
execute
dbms_repcat.generate_replication_support( -
'SCOTT', -
'EMP', -
'table');

Dropping Multi-master Replication

As you’d expect, there will be instances when you may need to turn-off multi-master replication. Some of the obvious cases include database maintenance activities such as upgrades and reorganizations. You can use this sample script to disable multi-master replication.

connect repadmin/repadmin


REM Stop replication
execute dbms_repcat.suspend_master_activity(gname=>'MYREPGRP');

REM Delete replication groups
-- execute dbms_repcat.drop_master_repobject('SCOTT', 'EMP',
'TABLE');
execute dbms_repcat.drop_master_repgroup('MYREPGRP');
execute dbms_repcat.remove_master_databases('MYREPGRP',
'newpubs.world');

REM Remove private database links to other master databases
drop database link newpubs.world;


connect sys

REM Remove the REPADMIN user
execute
dbms_defer_sys.unregister_propagator(username=>'REPADMIN');

execute

dbms_repcat_admin.revoke_admin_any_schema(username=>'REPADMIN')
;

drop user repadmin cascade;

REM Drop public database links to other master databases
drop public database link newpubs.world;

Phase IV: Monitoring Multi-master Replication

The final phase of implementing multi-master replication involves monitoring. A variety of dictionary views provide the key to monitoring complex multi-replication processes. I cannot stress enough the importance of checking these views on every database in the multi-master network.

*
DBA_REPSCHEMA. This view contains details for the replication schema
*
DBA_REPCATLOG. This view provides a log of all replication activities.
*
DBA_JOBS. Use this view to monitor all scheduled job in the database.
*
DBA_REPCAT. This view shows the replication catalog.
*
ALL_REPCONFLICT. This view provides a list of all replication conflicts.
*
ALL_REPRESOLUTION. For systems defined with pre-defined conflict resolution, this view lists the resolution of every conflict.
*
DBA_REPOBJECT. This view gives you a list of al replicated objects.
*
DBA_REPSITES. This view provides is a list of replicated sites.

At this point, you’ll want to closely review the following script, which is the one most commonly used to monitor procedural replication. Of course, you must run this script on each remote database.

connect repadmin/repadmin

set pages 50000

col sname format a20 head "SchemaName"
col masterdef format a10 head "MasterDef?"
col oname format a20 head "ObjectName"
col gname format a20 head "GroupName"
col object format a35 trunc
col dblink format a35 head "DBLink"
col message format a25
col broken format a6 head "Broken?"

prompt Replication schemas/ sites
select
sname,
masterdef,
dblink
from
sys.dba_repschema;

prompt RepCat Log (after a while you should see no entries):
select
request,
status,
message,
errnum
from
sys.dba_repcatlog;

prompt Entries in the job queue
select
job,
last_date,
last_sec,
next_date,
next_sec,
broken,
failures,
what
from
sys.dba_jobs
where
schema_user = 'REPADMIN';

prompt Replication Status:
select
sname,
master,
status
from
sys.dba_repcat;

prompt Returns all conflict resolution methods
select * from all_repconflict;

prompt Returns all resolution methods in use
select * from all_represolution;

prompt Objects registered for replication
select
gname,
type||' '||sname||'.'||oname object,
status
from
sys.dba_repobject;

select * from dba_repsites;

Resources for Defining Multi-master Replication

When it comes to defining multi-master replication for your shop, you don’t have to start from scratch. Oracle offers the following pre-defined PL/SQL packages that can assist you:

*
dbms_repcat package — This complex package provides over 50 stored procedures. Follow this link for a listing of the procedures in dbms_repcat.
*
dbms_reputil package — This package contains several stored procedures. Here is a list of the procedures in dbms_reputil.
*
dbms_defer_sys package — This collection contains 19 replication procedures. Here is a list of the procedures in dbms_defer_sys.

viernes, 11 de septiembre de 2009

Oracle Application Server 10g

Ver Plugins Instalados
about:plugins

/u01/app/oracle/j2ee2/opmn/conf
Archivo de Configuracion opmn.xml

bash-3.00$ vi opmn.xml

Luego de Modificar el Archivo se debe ejecutar

bash-3.00$ dcmctl updateconfig


SERVICIOS

opmnctl startall

DISCOVERER

http://fenix123.oracle.com:7778/discoverer/portletprovider

OIDDAS

http://fenix122.oracle.com:7777/oiddas/


INFRAESTRUCTURA

Oracle Identity Management

cd $ORACLE_HOME/bin

./oidadmin

usuario: orcladmin


DISCOVER CREATE END USER LAYER

eulapi -connect biuser/biuser@immr -create_eul -default_tablespace USERS -temporary_tablespace TEMP -private

-create_eul
-connect <**********>
-private
-default_tablespace USERS
-temporary_tablespace TEMP
Command completed.
-bash-3.00$ eulapi -connect biuser/biuser@immr -load "Sales History" -user sh_comp -object channels -object countries -object customers -object products -object times -object costs -object sales -log load.log
-load Sales History
-connect <**********>
-log load.log
-object channels
-user sh_comp
-object countries
-object customers
-object products
-object times
-object costs
-object sales
Command completed.

DISCOVERE PLUS

http://fenix123.oracle.com:7778/discoverer/plus


Editar mod_oc4j.conf en /u01/app/oracle/j2ee1/Apache/Apache/conf/

En este Archivo se encuentra la configuracion de todos los servicios de OAS Capa Media

CONFIGURACION DE FORMS

forms.conf

/u01/app/oracle/j2ee1/forms/server

Configuracion Funcione Java

/u01/app/oracle/j2ee1/forms/server

formsweb.cfg

jpi_mimetype=application/x-java-applet;jpi-version=1.4.2_06
jpi_mimetype=application/x-java-applet;jpi-version=1.6.0_01

Actualiza un archivo po linea de comandos se debe ejecutar

dcmctl updateconfig -ct ohs
dcmctl restard -ct ohs
dcmctl start -ct ohs

Kill -1 reiniciar un proceso

cd /u01/app/oracle/j2ee1/opmn/logs ver los Archivos segun el error

ODL (Oracle Diagnostic Loader) Estandar

EL log loader es un log para guardar en la base de datos esta en la siguiente ruta

/u01/app/oracle/j2ee1/dcm/logs/dcmctl_logs

Modificar el Archivo para crear repositorio en base de datos

/u01/app/oracle/immr/diagnostic/config/ archivo logloader.xml

Para borrar los logs luego de crear el repositorio en bd

SQL> @ORACLE_HOME/diagnostics/admin/dmrep_cleanup 7 DAY

bash-3.00$ export LD_LIBRARY_PATH=$ORACLE_HOME/lib
bash-3.00$ ./logloader -storePassword -user dmrepuser -pwd dmreppwd

EL archivo logloader.xml debe quedar asi.









Configuracion OC4J

Farm > Application Server: j2ee1.fenix123.oracle.com > OC4J: home >

Java Options

-Xmx8m -Xms8m -Xss64k

AggreSpy Performance

http://127.0.0.1:7201/dmsoc4j/AggreSpy

CAMBIAR PASSWORD OID - ODS

dpasswd to change the ODS password.

Probar Servicios Ldap

ldapbind -h fenix120.oracle.com -p 2103

oidctl

viernes, 4 de septiembre de 2009

Roles y Privilegios

Ver Privilegios de sysdba

SELECT grantee,granted_role from DBA_ROLE_PRIVS where granted_role='DBA';

select * from v$pwfile_users;

SQL> select * from v$pwfile_users;

USERNAME        SYSDB SYSOP SYSAS SYSBA SYSDG SYSKM     CON_ID
------------------------------ ----- ----- ----- ----- ----- ----- ----------
SYS        TRUE  TRUE  FALSE FALSE FALSE FALSE     0
SYSDG        FALSE FALSE FALSE FALSE TRUE  FALSE     0
SYSBACKUP        FALSE FALSE FALSE TRUE  FALSE FALSE     0
SYSKM        FALSE FALSE FALSE FALSE FALSE TRUE     0

Solaris 10 Manejo de Zonas

How to Reboot a Zone
You must be the global administrator in the global zone to perform this procedure.

Become superuser, or assume the Primary Administrator role.

To create the role and assign the role to a user, see Using the Solaris Management Tools With RBAC (Task Map) in System Administration Guide: Basic Administration.

List the zones running on the system.

global# zoneadm list -v

You will see a display that is similar to the following:


ID NAME STATUS PATH BRAND IP
0 global running / native shared
1 my-zone running /export/home/my-zone native shared

Use the zoneadm command with the -z reboot option to reboot the zone my-zone.

global# zoneadm -z my-zone reboot

List the zones on the system again to verify that my-zone has been rebooted.

global# zoneadm list -v

You will see a display that is similar to the following:

ID NAME STATUS PATH BRAND IP
0 global running / native shared
2 my-zone running /export/home/my-zone native shared

miércoles, 2 de septiembre de 2009

Date Functions

Date Calculations

Returns A Day A Specified Number Of Days In The Future Skipping Weekends

CREATE OR REPLACE FUNCTION business_date (start_date DATE,
Days2Add NUMBER) RETURN DATE IS
Counter NATURAL := 0;
CurDate DATE := start_date;
DayNum POSITIVE;
SkipCntr NATURAL := 0;
BEGIN
WHILE Counter < Days2Add LOOP
CurDate := CurDate+1;
DayNum := TO_CHAR(CurDate, 'D');

IF DayNum BETWEEN 2 AND 6 THEN
Counter := Counter + 1;
ELSE
SkipCntr := SkipCntr + 1;
END IF;
END LOOP;
RETURN start_date + Counter + SkipCntr;
END business_date;
/


Business Date function, above, enhanced by Larry Benton to handle negative values for the days2add parameter.

CREATE OR REPLACE FUNCTION business_date (start_date DATE,
days2add NUMBER) RETURN DATE IS
Counter NATURAL := 0;
CurDate DATE := start_date;
DayNum POSITIVE;
SkipCntr NATURAL := 0;
Direction INTEGER := 1; -- days after start_date
BusinessDays NUMBER := Days2Add;
BEGIN
IF Days2Add < 0 THEN
Direction := - 1; -- days before start_date
BusinessDays := (-1) * BusinessDays;
END IF;

WHILE Counter < BusinessDays LOOP
CurDate := CurDate + Direction;
DayNum := TO_CHAR( CurDate, 'D');

IF DayNum BETWEEN 2 AND 6 THEN
Counter := Counter + 1;
ELSE
SkipCntr := SkipCntr + 1;
END IF;
END LOOP;

RETURN start_date + (Direction * (Counter + SkipCntr));
END business_date;
/

Returns The First Day Of A Month


CREATE OR REPLACE FUNCTION fday_ofmonth(value_in DATE)
RETURN DATE IS
vMo VARCHAR2(2);
vYr VARCHAR2(4);
BEGIN
vMo := TO_CHAR(value_in, 'MM');
vYr := TO_CHAR(value_in, 'YYYY');
RETURN TO_DATE(vMo || '-01-' || vYr, 'MM-DD-YYYY');
EXCEPTION
WHEN OTHERS THEN
RETURN TO_DATE('01-01-1900', 'MM-DD-YYYY');
END fday_ofmonth;
/

Time Calculations

CREATE OR REPLACE FUNCTION time_diff (
DATE_1 IN DATE, DATE_2 IN DATE) RETURN NUMBER IS

NDATE_1 NUMBER;
NDATE_2 NUMBER;
NSECOND_1 NUMBER(5,0);
NSECOND_2 NUMBER(5,0);

BEGIN
-- Get Julian date number from first date (DATE_1)
NDATE_1 := TO_NUMBER(TO_CHAR(DATE_1, 'J'));

-- Get Julian date number from second date (DATE_2)
NDATE_2 := TO_NUMBER(TO_CHAR(DATE_2, 'J'));

-- Get seconds since midnight from first date (DATE_1)
NSECOND_1 := TO_NUMBER(TO_CHAR(DATE_1, 'SSSSS'));

-- Get seconds since midnight from second date (DATE_2)
NSECOND_2 := TO_NUMBER(TO_CHAR(DATE_2, 'SSSSS'));

RETURN (((NDATE_2 - NDATE_1) * 86400)+(NSECOND_2 - NSECOND_1));
END time_diff;
/

Calculating time from seconds

SELECT DECODE(FLOOR(999999/86400), 0, '',
FLOOR(999999/86400) || ' day(s), ') ||
TO_CHAR(TO_DATE(MOD(999999, 86400),'SSSSS'), 'HH24:MI:SS') AS elapsed
FROM dual;

FUNCTION SQL Examples

FUNCION TO_CHAR

SQL> SELECT DISTINCT(TO_CHAR(HGO_FCH_REGISTRO,'YYYY')) FROM HIS_SEG_OFERTA;

(TO_CHAR(HGO_FCH_REGISTRO,'YYY
---------------------------------------------------------------------------
2009
2019
2006
2008
2007
2005
2022

SELECT * FROM HIS_SEG_OFERTA WHERE TO_CHAR(HGO_FCH_REGISTRO,'YYYY') > 2009
/

martes, 1 de septiembre de 2009

Oracle RAC Comands

VER ESTADO SERVICIOS DEL CLUSTER

$ crs_stat -t

Name Type Target State Host
------------------------------------------------------------
ora....01.lsnr application ONLINE ONLINE ct1b...ip01
ora....p01.gsd application ONLINE OFFLINE
ora....p01.ons application ONLINE OFFLINE
ora....p01.vip application ONLINE ONLINE ct1b...ip01
ora....02.lsnr application ONLINE ONLINE ct1b...ip02
ora....p02.gsd application ONLINE ONLINE ct1b...ip02
ora....p02.ons application ONLINE OFFLINE
ora....p02.vip application ONLINE ONLINE ct1b...ip02
ora.sirs.db application ONLINE ONLINE ct1b...ip02
ora....s1.inst application ONLINE ONLINE ct1b...ip01
ora....s2.inst application ONLINE ONLINE ct1b...ip02
ora...._srv.cs application OFFLINE OFFLINE
ora....rs1.srv application OFFLINE OFFLINE
ora....rs2.srv application OFFLINE OFFLINE

SUBIR SERVICIOS DEL NODEAPPS

$ srvctl start nodeapps -n ct1bosunsipip02
$ crs_stat -t
Name Type Target State Host
------------------------------------------------------------
ora....01.lsnr application ONLINE ONLINE ct1b...ip01
ora....p01.gsd application ONLINE ONLINE ct1b...ip01
ora....p01.ons application ONLINE ONLINE ct1b...ip01
ora....p01.vip application ONLINE ONLINE ct1b...ip01
ora....02.lsnr application ONLINE ONLINE ct1b...ip02
ora....p02.gsd application ONLINE ONLINE ct1b...ip02
ora....p02.ons application ONLINE ONLINE ct1b...ip02
ora....p02.vip application ONLINE ONLINE ct1b...ip02
ora.sirs.db application ONLINE ONLINE ct1b...ip02
ora....s1.inst application ONLINE ONLINE ct1b...ip01
ora....s2.inst application ONLINE ONLINE ct1b...ip02
ora...._srv.cs application OFFLINE OFFLINE
ora....rs1.srv application OFFLINE OFFLINE
ora....rs2.srv application OFFLINE OFFLINE

SUBIR LISTENER CLUSTER

srvctl start listener -n ct1bosunsipep01

SUBIR TODOS LOS SERVICIOS

$ crs_start -all

bash-3.00$ crs_stat -t
Name Type Target State Host
------------------------------------------------------------
ora....01.lsnr application ONLINE ONLINE ct1b...ip01
ora....p01.gsd application ONLINE ONLINE ct1b...ip01
ora....p01.ons application ONLINE ONLINE ct1b...ip01
ora....p01.vip application ONLINE ONLINE ct1b...ip01
ora....02.lsnr application ONLINE ONLINE ct1b...ip02
ora....p02.gsd application ONLINE ONLINE ct1b...ip02
ora....p02.ons application ONLINE ONLINE ct1b...ip02
ora....p02.vip application ONLINE ONLINE ct1b...ip02
ora.sirs.db application ONLINE ONLINE ct1b...ip02
ora....s1.inst application ONLINE ONLINE ct1b...ip01
ora....s2.inst application ONLINE ONLINE ct1b...ip02
ora...._srv.cs application ONLINE ONLINE ct1b...ip02
ora....rs1.srv application ONLINE ONLINE ct1b...ip01
ora....rs2.srv application ONLINE ONLINE ct1b...ip02


# Start and stop cluster
srvctl start database -d db10g
srvctl stop database -d db10g

# Start and stop individual instance
srvctl start instance -d db10g -i db10g1
srvctl stop instance -d db10g -i db10g1

# Get status of whole database or specific instance
srvctl status database -d db10g
srvctl status instance -d db10g -i db10g1

# Get current database config
srvctl config database -d db10g

start_crs.sh
/app/oracle/crs/10.2.0.3/bin/crsctl start crs

stop_crs.sh
/app/oracle/crs/10.2.0.3/bin/crsctl stop crs

status_crs.sh
/app/oracle/crs/10.2.0.3/bin/crs_stat -t


- Dirección pública e interconnect.
$ORA_CRS_HOME/bin/oifcfg getif

- Para las direcciones virtuales
$ srvctl config nodeapps -n nombre_nodo -a

rac1-> srvctl status nodeapps -n rac1
VIP is running on node: rac1
GSD is running on node: rac1
Listener is running on node: rac1
ONS daemon is running on node: rac1

rac1-> srvctl status nodeapps -n rac2
VIP is running on node: rac2
GSD is running on node: rac2
Listener is running on node: rac2
ONS daemon is running on node: rac2


rac1-> srvctl status asm -n rac1
ASM instance +ASM1 is running on node rac1.

rac1-> srvctl status asm -n rac2
ASM instance +ASM2 is running on node rac2.

rac1-> srvctl status database -d devdb
Instance devdb1 is running on node rac1
Instance devdb2 is running on node rac2

rac1-> srvctl status service -d devdb

Check ONS Daemon si esta corriendo

onsctl ping


ORACLE_HOME/bin/onsctl help

usage: ORACLE_HOME/bin/onsctl

start|stop|ping|reconfig|debug
start - Start opmn only.
stop - Stop ons daemon
ping - Test to see if ons daemon is running
debug - Display debug information for the ons
daemon
reconfig - Reload the ons configuration
help - Print a short syntax description
(this).

$ onsctl start
onsctl: ons started


lLSNRCTL> set help
The following operations are available after set
An asterisk (*) denotes a modifier or extended command:

password rawmode
displaymode trc_file
trc_directory trc_level
log_file log_directory
log_status current_listener
inbound_connect_timeout startup_waittime
save_config_on_stop dynamic_registration

LSNRCTL> show inbound_connect_timeout
Connecting to (ADDRESS=(PROTOCOL=tcp)(HOST=)(PORT=1521))
LISTENER parameter "inbound_connect_timeout" set to 60
The command completed successfully


srvctl status service -d sirspe Ver servicios

Verificar instalacion CRS

/app/oracle/crs/10.2.0.3/bin/ olsnodes -n

$ olsnodes -n
ct1bosunsipep01 0
ct1bosunsipep02 1


CHEQUEAR EL TIPO DE FAILOVER

select instance_name, host_name,
NULL AS failover_type,
NULL AS failover_method,
NULL AS failed_over
FROM v$instance
UNION
SELECT NULL, NULL, failover_type, failover_method, failed_over
FROM v$session
WHERE username = 'SYSTEM';

VER SERVICIO DEL CLUSTER EN CADA UNO DE LOS NODOS

srvctl status database -d sirspe

VER SERVICIOS DEL CLUSTER

crs_stat -t

SUBIR TODOS LOS SERVICIOS DEL CLUSTER

crs_start -all

BAJAR TODOS LOS SERVICIOS DEL CLUSTER

crs_stop -all


srvctl start nodeapps -n
srvctl start nodeapps -n
srvctl start asm -n
srvctl start asm -n
srvctl start database -d
srvctl start service -d -s

crs_stat -t

srvctl stop service -d -s
srvctl stop database -d
srvctl stop asm -n
srvctl stop asm -n
srvctl stop nodeapps -n
srvctl stop nodeapps -n


Shut down the Oracle Cluster Synchronization Services (CSS) daemon as the root user:

# /etc/init.d/init.cssd stop


Shut down all ASM instances on all nodes. To shut down an ASM instance, enter the following command where node is the name of the node where the ASM instance is running:

$ oracle_home/bin/srvctl stop asm -n node

Stop all node applications on all nodes. To stop node applications running on a node, enter the following command where node is the name of the node where the applications are running:

$ oracle_home/bin/srvctl stop nodeapps -n node