RMAN備份

The traditional user-managed backup method consists simply of using the operating system commands to copy the relevant files to a different location and/or to a tape device. With RMAN, you back up the database files fromwithin the database with the help of the database server itself. RMAN can make backups of datafiles and datafile image copies, control files and control file image copies, archived redo logs, theSPFILE, and RMAN backup pieces. Oracle recommends using the RMAN interface to back up your databases.
  Note 

Most "old-school" Oracle DBAs will be familiar with operating system commands, but newer DBAs may want to focus on RMAN, which offers ease of use, safety, and features that the traditional methods don't have. You can use all the RMAN backup and recovery functionality through the OEM interface (Database Control or Grid Control), without needing to remember complex commands.

RMAN simplifies the backup procedures by enabling the use of powerful yet easy-to-write backup and recovery scripts. RMAN also offers features such as corruption detection within the data blocks and the ability to back up only the changed blocks in the database. You can save RMAN's scripts in the database and use them right from there, so you don't need to write operating system-based scripts. RMAN automatically ensures the backup of all the database files, which eliminates the human-error component that is present in operating system-based backups.

Despite its sophistication, RMAN has some limitations. You can't, for example, read from or write directly to a tape device using RMAN; you need to use what's known as a media management layer to make tape backups.

  Note 

RMAN can create and manage backups on disk and on tape devices, also referred to as system backup to tape (SBT) devices, move backups on disk to tape, and restore backups from tape. However, RMAN interacts with SBT devices through an MML, or media manager. Oracle provides its own MML, in the form of Oracle Secure Backup.

Benefits of RMAN

RMAN provides an array of benefits compared to user-managed backup methods, including the following:

  • You can perform incremental backups using RMAN. The size of the backups doesn't depend on database size; rather, it depends on the activity level within the database, because unchanged blocks are skipped during incremental backups. You can't perform incremental backups any other way. You can perform incremental exports, but that isn't considered a real backup for all databases.

  • You can repair a datafile with a few corrupt data blocks online, without needing to resort to restoring a file from backup. This is calledblock media recovery.

      Tip 

    Even if you use user-managed backups, you can perform block media recovery by cataloging your datafile and archiving redo log backups into the RMAN repository.

  • Human error is minimized because RMAN, not the individual DBA, keeps track of all the file-names and locations. Once you understand the use of the RMAN utility, it's easy for you to take over the backup and recovery of databases from another DBA.

  • A simple command, such as BACKUP DATABASE, can back up an entire database, without the need for complex scripts.

  • The unused block compression feature of RMAN lets you skip copying never-used data blocks in a datafile during a backup, thus saving storage space and backup time.

  • It's easy to automate the backup and recovery process through RMAN. RMAN can also automatically parallelize your backup and recovery sessions.

  • RMAN can perform error checking during backups and recovery, thus ensuring that the backed-up files aren't corrupt. RMAN has the capability to recover any corrupted data blocks without taking the datafile offline.

  • During online backups, no redo is generated, unlike when online backups are performed using the operating system utilities. Thus, the overhead is low for online backups.

  • The binary compression feature reduces the size of backups saved on disk.

  • If you use the recovery catalog, you can store backup and recovery scripts directly in it.

  • RMAN can perform simulated backups and restores.

  • RMAN enables you to make image copies, which are similar to operating system-based backups of files.

  • RMAN can be easily integrated with powerful third-party media management products to make tape backups effortless.

  • RMAN is integrated well with the OEM backup functionality, so you can schedule backup jobs easily for a large number of databases through a common management framework.

  • You can easily clone databases and maintain standby databases using the RMAN functionality.

As the preceding list clearly shows, it's no contest when it comes to the question of whether you should be using operating system-based backup and recovery techniques (user-managed backup and recovery) or RMAN. Therefore, you'll see quite a bit of discussion about RMAN in this chapter and the next, which deals with recovering databases. Oracle maintains that both RMAN and traditional user-managed backup and recovery methods are equally valid and effective, but recommends the use of RMAN.

RMAN Architecture

RMAN operates via server sessions connecting to the target databases, which are the databases you want to back up or recover. The collection of information about the target database—such as its schema information, backup copy information, configuration settings, and backup and recovery scripts—is called the RMAN repository. RMAN uses this metadata about the target databases to perform its backup and recovery activities. RMAN periodically retrieves metadata from the target database control file and saves it in the recovery catalog.

Following is a list of the entities that enable RMAN to perform its backup and recovery functions:

  • Target database: This is the database that the RMAN needs to back up. RMAN server sessions running in the target database perform the backup and recovery operations.

  • RMAN repository: This is RMAN's metadata about backups, archived redo logs, and its own activities. The control file of each database is the primary storage for RMAN's repository.

  • Recovery catalog schema: This is the database schema in the recovery catalog database that owns the RMAN backup and recovery metadata (the RMAN repository).

  • RMAN client: You manage RMAN operations through RMAN client sessions. The RMAN client is a command-line interface through which you issue commands to perform backup and recovery operations by communicating with the RMAN server process. You can issue special RMAN commands, as well as SQL statements from the RMAN client. The client starts the RMAN server sessions on the target database and directs them to perform the backup and recovery operations. The RMAN client uses Oracle Net to connect to a target database, so it can be located on any host that is connected to the target host through Oracle Net.

  • RMAN executable: This is the actual program that manages all backup and recovery operations. You can find the RMAN executable (also known simply asrman) in the $ORACLE_HOME/bin directory. You specify the backup or recovery operation, and the RMAN executable performs it for you by interacting with the target database. It records the results in the control file and the optional recovery catalog.

  • Server processes: These are the background processes that facilitate communication between the RMAN executable and the target database. The server process performs the real work of reading and writing to disk devices and tape drives during backup and recovery.

  Note 

Three entities are optional when you use RMAN: the flash recovery area, the recovery catalog database (and the recovery catalog schema), and media management software.

The RMAN Repository and Recovery Catalog

You have a choice of two locations for storing the RMAN repository: you can let RMAN store it in the target database control file, or you can configure and use the optional recovery catalog to manage the metadata. The RMAN repository contains information about the following items:

  • Datafile backup sets and copies

  • Archived redo log copies and backup sets

  • Tablespaces and datafile information

  • Stored scripts and RMAN configuration settings

By default, RMAN stores all metadata in the control file. All RMAN information is first written in the control file, and then to the recovery catalog if one exists. For instance, when RMAN creates a new backup set, you can view the information in the V$BACKUP_SET view. You can also view the same information in the recovery catalog view, RC_BACKUP_SET. Thus, for every change to the RMAN repository, information is recorded in two places: the control file and the optional recovery catalog. The recovery catalog versions of the RMAN repository are stored in database tables. The control file version of the repository is stored as records within the control file.

If you wish, you can manage the RMAN with just the information in the control file. The objections you'll hear regarding using the recovery catalog are that it's too complex to maintain and that it needs another database to manage it. However, there are some RMAN commands you can use only when you use the recovery catalog. You can also use RMAN-stored scripts only if you use the recovery catalog. If you use the control file, you run the risk of some of the historical data being overwritten, but the recovery catalog will safeguard all such data. This is because the control file allocates a finite space for backup-related activities, while the recovery catalog has more room for storing backup history. One recovery catalog in your system can perform backup, restore, and recovery activities for dozens of Oracle databases. Thus, you can centralize and automate backup and recovery operations by using the recovery catalog. Oracle recommends that you use a dedicated database for running the recovery catalog, but it isn't absolutely necessary.

  Note 

You're strongly advised to use the recovery catalog so you can take advantage of the full range of features provided by RMAN. The discussion of RMAN's features in this chapter and the next assumes the existence of the recovery catalog.

The Media Management Layer

You can make backups directly to your operating system disks using RMAN. If you want to make backups to tape, you'll need additional software called an MML or a media manager. RMAN can move backups on disk to tape and restore the tape backups if necessary. Oracle Database 11g contains a proprietary media management product, called Oracle Secure Backup, which I discuss in the "Oracle Secure Backup" section later in this chapter.

Connecting to RMAN

