Oracle Tuning Basics

Life Cycle of a Cursor

The following describes the steps carried out during the processing a cursor:

Open Cursor: A memory structure for the cursor is allocated in the server-side memory of the server process associated with the session - user global area (UGA). At this there isn’t a SQL statement associated with the cursor yet.

Parse Cursor: A SQL statement is associated with the cursor at this point. Its parsed representation which includes the execution plan is loaded into the shared pool - library cache. The structure in the UGA is updated with the pointer to the location of the shareable cursor in the library cache.

Define Output Variables: If the SQL statement will return data, the variables to receive that data must be defined. This holds true for queries, DELETE, INSERT, and UPDATE statements that use the RETURNING clause.

Bind Input Variables: If the SQL statement uses bind variables; their values have to be specified (provided). Checking isn’t performed during the binding stage. If the data being passed is invalid then a runtime error will be raised during the actual execution.

Execute Cursor: The SQL statement is executed but be warned that the Engine doesn’t always perform anything of significance during this phase. Generally, for many types of queries, the actual processing occurs during the fetch phase.

Fetch Cursor: If the SQL statement is going to return data then this is the step that retrieves that data. This is the step (phase) where most of the processing is performed, especially for queries. For queries, rows might be partially fetched - meaning that the cursor might be closed before all of the rows are fetched!

Close Cursor: The resources associated with the cursor in the UGA are freed and made available for other cursors. The shareable cursor in the library cache remains and in the future it may be reused - that is the hope.

In order to understand this process it may be best to think about each step being executed separately in the order show below. In practice though, different optimization methods (techniques) are used to attempt to speed up the overall processing.

Parsing Processing Narrative

VPD Predicates: If you are using Virtual Private Database (VPD), formerly know as row-level security and it is active for one of the tables referenced in the parsed SQL statement, the predicates generated by the security policies are included in the WHERE clause.

Check Syntax, Semantics and Access Rights: This stage validates that the SQL statement is in fact correctly formed in terms of syntax, semantics and that all of the objects referenced by the statement exist and that the user has the necessary privileges to access them.

Store Parent Cursor in Library Cache: When a shareable parent cursor is not available yet then memory is allocated from the library cache and a new parent cursor is stored within that memory. The key information associated with the parent cursor is the text of the SQL statement.

Logical Optimization: It is during this phase that the new and semantically equivalent SQL statements are produced by applying different transformation techniques. The number of execution plans considered search space increases. The transformations increase the number of execution plans considered otherwise, the search space is limited.

Physical Optimization: Several options are performed during this stage the first step is to generate the execution plans related to each SQL statement resulting from the previous - Logical Optimization step. Then, based on the statistics found in the data dictionary or gather by dynamic sampling a cost is mapped (assigned) to each execution plan. Then the execution plan with the lowest cost is selected - hopefully, the most efficient execution plan is chosen from all of those generated in the search space.

Store Child Cursor: Memory is allocated and the shareable child cursors occupy that memory space and the children are mapped back to the parent cursor. The key elements associated with the child cursor are the execution plan and the execution environment.

Once the parent and child cursors are stored in the library cache they can be viewed via the views v$sqlarea and v$sql - the parent via v$sqlarea and the children via v$sql. The cursors are identified by accessing three columns address, hash_value, and child_number. In 10g+ you can use sql_id instead of the pair address and hash_value.

When shareable parent and child cursors are available and only the first two operations are carried out then the parse is termed a soft parse and when all of the operations are performed that is termed a hard parse.

Performance Implications

In regards to performance hard parses should be avoided like the plague. The whole purpose, the existence of shareable cursors in the library cache is to reuse the shareable cursors in the library cache. There are two primary reasons why hard parses are expensive in terms of resource consumption: the first is that the logical and physical optimizations are highly intensive CPU operations and the second is that memory is required for storing the parent and child cursors in the library cache. The library cache is shared across all sessions requiring the memory allocations for the library cache to be serialized. A latch protects the shared pool has to be obtained before the memory can be allocated for both the parent and the child cursors. Even if the impact of soft parses are lower than that of hard parses it is desirable to avoid soft parses as well because they require memory serialization the same as hard parses.

In order to search for a shareable cursor a latch must be obtained before the library cache can be searched. In summary, both soft and hard parses should be avoided as much as possible because by their very nature they limit the scalability of applications.

Shareable Cursors

The result or outcome of a parse operation is the generation of a parent and child cursor that ends up stored in the library cache. Obviously, the purpose of storing these two objects is so that they can be reused and thereby result in avoidance of a hard parse.

To understand how the sharing of parent and child cursors works several examples will be used to help illustrate the concept. The first example will illustrate the case where a parent cursor can not be shared. The essential information related to a parent cursor is its SQL text. Several SQL statements share the same parent cursor if their text is exactly the same and this is one of the basic requirements. The most common examples of demonstrating this concept is to use SQL statements that differ only in case (upper and lower) and then statements that have whitespace differences.

select oprid from psoprdefn where oprid != NULL;
select OPRID FROM PSOPRDEFN WHERE oprid != null;
select oprid from psoprdefn where oprid != NULL;
select oprid FROM PSOPRDEFN WHERE oprid != null;

The 1st and 3rd SQL statements will share the same parent cursor, however, the 2nd and 4th statements will each show up in v$sqlarea with unique plans because of the whitespace in statement 4 and statement 2 won’t match statements 1 or 3 because of case.

Use select sql_id, sql_text, executions from v$sqlarea where sql_text like ‘oprid’;

The next set of SQL statements illustrate the case where the parent cursor but not the child cursor can be shared. The key here is that the execution environment is related to the child cursor as well as the execution plan. The execution environment is a key because if it changes then the execution may change as well. As a result SQL statements are able to share the same child cursor only if they share the same parent cursor and their exeuction environments are compatible. To show this the same SQL statement is executed with two different values used for the initialization parameter optimizer_mode.

alter session set opimizer_mode=all_rows;

select count(*) from psoprdefn;

alter session set optimizer_mode=first_rows_10;

select count(*) from psoprdefn;

The result is that a single parent cursor and two child cursors are created. It is key to note that both child cursors have the same execution plan (the column plan_hash_value are the same, have the same value). This illustrates very well that a new child cursor was generated because of a difference in execution environment and not because another execution plan was generated.

select sql_id, child_number, sql_text, optimizer_mode, plan_hash_value
from v$sql
where sql_id = (select prev_sql_id from v$session where sid=sys_context(’userenv’,’sid’));

In order to discover which mismatch led to several child cursors it is possible to query the view v$sql_shared_cursor. You may be able to find that for each child cursor except the first one, why it was not possible to share a previously created child cursor. For several types of incompatibility there is a column that is set to either N (not a mismatch) or Y (mismatch) - there are 60 types of incompatibility in Oracle 11g. Use the following query to confirm that for the previous example, the mismatch for the second child cursor was because of a different optimizer mode. You need to be aware that this view may not provide you with a reason for ALL situations.

select child_number, optimizer_mode_mismatch
from v$sql_shared_cursor where sql_id = ”;

Get the from the previous SQL statement.

It is common to see quite a few hard parses caused by nonshared parent cursors than nonshared child cursors. In fact it is more common to discover that there are few child cursors for each parent cursor. If the parent cursors cannot be shared then that means the text of the SQL statements is constantly changing. This is common if either the SQL statements are dynamically generated or literals are used instaed of bind variables. Dynamically generated SQL statements cannot be avoided. It may be possible to use bind variables but it is not always good to use them for some sitations.

Bind Variables

Bind variables impact applications and especially PeopleSoft in two ways. They make programming either easier or more difficult depending on whether or not less or more code is written. If you are writing PL/SQL code it is easier to execute that code with bind variables. If you are programming using Java then it may be easier to execute your code without the use of bind variables. In terms of performance bind variables can be a good and a bad influence.

Advantage

The postive side of bind variables is their use can influence the sharing of cursors located in the library cache in a positive way and avoid the hard parses and the overhead associated with hard parses.

The use of bind variables can cause fewer child cursors to be generated and result in more matches and hence fewer hard parses. However, there are situations where child cursors are generated when bind variables are used. An example is a SQL statement where the size of a variable changes and this will result in a child cursor being created because the execution environment will have changed if an earlier (previous) incarnation of a similar SQL statement used a different size for the same variable.