You can connect to RMAN by simply typing rman at the operating system prompt. (Make sure you've set the path variables correctly; in some operating systems, such as SUSE Linux, you may get the operating system's utility, named rman, instead of Oracle's RMAN utility.) This will get you theRMAN> prompt, at which point you can type in the various commands. You can also use the RMAN commands in batch mode or through pipes by using Oracle's DBMS_PIPE package.

You don't need to be a SYSDBA privilege holder to just connect to the RMAN catalog; you can do so with the special rman account and password. As you'll see later in the "Creating the Recovery Catalog" section, the user rman is the owner of the catalog. You can connect to RMAN through database password authentication. You can also connect to the database using operating system authentication. The following sections describe each of these methods.

Connecting to RMAN Using Database Authentication

You can log into the RMAN utility using your database credentials. You issue backup/recovery commands after connecting to the target database. To finish your RMAN session, use theexit command. Here is an example of connecting to the database named orcl, which is the target database:

$ rman

Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:09:16 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.
RMAN> CONNECT TARGET /
connected to target database: ORCL (DBID=1080111806)
RMAN> exit
Recovery Manager complete.
$

The following way of specifying the credentials at the operating system level is equivalent to the preceding commands:

$ rman target system/system__passwd

Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:38:16 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.connected to
 target database: ORCL (DBID=1080111806)
RMAN>

Connecting to RMAN Using Operating System Authentication

You can also log in to RMAN using operating system authentication, without using a database user account and password. Here's how you do this:

$ rman target /

Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:09:16 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.
connected to target database: ORCL (DBID=1080111806)
RMAN>

Connecting to the Recovery Catalog

The preceding login examples connect directly to the target database without a recovery catalog. Once you configure the optional recovery catalog, you have the option of connecting to the recovery catalog first and performing all your backup/recovery actions through it. This is the option Oracle strongly recommends because of the benefits of using the recovery catalog. In the following, the recovery catalog is in the database nick and the target database is orcl:

$ rman target orcl catalog rman/rman@nick

Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:09:16 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.target database Password:
connected to target database: ORCL (DBID=1065483535)
connected to recovery catalog database
RMAN>

Redirecting Output to a Log File

By default, RMAN outputs everything to the screen, but you can have it redirect the output to a log file by specifying the parameterLOG when starting RMAN. For example:

$ rman LOG /u01/app/oracle/rman.log

When you specify the LOG parameter, RMAN doesn't display any output to you. To make RMAN log its output as well as send it to standard output, use the Linux or UNIXtee command, as shown here:

$ rman  |  tee /u01/app/oracle/rman.log

The tee command makes RMAN output visible to you, while sending it simultaneously to a log file.

Scripting with RMAN

As you'll see in upcoming sections of this chapter, you can use simple manual RMAN commands, such asBACKUP DATABASE and LIST OBSOLETE. However, manual commands aren't the only or the best way to give directives to RMAN. RMAN comes with a powerful scripting language that lets you encapsulate common backup tasks easily. You can store RMAN scripts either in the recovery catalog or as text files. You can create scripts designed for a single database or global scripts that can be used in several databases.

RMAN offers two sorts of scripts: stored scripts (kept in the RMAN recovery catalog) and text scripts (kept in regular text files). Stored scripts have the advantage that any user who logs into RMAN can access them easily. You can use stored scripts as alternatives to command files for any set of RMAN commands that you regularly execute. Unlike command files, which are stored on the file system, stored scripts are stored in the recovery catalog.

When you need to use a large number of configuration parameters for a particular backup, it's much easier to use a script. RMAN scripts thus perform the same function as regular scripts in UNIX or SQL: they make it easier to store and rerun long sets of commands.

Using Command Files

You can create operating system command files for regularly scheduled RMAN backup jobs. Inside a command file, you can use the@filename syntax to specify a command file that you want RMAN to execute. For example, you can create a command file namedtestfile1 with the following RMAN command:

BACKUP DATABASE PLUS ARCHIVELOG;

You can then run the command file testfile1 from the operating system command line as follows:

$ rman target / @testfile1

Note that you can also specify the @filename syntax at the RMAN prompt to execute a command file, as shown here:

RMAN> @testfile1

You can also specify the USING clause at the command-line prompt to specify values for use in substitution variables in a command file, thus making a command file dynamic. I provide a simple example that shows how to create and execute a dynamic shell script. The script calls a command file that contains the substitution variables.

  1. Create a command file (monthly_backup.cmd) that uses substitution variables, as shown here:

    #monthly_backup.cmd
    CONNECT TARGET /
    RUN
    {
      ALLOCATE CHANNEL c1
        DEVICE TYPE sbt
        PARMS 'ENV=(OB_MEDIA_FAMILY=&1)';
      BACKUP DATABASE
        TAG &2
        FORMAT '/u02/app/oracle/bck/&1%U.bck'
        RESTORE POINT &3;
    }
    EXIT;
    

The command file monthly_backup.cmd uses three substitution variables to name the tape set, to provide theFORMAT string specification, and to name the restore point.

  1. Next, create a shell script you'll use to run themonthly_backup.cmd file. The shell script mybackup.sh contains three shell variables, and you can pass the values for those variables at the command line when you execute the script.

    #!/bin/tcsh
    # name: mybackup.sh
    # usage: use the tag name and number of copies as arguments
    set media_family = $argv[1]
    set format = $argv[2]set restore_point = $argv[3]
    rman @'/u01/app/oracle/scripts/monthly_backup.cmd' USING $media_family $format Image from book
    $restore_point
    

Now you have a shell script (mybackup.sh) that you can execute by passing arguments at the command line to specify values for our three substitution variables.

  1. Execute the mybackup.sh shell script, as shown here:

    % mybackup.sh archival_backup bck0906 FY06Q3
    

Each time you run the mybackup.sh script, you can specify different values for the three substitution variables, right at the command line.

Creating and Running Stored Scripts

All stored scripts in RMAN are created with theCREATE SCRIPT command, followed by the actual script contents enclosed within a pair of curly brackets,{ }. You can use any commands within the brackets of aCREATE SCRIPT command that you can use in a RUN block. The RMAN scripts do look a bit cryptic at first, but they are highly effective and actually easy to write.

Here's a simplified nightly backup script that performs a full database backup. Note that by using the keywordSQL, you can include regular SQL commands within your RMAN backup script.

RMAN> CREATE SCRIPT nightly_backup {
2>    ALLOCATE CHANNEL c1 TYPE DISK;
3>    BACKUP DATABASE FORMAT '/u01/app/oracle/%u';
4>    SQL 'ALTER DATABASE BACKUP CONTROLFILE TO TRACE';
5>    }
created script nightly_backup
RMAN>

You execute a script with the RUN command and theEXECUTE SCRIPT command. So, now that you have created the scriptnightly_backup, all you need to do to run the full backup is to execute the script as follows:

RMAN> RUN {EXECUTE SCRIPT nightly_backup;}
executing script: nightly_backup
allocated channel: c1
channel c1: sid=19 devtype=DISK
. . .
RMAN>

RMAN scripting enables you to perform complex tasks in a few short lines. The following script uses two tape devices to perform a full database backup. The script allocates the two channels (connections to the server), completes the backup in a specified format, and releases the channels.

RMAN> RUN {
2>    ALLOCATE CHANNEL c1 TYPE 'sbt_tape';
3>    ALLOCATE CHANNEL c2 TYPE 'sbt_tape';
4>    BACKUP
5>    FORMAT  'full d%d_u%u'
6>    FILESPERSET 10
7>    DATABASE;
8>    RELEASE CHANNEL c1;
9>    RELEASE CHANNEL c2;
10>   }

If you wish, you can incorporate RMAN commands in an operating system file, called acommand file. Here is an example that shows how you can use an operating system file to execute RMAN commands and store the results in a log file (output.txt):

$ rman TARGET/CATALOG rman/cat@catdb CMDFILE commandfile.rcv LOG outfile.txt

Checking the Syntax of RMAN Scripts

You can use the CHECKSYNTAX parameter to check the syntax of a script (or any RMAN command) you plan to use with RMAN. Here's an example that shows a script contained in the script filetestfile that has the correct syntax:

$ rman CHECKSYNTAX @/tmp/testfile
Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:09:16 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.

RMAN> # command file with correct syntax
2> restore database;
3> recover database;
4>
The cmdfile has no syntax errors
 Recovery Manager complete.
$

Creating Global RMAN Scripts

The scripts you've seen so far are local scripts, since you can use them only in the database in which you create them. You can also create and execute an RMANglobal script against a database registered in the recovery catalog, providing your RMAN client is connected to the recovery catalog and the targetdatabase simultaneously. You can get databases to share RMAN scripts if they connect to the database with the RMAN catalog. The following statement shows the syntax for creating a global script:

RMAN> CREATE GLOBAL SCRIPT global_full_backup
      {
      BACKUP DATABASE PLUS ARCHIVELOG;
      DELETE OBSOLETE;
      }
created global script global_full_backup
RMAN>

You execute a global script in the same way as a local script:

RMAN> RUN {EXECUTE GLOBAL SCRIPT global_full_backup};}

Printing a Script

The following PRINT SCRIPT command prints out the contents of the global script example:

RMAN> PRINT GLOBAL SCRIPT global_full_backup;
printing stored global script: global_full_backup
  {backup database plus archivelog ;
   delete obsolete;
  }
RMAN>

Listing Script Names

The LlST . . . SCRIPT NAMES command lets you view the names of all the scripts you stored in a recovery catalog. Here's an example:

RMAN> LIST SCRIPT NAMES;

The LIST . . . SCRIPT NAMES command shows all local and global scripts that you can execute for the database you are currently connected to. To view the script names for all the databases registered in the recovery catalog, execute the LIST ALL SCRIPT NAMES command instead.

Deleting Stored Scripts

Use the DELETE SCRIPT command to delete a stored script from the recovery catalog, as shown here:

RMAN> DELETE SCRIPT 'my-script';

If the script is global, use the DELETE GLOBAL SCRIPT command instead.

Creating Dynamic Stored Scripts

You can create a dynamic stored script by specifying substitution variables while creating a script with theCREATE SCRIPT command. The USING clause lets you specify values for the substitution variables in a command file. Follow these steps to create and use a dynamic stored script:

  1. Create a command file that you can use to create a stored script. In our example, the command file is namedmyscript.rman, and it contains the CREATE SCRIPT command to create the new stored script. Use substitution variables for values that you want to assign dynamically.

    RMAN> CREATE SCRIPT quarterly {
          ALLOCATE CHANNEL c1
          DEVICE TYPE sbt
          PARMS 'ENV=(OB_MEDIA_FAMILY=&1)';
          BACKUP
            TAG &2
            FORMAT '/disk2/bck/&1%U.bck'
            KEEP FOREVER
            RESTORE POINT &3
            DATABASE;
            }
    

The QUARTERLY script (created using the command filemyscript.rman) uses three substitution variables: OB_MEDIA_FAMILY to specify the name of the tape set, FORMAT to specify the format string, andRESTORE_POINT to specify the name of the restore point.

  1. Connect to the target database and the recovery catalog, specifying initial values for the three substitution variables in theQUARTERLY script. Place the values after the keyword USING, as in the following example:

    $ rman target / catalog rman@catdb USING arc_backup bck0908 FY08Q3
    

Note that at this point, you're merely logged in to RMAN: specifying theUSING clause during the RMAN login enables you to pass values for the three substitution variables in the script. You'll create the script in the next step.

  1. Once you log in to RMAN, execute the command filemyscript.rman to create the stored script QUARTERLY.

    RMAN> @catscript.rman
    

RMAN now has a new stored script named QUARTERLY, which can accept different values for its three substitution variables.

Now that you have created the dynamic stored script, you can execute it every quarter by passing the correct values for the three substitution variables. For example, I can assign the following values to the substitution variables:arch_bkp for the media family, bkp1208 as part of theFORMAT string, and FY0804 as the name of the restore point. Here's how to invoke the stored script with those parameter values:

RUN
{
  EXECUTE SCRIPT quarterly
    USING arch_bkp
    bkp1208
    FY08Q4;
}

As the example shows, it's very easy to pass different runtime values for the variables inside the dynamic stored script.

Converting RMAN Scripts

You can change scripts from the text format to a stored script and vice versa. Here's how an RMAN command can send the contents of a stored script to a text file:

RMAN> PRINT script nightly_backup to file 'test.txt';
script nightly_backup written to file test.txt
RMAN>

Replacing a Stored Script

You can issue the REPLACE SCRIPT command to update a stored script. Here's an example:

RMAN> REPLACE SCRIPT full_backup
      {
        BACKUP DATABASE;
      }

If the script full_backup doesn't exist, RMAN creates the script. To replace a global script, execute theREPLACE GLOBAL SCRIPT command.

Important RMAN Terms

RMAN uses some special terminology. To use RMAN effectively, you need a good understanding of the terms discussed in the following sections.

Backup Piece

A backup piece is an operating system file containing the backup of a datafile, a control file, or archived redo log files. This backup information is stored in an RMAN-specific format.

Backup Set

A backup set is a logical structure that consists of one or more RMAN backup pieces (the default is one backup piece per backup set). You can create a backup set on disk or tape. If you back up a database, datafile, tablespace, or archivelog, RMAN groups the complete set of relevant backup pieces into one backup set. When you issue the backup command, RMAN creates the backup set to hold the output. Remember that a backup set is a file or set of files in a proprietary format that only RMAN can understand. Thus, only RMAN is able to use the backup sets to recover the database.

By default, RMAN creates a backup set when you use a backup command, whether you are copying to disk or tape (through a media manager).

Image Copy

Image copies are similar to the copies you can make of operating system files with thecp command in UNIX or the copy command in DOS. You can make image copies of datafiles, control files, and archived redo log files. RMAN image copies can be made only to disk; they can't be made to tape.

RMAN can also use copies that you make using non-RMAN operating system utilities. These types of copies are calleduser-managed copies or operating system copies. Really, there's no difference between RMAN image copies and normal copies made with thecp command, for example, except that image copies made through the RMAN tool have information about them written to the control file or the recovery catalog. If you use an operating system command such asdd to produce image copies, you can then use the RMAN CATALOG command to record these copies in the RMAN repository. Thus, you can use a manually copied datafile during a recovery, if you first use theCATALOG command to register the file with RMAN. You can then use these user-made copies of datafiles in RMAN operations through theRESTORE and SWITCH commands.

You use the RMAN command BACKUP AS COPY to make image copies. You may also direct RMAN to always produce image copies rather than backup sets (thus changing the default behavior of making backup sets) by performing the following configuration change:

RMAN> CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COPY;
new RMAN configuration parameters:
CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COPY PARALLELISM 1;
new RMAN configuration parameters are successfully stored
released channel: ORA_DISK_1
starting full resync of recovery catalog
full resync complete
RMAN>

You can use the image copies produced by the RMANBACKUP AS COPY command just like any other file copies made with operating system utilities.

Proxy Copy

RMAN can also perform a special kind of backup called theproxy copy, where the media manager is given control of the copying process. Proxy copies can't be used with disks. Here's an example of how you specify a proxy copy:

RMAN> BACKUP DEVICE TYPE sbt PROXY DATAFILE 2;

Channel

An RMAN session must use some kind of a connection to the server to perform backup and recovery work, andchannels represent those connections. Channels specify the specific device, disk, or tape that will be used for the backup or recovery. You can either have preconfigured channels (somewhat like default channels) or specify the channel manually.

You can use automatic channel allocation to configure channels persistently across sessions. In the following examples, the default device is set to an SBT in the first case and to disk in the second case:

RMAN> CONFIGURE DEFAULT DEVICE TYPE TO sbt; /* tape device */
RMAN> CONFIGURE DEFAULT DEVICE TYPE TO disk; /* OS file system */

These devices are made part of the RMAN configuration, and until they are changed again through the use of theCONFIGURE command, they remain the default device types for all RMAN sessions.

You can manually set the channel type by using theALLOCATE CHANNEL command. The following command sets the device tosbt, which indicates a sequential tape device. Note that the example uses aRUN block for allocating the channel. A RUN block is used in RMAN when you need to set up the environment for the statements within the block:

RMAN> RUN
      {ALLOCATE CHANNEL a1 DEVICE TYPE sbt;
      backup database;
      }
RMAN>

Specifying Backup Tags and Backup Formats

RMAN lets you use a tag for every backup so you can easily identify the backup. Thus, when you perform a restore or recovery operation, you can specify the tag to identify the backups to use. Tags are very useful in identifying various backups, especially those created using incremental backup strategies. Here's a simple example, showing how you can tag a full database backup:

RMAN> BACKUP TAG 'weekly_full_db_bkup' DATABASE;

You can use the FORMAT option with backup commands to specify a location and name for backup pieces and copies. You use substitution variables to generate unique filenames. Here's an example that shows how you can specify a file format, as well as the location, using the FORMAT option:

RMAN> BACKUP FORMAT='AL_%d/%t/%s/%p' ARCHIVELOG LIKE '%arc_dest%';

Making Copies of RMAN Backups

You cannot produce multiple copies of an RMAN image copy while performing the backup itself. However, you can make multiple copies of backup sets within aBACKUP command. You may send each backup copy to a different disk or tape location. You can produce up to four copies of each backup piece in a backup set within a singleBACKUP command. You can specify multiple copies in one of the following ways:

  • Use the CONFIGURE . . . BACKUP COPIES option.

  • Use SET BACKUP COPIES in aRUN block.

  • Use the COPIES option in theBACKUP command.

The following example demonstrates how to make copies of a backup to multiple disks:

RMAN> BACKUP DEVICE TYPE DISK
      COPIES 2 DATAFILE 1
      FORMAT '/disk1/df1_%U', '/disk2/df1_%U';

If you already have a previously made backup on a disk and wish to make a copy of it to another disk, use theBACKUP AS BACKUPSET command in the following way:

RMAN> BACKUP DEVICE TYPE DISK AS BACKUPSET DATABASE PLUS ARCHIVELOG;

If you would rather copy the previously made backup sets on disk to tape, use the following version of theBACKUP BACKUPSET command:

RMAN> BACKUP DEVICE TYPE sbt BACKUPSET ALL

After making image copies of a datafile, tablespace, or database, you can back up the image copies of the backups, as either image copies or backups sets. Here are some examples:

  • Create an image copy of a database:

    RMAN> BACKUP AS COPY DATABASE;
    
  • Copy the previous image copy of the database:

    RMAN> BACKUP AS COPY COPY OF DATABASE;
    
  • Make an image copy of a single tablespace:

    RMAN> BACKUP AS COPY TABLESPACE SYSAUX;
    
  • Create a backup set from the tablespace image copy:

    RMAN> BACKUP AS BACKUPSET COPY OF TABLESPACE SYSAUX;
    
  • Copy a datafile:

    RMAN> BACKUP AS COPY DATAFILE 2;
    
  • Copy the datafile copy:

    RMAN> BACKUP AS COPY COPY OF DATAFILE 2;
    

RMAN Backup Locations

Let's say you configured DISK as the default device, using theCONFIGURE DEFAULT DEVICE TYPE command. The actual location on disk where RMAN will create its backup files is determined in the following manner:

  • As described earlier in the chapter, you can specify a backup location and name using theFORMAT parameter, in which case, this location will override any location you specified for the flash recovery area. Here's an example:

    RMAN> BACKUP DATABASE FORMAT '/tmp/%U'; /* %U generates a unique filename */
    
  • If you don't specify the FORMAT parameter in the backup command, RMAN uses the flash recovery area as the default location for storing the backups, as is the case in the following example:

    RMAN> BACKUP DATABASE;
    
  • If you have not configured a flash recovery area and also don't specify theFORMAT parameter during the backup, RMAN will store the backups in an operating system-specific directory on disk.

RMAN Commands

You need to be familiar with a limited set of commands to use the RMAN utility for performing backups. You'll encounter the specific commands pertaining to restoring and recovering databases inChapter 16. The following sections describe the RMAN commands related to backups, grouped into the following types:

  • Backup commands

  • Job commands

  • Copy commands

  • Reporting commands

  • Listing commands

  • Validating commands

Backup Commands

The most important backup command is obviously theBACKUP command. As noted earlier, you can either specify a channel manually at backup time or let RMAN allocate a default channel.

The BACKUP command allows you to back up the entire database, a tablespace, single datafile (current or a copy), control file (current or a copy),SPFILE, archived redo log, and other backup sets. Here are some examples showing how to use theBACKUP command:

RMAN> BACKUP DATABASE;
RMAN> BACKUP TABLESPACE users;
RMAN> BACKUP DATAFILE '/u01/app/oracle/oradata/finance/users01.dbf';

The use of the simple BACKUP DATABASE command is the same as using theBACKUP AS BACKUPSET DATABASE command. When you use the preceding commands, RMAN generates one or morebackup sets, which are RMAN-specific logical backup units.

Image Copy Backups

When you use the BACKUP AS COPY version of the command, RMAN generatesimage copies of the files you want to back up. In order to make corresponding image copy backups for the previous examples, use the following commands:

RMAN> BACKUP AS COPY DATABASE;
RMAN> BACKUP AS COPY TABLESPACE USERS;
RMAN> BACKUP AS COPY DATAFILE '/u01/app/oracle/oradata/finance/users01.dbf';

  Note 

By default, RMAN creates all backups as backup sets, on tape or on disk.

None of the previous examples used names for the backups created by RMAN. In all such cases, RMAN assigns a default tag to the backups it creates. As explained earlier, you can use theTAG parameter to specify a backup tag. Here's an example, showing how to attach the tagweekly_backup to an RMAN backup:

RMAN> BACKUP DATABASE TAG = 'weekly_backup';
Logical Checking of RMAN Backups

You can use the keyword LOGICAL during a backup to let RMAN perform alogical check of the backup files. Here is an example that checks for logical corruption in the copy of a database copy (duptest), which is made from the copy of a database (test):

RMAN> BACKUP AS COPY COPY OF DATABASE FROM TAG 'TEST' CHECK LOGICAL TAG 'DUPTEST';
Incremental Backups

All the BACKUP commands in the preceding sections arefull backup commands. You can also perform incremental backups using RMAN, and in fact, this is one of the big advantages of using RMAN. Incremental backups are much faster than backing up the entire database. Incremental backups will back up only those data blocks that changed since a previous backup.

Incremental backups can be either level 0 or level 1. A level 0 incremental backup copies all data blocks just like a full backup, and acts as the base for subsequent incremental backups. To perform a level 1 incremental backup, you must first have a base level 0 backup.

RMAN provides two types of incremental backups:

  • Differential backup: Backs up all blocks changed after the most recent incremental backup at level 1 or 0.

  • Cumulative backup: Backs up all blocks changed after the most recent incremental backup at level 0.

The following command gets a level 0 backup to start with:

RMAN> BACKUP INCREMENTAL LEVEL 0 DATABASE;

Once you have the level 0 backup, you perform a level 1 differential incremental backup:

RMAN> BACKUP INCREMENTAL LEVEL 1 DATABASE;

A cumulative incremental backup at level n will perform a backup of all changed blocks since the last backup at leveln-1 or lower. So, if you perform the cumulative incremental backup at level 2,it will back up all data blocks changed since level 0 or level 1. Although you can perform a level 2 incremental backup, according to Oracle, only level 0 and level 1 are permitted.

The size of your incremental backup file will depend on the number of changed blocks and the incremental level. Cumulative backups will, in general, be larger than differential backups, since they duplicate the data copied by backups at the same level. However, cumulative backups have the advantage that they reduce recovery time, because you apply only one backup. Thus, Oracle recommends using cumulative backups, if space isn't a problem on your server.

Here's an example that shows how you can use a combination of incremental backups to come up with your backup strategy:

  • On Sunday, perform an incremental level 0 backup.

  • On Monday through Saturday, perform differential incremental level 1 backups.

  • Repeat the cycle next week.

In this strategy, if you need to recover data on Thursday evening, you apply the incremental backups from Monday, Tuesday, and Wednesday to Sunday's level 0 backup.

Consider an alternative strategy using cumulative backups:

  • On Sunday, perform an incremental level 0 backup.

  • On Monday through Saturday, perform cumulative incremental level 1 backups.

  • Repeat the cycle next week.

Note that in this case, the daily cumulative level 1 backup backs up all blocks changed since the Sunday backup. Thus, if you need to recover your database on Thursday, you need to apply only one cumulative backup from the night before to Sunday's incremental level 0 backup.

Job Commands

You can't use the ALLOCATE CHANNEL andSWITCH commands as stand-alone commands. You must use them with theRUN command, as follows:

RMAN> RUN
      {ALLOCATE CHANNEL c1 DEVICE TYPE sbt
      PARMS='ENV=(NSR_GROUP=default)';
      BACKUP DATAFILE 1;
      }
allocated channel: c1
channel c1: sid=11 devtype=SBT_TAPE
channel c1: MMS Version 2.2.0.1

The SWITCH command is similar to theALTER DATABASE RENAME DATAFILE command. It lets you replace a datafile with file copy made by RMAN.

Datafile Copies

The RMAN BACKUP AS COPY command makes a plain copy of a datafile (you can also use the oldCOPY command to do this, but Oracle deprecated the COPY command in Oracle Database 10g). These image copies are identical to the copies made by using operating system utilities. Here's an example:

RMAN> BACKUP AS COPY DATAFILE 1;
Starting backup at 05-JUN-08
using channel ORA_DISK_1
channel ORA_DISK_1: starting datafile copy
input datafile fno=00001 name=C:\ORALE\PRODUCT\11.1.0\ORADATA\NEWS\SYSTEM01.DBF

output filename=C:\ORALE\PRODUCT\11.1.0\FLASH_RECOVERY_AREA\NEWS\DATAFILE\O1_MF_
SYSTEM_0Q2XPZ1Y_.DBF tag=TAG20041016T143037 recid=2 stamp=539706790
channel ORA_DISK_1: datafile copy complete, elapsed time: 00:02:35
channel ORA_DISK_1: starting datafile copy
copying current controlfile
output filename=C:\ORALE\PRODUCT\11.1.0\FLASH_RECOVERY_AREA\NEWS\CONTROLFILE\O1_
MF_TAG20041016T143037_0Q2XVT4T_.CTL tag=TAG20041016T143037 recid=3 stamp=5397067
96
channel ORA_DISK_1: datafile copy complete, elapsed time: 00:00:07
Finished backup at 05-JUN-08
RMAN>

The following example illustrates the use of the olderCOPY command:

RMAN> COPY DATAFILE 1 TO 'c:\download\test.copy';
Starting backup at 05-JUN-08
using channel ORA_DISK_1
channel ORA_DISK_1: starting datafile copy
input datafile fno=00001 name=C:\ORALE\PRODUCT\11.1.0\ORADATA\ORCL\SYSTEM01.DBF
output filename=C:\DOWNLOAD\TEST.COPY tag=TAG20041009T124719 recid=2 stamp=53909
channel ORA_DISK_1: datafile copy complete, elapsed time: 00:01:35
Finished backup at 05-JUN-08
RMAN>
Backup Deletion

You use the DELETE command to remove physical backups made by RMAN. TheDELETE command deletes physical backups, updates control file records to indicate that the backups are deleted, and also removes their records from the recovery catalog (if you use one). You can delete backup sets, archived redo logs, and datafile copies.

  Caution 