example:

variable oprid number
variable addr1 varchar2(32)

execute :oprid := 232911; :addr1 := ‘380 Lake Avenue’;
insert into psoperdefn (oprid, addr1) values (:oprid, :addr1);
execute :oprid := 23912; :addr1 := ‘400 Michigan Street’;
insert into psoperdefn (oprid, addr1) values (:oprid, :addr1);
execute :oprid := 23913; :addr1 := ‘500 Gator Way’;
insert into psoprdefn (oprid, addr1) values (:oprid, :addr1);

select sql_id, child_number, executions
from v$sql where sql_text = ‘insert into psoprdefn (oprid, addr1) values (:oprid, :addr1)’;

SQL_ID CHILD_NUMBER EXECUTIONS
————- ———— ———-
953fbsj1crntc             0 6

I ran the procedure twice and the above shows that no child cursors were generated and I used bind variables. The next example below is going to change the size of addr1 by 1 to a size of 33 - this will be the only change.

variable oprid number
variable addr1 varchar2(33)

execute :oprid := 232914; :addr1 := ‘600 West Lake Avenue’;
insert into psoprdefn (oprid, addr1) values (:oprid, :addr1);
execute :oprid := 232915; :addr1 := ‘400 North Michigan Street’;
insert into psoprdefn (oprid, addr1) values (:oprid, :addr1);
execute :oprid := 232916; :addr1 := ‘500 East Gator Way’;
insert into psoprdefn (oprid, addr1) values (:oprid, :addr1);

SQL_ID         CHILD_NUMBER EXECUTIONS
————————- ———— —————–
953fbsj1crntc                                0 3
953fbsj1crntc                                1 3

The new child cursor was created because of the environment change as described above. The mismatch can be confirmed with the following SQL:

select child_number, bind_mismatch
from v$sql_shared_cursor
where sql_id = ‘953fbsj1crntc’
/

CHILD_NUMBER BIN
—————————
0                                N
1                                 Y

This happens because the database engine applies what is know as bind variable graduation. The purpose of this feature is to minimize the number of child cursors by graduating bind variables (which vary in size) into four groups driven by size. The first group contains the bind variables with up to 32 bytes, the second contains bind variables between 33 and 128 bytes and the third contains the bind variables between 129 and 2,000 bytes while the last group contains the bind variables of more than 2,000 bytes in size. Bind variables of datatype NUMBER are graduated to their maximum lenghth which is 22 bytes. As the next SQL statement illustrates the view v$sql_bind_metadata displays the maximum size of a group. Notice how the value of 128 is used, even if the variable of child cursor 1 is defined as 33.

select s.child_number, m.position, m.max_length,
decode(m.datatype,1,’VARCHAR2′,2,’NUMBER’,m.datatype) as datatype
from v$sql s, v$sql_bind_metadata m
where s.sql_id = ‘953fbsj1crntc’
and s.child_address = m.address
order by 1, 2
/

CHILD_NUMBER POSITION MAX_LENGTH DATATYPE
———— ———- ———- —————————————-
0                               1            22 NUMBER
0                               2            32 VARCHAR2
1                                1            22 NUMBER
1                                2          128 VARCHAR2

Each time a new child cursor is created, a new execution plan is generated. Whether this new execution plan is equal to one used by another child cursor will also depend on the value of the bind variables.

How to Grey Out Process Server Name, Recurrence, etc.

Some clients perfer to remove the ability to select a specific process scheduler, Recurrence and Type from the user’s profile for whatever reasson - security, force process requests to default to a specific process scheduler, etc.

In order to accomplish this you need to identify the user’s primary permissions list by viewing their profile. In general the field at the bottom of the page labeled “Primary” is their primary permission list. You need to go to the primary permission list for that user and click on the Process tab.

On the Process page, click on the link to the Process Profile Permissions. Once you have reached that page you need to uncheck the following flags and then save the changes before navigating away from this page:

  • Override Server Parameters
  • Override Output Parameters
  • Update Server Status
  • Enable Recurrence Selection

After saving the permission list you have to bounce your application server to enable the changes you just made. To grey out the Type and Format fields you have to override these fields at the process definition level for each process.

To make this change the navigation is as follows:

  1. Go to the Process Definition and open the Destination Page. To use an example you can change the Type field to File and the Destination Source to Process Definition.
  2. Save the definition. The user may be able to make changes to the process definition but they should be ignored because the defaults for the Process Definition will override any user selections.
  3. To verify if the Output Destination Type is being overridden correctly by the process definition, look at the parameter link on the Details page of Process Monitor. The parameters link contains the actual flags that are passed in the command line. The -OT flag determines the Output Destination Type.

The values for Output Destination Type, -OT are:

  1. Any
  2. None
  3. File
  4. Printer
  5. Window
  6. Email
  7. Web
  8. Default

Subtract one from the above values (WordPress won’t let me force the numbering to start with zero). After making changes to the process definitions you have to reboot the application server and process scheduler to ensure that the changes are recognized.

Restore Archive Logs to New Location using RMAN

Restore Archive Logs to New Location using RMAN

Oracle up to 10g

When attempting to restore archive logs that are already located on disk using RMAN you’ll receive an error if the archivelogs are stored within ASM because until Oracle 11g shipped you could not use the OS copy or move command to retrieve them.

The solution is to use RMAN to copy them from ASM to an OS filesystem:

RMAN> copy archivelog ‘+psdisk1/ORCLSID/archivelog/2008_10_30/thread_1_seq_2.245.88866622′ to ‘/tmp/oraclearchive’;

You would have to repeat this command for each archive log to be copied or try the following solution:

RMAN> change archivelog from logseq=60 until logseq=70 uncatalog;

Once the archivelos have been successfully uncataloged you are now able to successfully restore the archive logs to a new location.

RMAN> run {
set archivelog destination to ‘/tmp’;
restore archivelog from logseq=60 until logseq=70;
}

Following the successful restore of the archivelogs you can then continue to recatalog the archivelogs back into the ASM diskgroup.

Example:

RMAN> catalog archivelog ‘+psdisk1/ORCLSID/archivelog/2008_10_30/thread_1_seq.60.245.888666222′;

How To Move Datafile from a File System to ASM

Up to 10g R2:

Moving a datafile from the file system can be achieved in two ways:

1. While the database is in shutdown or mount stage
2. While the database is running with the select tablespace offline

Moving an Oracle datafile is in mount state is performed in the following way:

1. Shutdown and mount the database

SQL> shutdown immediate;
SQL> startup mount;

Check disk space in the ASM diskgroup you want to copy the datafile to:

SQL> select file#, name, (bytes/1048576) File_size_MB from v$datafile;

export ORACLE_SID=+ASM

SQL> select name, state, total_mb, free_mb from v$asm_diskgroup;

$ rman target=/
RMAN> copy datafile 4 to ‘+psdisk2′;

Update the controlfile with the new location of the datafile:

$ rman target /
RMAN> switch datafile 4 to copy;

The file is now in the new location;

SQL> select name from v$datafile;

The database may now be opened.

While the Database is Running (with the selected tablespace offline)

In order to move a datafile on a running active database, the tablespace where the datafile resides must be placed offline first. Identify the tablespace which contains the datafile and offline that tablespace.

SQL> select tablespace_name, file_name from dba_data_files where file_id=4;
SQL> alter tablespace users offline;

After you have taken the tablespace offline you can execute the same steps above for copying the datafile to the ASM Diskgroup and then put the tablespace back online.
_

RMAN General Commands Views, etc.

V$ Tables Related to Backup Recovery/Restore

Each release Oracle brought up new features and enhancements to RMAN improving its ease of use and functionality. Using the updateable persistent configuration options (CONFIGURE ….), backup up the database is easier then in the first version of RMAN introduced in 8i. It is help to list the Synonyms containing the word RMAN and BACKUP in them.

Here’s a list from an Oracle 11g database for those with BACKUP in the name:

OBJECT_NAME
——————————
V$BACKUP
V$BACKUP_SET
V$BACKUP_PIECE
V$BACKUP_DATAFILE
V$BACKUP_SPFILE
V$BACKUP_REDOLOG
V$BACKUP_CORRUPTION
V$BACKUP_DEVICE
V$BACKUP_SYNC_IO
V$BACKUP_ASYNC_IO
GV$BACKUP
GV$BACKUP_SET
GV$BACKUP_PIECE
GV$BACKUP_DATAFILE
GV$BACKUP_SPFILE
GV$BACKUP_REDOLOG
GV$BACKUP_CORRUPTION
GV$BACKUP_DEVICE
GV$BACKUP_SYNC_IO
GV$BACKUP_ASYNC_IO
V$BACKUP_FILES
V$RMAN_BACKUP_SUBJOB_DETAILS
V$RMAN_BACKUP_JOB_DETAILS
V$BACKUP_SET_DETAILS
V$BACKUP_PIECE_DETAILS
V$BACKUP_COPY_DETAILS
V$BACKUP_DATAFILE_DETAILS
V$BACKUP_CONTROLFILE_DETAILS
V$BACKUP_ARCHIVELOG_DETAILS
V$BACKUP_SPFILE_DETAILS
V$BACKUP_SET_SUMMARY
V$BACKUP_DATAFILE_SUMMARY
V$BACKUP_CONTROLFILE_SUMMARY
V$BACKUP_ARCHIVELOG_SUMMARY
V$BACKUP_SPFILE_SUMMARY
V$BACKUP_COPY_SUMMARY
V$UNUSABLE_BACKUPFILE_DETAILS
V$RMAN_BACKUP_TYPE
MGMT$HA_BACKUP

39 rows selected.

Here’s a list from the same Oracle 11g database with RMAN in the name:

OBJECT_NAME
——————————
V$RMAN_CONFIGURATION
GV$RMAN_CONFIGURATION
V$RMAN_STATUS
V$RMAN_OUTPUT
GV$RMAN_OUTPUT
V$RMAN_COMPRESSION_ALGORITHM
GV$RMAN_COMPRESSION_ALGORITHM
V$RMAN_BACKUP_SUBJOB_DETAILS
V$RMAN_BACKUP_JOB_DETAILS
V$RMAN_BACKUP_TYPE
V$RMAN_ENCRYPTION_ALGORITHMS
MGMT$HA_RMAN_CONFIG
MGMT$HA_RMAN_CONFIG_ALL

13 rows selected.

Controlfile views to reference are:

V_$ARCHIVE
V_$ARCHIVED_LOG
V_$ARCHIVE_DEST
V_$ARCHIVE_DEST_STATUS
V_$ARCHIVE_GAP
V_$ARCHIVE_PROCESSES
V_$BACKUP_ARCHIVELOG_DETAILS
V_$BACKUP_ARCHIVELOG_SUMMARY
V_$BACKUP_CONTROLFILE_DETAILS
V_$BACKUP_CONTROLFILE_SUMMARY
V_$BACKUP_DATAFILE
V_$BACKUP_DATAFILE_DETAILS
V_$BACKUP_DATAFILE_SUMMARY
V_$CONTROLFILE
V_$CONTROLFILE_RECORD_SECTION
V_$DATAFILE
V_$DATAFILE_COPY
V_$DATAFILE_HEADER
V_$SYSTEM_FIX_CONTROL
V_$PROXY_ARCHIVEDLOG
V_$PROXY_ARCHIVELOG_DETAILS
V_$PROXY_ARCHIVELOG_SUMMARY
V_$PROXY_DATAFILE
GV_$FOREIGN_ARCHIVED_LOG
GV_$PROXY_ARCHIVEDLOG
GV_$PROXY_DATAFILE
GV_$SESSION_FIX_CONTROL
V_$SESSION_FIX_CONTROL
V_$DLM_TRAFFIC_CONTROLLER
V_$FOREIGN_ARCHIVED_LOG
GV_$BACKUP_DATAFILE
GV_$CONTROLFILE
GV_$CONTROLFILE_RECORD_SECTION
GV_$DATAFILE
GV_$DATAFILE_COPY
GV_$DATAFILE_HEADER
GV_$DLM_TRAFFIC_CONTROLLER
GV_$ARCHIVE
GV_$ARCHIVED_LOG
GV_$ARCHIVE_DEST
GV_$ARCHIVE_DEST_STATUS
GV_$ARCHIVE_GAP
GV_$ARCHIVE_PROCESSES
DBA_REGISTERED_ARCHIVED_LOG
DBA_REPRESOL_STATS_CONTROL
USER_REPRESOL_STATS_CONTROL
ALL_REPRESOL_STATS_CONTROL
DBA_FLASHBACK_ARCHIVE
DBA_FLASHBACK_ARCHIVE_TABLES
DBA_FLASHBACK_ARCHIVE_TS
DBA_HIST_DATAFILE
DBA_HIST_WR_CONTROL
USER_FLASHBACK_ARCHIVE
USER_FLASHBACK_ARCHIVE_TABLES
GV_$SYSTEM_FIX_CONTROL
PS_CONTROL_TBL_VW
MGMT_V_DB_CONTROLFILES_ECM
MGMT_V_DB_DATAFILES_ECM
MGMT$DB_CONTROLFILES
MGMT$DB_CONTROLFILES_ALL
MGMT$DB_DATAFILES
MGMT$DB_DATAFILES_ALL

62 rows selected.

That is a lot of objects and views. To view the default RMAN configuration and then check the V$ view to see what is stored you can accomplish this with a query like this:

set linesize 132
column name format a40
column value format a40
set echo on
set serveroutput on

select * from v$rman_configuration
/

CONF# NAME VALUE
1 BACKUP OPTIMIZATION ON
2 DEFAULT DEVICE TYPE TO DISK
3 CONTROLFILE AUTOBACKUP ON
4 DEVICE TYPE DISK BACKUP TYPE TO COMPRESSED BACKUPSET
PARALLELISM 2

5 DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1
6 ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1
7 SNAPSHOT CONTROLFILE NAME TO ‘/opt/app/oracle/admin/backup/PS90HRD
V/backupsets/snapcf_ev.f’

8 MAXSETSIZE TO UNLIMITED
9 CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE DISK TO ‘+ps90hr_disk3/ps90hrdv/autoback
TYPE up/%F’

9 rows selected.

If you aren’t using a recovery catalog you can look at the controlfile since this is were backup information is maintained if you aren’t using a recovery catalog:

select type, records_total, records_used
from v$controlfile_record_section
where type like ‘%BACKUP%’
/

TYPE RECORDS_TOTAL RECORDS_USED
—————————- ————- ————
BACKUP SET 1227 224
BACKUP PIECE 1000 331
BACKUP DATAFILE 2126 2126
BACKUP REDOLOG 215 215
BACKUP CORRUPTION 1115 0
BACKUP SPFILE 131 93

6 rows selected.

The records used column isn’t zero because I’ve taken numerous backups, however, if you haven’t completed a backup yet this column will be zero. When RMAN reads the files to determine the files that will be backed up, if any corruption is detected then the corruption views are populated with that information such as file#, block# and contiguous blocks after the initial corrupt block.

RMAN will continue to use the persistent backup configuration settings once they are set unless they are overridden. The RMAN “SHOW” command displays those settings:

SHOW option [,parameter, ...]
RETENTION POLICY
EXCLUDE
BACKUP COPIES
CHANNEL
DEFAULT DEVICE TYPE
DEVICE TYPE
SNAPSHOT CONTROLFILE

ALL

RMAN> show all;

Recovery Manager: Release 11.1.0.6.0 - Production on Sat Nov 1 21:32:38 2008

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

show all;connected to target database: PS90HRDV (DBID=2173713801)
connected to recovery catalog database

RMAN>
RMAN configuration parameters for database with db_unique_name PS90HRDV are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION ON;
CONFIGURE DEFAULT DEVICE TYPE TO DISK;
CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO ‘+ps90hr_disk3/ps90hrdv/autobackup/%F’;
CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COMPRESSED BACKUPSET 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 ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM ‘AES128′; # default
CONFIGURE COMPRESSION ALGORITHM ‘BZIP2′; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/snapcf_ev.f’;

You can script the configuration parameters you want to use within a run block to change one or more parameters or just change a single parameter at a time from the RMAN prompt and not use the run block option.

Example:

CONNECT catalog rman/rman
crosscheck copy;
delete expired copy;
crosscheck backup;
delete expired backup;
run {
configure channel 1 device type disk clear;
configure channel 2 device type disk clear;
configure device type disk backup type to backupset parallelism 1;
backup spfile;
configure snapshot controlfile name to ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/snapcf_ev.f’;
backup current controlfile;
configure channel 1 device type disk format ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/df_t%t_s%s_p%p’ maxpieces
ize 1750 M;
configure channel 2 device type disk format ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/df_t%t_s%s_p%p’ maxpieces
ize 1750 M;
configure device type disk backup type to compressed backupset parallelism 2;
backup as compressed backupset incremental level 0 database tag=”ps90hrdv”;
configure channel 1 device type disk format ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/al_t%t_s%s_p%p’ maxpieces
ize 5000M;
configure channel 2 device type disk format ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/al_t%t_s%s_p%p’ maxpieces
ize 5000M;
backup archivelog all delete all input tag=”ps90hrdv_archivelogs”;
configure channel 1 device type disk clear;
configure channel 2 device type disk clear;
configure snapshot controlfile name to ‘/opt/app/oracle/admin/backup/PS90HRDV/backupsets/snapcf_ev.f’;
backup current controlfile;
configure channel 1 device type disk clear;
}

Create Consistent Backup Script

You can create a RMAN script to generate a database backup without a recovery catalog or with a recovery catalog. You can set the autocontrolfile autobackup feature during configuration so the backup controlfile is used as the catalog to avoid putting creating a separate RMAN database to use its catalog.

connect target;
run {
shutdown immediate;
startup mount pfile=’/opt/app/oracle/admin/ORACLE_SID/pfile/initORCLSID.ora’;
backup incremental level 0 database format ‘/opt/app/oracle/oradata/ORCLSID/backup/%d_bckup_%U’ tag=”closed_bkup”;
shutdown;
startup pfile=’/opt/app/oracle/admin/ORACLE_SID/pfile/initORCLSID.ora’;
}
exit

RMAN> list summary;
RMAN> list backup summary;
RMAN> list backup by file;

If you use for example 2 channels for your backup you’ll see 2 backupsets in the earlier query if you run that query again because RMAN will split the backup across 2 channels which means there will be 2 backupsets created plus there will be a 3rd controlfile backup that will be generated by the CONTROLFILE AUTOBACKUP feature.

A controlfile autobackup will generate a backup controlfile for each of the following commands if they are executed:

BACKUP DATABASE;
BACKUP TABLESPACE;
BACKUP DATAFILE;
BACKUP ARCHIVELOG;

To determine which datafiles need a backup execute the following command:

RMAN> report need backup;

To check and see if any RMAN Backupsets are obsolete and can be removed (deleted), important if you are generating disk backupsets and you don’t have unlimited disk space available to you.

RMAN> report obsolete;

SQL> select recid, stamp, completion_time, incremental_level from v$backup_set;

RECID STAMP COMPLETION_TIME INCREMENTAL_LEVEL
———- ———- ————— —————–
74 669457740 30-OCT-08
77 669458037 30-OCT-08
81 669465792 30-OCT-08
83 669465817 30-OCT-08
84 669501608 30-OCT-08
85 669501611 30-OCT-08
86 669502225 30-OCT-08
87 669502228 30-OCT-08
88 669502858 30-OCT-08 0
89 669503121 30-OCT-08 0
90 669503486 30-OCT-08 0
91 669503494 30-OCT-08
92 669503532 30-OCT-08
93 669503537 30-OCT-08
94 669507033 30-OCT-08
95 669507037 30-OCT-08
96 669507656 30-OCT-08
97 669507895 30-OCT-08
98 669508179 30-OCT-08
99 669508185 30-OCT-08
100 669508210 30-OCT-08
101 669508215 30-OCT-08
102 669509706 30-OCT-08
103 669509710 30-OCT-08
104 669510725 30-OCT-08
105 669510729 30-OCT-08
106 669645074 01-NOV-08
107 669645077 01-NOV-08
108 669645085 01-NOV-08
109 669645088 01-NOV-08
110 669645622 01-NOV-08 0
111 669646213 01-NOV-08 0
112 669646640 01-NOV-08
113 669646643 01-NOV-08
114 669646651 01-NOV-08
115 669646654 01-NOV-08
116 669647173 01-NOV-08 0
117 669647495 01-NOV-08 0
118 669647764 01-NOV-08 0
119 669647775 01-NOV-08

column handle format a32
column tag format a18
select recid, set_stamp, tag, status, handle
from v$backup_piece
order by set_stamp
/

RECID SET_STAMP TAG STA HANDLE
———- ———- —————— — ——————————–
93 669465816 TAG20081030T104336 A +PS90HR_DISK3/ps90hrqa/autobacku
p/c-2291650026-20081030-03

94 669501607 TAG20081030T204007 A /dbbackup/PS90HRQA/al_t669501607
_s84_p1

95 669501610 TAG20081030T204010 A +PS90HR_DISK3/ps90hrqa/autobacku
p/c-2291650026-20081030-04

96 669502225 TAG20081030T205024 A +PS90HR_DISK2/ps90hrqa/backupset
/2008_10_30/nnsnf0_tag20081030t2
05024_0.572.669505825

97 669502227 TAG20081030T205027 A +PS90HR_DISK3/ps90hrqa/autobacku
p/c-2291650026-20081030-05

100 669502244 PS90HRQA A /opt/app/oracle/admin/backup/PS9
0HRQA/backupsets/df_t669502244_s
88_p1

101 669502244 PS90HRQA A /opt/app/oracle/admin/backup/PS9
0HRQA/backupsets/df_t669502244_s
88_p2

98 669502245 PS90HRQA A /opt/app/oracle/admin/backup/PS9
0HRQA/backupsets/df_t669502245_s
89_p1

Recover Database Using an Autobackup of the Controlfile without a Recovery Catalog

Set the NLS_LANG environment variable to its proper setting depending on the values you created your database with. Example:

export NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P15

sqlplus> startup nomount;

Start RMAN but do not connect to the target database.

$ rman
RMAN>

Set the database identifier for the target database with the SET DBID command. RMAN displays the DBID whenever you connect to the target. You can also get it by running LIST or by querying the catalog.

Recovery Manager: Release 11.1.0.6.0 - Production on Sat Nov 1 20:57:08 2008

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

connected to target database: PS90HRDV (DBID=2173713801)

RMAN> SET DBID 2173713801;

You can use log files to determine the DBID also, every time RMAN connects to the database the DBID is displayed as shown above, if the database is open or mounted.

Connect to the target database:

RMAN> CONNECT TARGET;

Restore the backup controlfile, then perform the recovery by carrying out the following steps:

Optionally, specify the most recent backup time stamp that RMAN can use when searching for a controlfile autobackup to restore.

If a non-default format was used to create the control file, then specify a non-default format for the restore of the control file.

If the channel that created the control file autobackup was device type sbt (tape), then you must allocate one or more sbt (tape) channels. Because you don’t have a repository available you can’t use the automatic channels. If the autobackup was created on a disk channel, however, then you do not need to manually allocate a disk channel.

Restore the autobackup of the control file, optionally set the maximum number of days backward that RMAN can search (up to 366) and the initial sequence number that is should use in its search for the first day.

Mount the database, and because the repository is now available any automatic channels that you configured are now also available.

If the online logs are inaccessible, then restore and recover the database as described in the incomplete restore and recovery post. You must first terminate recovery by setting the UNTIL clause to a time, log sequence number or SCN before the online redo logs are processes. If the online logs are useable, then restore and recover the database as described in the complete restore and recovery post.

In the following example, the online redo logs have been lost. This example limits the restore of the control file autobackup, then performs the recovery of the database to log sequence 13456, which is the most recent archived log:

run {
set controlfile autobackup format for device type disk to ‘/opt/app/oracle/oradata/ORCLSID/backup/%F’;
allocate channel d1 device type disk;
restore controlfile from autobackup
maxseq 5 # start at sequence 5 and count down
maxdays 5; # start at UNTIL TIME and search back 5 days
mount database;
}