Always use RMAN'S DELETE command, rather than an operating system deletion command, to remove RMAN backups. Otherwise, the RMAN repository will contain records of backups that are no longer available.

The following example deletes all archived redo logs that RMAN has backed up at least twice to tape:

RMAN> DELETE ARCHIVELOG ALL BACKED UP 2 TIMES TO DEVICE TYPE sbt;

The DELETE OBSOLETE command will remove all backups you no longer need. You can runDELETE OBSOLETE periodically to delete all backups that are obsolete. A backup is obsolete if it's no longer needed for database recovery, according to your retention policy. TheDELETE EXPIRED command removes the recovery catalog records for expired backups and marks them asDELETED. This command is handy when you think you might have deleted RMAN backups or archived logs from disk with an operating system utility. You can first run theCROSSCHECK command so RMAN can mark the backups it can't find asexpired. An expired backup means that the backup file can't be found by RMAN. You can then use theDELETE EXPIRED command to remove the records for these files from the control file and the recovery catalog.

Reporting Commands

RMAN provides useful reporting commands that enable you to check your backup and recovery processes. You can query RMAN to see which files need backup and which files are obsolete and, therefore, removable.

Schema, Obsolete, Need Backup, and Unrecoverable Reports

The REPORT SCHEMA command lists all datafiles that are part of the target database.

The REPORT OBSOLETE command displays all the backups rendered obsolete based on the retention policy you choose:

RMAN> REPORT OBSOLETE;
RMAN retention policy will be applied to the command
RMAN retention policy is set to recovery window of 14 days
no obsolete backups found
RMAN>

If there are obsolete backups in the repository, you can delete them with theDELETE OBSOLETE command.

If you use the flash recovery area to store your backups, RMAN automatically deletes obsolete backups when it needs to make room for newer backups. Until then, obsolete backups will remain in the flash recovery area. If you aren't using a flash recovery area, you must manually run the DELETEOBSOLETE command periodically to remove the obsolete backup files.

The REPORT NEED BACKUP command lists any datafiles that need backup to conform with the retention policy you originally chose for your backups. The following example shows that no files need a backup:

RMAN> REPORT NEED BACKUP;
RMAN retention policy will be applied to the command
RMAN retention policy is set to redundancy 1
Report of files with less than 1 redundant backups
File #bkps            Name
---- ----- ---------------------------------------------------------
1      0   /u01/app/oracle/product/11.1.0/oradata/nicko/system01.dbf
2      0   /u01/app/oracle/product/11.1.0/oradata/nicko/undotbs01.dbf
3      0   /u01/app/oracle/product/11.1.0/oradata/nicko/sysaux01.dbf
4      0   /u01/app/oracle/product/11.1.0/oradata/nicko/users01.dbf
RMAN>

The REPORT UNRECOVERABLE command lists all unrecoverable datafiles. An unrecoverable file is a datafile with a segment that has undergone a nologging operation, and should therefore be backed up immediately.

Catalog Reports

The CATALOG command helps you identify and catalog any files that aren't recorded in RMAN's repository and thus are unknown to RMAN. Any one of the following events might cause this:

  • You restore a backup control file.

  • Your restore a standby control file.

  • You re-create the control file.

  • You enable the DB_RECOVERY_FILE_DEST parameter and then disable it.

In addition, you may create file backups of both datafiles and archived redo logs that RMAN won't be aware of. For example, you can use theCATALOG command to catalog database file copies you made as a level 0 backup. You can then do an incremental backup later by using the datafile copy as the basis.

You can catalog all datafile copies, backup pieces, or archivelogs on disk using theCATALOG command. Here are a couple of examples:

RMAN> CATALOG DATAFILECOPY '/u01/app/oracle/backup/users01.dbf';
RMAN> CATALOG BACKUPPIECE '/disk1/backups/backup_820.bkp';

By using the CATALOG START WITH command, you can make RMAN start searching for all uncataloged files in the directory you specify. This command is especially handy when your filenames are cryptic, as when you use an OMF or ASM file system. The following example shows how you can catalog multiple backup files in a directory at once, using theCATALOG START WITH command:

RMAN> CATALOG START WITH '/disk1/backups/';

RMAN will first list all files in the /disk1/backups directory and add them to its repository, after you confirm the operation.

If you notice a discrepancy between the recovery catalog entries and the actual backups on disk, RMAN will issue an error when you try to perform a backup or recovery. To get rid of invalid entries in the recovery catalog, you use the DELETE command with the FORCE option, as shown here:

RMAN> DELETE FORCE NOPROMPT ARCHIVELOG SEQUENCE 40;

Listing Commands

Several RMAN commands let you list various items, like backups and stored scripts in the recovery catalog.

The LIST BACKUP command shows you all the completed backups registered by RMAN. The command shows all backup sets and image copies, as well as the individual datafiles, control files, archived redo log files, and SPFILEs in the backup files. You can also list all backups by querying V$BACKUP_FILES and the RC_BACKUP_FILES recovery catalog view.Listing 15-1 shows the output of the LIST BACKUP command.

Listing 15-1:Using the LIST BACKUP Command

RMAN> LIST BACKUP;
List of Backup Sets
===================
BS Key  Type LV Size       Device Type Elapsed Time Completion Time
------- ---- -- ---------- ----------- ------------ ---------------
892     Full    169M         DISK          00:01:19       06-JUN-08
  List of Datafiles in backup set 892
  File LV Type Ckp SCN    Ckp Time Name
  ---- -- ---- ---------- --------- ----
  1       Full 81814      06-JUN-08 C:\ORALE\PRODUCT\11.1.0\
ORADATA\NEWS\SYSTEM01.DBF
. . .
List of Archived Logs in backup set 917


BS Key  Type LV Size       Device Type Elapsed Time Completion Time
------- ---- -- ---------- ----------- ------------ ---------------
928     Full      3M         DISK          00:00:06       06-JUN-08

   BP Key: 930   Status: AVAILABLE  Compressed: NO  Tag: TAG20041016T132630
  Controlfile Included:                       Ckp SCN: 81959 Ckp time: 06-JUN-08
RMAN>

The LIST COPY command is analogous to theLIST BACKUP command and shows you the complete list of all the copies made using RMAN.

RMAN> LIST COPY;

The LIST ARCHIVELOG ALL command will list all available archived log copies.

Finally, you can use the LIST SCRIPT NAMES command to display the names of all the stored scripts in the recovery catalog. TheLIST GLOBAL SCRIPT NAMES command will show all the global scripts.

Validating Commands

You can use the VALIDATE BACKUPSET command to validate backup sets before you use them from a recovery. In the following example, theVALIDATE command shows that backup set 1 can't be found by RMAN:

RMAN> VALIDATE BACKUPSET 1;
using channel ORA_DISK_1
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of validate command at 06/05/2008 13:14:04
RMAN-06004: ORACLE error from recovery catalog database: RMAN-20215: backup set
not found
RMAN-06159: error while looking up backup set
RMAN>

In addition, you can use the CROSSCHECK command to make sure that a backup is indeed present and is usable. You'll see an example of this command in the "Monitoring and Verifying RMAN Jobs" section later in this chapter.

RMAN Configuration Parameters

RMAN has several configuration parameters, which are set to their default values when you first use RMAN. You don't have to configure anything really to start using RMAN or learn how to use the various commands. Of course, as you become proficient with RMAN, you'll want to configure several of the configuration parameters to suit your needs. Use theSHOW ALL command to see the default values, as shown inListing 15-2.

Listing 15-2:Using the SHOW ALL Command

RMAN> SHOW ALL;
using target database control file instead of recovery catalog
RMAN configuration parameters for database with db_unique_name ORCL are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO '%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; # default
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
CONFIGURE COMPRESSION ALGORITHM 'BZIP2'; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO 'C:\ORCL\APP\ORACLE\PRODUCT\11.1.0\DB_1\D
ATABASE\SNCFORCL.ORA'; # default


You can view the current configuration values of all the RMAN parameters that you change from their default values by using the V$RMAN_CONFIGURATION view, as follows:

SQL> SELECT * FROM v$rman_configuration;
CONF#    NAME                           VALUE
----- ---------------------------- -----------------
1        DEFAULT DEVICE TYPE TO     'SBT_TAPE'
2        CONTROLFILE AUTOBACKUP       ON
3        BACKUP OPTIMIZATION          ON
4        RETENTION POLICY             TO REDUNDANCY 2
SQL>

If you haven't changed any of the configuration parameters from their default values, the previous query will not return any rows. You can use theCONFIGURE command to change the values of these RMAN configuration parameters. Let's take a closer look at some of the important configurable parameters and how you can change them.

Backup Retention Policy

A backup retention policy tells RMAN when to consider backups of datafiles and log files obsolete. Note that when you tell RMAN to consider a backup file obsolete after a certain time period, RMAN only marks the file obsolete—it doesn't delete it. You must go in and delete the obsolete files.

You can set a retention policy by using either of two methods: the defaultREDUNDANCY option or the RETENTION WINDOW option. In both cases, you use theCONFIGURE RETENTION POLICY command to set the retention policy for all of your database files by default.

The REDUNDANCY Option

The REDUNDANCY option lets you specify how many copies of the backups you want to retain. The default is 1. You set the retention policy this way:

RMAN> CONFIGURE RETENTION POLICY TO REDUNDANCY 2;
new RMAN configuration parameters:
CONFIGURE RETENTION POLICY TO REDUNDANCY 2;
new RMAN configuration parameters are successfully stored
starting full resync of recovery catalog
full resync complete
RMAN>

Let's say you're backing up your datafiles every day. The previous RMAN command specifies that RMAN keep only two backups of each database file. RMAN will also retain all redo logs required to recover the two days' worth of datafile backups. Any backups that are older than two days are considered obsolete. Of course, you can save to tape and archive a much older set of backups.

Archived backups are useful if you ever want to perform a PITR to a time further back than your recent backup. In addition, if your current backups end up being unusable, you have an alternative set of backups available.

The RECOVERY WINDOW Option

Setting the backup retention policy using the RECOVERY WINDOW option enables you to specify how far back in time you want to recover from when your database is affected by a media failure. RMAN will keep all backups of datafiles and log files one backup older than the recovery window. For example, if the recovery window is seven days, RMAN will save all backups starting from the backups done immediately before the seven-day period. You set the recovery window as follows:

RMAN> CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 14 DAYS;
old RMAN configuration parameters:
CONFIGURE RETENTION POLICY TO REDUNDANCY 2;
new RMAN configuration parameters:
CONFIGURE RETENTION POLICY TO RECOVERY WINDOW OF 14 DAYS;
new RMAN configuration parameters are successfully stored
starting full resync of recovery catalog
full resync complete
RMAN>

As you can see in this example, you can set the redundancy number or a recovery window, but not both. A change in the value of either of the two options will supersede the values of the existing option.

Default Device Type

The default device for backups is a disk; that is, RMAN will automatically make backups to a file system on your server. If you want to back up to tape, you configure the default device type tosbt (all tape destinations are referred to as sbt). Here's an example:

RMAN> CONFIGURE DEFAULT DEVICE TYPE TO sbt;
old RMAN configuration parameters:
CONFIGURE DEFAULT DEVICE TYPE TO DISK;
new RMAN configuration parameters:
CONFIGURE DEFAULT DEVICE TYPE TO 'SBT_TAPE';
new RMAN configuration parameters are successfully stored
starting full resync of recovery catalog
full resync complete
RMAN>

If you wish to switch the default device back to disk, you can do so with the following command:

RMAN> CONFIGURE DEFAULT DEVICE TYPE TO DISK;
old RMAN configuration parameters:
CONFIGURE DEFAULT DEVICE TYPE TO 'SBT_TAPE';
new RMAN configuration parameters:
CONFIGURE DEFAULT DEVICE TYPE TO DISK;
new RMAN configuration parameters are successfully stored
starting full resync of recovery catalog
full resync complete
RMAN>