RMAN> run {
restore database;
recover database;
alter database open resetlogs;
}

Backup the database after resetlogs.

RMAN Restore and Recover of a Database When the Repository and spfile/init.ora Files are Lost

Oracle Database RMAN Restore/Recovery without spfile/init.ora Files

You have for whatever reason lost your spfile and your initORACLESID.ora files and you find yourself in a situation where you need to restore and recover your database.

This doesn’t happen very often and hopefully it never happens to you. The situation can arise during clone (duplicating a database using RMAN) but for whatever the reasons may be for the lost of your initialization files (media problems, etc.) here’s an outline of steps that may help to get your database back up and running.

If you only have the physical backuppieces on disk or tape and have lost your database and initialization files this is basically a disaster and or you have a need to restore and recover a database from and old backup that has long since been deleted or aged out of the RMAN Repository (examples would be a disk backup that was copied to tape prior to its deletion from RMAN).

Oracle 8i you don’t have spfiles but the Disk Backuppieces need to be restored or located in their original backup location, if there are backuppieces that are unknown to the restored control file it isn’t possible to catalog these files in this release but you can manually extract the information from the backupieces using PL/SQL.

Oracle 9i you can restore the spfile from an autobackup as well as the controlfile. You can’t catalog backuppieces unknown to the restored controlfile (same as 8i) but you can use PL/SQL to extract the information from the backuppieces. The disk backupieces must be located in their original backup locations.

Oracle 10g and 11g allows you to restore the spfile and controlfile from autobackups. You don’t have to place the original disk backuppieces in the same exact location as the original backup location. You can catalog unknown backuppieces that are missing from the restored controlfile and you can use PL/SQL to extract any missing information that you may need.

The goal is to restore the spfile and controlfile either from an autobackup controlfile or via a manual extraction process from an rman backuppiece so that the instance can be mounted. The restored controlfile then becomes the RMAN repository (no catalog), allowing a ‘normal’ catalog-free restore and recovery of the database to be executed.

The restore controlfile should therefore should also contain the metadata for the database and archivelog backups which will need to be restored and recovered.

The following constraints have to be acknowledged and understood:

  1. It is not possible to restore an init.ora file from a backuppiece as init.ora files are never included in a backup for any Oracle release.
  2. It is your responsibility to identify the required backuppieces required for the restore. This is where RMAN reports/listings come into play, if you generate these after each backup and store somewhere you can refer to these reports or similar type of listings.
  3. The DBID of the target database has to be known
  4. Unless you are using 10g+ all disk backuppieces must reside in the original backup location in case you need to restore to a new host and identical backup directory must be created on that host.
  5. If you have to restore the spfile, controlfiles and datafiles by extracting this information from the backuppieces you will need to contact Oracle Support Services to work with them in order to accomplish these tasks.
  • Keep the backup logs for at least one complete backup cycle so that the backuppieces and the target DBID can be identified by reviewing these files.
  • Pick a format for the backuppiece that makes it easy to identify these files by name should the log files no longer be available.
  • 8i Only - backup your init.ora file using any means possible. I have a crontab script that executes nightly that creates copies of my spfiles (10g and 11g) as well as the listener.ora, tnsnames.ora and other files that aid in the recovery process should I find myself in a situation that requires access to these files. I’ll include the script I use at the end of this post.
  • 8i Only - make sure you backup the controlfile after every backup or archivelog backup, this is just good practice and you’ll see why if you have find yourself in a situation where you need this file. You should always have a controlfile backup that contains the latest backup metadata.
  • 9i+ always use an spfile because RMAN can backup this file automatically whenever an operation occurs (within RMAN) that warrants a backup.
  • 9i+ always turn on CONTROLFILE AUTOBACKUP ON
  • Become as familiar as possible with your RMAN configuration, monitor where the backups are written, review the logs daily, review your backup frequency and most importantly know where the backup of the controlfile is located at.

Restoring When Everything is Gone

  1. Restore the init.ora file - applies for All Releases. RMAN has to connect to a running instance (a database started with an init.ora file in nomount mode). If an init.ora file is used rather than a spfile this needs to be restored from an OS backup or manually recreated in the proper format.
  2. Restoring the SPFILE and CONTROLFILE when CONTROLFILE AUTOBACKUP is NOT USED - relevant to Oracle 8i (where controlfile AUTOBACKUP didn’t exist), Oracle 9i+ where the persistent configuration CONTROLFILE AUTOBACKUP was set to OFF (not the default).
  • Figure out the latest controlfile backuppiece - if at all possible this should contain the latest metadata for the database and archivelog backups that required for the restore/recovery purposes. Use the past RMAN logs, check available backup directories on disk or query the media manager for your tape catalog to identify this information.
  • Extract the controlfile - Oracle 9i+ you can restore the control file from an explict backuppiece. Start the database in nomount mode via SQL*Plus and issue the command RMAN> restore controlfile from ‘backuppiece’;. If you are having problems identifying which backuppiece may contain a controlfile you will have to try various backuppieces until you locate a controlfile. If you can not locate one you’ll have to call Oracle Support for help and you’ll need to provide them with the following information: Current Schema of the database, files that were backed up, what time they were backed up and names of the backup pieces containing the Database’s files.
  • Mount the Instance - once the controlfile has been located and extracted you can continue and the next step is to mount the instance so jump down to Step 3.
  • Restoring the SPFILE and CONTROLFILE when CONTROLFILE AUTOBACKUP is ON - Oracle 9i+ where the parameter CONTROLFILE AUTOBACKUP is set to ON (default). The autobackup controlfile feature is there to help ease the pain of recovery when the RMAN repository is gone. Controlfile autobackup formats have to include the %F which makes them easy to find and identify. %F equates to - “c-t-yyyymmdd-” (I’m having issues display the proper syntax due to my inability to figure out how to block quote a block of text so I’ll fix this later when I figure out how to do that) . If the controlfile backups are written to disk, the default location is /dbs (unix) and /database (windows) so that is the locations to look for the autobackup files first. If you don’t find them they were written to a non-default directory and if you don’t know where the non-default directory is you’ll have to do a search of ‘find’ in unix to locate them. If you find the file you can use the ‘SET CONTROLFILE AUTOBACKUP FORMAT’ in the script below to force RMAN to use the correct location for the autobackup file. For autobackups written to tape, no further action is required other than to allocate a channel - check the rman logs to find out what the media manager environment variables if any were specified for the channel and make sure you set up a similar if the same variable configuration.
  • Startup the Instance in NOMOUNT mode as follows (you can’t use SQL*Plus for this so don’t try):$ rman target /

RMAN> startup nomount;
RMAN> set dbid=”dbid#”;
RMAN> run {
set controlfile autobackup format for device type disk to ‘path/%F’;
restore spfile from autobackup;
restore controlfile from autobackup;
startup force mount;
}

Notes: You get the dbid from the name of the controlfile autobackup filename or the rman backup logs. If you can’t find or identify the DBID you’re stuck. The ’set controlfile autobackup format’ is only necessary if the controlfile autobackup is in a non-default location - set ‘path’ accordingly. If you are using tapes for the restore: set controlfile autobackup format for device type sbt to ‘%F’;. ’startup FORCE mount’ is required because the instance was originally started without an spfile and if you try to mount without restarting it will fail.

3. Query the Backup History in the Restored Controlfile - Oracle 8i,9i,10g and 11g - after you’ve restored the controlfile and mounted the instance you now need to confirm that the controlfile actually contains the metadata for the database and the archivelog backups that will be required to restore and recover the database. You can use a command similiar to the following for this purpose:

RMAN> list backup;
RMAN> list backup of database completed after ‘date’;
RMAN> list backup of database completed between ’start date’ and ‘end date’;

The date must be in the appropriate NLS format (NLS_DATE_FORMAT).

Once you’ve found the database backup(s) you need then get the checkpoint scn of the backup (you’ll need this for the restore). You can see the SCN in the output of the above list commands. Then check that the archivelogs needed for the recovery have been backed up and recorded:

RMAN> list backup of archivelog from scn=xxxx;

Now if all the required metadata required for the restore and recovery are present you can continue on with the restore and recovery steps. You need to pick a archive log sequence number to specify for the restore and recovery process.

RMAN> run {
set until sequence = xx thread 1;
restore database;
recover database;
alter database open resetlogs;
}

3.1 Restored CONTROLFILE does NOT CONTAIN THE DATABASE BACKUP METADATA - Oracle Releases 8i and 9i - located a later (newer) controlfile and try again. Otherwise, phone Oracle Support Services for assistance.

Once the datafiles and archivelogs have been extracted the recovery can be start via RMAN to recover up to (and including the log sequence xx).

RMAN> run {
set until sequence xx thread 1;
recover database;
alter database open resetlogs;
}

Oracle Release 10g+

Catalog the required backuppiece(s) into the restored backuppiece ‘X’;

For Disk Backup Pieces:

RMAN> catalog backuppiece ‘path\X’;

Where ‘X’ is the name of the backuppiece.

All of the information regarding the backuppiece content are in the backuppiece header and once you catalog the backuppiece you can then query the contents (list backupset xx;) and proceed with the restore and recovery of the database as normal.

Oracle 11g asmcmd - new commands

New asmcmd Commands in Oracle 11g

Oracle introduced three new features into the ASMCMD utility to improve node recovery after a crash, to help repair bad blocks on a disk, copy files and to simplify the listing of the ASM disks in a diskgroup.

ASMCMD cp Command

The ASMCMD cp option lets you copy files between ASM disk groups and the OS file systems and between two ASM servers.

The following file copy is now available:

1. ASM Diskgroup to OS filesystem
2. OS filesystem to ASM Diskgroup
3. ASM Diskgroup to another diskgroup

ASM Diskgroup to OS Filesystem

ASMCMD> cp +psdisk1/ORCLSID/datafile/users.212.43245666 /opt/app/oracle/oradata/ORCLSID/users01.dbf

OS Filesystem to ASM Diskgroup

ASMCMD> cp /opt/app/oracle/oradata/ORCLSID/users01.dbf +psdisk1/ORCLSID/datafile/users01.dbf

ASM Diskgroup to Another Diskgroup

ASMCMD> create diskgroup psdisk2 external redundancy disk ‘/dev/oracleasm/ct3dl4′,’/dev/oracleasm/ct3dl5′;

ASMCMD> cd psdisk2
ASMCMD> mkdir prod
ASMCMD> cd prod
AMSMCD> mkdir datafile
AMSMCD> cd datafile
ASMCMD> pwd

SQL> create tablespace psdefault size 10M;

SQL> select name from v$datafile;

cp +psdisk1/ORCLSID/datafile/psdefault.212.34343434 +psdisk2/PROD/datafile/psdefault

ASMCMD> cp +psdisk/ORCLSID/datafile/psdefault.212.34343434 +psdisk2/prod/datafile/psdefault

The alias for psdefault is created in the folder +PSDISK2/PROD/datafile and the actual file is created in the +PSDISK2/PROD/datafile with a fully qualified ASM filename.

ASMCMD> cd +psdisk1/ORCLSID/DATAFILE
ASMCMD> ls -ltr
ASMCMD> cd +psdisk2/PROD/DATAFILE
ASMCMD> ls -ltr

ASMCMD md Backup and md Restore Commands

ASMCMD has been extended to include the ASM disk group metadata backup and restore functionality. This now provides us with the ability to recreate a pre-existing ASM disk group with the same disk paths, disk names, failure groups, attributes, templates, and alias directory structures.

In 10g if an ASM disk group was lost, the only possible way to restore the lost files was to use RMAN but you would have to manually recreate the ASM disk groups and all of the required user directories and templates.

In 11g you can take a backup of the ASM diskgroup metadata using the md_backup command which creates a backupfile containing the metadata for one or more of your diskgroups. The default is all mounted disk groups are included in the backup file which is saved in your current working directory. If the name of the backup file is not supplied then ASM names the file ASMBR_BACKUP_INTERMEDIATE_FILE.

ASMCMD> md_backup -b dgbackup -g psdisk1
Disk group to be backed up: PSDISK1

In restore mode, the previously generated file is read to reconstruct the diskgroup along with its metadata. You have the possibility to control the behaviour in restore mode by specifying a full, nodg, or newdg restore.

The full mode restores the diskgroup exactly as it was at the time of the last backup.

ASMCMD> md_restore -b dgbackup -t full -g psdisk1
Current Diskgroup being restored: PSDISK1
ASMCMD-09353: CREATE DISKGROUP failed
ORA-15018: diskgroup cannot be created
ORA-15030: diskgroup name “PSDISK1″ is in use by another diskgroup(DBD ERROR: OCIStmtExecute)

I didn’t wipe out or blow away my existing diskgroup but the above illustrates the ASM won’t restore and write over a valid diskgroup.

SQL> drop diskgroup psdisk1;
Diskgroup dropped.

ASMCMD> md_restore -b dgbackup -t full -g psdisk1
Current Diskgroup being restored: PSDISK1
….

SQL> select group_number, name, type from v$asm_diskgroup;

The nodg mode restores the attributes, templates and directory structure specified in the backup file to an existing disk group.

ASMCMD> md_restore -b dbbackup -t nodg -g psdisk1
Current Diskgroup being restored: PSDISK1
….
_

RMAN Info

RMAN General Info Oracle

RMAN’s %s format represents the backup set number and is essentially a counter in the controlfile that is incremented for each backupset. The counter starts at 1 and is unique for the lifetime of the control file. If you restore a backup control file, then it is possible duplicate values could result. You can initialize the counter back to 1 by issuing a CREATE CONTROLFILE command.

The %s doesn’t represent the same number that is in the BS_KEY column in the RC_BACKUP_SET RMAN Catalog view.

There are two different numbers tracked for the backup sets, BS_KEY which is a unique value within the catalog and the RECID which is unique to the controlfile.

example:

connect / as sysdba
select max(recid) from v$backup_set;

execute an RMAN backup:

configure channel type disk format ‘….’;

select max(set_count) from v$backup_set;

in the catalog: connect rman/rman@rman.db.name.com

select max(bs_key) from rc_backup_set;

The RESTORE command supports a PREVIEW option, which identifies the backups (backup sets or image copies, on disk or sequential media like tapes) required to carry out a given restore operation.

You can use RESTORE.. PREVIEW to ensure that all of the required backups are available or to identify situations where you may want to instruct RMAN to use or avoid a specific backup.

RESTORE… PREVIEW can show you that RMAN will request a tape during the restore process which you know is not located onsite. You can then execute the command CHANGE… UNAVAILABLE to set the backup status to UNAVAILABLE. If you then execute the RESTORE… PREVIEW command again, RMAN will not include that media you just marked as UNAVAILABLE and will show only the media it will use to perform the restore operation.

RESTORE… PREVIEW can be applied to any RESTORE operation to create a detailed report of every backup that will be requested during the RESTORE operation:

RESTORE DATABASE PREVIEW;
RESTORE TABLESPACE users PREVIEW;
RESTORE DATAFILE n PREVIEW;
RESTORE ARCHIVELOG FROM LOGSEQ xxxx PREVIEW;
RESTORE ARCHIVELOG FROM TIME ‘SYSDATE-6′ PREVIEW;
RESTORE ARCHIVELOG FROM SCN xxxxxx PREVIEW;
RESTORE… PREVIEW output is in the same exact format as the output of the LIST command.

If the detailed report produced by RESTORE… PREVIEW provides more information than you need, you can add the SUMMARY option to the command which will suppress much of the detail about specific files that will be used and affected by the restore process.

RESTORE DATABASE PREVIEW SUMMARY;
RESTORE TABLESPACE users PREVIEW SUMMARY;
RESTORE DATAFILE x PREVIEW SUMMARY;
RESTORE ARCHIVELOG FROM LOGSEQ xxx PREVIEW SUMMARY;
RESTORE ARCHIVELOG FROM TIME ‘SYSDATE-6′ PREVIEW SUMMARY;
RESTORE ARCHIVELOG FROM SCN xxxxxx PREVIEW SUMMARY;
RESTORE… PREVIEW SUMMARY reports are in the same format as output from the LIST SUMMARY command.