Encryption and Compression Parameters

You must have the Oracle Advanced Security option to create an encrypted RMAN backup on disk. If you want to create encrypted backups on tape, you must use the Oracle Secure Backup SBT interface. You can query the V$RMAN_ENCRYPTION_ALGORITHM view to see the various encryption algorithms that RMAN supports. RMAN provides the following three modes of encryption:

  • Transparent encryption: Requires Oracle Public Key Infrastructure (PKI).

  • Password-based encryption: Requires a password during the backup and the restore of the backup.

  • Dual-mode encryption: Enables the encryption through either of the first two modes. Decryption can be performed either by supplying a password or by using the Oracle Wallet.

You can use the CONFIGURATION ENCRYPTION and theSET ENCRYPTION commands to encrypt RMAN backups.

In addition to encrypting RMAN backups, you can also specify the compression of RMAN backups. You must use theCONFIGURE COMPRESSION command to instruct RMAN to compress the backups it makes. TheCONFIGURE COMPRESSION ALGORTIHM command enables you to specify one of two available compression algorithms: BZIP2 and ZLIB. The default compression algorithm is ZLIB, which Oracle claims is significantly faster (by about 40 percent) than the alternative algorithm, BZIP2. You can query the V$RMAN_COMPRESSION_ALGORITHM view to examine Oracle's description of the difference between the two algorithms. For example:

SQL> select algorithm_name,algorithm_description, is_default
  2  from v$rman_compression_algorithm;

ALGORITHM     ALGORITHM DESCRIPTION                       IS_DEFAULT
---------    ----------------------------------------     ----------
ZLIB         fast but little worse compression ratio      YES
BZIP2        good compression ratio but little slower     NO
SQL>

As you can see, the ZLIB algorithm is faster, but the BZIP2 algorithm provides a superior compression ratio.

Channel Configuration

Channels are the means by which RMAN conducts its backup and recovery operations, and they represent a single stream of data to a particular device (such as a tape). If you have four channels configured, four connections will be made to the target database to open four separate server sessions.

The following example configures two channels, with channel 1 backing up to the backup directory under/test01 and channel 2 backing up to the backup directory under/test02:

RMAN> CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT
 '/test01/app/oracle/oradata/backup/%U';
new RMAN configuration parameters:
CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT'/test01/app/oracle/oradata/backup/%U';
new RMAN configuration parameters are successfully stored
RMAN> CONFIGURE CHANNEL 2 DEVICE TYPE DISK FORMAT
'/test02/app/oracle/oradata/backup/%U';
new RMAN configuration parameters:
CONFIGURE CHANNEL 2 DEVICE TYPE DISK
FORMAT'/test02/app/oracle/oradata/backup/%U';
new RMAN configuration parameters are successfully stored

  Note 

The DISK PARALLELISM parameter and theCHANNEL parameter are related to each other. For example, if the degree of parallelism is 4 and you have specified only two or even no channels at all, RMAN will open four generic channels. If, on the other hand, you have manually configured six channels but set the degree of parallelism to 1, RMAN will use only the first channel and ignore the other five.

If you start the backup with multiple channels, the failure of one channel, say, due to the failure of a tape device, won't stop the backup job. RMAN will instead complete the job using the remaining channels, and report the problem in the V$RMAN_OUTPUT view. This is also known as RMAN's Automatic Channel Failover feature.

Degree of Parallelism

The degree of parallelism (the default degree is 1) denotes the number of channels that RMAN can open during a backup or recovery. The time taken to complete the backup or recovery will decrease as you increase the degree of parallelism.

RMAN> CONFIGURE DEVICE TYPE DISK PARALLELISM 4;
old RMAN configuration parameters:
CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COPY PARALLELISM 1;
new RMAN configuration parameters:
CONFIGURE DEVICE TYPE DISK PARALLELISM 4 BACKUP TYPE TO COPY;
new RMAN configuration parameters are successfully stored
released channel: ORA_DISK_1
starting full resync of recovery catalog
full resync complete
RMAN>

Backup Optimization

The BACKUP OPTIMIZATION option ensures that RMAN doesn't perform a file backup if it has already backed up identical versions of the file. Here is how you turn on this option:

RMAN> CONFIGURE BACKUP OPTIMIZATION ON;
new RMAN configuration parameters:
CONFIGURE BACKUP OPTIMIZATION ON;
new RMAN configuration parameters are successfully stored
starting full resync of recovery catalog
full resync complete
RMAN>

Control File Parameters

RMAN has several configuration parameters that deal with control file backups. The following sections cover the important control file parameters.

Control File Auto-Backup

If you set the CONTROLFILE AUTOBACKUP option toON, each time you do a backup of your datafiles, the control file is automatically backed up along with theSPFILE. Here's how you configure this:

RMAN> CONFIGURE CONTROLFILE AUTOBACKUP ON;
old RMAN configuration parameters:
CONFIGURE CONTROLFILE AUTOBACKUP OFF;
new RMAN configuration parameters:
CONFIGURE CONTROLFILE AUTOBACKUP ON;
new RMAN configuration parameters are successfully stored
starting full resync of recovery catalog
full resync complete
RMAN>

Now, if you use any BACKUP command, the control file and theSPFILE (if there is one) are both automatically backed up, as shown in the following example:

RMAN> BACKUP TABLESPACE sysaux;
Starting backup at 06-JUN-08
. . .

channel ORA_DISK_1: datafile copy complete, elapsed time: 00:01:16
Finished backup at 06-JUN-05
Starting Control File Autobackup at 06-JUN-05
Finished Control File Autobackup at 06-JUN-05
RMAN>
Control File Backup Location and Format

You can use the control file AUTOBACKUP FORMAT parameter to specify the location and format of the control file backups. Here's an example:

RMAN> CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO
 '/test01/app/oracle/oradta/backup/cf_%F';
 new RMAN configuration parameters:
 CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR
 DEVICE TYPE DISK TO '/test01/app/oracle/oradata
 /backup/cf_%F'; new RMAN configuration parameters
 are successfully stored
RMAN>
Archivelog Deletion Policy

You can set up a persistent policy that regulates when archived redo logs become eligible for deletion from disk. The archived redo log deletion policy you configure applies to all archiving destinations, including the flash recovery area.

The database removes all eligible logs from the flash recovery area automatically. You can also manually delete an eligible archived redo log from any location, including the flash recovery area, by issuing either theDELETE ARCHIVELOG or BACKUP . . . DELETE INPUT command.

By default, RMAN's archived redo log deletion policy is configured toNONE. Under this policy of NONE, an archived redo log will be considered for deletion only if the archived redo log has been transferred to the location specified by theLOG_ARCHIVE_DEST_n parameter, and then it must also have been backed up at least once to disk or tape.

You can configure an explicit archived redo log deletion policy. Issue theCONFIGURE ARCHIVELOG DELETION POLICY BACKED command to configure the policy, as shown in the following example:

RMAN> CONFIGURE ARCHIVELOG DELETION POLICY
      TO BACKED UP 2 TIMES TO SBT;

This command specifies that all archived redo logs are eligible for deletion after they have been backed up to tape twice.

Working with the Recovery Catalog

Using the recovery catalog is purely optional, as Oracle can use the control file to store the RMAN repository data (metadata). However, as explained earlier in this chapter, it's a good idea to spend the little time it takes to create and use the recovery catalog. I assume the use of the recovery catalog in the discussions in this and thenext chapter.

  Tip 

Make sure that the database in which the recovery catalog is being created runs in archivelog mode. This ensures that you can always perform a PITR.

To create the recovery catalog, you must first connect to the database in which you want to create the recovery catalog. You need to create a new recovery catalog owner schema (usually named rman), grant the necessary privileges to it, and then create the recovery catalog. Once you create the catalog, you can register databases in it.

Creating the Recovery Catalog Schema

In order to use the recovery catalog, you need to first create a recovery catalog schema. You can create this schema or user in an existing tablespace or in a new tablespace created for this purpose. The recovery catalog itself is stored in the default tablespace of this schema. The following example creates a schema called rman:

SQL> CREATE USER RMAN IDENTIFIED BY rman
     TEMPORARY TABLESPACE temp
     DEFAULT TABLESPACE rman_tbsp
     QUOTA UNLIMITED ON rman_tbsp
User created.
SQL>

Make sure you first create the rman_tbsp tablespace for the user rman.

Making the Necessary Grants

The new rman schema owner, rman, needs privileges to maintain and query the recovery catalog. You do this by granting the user the RECOVERY_CATALOG_OWNER role. The following code shows how to make the necessary grants to user rman:

SQL> GRANT RECOVERY_CATALOG_OWNER TO rman;
Grant succeeded.
SQL>

Connecting to RMAN

You can connect to RMAN in one of two ways. One way is to first invoke RMAN, and then use theCONNECT CATALOG command to connect to it, as shown here (nicko is the database containing the recovery catalog in this example):

$ rman
Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:36:34 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.
RMAN> CONNECT CATALOG rman/rman@nicko
connected to recovery catalog database
RMAN>

You can also connect directly from the operating system level, as follows:

$ rman CATALOG rman/rman@nicko
connected to recovery catalog database
RMAN>

When you connect to the catalog database directly, you still aren't connected to the target database (unless the target and the catalog database are the same). To connect to the target database, you must now use the following command from within the RMAN interface (nina is the target database name):

RMAN> connect target nina
Connected to target database: NINA (DBID=1974138212)
RMAN>

Instead of first connecting to the recovery catalog and then to the target database, you can use the following method to connect to the recovery catalog and to the target database in one step:

$  rman catalog rman/rman@nicko target nina
Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:36:34 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.target database password:
connected to target database: NINA (DBID=1974138212)
connected to recovery catalog database
RMAN>

  Tip 

Although you can create the recovery catalog schema in the target database itself, Oracle recommends that you use a dedicated recovery catalog database, to secure the recovery catalog. This way, if the target database needs to be recovered, you'll have the necessary recovery data available in the recovery catalog.

Creating the Recovery Catalog

If you want to utilize the recovery catalog (instead of the default method of using the control file) to store the RMAN metadata, you must first create it in the recovery catalog owner's (rman) schema.

First, connect to the catalog database in one of the two ways shown in theprevious section. Next, use the CREATE CATALOG command, which will create the recovery catalog:

RMAN> CREATE CATALOG;
recovery catalog created
RMAN>

The CREATE CATALOG command creates the RMAN recovery catalog in the tablespace rman_tbsp, which you assigned as the default tablespace for the user rman.

The DROP CATALOG command will remove the recovery catalog:

RMAN> DROP CATALOG;
Recovery catalog owner is RMAN
Enter DROP CATALOG command again to confirm catalog removal
RMAN> DROP CATALOG;
Recovery catalog dropped
RMAN>.

Registering a Database

For RMAN to do its job, you need to register the target database you want to back up and recover. Registration means that a database is enrolled in the recovery catalog. Once you register the database, RMAN will automatically get all the relevant metadata pertaining to the target database and store it in its own schema.

You don't need a separate recovery catalog for each of your Oracle databases; you can register all your databases in a single recovery catalog.

To register a new database in the recovery catalog, first connect to the target database:

$ rman catalog rman/rman@nicko target nina
Recovery Manager: Release 11.1.0.6.0 - Production on Thu Mar 27 11:36:34 2008
Copyright (c) 1982, 2007, Oracle.  All rights reserved.
target database Password:
connected to target database: NINA (DBID=1974138212)
connected to recovery catalog database
RMAN>


  Caution 

Make sure you set the ORACLE_SID to the target database SID before you register a database in the recovery catalog. Otherwise, when you specify the target, you'll connect to the database whose instance name matches the ORACLE_SID of your UNIX session, not to the target database.

Next, register the database in the recovery catalog:

RMAN> REGISTER DATABASE;
database registered in recovery catalog
starting full resync of recovery catalog
full resync complete
RMAN>

The target database is now successfully registered in the recovery catalog. At this point, you can use theREPORT SCHEMA command to make sure all the datafiles of the target database show up in the list.

You can also issue the following command to check the incarnation of the database:

RMAN> LIST INCARNATION;
List of Database Incarnations
DB Key  Inc Key DB Name      DB ID      STATUS   Reset SCN   Reset Time
------- ------- -------- -----------  ---------- ----------  -----------
1        8       NINA     1974138212    PARENT        1      11-JAN-08
1        2       NINA     1974138212    CURRENT  318842      05-JUN-08
RMAN>

Maintaining the Recovery Catalog

If you choose to create and use a recovery catalog, you must know how to maintain it. The following sections explain important recovery catalog maintenance tasks.

Resynchronizing the Recovery Catalog

Changes made to the target database structure aren't automatically propagated to the recovery catalog. TheBACKUP and COPY commands automatically perform a resynchronization each time you perform a backup or copy. But you may need to manually resynchronize the recovery catalog under two circumstances: when your target database has just undergone a number of physical changes and when the target database is performing a very large number of log switches in between the backups.

During a resync operation, RMAN reads the target database's control file to update the information it keeps regarding datafiles, log switches, physical schema, and so forth. Oracle recommends that you resynchronize the recovery catalog after making any changes to the physical structure of a target database. You issue theRESYNC CATALOG command as follows, after connecting to the target database:

RMAN> RESYNC CATALOG;
starting full resync of recovery catalog
full resync complete
RMAN>

Backing Up the Recovery Catalog

You should always back up the recovery catalog database immediately after you back up the target database. Backing up the recovery catalog becomes even more critical if you're using a single recoverycatalog to store the metadata of all the databases in your system. You should follow these principles to afford the maximum possible security to the recovery catalog database:

  • Back up the recovery catalog on a frequent basis.

  • Never store the recovery catalog in the target database. You could end up losing the target database and the recovery catalog at the same time if there's a media failure.

  • Always run the database holding the recovery catalog in archivelog mode.

  • Make multiple copies of the recovery catalog database backup, preferably to tape, in addition to disk backups.

  • Set the retention policy to a value greater than 1.

  • Set CONTROLFILE AUTOBACKUP toON, thus ensuring that you can always recover the recovery catalog database, provided you have the control file auto-backup on hand.

  • Set a very high value for CONTROL_FILE_RECORD_KEEP_TIME, so the control file won't be over-written quickly, wiping out your RMAN repository data.

Note that in addition to using RMAN to back up the recovery catalog database, you can use the Data Pump Export utility to create logical backups of the recovery catalog database.

Recovering the Recovery Catalog

In order to restore and recover the recovery catalog database, you must first restore the control file and the server parameter file for the database from the auto-backups you made earlier. You can then restore and recover the database itself.

If you have failed to make backups of your recovery catalog, or if you have made the backups but are unable to use them (perhaps because you have lost parts of them), you must re-create the recovery catalog. You can re-create the recovery catalog in one of the following ways:

  • Execute the RESYNC CATALOG command to update the recovery catalog with the repository information from the control file of the target database. Of course, any aged out metadata will be lost for good.

  • Execute the CATALOG START WITH . . . command to recatalog any available backups.

Cataloging Backups

You can issue the CATALOG command to catalog older backups in the recovery catalog. By issuing theCATALOG command, you can catalog older backups that have aged out of the control file, thus enabling RMAN to use those backups during a file restore operation. Here's an example that shows how to use theCATALOG command:

RMAN> CATALOG DATAFILECOPY '/u01/old_backups/users01.dbf';

You can execute the CATALOG START WITH command to catalog multiple files in a directory, as shown here:

RMAN> CATALOG START WITH '/u01/old_backups/';

RMAN waits for your confirmation after listing each file, before adding the file to the recovery catalog.

Upgrading the Recovery Catalog

If your RMAN client is from the Oracle 11.1 release, but the recovery catalog schema is from an older version, you must upgrade the recovery catalog. You can determine the schema version of the recovery catalog by executing the following query:

SQL> SELECT * FROM rcver;

VERSION
---------
10.02.00

If the output of this query shows multiple rows, the highest version number is the catalog schema version. In our example, there's only one version number, 10.2.0, meaning that the catalog version is 10.2.0.

In order to upgrade the recovery catalog, follow these steps:

  1. If the recovery catalog owner that you created is from a release before 10.1, execute the followingGRANT command (assuming that rman is the catalog owner):

    SQL> GRANT CREATE TYPE TO rman;
    
  2. Start RMAN and connect to the recovery catalog database.

    RMAN> connect catalog rman/rman;
    
  3. Execute the UPGRADE CATALOG command.

    RMAN> UPGRADE CATALOG;
    
  4. Confirm the command by rerunning it.

    RMAN> UPGRADE CATALOG;
    

You can now use the recovery catalog with the RMAN client from the Oracle Database 11g release.

Importing Recovery Catalogs

You may have multiple recovery catalogs, each taking care of databases from different versions of the Oracle database. You can consolidate those recovery catalogs into one catalog, by using theIMPORT CATALOG command. By default, the command imports metadata for all databases registered in the source recovery catalog to the destination recovery catalog. You can, however, specify the databases you want to import into the destination catalog. Also by default, RMAN unregisters an imported database from the source recovery catalog, but you can retain the imported databases in the source catalog by adding theNO UNREGISTER clause to the IMPORT CATALOG command.

Your target databases, recovery catalog databases, and the recovery catalog schema can be from different database versions. However, Oracle recommends that you consolidate all your recovery catalogs into a single catalog at the most recent version of the recovery catalog schema. The IMPORT CATALOG command helps you do this.

In the following example, I use the IMPORT CATALOG command to merge two recovery catalogs, one from the 10.2 release and the other from 11g, into a single 11g release catalog schema. Here are the steps:

  1. Connect to the destination recovery catalog.

    $ rman
    RMAN> connect catalog rman/rman@rman11
    
    
  2. Issue the IMPORT CATALOG command along with the connection information for the source recovery catalog (rman10) in step 1.

    RMAN> import catalog rman1/rman1@rman10;
    Starting import catalog at 30-MAR-08
    connected to source recovery catalog database
    import validation complete
    database unregistered from the source recovery catalog
    Finished import catalog at 30-MAR-08
    RMAN>
    

By default, the IMPORT CATALOG command imports all the registered databases from the source catalog into the destination catalog, but you can specify a particular database or databases, as shown here:

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

The first example shows how you can specify one or more database identifiers (DBIDs), whereas the second example shows how you can give the names of databases to import. In either case, you are able to limit the import to a specific database or databases.

Moving the Recovery Catalog

You can move the recovery catalog to a different database by using theIMPORT CATALOG command. First, create an empty recovery catalog into the destination database and then issue theIMPORT CATALOG command, as shown in the following example:

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

The IMPORT CATALOG command moves the recovery catalog contents to the destination database.

The IMPORT CATALOG command imports the source_db recovery catalog contents to a catalog in the target_db database.

Dropping a Recovery Catalog

Execute the DROP CATALOG command to remove a recovery catalog, as shown here:

RMAN> DROP CATALOG;

When you drop the recovery catalog, the actual backups made by RMAN will be untouched. The control files of the target database will contain records of the most recent backups made by RMAN. You can re-create the recovery catalog and register the target database to make the existing backups usable by RMAN again.

Virtual Private Catalogs

Once you register various databases in a recovery catalog, as the recovery catalog owner, you must grant permissions for some users to access the recovery catalog. Even if a user needs access to just one or two databases, you are forced to allow the user access to all databases you registered in the catalog. To enhance security, Oracle recommends that you maintain one central recovery catalog called abase recovery catalog in which you register all the databases you wish to manage, and thencreate smallervirtual private catalogs that allow access to sets of databases. A virtual private catalog is merely a set of synonyms and views based on the base recovery catalog, but stored in the schema of the virtual private catalog owner. Thus, you will maintain a single recovery catalog as before while also having the ability to grant users access to subsets of your catalog via virtual private catalogs that you define.

In order to create a virtual private catalog, you must first create an owner for the virtual private catalog. After this, you can go ahead and create the virtual private catalog itself. In the following sections, I show you how to first create the virtual private catalog owner and then the virtual private catalog itself.

Creating the Virtual Private Catalog Owner

Follow these steps to create a new virtual private catalog owner:

  1. Start SQL*Plus and connect to the recovery catalog database as a user with administrator privileges (SYS). For example:

    SQL> connect sys/sammyy1 as sysdba
    
  2. Execute the following statement to create the virtual private catalog owner:

    SQL> CREATE USER virtual1 IDENTIFIED BY virtual1
         DEFAULT TABLESPACE virtual_tbsp1
    
  3. Grant the new owner the RECOVERY_CATALOG_OWNER role:

    SQL> GRANT recovery_catalog_owner TO virtual1;
    Start RMAN and connect as the base recovery catalog owner:
    RMAN> CONNECT CATALOG rman/rman@catdb
    
  4. So the new virtual recovery catalog owner can work with databases, grant the privileges necessary:

    RMAN> GRANT CATALOG FOR DATABASE prod1 to virtual1;
    

The previous command grants rights to the virtual private catalog owner virtual1 to manage the prod1 database. TheGRANT CATALOG command grants access to the user virtual1 for just the prod1 database. You can optionally grant the new user the capability to register new databases in the virtual private catalog owned by virtual1 by issuing theREGISTER DATABASE command as shown here:

RMAN> GRANT REGISTER DATABASE TO virtual1;

Now that the new virtual private catalog owner has been created, it's time to create the virtual private catalog itself.

Creating the Virtual Private Catalog

Once you've created the new virtual recovery catalog owner, create the virtual private catalog using the following steps:

  1. Connect to the base recovery catalog database as the new virtual private catalog owner. For example:

    RMAN> CONNECT CATALOG virtual1/virtual1@catdb;
    
  2. Issue the command to create the virtual private catalog:

    RMAN> CREATE VIRTUAL CATALOG;
    

The user virtual1 is now ready to work with the virtual private catalog, with access to one database, prod1.

Dropping a Virtual Private Catalog

The base recovery catalog owner can drop the virtual private catalog in a similar fashion as the base recovery catalog, by issuing the following command:

RMAN> DROP CATALOG;

Revoking Access Granted Through a Virtual Private Catalog

To revoke access to any database from the virtual private catalog owner, issue theREVOKE CATALOG command as shown here:

RMAN> REVOKE CATALOG FOR DATABASE prod1 FROM virtual1;

You can provide a database name as shown here or the DBID for the database. You can revoke the right of the virtual private owner to register new databases in the virtual private catalog (and thus in the base recovery catalog) by issuing the following command:

RMAN> REVOKE REGISTER DATABASE FROM virtual1;

Examples of RMAN Backups

The following sections take you through a few examples of various kinds of backups you can perform using RMAN.

Backing Up an Entire Database

If you want to back up the entire database, you use theBACKUP DATABASE command. RMAN will automatically back up all the datafiles that are part of the database, as shown inListing 15-3.

Listing 15-3:Backing Up a Database Using RMAN

RMAN> BACKUP DATABASE;
Starting backup at 06-JUN-08
using channel ORA_DISK_1
channel ORA_DISK_1: starting full datafile backupset
channel ORA_DISK_1: specifying datafile(s) in backupset
input datafile fno=00001 name=C:\ORALE\PRODUCT\10.1.0\ORADATA\ORCL\SYSTEM01.DBF
input datafile fno=00003 name=C:\ORALE\PRODUCT\10.1.0\ORADATA\ORCL\SYSAUX01.DBF
input datafile fno=00005 name=C:\ORALE\PRODUCT\10.1.0\ORADATA\ORCL\EXAMPLE01.DBF
input datafile fno=00002 name=C:\ORALE\PRODUCT\10.1.0\ORADATA\ORCL\UNDOTBS01.DBF
input datafile fno=00004 name=C:\ORALE\PRODUCT\10.1.0\ORADATA\ORCL\USERS01.DBF
. . .
Starting Control File Autobackup at 06-JUN-08
piece handle=C:\ORACLE\PRODUCT\10.1.0\FLASH_RECOVERY_AREA\ORCL\AUTOBACKUP\2005_06
_06\O1_MF_N_539094997_0PJ8FDBF_.BKP comment=NONE
Finished Control File Autobackup at 06-JUN-08
RMAN>