To backup the controlfile using RMAN:
run {
allocate channel d1 type disk format ‘c:\backup\%U’; (windows format)
allocate channel d1 type disk format ‘/opt/app/oracle/admin/backup/snapcf_ev.f’; (unix format)_
backup current controlfile;
}

To check the backup of controlfile using RMAN:
list backup of controlfile;

To recover using backup controlfile: (startup nomount)
run {
allocate channel d1 type disk;
restore controlfile;
alter database mount;
restore database;
recover database;
sql ‘alter database open resetlogs’;
}

To backup all datafiles and controlfile using RMAN:
run {
allocate channel d1 type disk;
backup full tag=’full_bkup” database include current controlfile format=’/opt/app/oracle/admin/backup/df_t%t_s%s_p%p’;
release channel d1;
}

To check all backups of datafiles using RMAN:
list backupset;

To restore because of missing / corrupt file(s) (first mount the database and then execute RMAN):
run {
allocate channel d1 type disk;
restore database;
recover database;
}

Restore until time: The ‘SET UNTIL TIME’ must match with the variable NLS_DATE_FORMAT, prior to logging onto RMAN set the NLS_DATE_FORMAT with the desired format.

ex: Unix - export NLS_DATE_FORMAT=’YYYY-MM-DD:HH24:MI:SS’;
Windows - set NLS_DATE_FORMAT in the registry or Control Panel->System->Environment Variables:
run {
set until time ‘October 1 2008 12:00:00′;
allocate channel d1 type disk;
shutdown abort;
startup nomount;
restore controlfile;
alter database mount;
restore database;
recover database;
sql ‘alter database open resetlogs’;
}

Purge Obsolete Backups:
rman> report obsolete redundancy 3 device type disk;

Use the report id returned to fill in the xxx below;
rman> report obsolete orphan;

rman> allocate channel for maintenance type disk;
allocate channel for delete type disk;
change backuppiece ‘/opt/app/oracle/admin/backup/xxxx’ delete;
release channel;

To Backup All Archive Logs:
run {
allocate channel d1 type disk format ‘/opt/app/oracle/admin/backup/al_t%t_s%s_p%p’;
backup archivelog all delete input;_
}

To Remove All Archive Log Files After Backup Up
backup archivelog all delete input;

Skip an Archive Log File that can’t be read or manually deleted
backup archivelog skip inaccessible;

To Remove One Archive Log That you Manually Deleted and Now Get an RMAN-6089 (prior to 8.0):
allocate channel for delete type disk; or ‘SBT_TAPE’;
change archivelog ‘/opt/app/oracle/admin/backup/filename’ delete;
and/or
resync catalog;

To Remove One Archive Log That you Manually Deleted and Now Get an RMAN-6089 (prior to 8.1):
allocate channel for maintenance type …
change archivelog uncatalog

Oracle 11G RMAN Worksheet Sizing

Flash Recovery Area Sizing / RMAN Image Backups

===================================================================================

Type Size Per File or Set Total Per Cycle (Week) Total Description
Full Backup Set 0 0 0 Use Image Copies, so size is 0
Image Copied 3,000 2 6,000 Need 2 Level 0 Backups per Cycle, 1 week cycle
Archived Redo Logs 100 2 200 Two days worth of archived redo logs available
Incremental copy of datafiles 200 6 600
Control file autobackup 0.2 7 1.4
Total Space Required 6,801

Flash Recovery Area Sizing / RMAN Regular Backups

=================================================================================

Type Size Per File or Set Total Per Cycle (Week) Total Description
Full Backup Set 0 0 0 Use Image Copies, so size is 0
Image Copied 3,000 2 6,000 Need 2 Level 0 Backups per Cycle, 1 week cycle
Archived Redo Logs 100 2 200 Two days worth of archived redo logs available
Incremental copy of datafiles 200 6 600
Control file autobackup 0.2 7 1.4
Total Space Required 6,801

Flash Area Recovery Sizing for RMAN Image Backups w/Merge

===================================================================================

Type Size Per File or Set Total Per Cycle (Week) Total Description
Full Backup Set 0 0 0 Use Image Copies, so size is 0
Image Copied 3,000 2 6,000 Need 2 Level 0 Backups per Cycle, 1 week cycle
Archived Redo Logs 100 2 200 Two days worth of archived redo logs available
Incremental copy of datafiles 200 6 600
Control file autobackup 0.2 7 1.4
Total Space Required 6,801

Oracle 9i / 10g RMAN Duplicate Database Errors

Recovering from RMAN Errors

The options for Manual Completion of an RMAN Duplication Task vary depending on which phase of the duplication failed. The following examples cover Oracle 9i and 10g. Manual completion steps out outlined per phase and most likely you’ll only two to execute a couple of the steps depending on where the failure occurred.

Restore Failure

If you receive an error during the RMAN restore of the database you need to determine what caused the problem and fix it. If very few files have been restored it may be easier to just start over and rerun the task from the beginning. If the duplication process failed after running for a long period of time and you rather not to start from the beginning (especially if it takes hours+) then you can try to recover manually and attempt to complete the process.

A likely cause if you are going from one server to another server is missing files or the rare outside possibility of a bad block in a file required for restore. You need to address whatever problem caused the file(s) to be missing from the restore location.

Remember that in order to successfully duplicate a database using RMAN’s DUPLICATE feature is that ALL files required to restore the database must be present on the remote server and in the same exact location unless you catalog the files if they are intentionally located in another directory. RMAN will not even start the restore process if it can’t find the backupsets in the expected location. A reason RMAN may be interrupted in this phase is because during the copy operating you ran out of disk space in the filesystem where you were depositing the backupsets, backup current controlfile and backup spfile and RMAN can’t locate one of the backupsets or arcivelog files.

$ export ORACLE_SID= (name of database cloning to)
$ rman target /
RMAN> run {
set until scn xxxxxxxx;
restore current controlfile from ‘restore directory’;
alter database mount;
set newname for datafile 1 to ”;
set newname for datafile 2 to ”;
….
restore datafile i,i2,….;
}

You need to identify the SCN from the output from the failed RMAN duplicate log and you must use the ‘SET NEWNAME’ for each datafile that remains to be restored as DB_FILE_NAME_CONVERT will not work with a normal restore.

For Oracle 10g+ it really is best to start over if RMAN failed during the first phase or restore step. Any files that have already been restored will be skipped and the duplicate process can be restarted without manual intervention.

Phase 2 Failure

This is the controlfile creation or switch of the datafile names after the datafiles have been restored. You need to review the log files and identify what the problem is and make sure you make a list to use for all the datafiles that have not been switched over. You can then attempt to complete this step manually by rename each datafile if the auxiliary instance uses a different file structure or the ASM Disk Group is different than that of the target’s directory structure or ASM Disk Group.

After the rename (switch) of all the datafiles that need to be renamed:

CREATE CONTROLFILE REUSE SET DATABASE RESETLOGS ARCHIVELOG

SQL> alter database backup controlfile to trace;

Phase 3 Failure

Failure during the recovery of the restored datafiles. This is the next phase where each datafile is recovered to either a point in time or SCN. Determine the cause from the log file and then to continue after fixing the problem:

$ rman target / auxiliary sys/@
RMAN> run {
set until scn xxxxxxx;
recover clone database;
alter clone database open resetlogs;
}

Get the ‘UNTIL SCN’ value from the duplicate logfile, connect to the target. Archivelogs will be automatically restored at 10g, restored into the Flash Recovery Area if this is defined. After completing recovery, change the Database Identifier (DBID) using the NID utility on Windows:

$ nid target=sys/oracle

DBNEWID …….
…..
Change database ID of database AUX? (Y/N)=>Y

The manual duplication process should be complete and you can jump down to Step 6 - Final Actions.

Phase 4 Failure

This phase is the controlfile recreation phase. Check the rman duplicate log and identify the reason the recovery didn’t complete - look for:

media recovery complete
Finished recover at

Figure out what the problem is and fix the cause then execute the following after fixing the cause:

CREATE CONTROLFILE REUSE SET DATABASE ‘AUX’ RESETLOGS ARCHIVELOG

Make sure ALL the files have been restored in the DATAFILE section of the RMAN duplicate log.