Backing Up the Archived Logs

You use the BACKUP ARCHIVELOG ALL command to back up all archived logs that you haven't backed up before. You can also use the commandBACKUP DATABASE PLUS ARCHIVELOG to back up all datafiles as well as any archived redo log files, as shown inListing 15-4.

Listing 15-4:Backing Up a Database and Archived Logs Using RMAN

RMAN> BACKUP DATABASE PLUS ARCHIVELOG;
Starting backup at 06-JUN-08
current log archived
allocated channel: ORA_DISK_1
channel ORA_DISK_1: sid=38 devtype=DISK
channel ORA_DISK_1: starting archive log backupset
channel ORA_DISK_1: specifying archive log(s) in backup set
input archive log thread=1 sequence=4 recid=1 stamp=539702327
. . .
16\O1_MF_ANNNN_TAG20041016T132206_0Q2SPK4S_.BKP comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:05
Finished backup at 06-JUN-08
RMAN>


  Note 

If you're running in archivelog mode, your redo log files are being archived continuously. Therefore, there's no need to back up your online redo log files. In fact, RMAN doesn't let you back up the online redo log files. The best way to protect the online logs against media failure is to multiplex them, with duplicate online log members on different disks attached to different disk controllers. Losing an online redo log could mean loss of data if you don't have a copy.

Performing an Online Backup with a Script

The RMAN utility performs online backups in a more efficient manner than the normal user-managed backups, besides providing many extra benefits that make the backups far easier and safer. For one thing, you don't need to place the tablespaces into the begin backup and end backup modes. In addition, you back up only the used space in the database, not the entire allocated space. You also take care of any fractured blocks, because RMAN will continue to read the blocks until it gets a consistent read.

  Caution 

You should never back up your online redo log files when performing an online backup, because you'll run the risk of accidentally restoring the backed up log files and thus corrupt your database.

Listing 15-5 shows a typical script that performs online backups using RMAN, assuming you are backing up to disk.

Listing 15-5:Performing an Online Backup with RMAN

RMAN> RUN {
# backup the database to disk
ALLOCATE CHANNEL d1 TYPE DISK;
ALLOCATE CHANNEL t2 TYPE DISK;
ALLOCATE CHANNEL t3 TYPE DISK;
#backup the whole db
BACKUP
TAG whole_database_open
FORMAT '/u01/oradata/backups/db_%t_%s_p%p'
DATABASE;
# switch the current log file
SQL 'alter system archive log current';
#backup the archived logs
BACKUP
ARCHIVELOG ALL
FORMAT '/u11/oradata/backups/al_%t_%s_p%p';
# backup a copy of the control file
BACKUP
CURRENT CONTROLFILE
TAG = cf1
FORMAT '/u12/oradata/backups/cf_%t_%s_p%p';
RELEASE channel d1;
RELEASE channel d2;
RELEASE channel d3;
 }
RMAN>

Backing Up the Control File

The BACKUP CURRENT CONTROLFILE command backs up the control file, as shown inListing 15-6.

Listing 15-6:Backing Up a Control File Using RMAN

RMAN> BACKUP CURRENT CONTROLFILE;
Starting backup at 06-JUN-08
using channel ORA_DISK_1
channel ORA_DISK_1: starting full datafile backupset
channel ORA_DISK_1: specifying datafile(s) in backupset
including current controlfile in backupset
channel ORA_DISK_1: starting piece 1 at 06-JUN-08
channel ORA_DISK_1: finished piece 1 at 06-JUN-08
piece handle=C:\ORALE\PRODUCT\10.1.0\FLASH_RECOVERY_AREA\NEWS\BACKUPSET\2005_06_
06\O1_MF_NCNNF_TAG20041016T132630_0Q2SYTM3_.BKP comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:07
Finished backup at 06-JUN-08
RMAN>

If you had already configured the automatic backup of the control file with theCONFIGURE CONTROLFILE AUTOBACKUP ON command, you can back up the entire database—datafiles, log files, and the control file—with the RMAN commandBACKUP DATABASE PLUS ARCHIVELOG (see Listing 15-4).

Backing Up a Tablespace

You can back up individual tablespaces if you are operating the database in archivelog mode:

RMAN> BACKUP TABLESPACE USERS;

Backing Up a Datafile

You can back up a single datafile by simply using the commandBACKUP DATAFILE filename or, optionally, specifying the destination as well. In the first case, RMAN will store the backup files in the flash recovery area. Here's an example:

RMAN> BACKUP DATAFILE  '/u01/orcl/oradata/system01.dbf';

Restarting an RMAN Backup

If an RMAN backup fails before it completes, you can resume the backup from the point where it failed, without needing to redo the entire backup. Let's say you perform a daily backup, and the last backup failed midway. After the backup failure, issue the following command:

RMAN> BACKUP DATABASE NOT BACKED UP SINCE TIME 'SYSDATE-1';

Note that the BACKUP DATABASE NOT BACKED UP SINCE TIME command will back up only those files that you haven't backed up before.

Specifying Limits for Backup Duration

Sometimes, a nightly backup interferes with the performance of a critical database job. To help with this, you can direct the database to take longer to finish the backup. TheDURATION option for the RMAN BACKUP command provides this capability. When you use theDURATION option, RMAN will figure out the appropriate backup speed for the job. You can also add your own directives to either minimize the backup time (MINIMIZE TIME) or to minimize the load (MINIMIZE LOAD) on your system.

You can use the DURATION clause with backup commands, such asBACKUP AS COPY, to specify the time (in hours and minutes) Oracle should take when doing a backup job:

DURATION <hrs>:<mins> [PARTIAL] [MINIMIZE {TIME|LOAD}]

The options are as follows:

  • PARTIAL: You can override RMAN's default behavior when the backup job runs past the interval you specify by using thePARTIAL clause. This clause prevents RMAN error messages.

  • MINIMIZE TIME: This tells RMAN to finish the backup as fast as it can.

  • MINIMIZE LOAD: This option tells RMAN to slow down if it is within its allotted time for backing up.

  Note 

You must use disks if you want to use the MINIMIZE LOAD option, because you will probably want a tape backup to finish as quickly as possible.

Remember that the DURATION clause'sPARTIAL option leads to an error if the backup exceeds its time limit. TheMINIMIZE TIME option gets the job done the fastest. TheMINIMIZE LOAD option minimizes resource use.

Here's an example of this clause:

RMAN> BACKUP AS COPY
2>    DURATION 04:00
3>    MINIMIZE TIME DATABASE;

This says

  • Limit the backup time to four hours (DURATION 04:00).

  • Run the backup at full speed, telling it to finish within the four-hour limit (MINIMIZE TIME) if possible.

  • Back up the entire database (DATABASE).

Incrementally Updated Backups

Using the incrementally updated backups feature, you can use image file backups and apply incremental backups to them, thus advancing or rolling forward the initial image copy to the time when you took the level 1 incremental backup. When you perform recovery, you can use the incrementally updated image copy as if it were an actual image copy taken at the time of the incremental backup. Using incrementally updated backups truly revolutionizes backup strategies, as you always have an updated image copy available, no matter when you took the first level 0 full backup. The incrementally updated backup command looks like this:

RMAN> BACKUP INCREMENTAL LEVEL 1 FOR RECOVER OF COPY
      WITH TAG 'incr-update' LEVEL 0 DATABASE;

This command will take the incremental level 1 backup and update the existing level 0 full backup— in effect, updating the previous level 0 backup to the current day's level 0 backup.

You can run the script shown in Listing 15-7 to set up an incrementally updated backup.

Listing 15-7:Performing Incrementally Updated Backups Using RMAN

RMAN> RUN {
      RECOVER COPY OF DATABASE WITH TAG 'incr_update';
      BACKUP INCREMENTAL LEVEL 1 FOR RECOVER OF COPY WITH TAG 'incr_update'
      DATABASE;
      }

In this script, the RECOVER COPY command will make RMAN apply any incremental level 1 backups to a set of datafile copies with the same tag. TheBACKUP command will create a level 1 incremental backup. However, the very first time the script runs, if there isn't already a level 0 backup, the command creates a level 0 backup as a starting point for the incremental backup strategy.

This is what happens when you execute the script:

  • On the first day, the BACKUP command will create a level 0 backup, since there isn't one already.

  • On the second day, the BACKUP command creates a level 1 incremental backup.

  • On the third day, and every day forward, the RECOVER COPY command will apply the level 1 backups to the level 0 backup, thus updating it continuously.

Using the script in Listing 15-7 will make it unnecessary for you to apply multiple incremental backups to the initial level 0 backup. Each day, as the incremental backup (level 1) of that day is applied to the level 0 backup, the level 0 backup becomes a full level 0 backup of that day. You don't need another full database backup. If you need to perform a recovery, you use the latest level 0 backup, which is the updated product of all incremental level 1 backups since the first level 0 backup, and then apply the archivelogs to it.

Fast Incremental Backups

During incremental backups, Oracle must scan the entire datafile. This ensures unnecessarily long incremental backup times.

The change-tracking file, which was new in Oracle Database 10g, is used to track the physical location of all database block changes. RMAN reads this file to discover which data blocks it has to read and copy. RMAN therefore avoids reading entire datafiles, and backup times will be dramatically reduced.

The change-tracking writer (CTWR) background process, another feature that was new in Oracle Database 10g, writes the block-change information to the change-tracking file.

Enabling Block-Change Tracking

If you want to track block changes, you must explicitly enable the feature, as shown here:

SQL> ALTER DATABASE
  2  ENABLE BLOCK CHANGE TRACKING
  3  USING FILE '/u01/oradata/finance/changetrack.log';
Database altered.
SQL>

To rename or relocate a change-tracking file, use theALTER DATABASE RENAME FILE statement (ensure that the database is in the mount stage before you rename the change-tracking file):

SQL> ALTER DATABASE RENAME FILE
     '/u01/app/oracle/finance/changetrack.log'
     TO
     '/u02/app/oracle/finance/changetrack.log';

Database altered.
SQL>

You can disable block-change tracking with the following statement:

SQL> ALTER DATABASE DISABLE BLOCK CHANGE TRACKING;
Database altered.
SQL>

Monitoring Block-Change Tracking

You can monitor block-change tracking with the V$BLOCK_CHANGE_TRACKING and V$BACKUP_DATAFILE views.

The V$BLOCK_CHANGE_TRACKING view shows the name, size, and status of the file, as shown in this example:

SQL> SELECT filename,status,bytes
  2  FROM v$block_change_tracking;

FILENAME                                            STATUS       BYTES
------------------------------------------------  ----------   ---------
/U01/APP/ORACLE/ORADATA/FINANCE/CHANGETRACK.LOG     ENABLED     11599872
SQL>

In the V$BACKUP_DATAFILE view, use the ratio between the BLOCKS_READ column and the DATAFILE_BLOCKS column to calculate the percentage of blocks Oracle is reading. If the BLOCKS_READ to DATAFILE_BLOCKS ratio is too high, you may have to take more frequent backups.

RMAN Compressed Backups

You can compress RMAN backups if you need to save space. The compression factor depends on the nature of the data in your datafiles. Oracle recommends that you use RMAN's built-in compression capability instead of an external compression utility. You must take care not to use both RMAN compression and an external compression utility together.

  Note 

You can't compress an image copy. You can compress a backup only if you are using backup sets.

Here is the RMAN command to compress a backup set:

RMAN> BACKUP AS COMPRESSED BACKUPSET DATABASE PLUS ARCHIVELOG;