Phase 5 Failure

This failure would be in the phase that opens the database with resetlogs. Check the log file again and fix the problem. Look for Thread x closed at log sequence y

If the resetlogs was completed, determine what cause the error and fix the problem and restart the auxiliary instance. If resetlogs wasn’t completed successfully, determine what cause that problem and then open the clone database with resetlogs using RMAN (you can’t use SQL*Plus for this step) and connect to the target database first:

$ rman target / auxiliary sys/oracle@
RMAN> alter clone database open resetlogs;

If the duplication process failed only in steps 5 then you are done, no further action is required. The DBID will have already been changed. Otherwise, execute the NID command to change the DBID (Windows).

Final Steps

$ rman target / auxiliary sys/oracle@
RMAN> alter clone database open resetlogs;

Add any temp files missing to the new cloned auxiliary database. Files that were manuall restored to the auxiliary instance will be cataloged as datafile copies. Connect to the original target and execute:

RMAN> list copy of database;
RMAN> crosscheck copy of datafile ;
RMAN> delete expired copy of datafile
;

Duplicating a Database using Oracle 11g RMAN

RMAN Duplicate Database Feature in 11G

You can create a duplicate database using the RMAN duplicate command. The duplicate database will have a different DBID from the source database and it functions entirely independently because it is completely independent once the duplication has taken place and the duped database is open for use.

Starting with Oracle 11g there are now two ways to duplicate a database:

1. Active database duplication
2. Backup-based duplication

Active database duplication involves copying the live running database over the network to the auxiliary destination and creating the duplicate database. The backup-based duplication requires copying over using NFS to make available the backupset(s) to the destination database. The only difference between the two is you do not need pre-existing RMAN backups and copies (archivelogs). The duplication work is performed by the auxiliary channel and this channel corresponds to a server session on the auxiliary instance on the auxiliary (destination) host.

The active database duplication is slower because it is using the network to transport the data blocks instead of accessing existing RMAN backupsets. RMAN carries out the following steps as part of the duplication process:

1. Creates a control file for the duplicate database
2. Restarts the auxiliary instance and mounts the duplicate control file
3. Creates the duplicate datafiles and recovers them with incremental backups and archived redo logs
4. Opens the duplicate database with the RESETLOGS option

In the case of active database duplication, RMAN copies the target datafiles over the network to the auxiliary (destination) instance.

A RAC Target database can be duplicated as well, this feature is not restricted to non-RAC databases. The procedure is the same as what is outlined below. If the auxiliary database needs to be a RAC-database then you start the process to duplicate a single instance and convert the auxiliary to RAC after the duplicate process has succeeded.

The next section is devoted to describing the process for Active Database Duplication.

Active Database Duplication

1. Prepare the auxiliary database instance
2. Create the initialization parameter file for the Auxiliary instance

If you are using SPFILE then according to Oracle the only parameter required for the duplicate database is the DB_NAME parameter. The rest of the parameters can be set in the DUPLICATE command. If you are not using the SPFILE technique for your Oracle initialization parameter file then you will need to create an init.ora file and set the initialization parameters. Again according to Oracle the only required parameters are:

DB_NAME
CONTROL_FILES
DB_BLOCK_SIZE
DB_FILE_NAME_CONVERT
LOG_FILE_NAME_CONVERT
DB_RECOVERY_FILE_DEST

However, I have found if I use a full meaning a copy of one of my running Database’s parameter file it is easier than specifying the parameters in the DUPLICATE command itself. That is a personal preference and you should go with whatever works best for you. I use SPFILE files for all my Oracle Databases and whenever I have a need to duplicate one of them I will generate (create) an init.ora initialization parameter file for use with RMAN. I will then use my favorite editor to search and replace the database specific parameters with my new Oracle Database parameters like DB_NAME, DB_RECOVERY_FILE_DEST, etc.

3. Create the Oracle Password file for the Auxiliary Instance - this is a requirement for RMAN in order to duplicate a database you need to connect directly to the auxiliary instance using the password file with the same SYSDBA password as the target database’s password. The passwords have to match exactly in order for this to work. You can specify the PASSWORD FILE option on the DUPLICATE command in which case if you do RMAN will copy the source database password file to the destination host and overwrite any existing password file with the same name as the auxiliary instance’s name.

4. Make the necessary changes to the listener.ora and tnsnames.ora file in order to establish SQL*Net connectivity before starting the RMAN duplicate session. You have to be able to connect through Oracle Net to the target and the auxiliary instance in order to use Active Database duplication.
5. Start the Auxiliary instance from SQL*Plus - start the database and put it in nomount mode but first take care of the following steps:

I always create a link in $ORACLE_HOME/dbs to the initialization file and I just rename this link when I’m finished with RMAN to switch over to using a spfile instead of the pfile method. This way you do not have to type in a lot of characters whenever you stop, start the auxiliary instance because more than likely you will have to execute the process more than once unless you get it right the very first time! I set up the ADR - in Oracle 11G the new Automatic Diagnostic Recovery filesystem (if you aren’t using ADR set up the $ORACLE_BASE/admin/$ORACLE_SID/bdump/…._) directories prior to bringing up the auxiliary instance in nomount mode. You will need to create the supporting directories prior to starting the auxiliary instance.

Windows:

Create the parameter file (using Oracle’s example):

initNEW.ora
DB_NAME=NEW
diagnostic_dest=’E:\opt\oracle’
DB_FILE_name_CONVERT=(’I:\oradata\OLD’,'E:\oradata\NEW’)
LOG_FILE_NAME_CONVERT=(’I:\oradata\onlinelog\OLD’,'E:\oradata\onlinelog\NEW’)
SGA_TARGET=26214400
CONTROL_FILES=’E:\oradata\controlfile\NEW\control01.dbf’
COMPATIBLE=11.1.0.0.0

Create the Database Service (Windows Only) and password file:

% set ORACLE_SID=NEW
% set ORACLE_HOME=E:\opt\app\oracle\product\11.1.0\db_1
% oradim -NEW -SID NEW
% orapwd FILE=E:\opt\app\oracle\product\11.1.0\db_1\database\PWPDNEW.ora PASSWORD=sys

% sqlplus “/ as sysdba”
sql> startup nomount;

6. Create the necessary Oracle Net connectivity in the listener.ora and tnsnames.ora files - you need to make sure you specify SERVER = DEDICATED in the tnsnames.ora entry for your auxiliary instance and if you are using Oracle on HP-UX 11i v3 Itanium there is a bug that requires you to use the string ‘(UR=A)’ at the end of the tnsnames.ora entry (put it after the SERVICE_NAME entry). Confirm the connectivity to the target, auxiliary and you may want to confirm connectivity to your RMAN catalog even though you will not be using the catalog for this type of database duplication.

7. Start RMAN and connect to the source database by specifying the source as the target database. The duplicate database instance will be specified in the AUXILIARY connection. You can invoke the RMAN client on any host so long as that host has connectivity and you can connect to all of the required database instances. If the auxiliary instance requires a text-based initialization parameter file (pfile) then this file must exist and it must reside on the same host that runs the RMAN client application.

% rman
rman> connect target sys/sys@old;
rman> connect auxiliary sys/sys

8. Next you will be issuing the DUPLICATE database command in order to start the duplicate process and the simplest case is when you duplicate the target database to a different host and use a different directory structure. This example will assume you are using a recovery catalog, the target database is on hosta and it contains four datafiles. You duplicate the target to database AUX on a different host (hostb) and hostb has a different directory structure. The tablespace USERS is a read-only tablespace for the purpose of this example. Execute the duplciate database command from the Auxiliary site:

rman duplicate target database to ‘NEW’ from active database db_file_name_convert ‘i:\oradata\OLD’,'e:\oradata\NEW’;

A dedicated listener configuration for RMAN is required. Using instance registration requires that the database be mounted in order to register with the listener. RMAN also requires SYSDBA access to the nomount instance (Auxiliary). The control files will be create using the location and names specified in the Oracle initialization file. The use of log_file_name_convert and db_file_name_convert instructs RMAN to generate the “set newname” commands for you. You can create your own set instead of using these two commands and you can use the ‘logfile’ command to specify where the log files will be created and what size they will be created with.