The V$BACKUP_FILES view contains information about backup filenames and file sizes. In addition, it will tell you the compression status. Here's an example query showing how to do this:

SQL> SELECT fname, compressed, backup_type
     FROM v$backup_files;

Oracle Corporation believes that the RMAN binary compression technique will reduce the space used by the backup file by about 50 to 75 percent.

Archival Backups

Sometimes, you may want to make a backup for long-term storage. Your goal is not to someday use the backup for restoring the database, but to use the backup to restore data as it appeared at the time of the backup. You may also do this to satisfy regulatory requirements. These types of backups are calledarchival backups, or long-term backups, which you can make on tape devices and store offsite.

You can use the KEEP option with theBACKUP command to make long-term backups. The KEEP clause exempts a backup from the currently configured backup retention policy. TheKEEP clause instructs RMAN to back up the datafiles, the control file, and theSPFILE. RMAN also generates an archived redo log backup automatically to help recover the database to a consistent state. You can also change an existing backup into an archival backup by using theCHANGE command. You can specify that a backup be kept indefinitely by specifying theKEEP FOREVER clause or limit the retention time by specifying theKEEP UNITL TIME clause with the BACKUP orCHANGE command.

In the following example, I use an optional RESTORE POINT clause to indicate the SCN to which the database must be recovered in order for it to be consistent. This SCN is captured right after the datafile backups are made. RMAN will save this restore point as long as you keep the backup. Here are the steps to make a long-term archival backup.

Connect to the target database and a recovery catalog. You'll need the recovery catalog connection only if you specify theKEEP FOREVER clause, but not for the KEEP clause.

RUN
{
ALLOCATE CHANNEL ch1
DEVICE TYPE sbt
PARMS 'ENV=(OB_MEDIA_FAMILY=archival_backup)';
BACKUP DATABASE
  TAG quarterly
KEEP FOREVER
RESTORE POINT FY08Q2;
}

This code generates a backup of all the datafiles and the archived logs and also creates a restore point to which to restore the database. TheKEEP FOREVER clause will save the backup indefinitely. If you want to save a backup for a limited amount of time instead, you can do so by specifying theKEEP UNTIL TIME clause instead of theKEEP FOREVER clause, as shown here:

RUN
{
ALLOCATE CHANNEL ch1
DEVICE TYPE sbt
PARMS 'ENV=(OB_MEDIA_FAMILY=archival_backup)';
BACKUP DATABASE
  TAG quarterly
KEEP UNTIL TIME 'SYSDATE+365'
RESTORE  POINT FY08Q2;
}

This code will keep the backup for 365 days, after which the backup becomes obsolete and thus eligible for deletion.

Limiting the Size of RMAN Backups

You can limit the maximum size of an RMAN backup set by specifying theMAXSETSIZE parameter. An advantage to limiting a backup set to a certain size is that if the RMAN backup fails midway, you can use RMAN's restartable backup capability to backup only those files that weren't backed up before the failure. Here's an example showing how to limit a backup set's size:

RMAN> BACKUP DEVICE TYPE sbt
      MAXSETSIZE 250M
      ARCHIVELOG ALL;

You can specify the SECTION SIZE parameter to create a multisection backup, which is a backup set in which each backup piece contains blocks from one section of the file that's being backed up. You can use the SECTION SIZE parameter to perform a parallel backup of a very large datafile. Here's an example showing how to specify theSECTION SIZE parameter:

RMAN> BACKUP
      SECTION SIZE 250M
      TABLESPACE TEST;

Let's say the TEST tablespace is 1GB in size. You can set up four SBT channels, (parallel setting for the SBT device must be set to 4), and thus break up the backup into four parallel streams, thereby enhancing performance.

Encrypting RMAN Backups

You can configure two types of encryption for RMAN backups. First is transparent encryption, which you can configure with theCONFIGURE ENCRYPTION command. The second type of encryption is dual-mode or password-mode encryption. You can use theSET ENCRYPTION command to specify this type of encryption at the RMAN session level. I explain the procedures for setting up the two types of encryption in this section.

To configure transparent-mode encryption for backups, just use theCONFIGURE command as shown earlier in this chapter, Once you set up this persistent configuration parameter, all further backups will be in encrypted format.

Follow these steps to set up password-mode encryption:

  1. Connect to the target database through RMAN.

    RMAN> connect target /
    
    connected to target database: ORCL (DBID=1170903133)
    using target database control file instead of recovery catalog
    
    RMAN>
    
  2. Issue the SET ENCRYPTION ON IDENTIFIED BY PASSWORD ONLY command as shown here:

    RMAN> set encryption on identified by sammyy1 only;
    
    executing command: SET encryption
    
    RMAN>
    

The keyword ONLY tells RMAN to use password-enabled encryption even if you've configured transparent configuration with theCONFIGURE ENCRYPTION command. Any backups you make from now on will be encrypted.

  Tip 

Since wallet-based encryption doesn't involve the use of passwords, it's more secure than password-based encryption. Also, wallet-based encryption makes it easier to transport tablespaces.

Dual-mode encryption refers to data that's protected both by transparent encryption as well as with a password. In order to set up dual-mode encryption, you follow the same steps as you did for enabling password-based encryption, but you must leave out the ONLY keyword.

You must be aware that encrypting RMAN backups involves a CPU overhead. To overcome this, you can run an encrypted backup with multiple RMAN channels.

Monitoring and Verifying RMAN Jobs

You can monitor RMAN's backups using several important data dictionary views. The V$BACKUP_CORRUPTION and V$COPY_CORRUPTION views, for example, provide important information about corrupt blocks. (I'll discuss data block corruption in the "Database Corruption Detection" section later in this chapter.) You can use the V$RMAN_OUTPUT view to monitor a running RMAN job.

The V$RMAN_STATUS view shows the status of all completed jobs as well as commands, as shown here:

SQL> SELECT operation, status, start_time, end_time
     FROM v$rman_status;

OPERATION       STATUS            START_TIME        END_TIME
---------    ---------            ----------       ---------
LIST         COMPLETED             28-APR-08       28-APR-08
VALIDATE     COMPLETED             28-APR-08       28-APR-08
BACKUP          FAILED             28-APR-08       28-APR-08
BACKUP       COMPLETED             29-APR-08       29-APR-08
. . .
SQL>

You can estimate the backup's progress using the following query on the V$SESSION_LONGOPS view:

SQL> SELECT TO_CHAR(start_time,'DD-MON-YY HH24:MI') "Start of
     backup",Sofar, totalwork,
     elapsed_seconds/60 "ELAPSED TIME IN MINUTES",
     ROUND(sofar/totalwork*100,2) "Percentage Completed so far"
     FROM v$session_longops
     WHERE opname='prod1_dbbackup';

To ensure the backups made using RMAN are useful during a recovery, you can use theCROSSCHECK and VALIDATE commands, as described in the following sections.

Cross-Checking Backups Made with RMAN

RMAN provides the useful CROSSCHECK command to enable you to check that the backup sets and image copies listed in the recovery catalog actually exist in their specified locations and haven't been accidentally deleted or written over. In addition, the command verifies the headers and ensures that RMAN can read the files. TheCROSSCHECK command can thus test both the existence and the read-ability of the backups. Here's an example of the use of theCROSSCHECK command in RMAN:

RMAN> CROSSCHECK BACKUPSET 326;
allocated channel: ORA_DISK_1
. . .
channel ORA_DISK_4: sid=21 devtype=DISK
crosschecked backup piece: found to be 'AVAILABLE'
Crosschecked 1 objects
RMAN>

As you can see, RMAN has cross-checked the backup piece and found it to be available, which confirms that the backup files exist and are usable.

Using the RMAN VALIDATE Command

RMAN helps detect both physical and logical corruption. When RMAN encounters corrupt blocks of either kind, it logs the information to the control file and the recovery catalog. TheVALIDATE command helps you ensure that the backed-up files exist in the proper locations, and that they are readable and free from any logical and physical corruption. You simply issue the following command to test any particular backup set:

RMAN> VALIDATE BACKUPSET 9;

To test the entire database and archived log backup sets, you issue the following command:

RMAN> BACKUP VALIDATE DATABASE ARCHIVELOG ALL;

If the backup set does not exist, RMAN will let you know. If the command does not result in any errors, you can assume that the specified backup set exists and can be used in the recovery process.

The following command doesn't restore any datafiles; it merely validates that the contents of the backup sets are restorable.

RMAN> RUN {
      ALLOCATE CHANNEL d1 TYPE DISK;
      RESTORE DATABASE VALIDATE;
      {

The BACKUP_VALIDATE command checks for both logical and physical corruption in the datafiles and also determines whether RMAN can back up a datafile. By ensuring that RMAN can back up your datafiles, you know that your RMAN backups will be usable and valid.

You can use the BACKUP_VALIDATE command only at the dataset level, whereas you can use theVALIDATE command at the backup set, tablespace, datafile, or even data block level. You can also use the latter command to check the integrity of the flash recovery area. You can proactively run theVALIDATE command to check for missing datafiles or corrupt data blocks. RMAN logs any failures it finds during the validate command execution in the Automatic Diagnostic Repository (ADR). You can then use the Data Recovery Advisor to view the failures and to fix them. Although by default the VALIDATE command checks for physical data block corruption (interblock), you can specify theCHECK LOGICAL clause to include logical intrablock corruption checks.

Here's an example that shows how to execute the VALIDATE DATABASE command to check for data block corruption at the database level:

RMAN> VALIDATE DATABASE;

Starting validate at 01-APR-08
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=155 device type=DISK
. . .
channel ORA_DISK_1: validation complete, elapsed time: 00:17:07
List of Datafiles
=================
File Status Marked Corrupt Empty Blocks Blocks Examined High SCN
---- ------ -------------- ------------ --------------- ----------
1    OK     0              12542        72960           4351550
  File Name: C:\ORCL11\APP\ORACLE\ORADATA\ORCL11\SYSTEM01.DBF
  Block Type Blocks Failing Blocks Processed
  ---------- -------------- ----------------
  Data       0              48959
  Index      0              9143
  Other      0              2316
. . .
including current control file for validation
including current SPFILE in backup set
channel ORA_DISK_1: validation complete, elapsed time: 00:00:02
List of Control File and SPFILE
===============================
File Type    Status Blocks Failing Blocks Examined
------------ ------ -------------- ---------------
SPFILE       OK     0              2
Control File OK     0              594
Finished validate at 01-APR-08

RMAN>

You can parallelize the database validation by specifying theSECTION SIZE parameter, which divides a file into sections.

Using the RESTORE VALIDATE Command

You can use the RESTORE . . . VALIDATE command to check whether a certain object of interest is among RMAN's backup sets. Here's an example:

RMAN> RESTORE TABLESPACE users VALIDATE;
Starting restore at 29-JUN-05
. . .
Finished restore at 29-JUN-05
RMAN>

Using the RESTORE PREVIEW Command

In order to successfully restore a database or any part of it, RMAN should have access to all the necessary datafiles and archived redo log files. RMAN provides a handy PREVIEW option you can use with the RESTORE command, which lets you identify all the backup files necessary for a specific restore operation. You can then ensure that all the backups are available before issuing the RESTORE command.

Here are some examples of how you can use the RESTORE command with the PREVIEW option:

RMAN> RESTORE DATABASE PREVIEW;
RMAN> RESTORE TABLESPACE users PREVIEW;
RMAN> RESTORE DATAFILE 3 PREVIEW;

The RESTORE . . . PREVIEW command provides a detailed report of all backups that are necessary for that RESTORE command to succeed. If you want a summary report instead, use the PREVIEW SUMMARY option instead, as shown here:

RMAN> RESTORE DATABASE PREVIEW SUMMARY;
. . .
List of Backups
. . .
List of Archived Log Copies
. . .
Finished Restore at 29-JUN-05
RMAN>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章