четверг, 19 февраля 2009 г.

Postinstall scripts (Запуск дополнительных скриптов)

Запустить остановленный после обновления экземпляр основной БД

su – oracle

--Setup New Environment for 12c
. oraenv
ORACLE_SID = [+ASM] ? TESTDB

sqlplus / as sysdba
SQL> STARTUP
SQL> exit

ВАРИАНТ 1
cd $ORACLE_HOME/rdbms/admin
$ sqlplus / as sysdba
SQL> @utlu121s.sql
SQL> @catuppst.sql
SQL> @utlrp.sql
SQL> @utluiobj.sql
SQL> exit

ВАРИАНТ 2
cd $ORACLE_HOME/rdbms/admin
$ORACLE_HOME/perl/bin/perl catcon.pl -n 1 -e -b utlu121s -d '''.''' utlu121s.sql
$ORACLE_HOME/perl/bin/perl catcon.pl -n 1 -e -b catuppst -d '''.''' catuppst.sql
$ORACLE_HOME/perl/bin/perl catcon.pl -n 1 -e -b utlrp    -d '''.''' utlrp.sql
$ORACLE_HOME/perl/bin/perl catcon.pl -n 1 -e -b utluiobj -d '''.''' utluiobj.sql


Обязательно проверить целостность системного словаря БД после обновления на предмет
раннего обнаружения ошибок и их устранение если таковые есть.


Note 556610.1  Script to Collect DB Upgrade/Migrate Diagnostic Information (dbupgdiag.sql)

cd < location of the script >
$ sqlplus / as sysdba
sql> alter session set nls_language='American';
sql> @dbupgdiag.sql
sql> exit


При использовании GI необходимо обновить зарегистрированный объект БД в репозитории GI
с указанием нового ORACLE_HOME=/u01/app/oracle/product/12.1.0.2


--Setup New Environment for 12c
. oraenv
ORACLE_SID = [+ASM] ? TESTDB

srvctl upgrade database -d TESTDB_OMEGA -o /u01/app/oracle/product/12.1.0.2



Post Upgrade Steps (Дальнейшие действия)

Загрузить PSU Modified SQL Files into the Database

--Setup New Environment for 12c
. oraenv
ORACLE_SID = [+ASM] ? TESTDB

sqlplus /nolog
SQL> CONNECT / AS SYSDBA
SQL> shutdown immediate
SQL> startup UPGRADE
SQL> quit

cd $ORACLE_HOME/OPatch
./datapatch –verbose

sqlplus /nolog
SQL> CONNECT / AS SYSDBA
SQL> shutdown
SQL> startup
SQL> @?/rdbms/admin/utlrp

Логи работы утилиты ./datapatch –verbose


Проверить наличие установленных PSU патчей в системном словаре БД

Проверка ВАРИАНТ 1

col action format a18
col action_time format a28
col version_id format a18
col description format a64
select action,
       version||'.'||bundle_id as version_id,
       description,
       status,
       ACTION_TIME,
       patch_id
from DBA_REGISTRY_SQLPATCH;

Проверка ВАРИАНТ 2

SQL> set serverout on
SQL> exec dbms_qopatch.get_sqlpatch_status;


Установка параметров инициализации экземпляра

В случае если обновление прошло удачно и откат БД не планируется,
необходимо внести изменения в параметры инициализации экземпляра основной и резервной БД
и выполнить рестарт каждого экземпляра.

--Setup New Environment for 12c
. oraenv
ORACLE_SID = [+ASM] ? TESTDB

$ sqlplus / as sysdba

-- Setup new compatible mode
--- !!! alter system set compatible = "12.1.0.2.0" scope=spfile sid='*';

-- Switch off new adaptive features for run in compatible mode 11gR2
alter system set optimizer_adaptive_features=FALSE scope=both sid='*';

Устранить известные критические ошибки для версии 12cR1 (12.1.0.2)
-- Bug in 12.1.0.2 - Note 2034610.1
alter system set "_optimizer_aggr_groupby_elim"        = FALSE       scope=spfile sid='*';
alter system set "_optimizer_reduce_groupby_key"       = FALSE       scope=spfile sid='*';
-- Bug 18304693 - Note 18304693.8
alter system set "_optimizer_cost_based_transformation"='EXHAUSTIVE' scope=spfile sid='*';
alter system set "_optimizer_reuse_cost_annotations"   = FALSE       scope=spfile sid='*';
-- Bug 22173980
alter system set "_rowsets_enabled"                    = FALSE       scope=spfile sid='*';
-- Bug 19894622
alter system set "_optimizer_unnest_scalar_sq"         = FALSE       scope=spfile sid='*';
-- Bug in 12.1.0.2 Bug 21056506
alter system set "_use_single_log_writer"              = TRUE        scope=spfile sid='*';
-- Bug in 12.1.0.2 Bug 22529728 - Note 22529728.8
alter system set "_optimizer_gather_stats_on_load"     = FALSE       scope=both   sid='*';

SQL> SHUTDOWN IMMEDIATE
SQL> STARTUP
SQL> exit



Запуск Data Guard брокера
Запустить работу Data Guard брокера на основной и резервной БД

Setup new 12c Environment

--Setup New Environment for 12c
. oraenv
ORACLE_SID = [+ASM] ? TESTDB

# sqlplus / as sysdba
SQL> ALTER SYSTEM SET DG_BROKER_START=TRUE scope=both sid='*';

Разрешить конфигурацию Data Guard брокера на основной и резервной БД
Выполнять на узле с ролью PRIMARY

--Setup New Environment for 12c
. oraenv
ORACLE_SID = [+ASM] ? TESTDB

# dgmgrl

DGMGRL> connect sys/*******@PRIMARY_DATABASE

DGMGRL> SHOW CONFIGURATION;
DGMGRL> ENABLE CONFIGURATION;
DGMGRL> SHOW CONFIGURATION;

Configuration - TESTDB

  Protection Mode: MaxPerformance
  Members:
  TESTDB_OMEGA - Primary database
    TESTDB_STB_OMEGA  - Physical standby database (disabled)

Configuration Status:
SUCCESS

DGMGRL> ENABLE DATABASE 'TESTDB_STB_OMEGA';
DGMGRL> SHOW DATABASE 'TESTDB_STB_OMEGA';
DGMGRL> exit

На этом шаге основные процессы обновления боевой конфигурации БД на версию 12с завершены.




Настройка Multipath on Linux

Подготовить ASM disk для Grid Infrastructure


http://docs.oracle.com/database/121/LADBI/app_manual.htm#LADBI8065
http://docs.oracle.com/cd/E11882_01/install.112/e47689/pre_install.htm#LADBI1202

Note: Oracle recommends that you create a single whole-disk PRIMARY partition
on each disk to use.

$ fdisk /dev/sdc

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): n
Command action
   e   extended
   p   primary partition (1-4)
p < -  Enter p
Partition number (1-4): 1
First cylinder (1-16709, default 1): 1
Last cylinder, +cylinders or +size{K,M,G} (1-16709, default 16709): 16709

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.


$ ls -al /dev/sdc*
brw-rw---- 1 root disk 8, 32 Jan 29 16:40 /dev/sdc
brw-rw---- 1 root disk 8, 33 Jan 29 16:40 /dev/sdc1

$ partprobe -s /dev/sdc

/dev/sdc: msdos partitions 1


Настройка ПО Multipath



To work on VMware Fusion, set the following on the .vmx file;
without this entry, the scsi_id command does not return any values by default.
disk.EnableUUID = "TRUE"

# su - root
# yum install device-mapper-multipath
# mpathconf
# mpathconf --enable --user_friendly_names y --with_module y --with_multipathd y --with_chkconfig y

# multipath -ll


mpathc (36000c298b7d4d54eb873153d6254bcae) dm-4 VMware,Virtual disk
size=128G features='0' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
  `- 2:0:2:0 sdc 8:32 active ready running
mpathb (36000c2914cdc65086c8f424e512044ec) dm-3 VMware,Virtual disk
size=128G features='0' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
  `- 2:0:1:0 sdb 8:16 active ready running


Ignoring Local Disks when Generating Multipath Devices


/dev/sda is the internal disk
/dev/sdb is the internal disk


# su – root

# /lib/udev/scsi_id --whitelisted --device=/dev/sda
36000c291ecbd84c5b584072ef62c2b0b

#  /lib/udev/scsi_id --whitelisted --device=/dev/sdb
36000c2914cdc65086c8f424e512044ec

vi /etc/multipath.conf


blacklist {
  wwid 36000c291ecbd84c5b584072ef62c2b0b
  wwid 36000c2914cdc65086c8f424e512044ec
}

# service multipathd reload

Create Alias


# su - root
# /lib/udev/scsi_id --whitelisted --device=/dev/sdc

36000c298b7d4d54eb873153d6254bcae

# vi /etc/multipath.conf
multipaths {
multipath {
  wwid 36000c298b7d4d54eb873153d6254bcae
  alias DATA_disk01
  }
}

# service multipathd reload

# multipath –ll


DATA_disk01 (36000c298b7d4d54eb873153d6254bcae) dm-4 VMware,Virtual disk
size=128G features='0' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
  `- 2:0:2:0 sdc 8:32 active ready running

List config Multipath


# cat /etc/multipath.conf

defaults {
        user_friendly_names yes
        find_multipaths     yes
}

multipaths {
multipath {
  wwid 36000c298b7d4d54eb873153d6254bcae
  alias DATA_disk01
  }
}

blacklist {
  wwid 36000c291ecbd84c5b584072ef62c2b0b
  wwid 36000c2914cdc65086c8f424e512044ec
}


# ls -al /dev/mapper

total 0
drwxr-xr-x  2 root root     160 Jan 29 23:12 .
drwxr-xr-x 20 root root    4280 Jan 29 23:12 ..
crw-rw----  1 root root 10, 236 Jan 29 17:45 control
lrwxrwxrwx  1 root root       7 Jan 29 23:13 DATA_disk01 -> ../dm-4
lrwxrwxrwx  1 root root       7 Jan 29 23:13 DATA_disk01p1 -> ../dm-5 -> Наш ASM диск
lrwxrwxrwx  1 root root       7 Jan 29 17:45 orabinvg-orabinlv -> ../dm-2
lrwxrwxrwx  1 root root       7 Jan 29 17:45 vg_dc1oel67-lv_root -> ../dm-0
lrwxrwxrwx  1 root root       7 Jan 29 17:45 vg_dc1oel67-lv_swap -> ../dm-1


Установка ASMLib


http://www.oracle.com/technetwork/server-storage/linux/asmlib/ol6-1709075.html
http://docs.oracle.com/database/121/LADBI/app_manual.htm#LADBI8065


$ su - root
$ yum install kmod-oracleasm
$ yum install oracleasm-support
$ download http://download.oracle.com/otn_software/asmlib/oracleasmlib-2.0.12-1.el6.x86_64.rpm
$ rpm -Uhv /tmp/oracleasmlib-2.0.12-1.el6.x86_64.rpm


-- Проверка

$ rpm -qa | grep asm
oracleasmlib-2.0.12-1.el6.x86_64
oracleasm-support-2.1.8-1.el6.x86_64
kmod-oracleasm-2.0.8-6.el6_7.x86_64


Configure ASMLib using the following command

$ /usr/sbin/oracleasm configure -i

Default user to own the driver interface []:        oracle
Default group to own the driver interface []:       oinstall
Start Oracle ASM library driver on boot (y/n) [n]:  y
Scan for Oracle ASM disks on boot (y/n) [y]:        y
Writing Oracle ASM library driver configuration:    done

Within /etc/sysconfig/oracleasm,
set the ORACLEASM_SCANORDER and ORACLEASM_SCANEXCLUDE parameters as follows:

# ORACLEASM_SCANORDER: Matching patterns to order disk scanning
ORACLEASM_SCANORDER="dm"

# ORACLEASM_SCANEXCLUDE: Matching patterns to exclude disks from scan
ORACLEASM_SCANEXCLUDE="sd"


Run the following oracleasm command to ensure that oracleasm is enabled.


# /etc/init.d/oracleasm enable

Writing Oracle ASM library driver configuration: done
Initializing the Oracle ASMLib driver:                     [  OK  ]
Scanning the system for Oracle ASMLib disks:               [  OK  ]

# /usr/sbin/oracleasm scandisks
# /usr/sbin/oracleasm listdisks


Создать ASM Disk


--Run the following oracleasm command to create and label all Oracle related volumes
--as an ASM disk. The example below creates an ASM disk labeled DATA_DISK01_P1.

# su - root
# /usr/sbin/oracleasm createdisk DATA_DISK01_P1 /dev/mapper/DATA_disk01p1

# /usr/sbin/oracleasm querydisk /dev/mapper/DATA_disk01p1

Device "/dev/mapper/DATA_disk01p1" is marked an ASM disk with the label "DATA_DISK01_P1"

# ls -al /dev/oracleasm/disks/*
brw-rw---- 1 oracle oinstall 252, 3 Jan 29 23:59 /dev/oracleasm/disks/DATA_DISK01_P1


How to map device name to ASMLIB disk (Doc ID 1098682.1)

su - root

#!/bin/bash
for asmlibdisk in `ls /dev/oracleasm/disks/*`
  do
    echo "ASMLIB disk name: $asmlibdisk"
    asmdisk=`kfed read $asmlibdisk | grep dskname | tr -s ' '| cut -f2 -d' '`
    echo "ASM disk name: $asmdisk"
    majorminor=`ls -l $asmlibdisk | tr -s ' ' | cut -f5,6 -d' '`
    device=`ls -l /dev | tr -s ' ' | grep -w "$majorminor" | cut -f10 -d' '`
    echo "Device path: /dev/$device"
done



ASMLIB disk name: /dev/oracleasm/disks/DATA_DISK01_P1
ASM disk name: DATA_DISK01_P1
Device path: /dev/dm-4





NetBackup robtest

mt -f /dev/rmt/0cbn status
mt -f /dev/rmt/1cbn status
mt -f /dev/rmt/2cbn status

/usr/openv/volmgr/bin/robtest

s d
unload d2
m d2 s2
m s2 d2
q




BACKUP DATABASE:


Level 0 incremental = Full backup

$ export ORACLE_SID=TESTDB
$ rman catalog rman/pwd@catdb target /

RMAN> run {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=MONTHLY';

BACKUP INCREMENTAL LEVEL=0
FORMAT 'orabk_%d_%T_%s_%p_%t'
DATABASE
INCLUDE CURRENT CONTROLFILE;

sql "alter system archive log current";

BACKUP
FORMAT 'orabk_arc_%d_%T_%s_%p_%t'
ARCHIVELOG ALL;

CROSSCHECK BACKUP;
DELETE NOPROMPT EXPIRED BACKUP;
CROSSCHECK ARCHIVELOG ALL;
DELETE NOPROMPT EXPIRED ARCHIVELOG ALL;
DELETE NOPROMPT ARCHIVELOG ALL BACKED UP 1 TIMES TO DEVICE TYPE sbt COMPLETED BEFORE 'sysdate-7';

RELEASE CHANNEL ch00;
}

RMAN>
RMAN> list backup;
RMAN> exit

$

Вы также можете запустить команду netbackup bplist, чтобы отобразить все файлы,
забэкапленные с определенного хоста
(Тип = 4 - Файлы типа Oracle)

$ bplist -C omega01 -t 4 -l -R  /




Incremental Cumulative Backup:

SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

BACKUP INCREMENTAL LEVEL=1 CUMULATIVE
FORMAT 'orabkIC_%d_%T_%s_%p_%t'
DATABASE
INCLUDE CURRENT CONTROLFILE;



Backup Archive Logs:
RMAN> run {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

sql "alter system archive log current";
BACKUP
FORMAT 'orabk_arc_%d_%T_%s_%p_%t'
ARCHIVELOG ALL;

RELEASE CHANNEL ch00;
}



RESTORE DATABASE:




Restore TESTDB database on TESTDB01 instance
- Shutdown database on TESTDB instance (no files are removed)
- Startup TESTDB database instance in Mount state
- Restore TESTDB database on TESTDB01 instance using RMAN

As we have control file intact, redologs intact, we have a clean recovery and the database is open as normal post recovery;
Поскольку у нас доступны и не повреждены:

-текущий controlfile 
-online redologs

то у нас будет полное восстановление

$ sqlplus / as sysdba

SQL> shutdown immediate;
SQL> startup mount;
SQL> exit

$

$ export $ORACLE_SID=TESTDB01

$ rman catalog rman/pwd@catdb target /

RMAN>

RMAN> run {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=MONTHLY';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

RESTORE DATABASE;
RECOVER DATABASE;

RELEASE CHANNEL ch00;
RELEASE CHANNEL ch01;
}


RMAN> ALTER DATABASE OPEN;

database opened

RMAN> list incarnation of database TESTDB;
RMAN> exit
$





Restore TESTDB database on TESTDB01 instance point-in-time using using SCN

For this restore, delete control file, redologs and all datafiles:
- Shutdown TESTDB01 database instance
- Remove all files(datafiles/redologs/controlfiles)
- Startup TESTDB01 database instance in nomount state
- Restore TESTDB database on TESTDB01 instance using RMAN
-- List the DB files to remove

SQL> shutdown immediate;
SQL> exit

$

-- Remove all DB files

$
$ rm /u02/oracle/TESTDB01/data/temp01.dbf
$ rm /u02/oracle/TESTDB01/data/users01.dbf
$ rm /u02/oracle/TESTDB01/data/undotbs01.dbf
$ rm /u02/oracle/TESTDB01/data/sysaux01.dbf
$ rm /u02/oracle/TESTDB01/data/system01.dbf
$ rm /u02/oracle/TESTDB01/data/ora_control1
$ rm /u02/oracle/TESTDB01/data/ora_control2
$ rm /u02/oracle/TESTDB01/data/redoA01.log
$ rm /u02/oracle/TESTDB01/data/redoB01.log
$ rm /u02/oracle/TESTDB01/data/redoA02.log
$ rm /u02/oracle/TESTDB01/data/redoB02.log
$

-- Startup Database instance in NOMOUNT state

$
$ export ORACLE_SID=TESTDB01

$ sqlplus / as sysdba
SQL> startup nomount ;
SQL>
SQL> exit
$

-- List archivelogs to grab SCN #

$ rman catalog rman/pwd@catdb target /

RMAN> list backup of archivelog all;

Archived Logs

in backup set 1842

Thrd Seq     Low SCN    Low Time  Next SCN   Next Time
---- ------- ---------- --------- ---------- ---------
1    5       230871     11-APR-17 262878     11-APR-17
1    6       262878     11-APR-17 262897     11-APR-17
1    7       262897     11-APR-17 264000     11-APR-17
1    8       264000     11-APR-17 264019     11-APR-17
1    9       264019     11-APR-17 264636     11-APR-17
1    10      264636     11-APR-17 264655     11-APR-17

RMAN>
RMAN>


Perfrom Point-in-time recovery

RMAN>

RMAN> run {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=MONTHLY';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

# Set the RESTOR SCN
SET UNTIL SCN 264655;

# Set the RESTOR time 6:30pm
# SET UNTIL TIME "to_date('2017-04-11:18:30:00', 'yyyy-mm-dd:hh24:mi:ss')";


RESTORE CONTROLFILE;
ALTER DATABASE MOUNT;

RESTORE DATABASE;
RECOVER DATABASE;

RELEASE CHANNEL ch00;
RELEASE CHANNEL ch01;
}

RMAN>
RMAN> ALTER DATABASE OPEN RESETLOGS;

RMAN>
RMAN> list incarnation of database TESTDB;

RMAN> exit




Restore ORADB database using RMAN to different Unix Host

Для восстановления базы данных из Netbackup на другой хост нам необходимо следующее:

ALTERNATE CLIENT SETUP:

NetBackup позволяет восстановить базу данных для клиента, отличного от того, который первоначально выполнял резервное копирование.
Это называется called alternate client restore.

Администратор Netbackup должен включить эту функцию, добавив client names в файл на Netbackup Master Server:
/usr/openv/netbackup/db/altnames/< client_name >

Например, резервное копирование производится с хоста omega01 и для его восстановления на хост omega02, тогда нужно

1) создать файл /usr/openv/netbackup/db/altnames/omega02
2) добавить запись omega01 в этот файл

RMAN CLIENT PARAMETER: при запуске RMAN вам нужно будет использовать NB_ORA_CLIENT = omega01 в команде SEND.

Это позволяет главному серверу Netbackup искать резервные копии на соответствующем носителе, где он был скопирован.


$ rman catalog rman/pwd@catdb
RMAN>
RMAN> LIST DB_UNIQUE_NAME ALL;

List of Databases
DB Key  DB Name  DB ID            Database Role    Db_unique_name
------- ------- ----------------- ---------------  ------------------
1702    TESTDB   2565746290       PRIMARY          TESTDB

RMAN>
RMAN> exit
$

-- Create dummy pfile with DB_NAME = TESTDB

$
$ cat $ORACLE_HOME/dbs/initTESTDB.ora
*.audit_file_dest='/u01/apps/oracle/admin/adump'
*.db_block_size=8192
*.db_name='TESTDB'
*.diagnostic_dest='/u01/apps/oracle'
*.memory_max_target=1000M
$


-- Start instance in NOMOUNT state

$
$ export ORACLE_SID=TESTDB
$



$ sqlplus / as sysdba
SQL> startup nomount;
SQL> exit
$

-- Launch RMAN and restore SPFILE for ORADB database

$
$ rman catalog rman/pwd@catdb target /

RMAN>
RMAN> run {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_CLIENT=omega01,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=MONTHLY';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_CLIENT=omega01,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

# Run Restore command
RESTORE SPFILE TO '/u01/apps/oracle/product/11.2.0/dbhome_1/dbs/testdb01_restored_spfile.ora' ;
}

RMAN> exit
$

-- verify the spfile is > 0 bytes

$ ls -ltr /u01/apps/oracle/product/11.2.0/dbhome_1/dbs/testdb01_restored_spfile.ora
-rw-r-----   1 oracle    dba        3584 Apr 17 22:42 /u01/apps/oracle/product/11.2.0/dbhome_1/dbs/testdb01_restored_spfile.ora
$


-- Create PFILE from RESTORED SPFILE

$ strings $ORACLE_HOME/dbs/testdb01_restored_spfile.ora

Note, values for audit_file_dest,
      control_files,
      diagnostic_dest,
      log_archive_dest
      db_name,
      service_name,
      instance_name

1) Create the initial directory structure with values noted above.
2) Set the ORACLE_SID to the instance_name noted above
3) Create init${ORACLE_SID}.ora pfile with the values from testdb01_restored_spfile.ora


-- Start oracle instance in NOMOUNT state with new pfile

$
$ export ORACLE_SID=TESTDB01

$ sqlplus / as sysdba
SQL> startup nomount ;
SQL> exit
$

-- Restore Control file now

$
$ rman catalog rman/pwd@catdb target /


RMAN> list backup ;


Handle: orabkIC_ORADB_20130411_5_1_812488789

   Media: XXX
  SPFILE Included: Modification time: 17-APR-17
  SPFILE db_unique_name: OTESTDB


RMAN>
RMAN>
RMAN>

RMAN> run {
# Restoring control file (NB_ORA_CLIENT is set to original host)

ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_CLIENT=omega01,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=MONTHLY';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_CLIENT=omega01,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

restore controlfile from  'orabkIC_ORADB_20130411_5_1_812488789';

}

RMAN> exit
$


$
$ mkdir -p /u02/oracle/DB01/data/
$ mkdir -p /u05/oracle/DB01/data/
$ mkdir -p /u03/oracle/DB01/data/
$ mkdir -p /u03/oracle/DB01/data/arch/
$
$

-- From archivelog backup, get the latest SCN number
-- RESTORE DATABASE until SCN Nubmer


$
$ rman catalog rman/pwd@catdb target /

RMAN>
RMAN> list backup of archivelog all ;

Archived Logs

 in backup set 1842
  Thrd Seq     Low SCN    Low Time  Next SCN   Next Time
  ---- ------- ---------- --------- ---------- ---------
  1    5       230871     11-APR-17 262878     11-APR-17
  1    6       262878     11-APR-17 262897     11-APR-17
  1    7       262897     11-APR-17 264000     11-APR-17
  1    8       264000     11-APR-17 264019     11-APR-17
  1    9       264019     11-APR-17 264636     11-APR-17
  1    10      264636     11-APR-17 264655     11-APR-17



RMAN>
RMAN>
RMAN>
RMAN> run {

ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_CLIENT=omega01,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=MONTHLY';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE'
SEND 'NB_ORA_SERV=nbsrv,NB_ORA_CLIENT=omega01,NB_ORA_POLICY=POL_ORADBBackup,NB_ORA_SCHED=DAILY';

# Set the RESTOR SCN
SET UNTIL SCN 264655;
# Restore Database
RESTORE DATABASE;
RECOVER DATABASE;

# Release Channel
RELEASE CHANNEL ch00;
RELEASE CHANNEL ch01;
}

RMAN>
RMAN> ALTER DATABASE OPEN RESETLOGS;
RMAN>
RMAN> exit
$
$



















OAS

На промышленном сервере:

15 01 * * 0 ${HOME}/bin/stop_app_all.sh > /dev/null 2>&1
30 02 * * 0 ${HOME}/bin/start_app_all.sh > /dev/null 2>&1
50 01 * * 1-5 ${HOME}/bin/pkg/ias_cold_backup/_run.sh > /dev/null 2>&1


$ more start_app_all.sh
#!/bin/bash

. ${HOME}/bin/.env
emctl start iasconsole
${ORACLE_HOME}/opmn/bin/opmnctl startall
###${ORACLE_HOME}/dcm/bin/dcmctl start -co myapp -a myapp
###${ORACLE_HOME}/dcm/bin/dcmctl start -co myapptest -a myapptest


$ more stop_app_all.sh
#!/bin/bash
. ${HOME}/bin/.env

###${ORACLE_HOME}/dcm/bin/dcmctl stop -co myapptest -a myapptest
${ORACLE_HOME}/dcm/bin/dcmctl stop -co myapp -a myapp

${ORACLE_HOME}/opmn/bin/opmnctl shutdown

emctl stop iasconsole


$ more backup_app_all.sh
#!/bin/bash
. ${HOME}/bin/.env
###${HOME}/bin/stop_app_all.sh
cd ${ORACLE_BASE}/
mv ${ORACLE_BASE}/backups/full/ora_j2ee.tar ${ORACLE_BASE}/backups/full/old_ora_j2ee.tar
tar -cvf ${ORACLE_BASE}/backups/full/ora_j2ee.tar ora_j2ee
###${HOME}/bin/start_app_all.sh


$ more copy_app_all.sh
#!/bin/bash
. ${HOME}/bin/.env
scp ${ORACLE_BASE}/backups/full/ora_j2ee.tar remote-serv:${ORACLE_BASE}/backups/full/ora_j2ee.tar


$cd ${HOME}/bin/pkg/ias_cold_backup/

$ more body.sh

echo "`date +%T` Begin IAS Cold Backup"
${HOME}/bin/pkg/ias_cold_backup/stop_app_all.sh
cd ${ORACLE_BASE}/
mv /oradata/backups/full/ora_j2ee.tar /oradata/backups/full/old_ora_j2ee.tar
tar -cf /oradata/backups/full/ora_j2ee.tar ora_j2ee
${HOME}/bin/pkg/ias_cold_backup/start_app_all.sh
scp /oradata/backups/full/ora_j2ee.tar remote-srv:/oradata/backups/full/ora_j2ee.tar
echo "`date +%T` End IAS Cold Backup"


На резервном сервере:

00 05 * * 1-5 ${HOME}/bin/pkg/refresh_ias/_run.sh > /dev/null 2>> /tmp/crontab_oracle.err


$cd ${HOME}/bin/pkg/refresh_ias/
$more body.sh

echo "`date +%T` Begin IAS Refresh"
${HOME}/bin/pkg/refresh_ias/stop_app_all.sh
sleep 30
ps -fu oracle
echo '******************************************************'
cd ${ORACLE_BASE}

if [ -d "ora_j2ee" ] ; then
rm -rf ora_j2ee
echo "test"
fi
#exit
tar -xf /opt/oracle/backups/full/ora_j2ee.tar

rm /opt/oracle/ora_j2ee/j2ee/myapp/config/myapp-data-sources.xml
cp /home/oracle/datasources/myapp-data-sources.xml /opt/oracle/ora_j2ee/j2ee/myapp/config/

${ORACLE_HOME}/chgip/scripts/chgiphost.sh -mid -silent -oldhost srv-app1.msk.sun.com -newhost srv-app2.msk.sun.com -oldip 192.168.22.1 -newip 192.168.22.2
mv ${ORACLE_HOME}/opmn/conf/opmn.xml ${ORACLE_HOME}/opmn/conf/old_opmn.xml
cat ${ORACLE_HOME}/opmn/conf/old_opmn.xml |sed '1,$s/app1/app2/' >${ORACLE_HOME}/opmn/conf/opmn.xml
mv ${ORACLE_HOME}/sysman/emd/targets.xml ${ORACLE_HOME}/sysman/emd/old_targets.xml
cat ${ORACLE_HOME}/sysman/emd/old_targets.xml |sed '1,$s/app1/app2/' >${ORACLE_HOME}/sysman/emd/targets.xml
mv ${ORACLE_HOME}/config/ias.properties ${ORACLE_HOME}/config/old_ias.properties
cat ${ORACLE_HOME}/config/old_ias.properties |sed '1,$s/app1/app2/' >${ORACLE_HOME}/config/ias.properties

ps -fu oracle

rm /opt/oracle/ora_j2ee/Apache/Apache/htdocs/index.html
cp /home/oracle/datasources/index.html /opt/oracle/ora_j2ee/Apache/Apache/htdocs/
cp /home/oracle/datasources/logo3.gif /opt/oracle/ora_j2ee/j2ee/myapp/applications/myapp/ecl/images/

sudo /bin/cp -p /home/oracle/datasources/.apachectl /opt/oracle/ora_j2ee/Apache/Apache/bin/.apachectl

sleep 5
${HOME}/bin/pkg/refresh_ias/start_app_all.sh

echo "`date +%T` End IAS Refresh"


NetBackup Media manager Device Configuration

На платформе Solaris:


cd /dev/rmt/
rm *
devfsadm -Cv


cd /usr/openv/volmgr/bin/driver
/usr/openv/volmgr/bin/sg.build all -mt 15 -ml 2
rm /kernel/drv/sg.conf
/usr/openv/volmgr/bin/driver/sg.install
/usr/openv/volmgr/bin/sgscan all

Запускаем
Configure Storage Device




Netbackup Status Code

Recommeddation action command

bperror -S -r


0 the requested operation was successfully completed
1 the requested operation was partially successful
2 none of the requested files were backed up
3 valid archive image produced, but no files deleted due to non-fatal problems
4 archive file removal failed
5 the restore failed to recover the requested files
6 the backup failed to back up the requested files
7 the archive failed to back up the requested files
8 unable to determine the status of rbak
9 an extension package is needed, but was not installed
10 allocation failed
11 system call failed
12 file open failed
13 file read failed
14 file write failed
15 file close failed
16 unimplemented feature
17 pipe open failed
18 pipe close failed
19 getservbyname failed
20 invalid command parameter
21 socket open failed
22 socket close failed
23 socket read failed
24 socket write failed
25 cannot connect on socket
26 client/server handshaking failed
27 child process killed by signal
28 failed trying to fork a process
29 failed trying to exec a command
30 could not get passwd information
31 could not set user id for process
32 could not set group id for process
33 failed while trying to send mail
34 failed waiting for child process
35 cannot make required directory
36 failed trying to allocate memory
37 operation requested by an invalid server
38 could not get group information
39 client name mismatch
40 network connection broken
41 network connection timed out
42 network read failed
43 unexpected message received
44 network write failed
45 request attempted on a non reserved port
46 server not allowed access
47 host is unreachable
48 client hostname could not be found
49 client did not start
50 client process aborted
51 timed out waiting for database information
52 timed out waiting for media manager to mount volume
53 backup restore manager failed to read the file list
54 timed out connecting to client
55 permission denied by client during rcmd
56 client’s network is unreachable
57 client connection refused
58 can’t connect to client
59 access to the client was not allowed
60 client cannot read the mount table
61 wbak was killed
62 wbak exited abnormally
63 process was killed by a signal
64 timed out waiting for the client backup to start
65 client timed out waiting for the continue message from the media manager
66 client backup failed to receive the CONTINUE BACKUP message
67 client backup failed to read the file list
68 client timed out waiting for the file list
69 invalid filelist specification
70 an entry in the filelist expanded to too many characters
71 none of the files in the file list exist
72 the client type is incorrect in the configuration database
73 bpstart_notify failed
74 client timed out waiting for bpstart_notify to complete
75 client timed out waiting for bpend_notify to complete
76 client timed out reading file
77 execution of the specified system command returned a nonzero status
78 afs/dfs command failed
79 unimplemented error code 79
80 Media Manager device daemon (ltid) is not active
81 Media Manager volume daemon (vmd) is not active
82 media manager killed by signal
83 media open error
84 media write error
85 media read error
86 media position error
87 media close error
88 Auspex SP/Backup failure
89 fatal error in Unitree file system
90 media manager received no data for backup image
91 fatal NB media database error
92 media manager detected image that was not in tar format
93 media manager found wrong tape in drive
94 cannot position to correct image
95 requested media id was not found in NB media database and/or MM volume database
96 unable to allocate new media for backup, storage unit has none available
97 requested media id is in use, cannot process request
98 error requesting media (tpreq)
99 NDMP backup failure
100 system error occurred while processing user command
101 failed opening mail pipe
102 failed closing mail pipe
103 error occurred during initialization, check configuration file
104 invalid file pathname
105 file pathname exceeds the maximum length allowed
106 invalid file pathname found, cannot process request
107 too many arguments specified
108 invalid date format specified
109 invalid date specified
110 Cannot find the NetBackup configuration information
111 No entry was found in the server list
112 no files specified in the file list
113 unimplemented error code 113
114 unimplemented error code 114
115 unimplemented error code 115
116 unimplemented error code 116
117 unimplemented error code 117
118 unimplemented error code 118
119 unimplemented error code 119
120 cannot find configuration database record for requested NB database backup
121 no media is defined for the requested NB database backup
122 specified device path does not exist
123 specified disk path is not a directory
124 NB database backup failed, a path was not found or is inaccessable
125 another NB database backup is already in progress
126 NB database backup header is too large, too many paths specified
127 specified media or path does not contain a valid NB database backup header
128 unimplemented error code 128
129 unimplemented error code 129
130 system error occurred
131 client is not validated to use the server
132 user is not validated to use the server from this client
133 invalid request
134 unable to process request because the server resources are busy
135 client is not validated to perform the requested operation
136 unimplemented error code 136
137 unimplemented error code 137
138 unimplemented error code 138
139 unimplemented error code 139
140 user id was not superuser
141 file path specified is not absolute
142 file does not exist
143 invalid command protocol
144 invalid command usage
145 daemon is already running
146 cannot get a bound socket
147 required or specified copy was not found
148 daemon fork failed
149 master server request failed
150 termination requested by administrator
151 Backup Exec operation failed
152 required value not set
153 server is not the master server
154 storage unit characteristics mismatched to request
155 unused b
156 unused f
157 unused d
158 failed accessing daemon lock file
159 licensed use has been exceeded
160 authentication failed
161 Evaluation software has expired. See www.veritas.com for ordering information
162 unimplemented error code 162
163 unimplemented error code 163
164 unable to mount media because its in a DOWN drive or misplaced
165 NB image database contains no image fragments for requested backup id/copy number
166 backups are not allowed to span media
167 cannot find requested volume pool in Media Manager volume database
168 cannot overwrite media, data on it is protected
169 media id is either expired or will exceed maximum mounts
170 unimplemented error code 170
171 media id must be 6 or less characters
172 cannot read media header, may not be NetBackup media or is corrupted
173 cannot read backup header, media may be corrupted
174 media manager - system error occurred
175 not all requested files were restored
176 cannot perform specified media import operation
177 could not deassign media due to Media Manager error
178 media id is not in NetBackup volume pool
179 density is incorrect for the media id
180 tar was successful
181 tar received an invalid argument
182 tar received an invalid file name
183 tar received an invalid archive
184 tar had an unexpected error
185 tar did not find all the files to be restored
186 tar received no data
187 unimplemented error code 187
188 unimplemented error code 188
189 the server is not allowed to write to the client’s filesystems
190 found no images or media matching the selection criteria
191 no images were successfully processed
192 unimplemented error code 192
193 unimplemented error code 193
194 the maximum number of jobs per client is set to 0
195 client backup was not attempted
196 client backup was not attempted because backup window closed
197 the specified schedule does not exist in the specified class
198 no active classes contain schedules of the requested type for this client
199 operation not allowed during this time period
200 scheduler found no backups due to run
201 handshaking failed with server backup restore manager
202 timed out connecting to server backup restore manager
203 server backup restore manager’s network is unreachable
204 connection refused by server backup restore manager
205 cannot connect to server backup restore manager
206 access to server backup restore manager denied
207 error obtaining date of last backup for client
208 failed reading user directed filelist
209 error creating or getting message queue
210 error receiving information on message queue
211 scheduler child killed by signal
212 error sending information on message queue
213 no storage units available for use
214 regular bpsched is already running
215 failed reading global config database information
216 failed reading retention database information
217 failed reading storage unit database information
218 failed reading class database information
219 the required storage unit is unavailable
220 database system error
221 continue
222 done
223 an invalid entry was encountered
224 there was a conflicting specification
225 text exceeded allowed length
226 the entity already exists
227 no entity was found
228 unable to process request
229 events out of sequence - image inconsistency
230 the specified class does not exist in the configuration database
231 schedule windows overlap
232 a protocol error has occurred
233 premature eof encountered
234 communication interrupted
235 inadequate buffer space
236 the specified client does not exist in an active class within the configuration database
237 the specified schedule does not exist in an active class in the configuration database
238 the database contains conflicting or erroneous entries
239 the specified client does not exist in the specified class
240 no schedules of the correct type exist in this class
241 the specified schedule is the wrong type for this request
242 operation would cause an illegal duplication
243 the client is not in the configuration
244 main bpsched is already running
245 the specified class is not of the correct client type
246 no active classes in the configuration database are of the correct client type
247 the specified class is not active
248 there are no active classes in the configuration database
249 the file list is incomplete
250 the image was not created with TIR information
251 the tir information is zero length
252 unused TIR error 2
253 unused TIR error 1
254 server name not found in the bp.conf file
255 unimplemented error code 255



NetBackup и Rman

 

The NetBackup provides sample scripts at following location:

UNIX/Linux: /usr/openv/netbackup/ext/db_ext/oracle/samples/rman
Windows: install_path\NetBackup\dbext\oracle\samples\rman

- UNIX and Linux: hot_database_backup.sh
- Windows: hot_database_backup.cmd
RUN {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE';
Add the send parameter line
BACKUP

# backup all archive logs
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE';
Add the send parameter line
BACKUP

ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
Add the send parameter line
BACKUP
    # recommended format
    FORMAT 'cntrl_%s_%p_%t'
    CURRENT CONTROLFILE;
RELEASE CHANNEL ch00;
}

SEND 'NB_ORA_SERV= master server name, NB_ORA_CLIENT= oracle server name, NB_ORA_POLICY= backup policy name';

In case of Unix Platform, send parameters values (i.e Master server name, Client name & Policy name) is case sensitive. We must use the same case in backup policy.

 

RMAN-03009: failure of allocate command on ch00 channel at 06/18/2014 08:36:11
ORA-19554: error allocating device, device type: SBT_TAPE, device name:
ORA-27211: Failed to load Media Management Library
Additional information: 2

If the Library is not linked, run following command on Netbackup client.

Browse to "installpath/netbackup/bin" or "/usr/openv/netbackup/bin"

[root@dbclient1 bin]# ./oracle_link
Wed Jun 18 04:52:26 EDT 2014
All Oracle instances should be shutdown before running this script.

Please log into the Unix system as the Oracle owner for running this script

Do you want to continue? (y/n) [n] oracle_link

NOTE : We can ignore the above prompt and continue by selecting 'Yes'.



$ more backupSPOD_tape.sh

ORACLE_HOME=/u01/app/oradb/product/11.2.0.2/dbhome_1
export ORACLE_HOME
ORACLE_SID=spod
export ORACLE_SID
rman target / catalog 'rman/passwd@catdb' << EOF

########################################## Clear configuration ###########################################
CONFIGURE RETENTION POLICY CLEAR;
CONFIGURE BACKUP OPTIMIZATION CLEAR;
CONFIGURE DEFAULT DEVICE TYPE CLEAR;
CONFIGURE CONTROLFILE AUTOBACKUP CLEAR;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK CLEAR;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE SBT CLEAR;
CONFIGURE DEVICE TYPE DISK CLEAR;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK CLEAR;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE SBT CLEAR;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK CLEAR;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE SBT CLEAR;
CONFIGURE CHANNEL DEVICE TYPE DISK CLEAR;
CONFIGURE CHANNEL DEVICE TYPE SBT CLEAR;
CONFIGURE MAXSETSIZE CLEAR;
CONFIGURE SNAPSHOT CONTROLFILE NAME CLEAR;
########################################### Configure #####################################################

CONFIGURE DEFAULT DEVICE TYPE TO sbt;
CONFIGURE CONTROLFILE AUTOBACKUP ON;
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE SBT_TAPE TO '%F';
CONFIGURE DEVICE TYPE 'SBT_TAPE' PARALLELISM 1 BACKUP TYPE TO BACKUPSET;
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE 'SBT_TAPE' TO 1;
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE 'SBT_TAPE' TO 1;
CONFIGURE SNAPSHOT CONTROLFILE NAME TO '/u01/app/oradb/product/11.2.0.2/dbhome_1/dbs/snapcf_orcl.f';
CONFIGURE RETENTION POLICY TO REDUNDANCY 2;

########################################### BACKUP SCRIPT #################################################

DELETE NOPROMPT obsolete redundancy 2;
CROSSCHECK BACKUP;
CROSSCHECK archivelog all;
CROSSCHECK COPY;
CROSSCHECK backup of database;
CROSSCHECK backup of controlfile;

RUN {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
SEND 'NB_ORA_SERV=nbsrv-1,NB_ORA_CLIENT=kr400-1,NB_ORA_POLICY=KR400_Oracle';


sql 'alter system switch logfile';
sql 'alter system archive log current';
backup database plus archivelog delete input;
sql 'alter system switch logfile';
sql 'alter system archive log current';

delete noprompt obsolete;
RELEASE CHANNEL ch00;
}
EOF
exit 0
$


$ more makeSPODT2_tape.sh
#!/bin/bash

# Create temporary password file, must have same password as primary
rm /u01/app/oradb/product/11.2.0.2/dbhome_1/dbs/orapwspodt2
orapwd file=/u01/app/oradb/product/11.2.0.2/dbhome_1/dbs/orapwspodt2 password=oracle

# Create temporary parameter file
echo "db_name=spodt2" > /u01/app/oradb/product/11.2.0.2/dbhome_1/dbs/initspodt2.ora

export ORACLE_SID=spodt2
export ORACLE_HOME=/u01/app/oradb/product/11.2.0.2/dbhome_1

# Start up the auxiliary instance nomount
sqlplus '/ as sysdba' << EOF
shutdown immediate;
STARTUP PFILE='/u01/app/oradb/product/11.2.0.2/dbhome_1/dbs/initspodt2.ora' NOMOUNT;
EOF

rman << EOF

connect catalog rman/passwd@catdb;
connect auxiliary sys/oracle@spodt2;

run {
ALLOCATE AUXILIARY CHANNEL c1 DEVICE TYPE 'SBT_TAPE';
SEND 'NB_ORA_SERV=nbsrv-1,NB_ORA_CLIENT=kr400-1,NB_ORA_POLICY=KR400_Oracle';


duplicate database 'spod' to 'spodt2'
spfile
SET CONTROL_FILES '/u03/app/oradb/oradata/spodt2/control1/control01.ctl','/u03/app/oradb/oradata/spodt2/control2/control02.ctl'
SET LOG_FILE_NAME_CONVERT '/u02/app/oradb/oradata/spod/','/u02/app/oradb/oradata/spodt2/'
SET DB_FILE_NAME_CONVERT '/u03/app/oradb/oradata/spod/','/u03/app/oradb/oradata/spodt2/'
;
}

EOF
exit 0

$


hot_database_backup.sh

#!/bin/sh
# ---------------------------------------------------------------------------
# Replace variables below, with the real data.
# ---------------------------------------------------------------------------
ORACLE_HOME=/u01/app/oracle/product/12.1.0.2
ORACLE_SID=TESTDB
ORACLE_USER=oracle
RMAN=rman
TARGET='target /'
RCVCAT='nocatalog'
BACKUP_HOME=${ORACLE_HOME}/admin/backup
NB_ORA_SCRIPTS=${BACKUP_HOME}/cmd
NBADMIN_MAIL='root'
LSM_SAVECTL="/usr/sbin/savefs -l full $BACKUP_HOME/ctl"
LSM_SAVEBOOT="/usr/sbin/savegrp -O"

# Function for find error in logfile. Usage: find_errors file err1 [ err2 ... ]
find_errors()
{
    FILE=$1
    while [ "$#" -gt 1 ]
    do
        if [ -f "$FILE" ] && grep "$2:" "$FILE" >/dev/null
        then
            echo "Checking for $2 ... found."
            return 0
        else
            echo "Checking for $2 ... not found."
        fi
        shift
    done
    return 1
}

OUTF=${BACKUP_HOME}/logs/`basename ${0} .sh`.`date +"%m%d%H%M%S"`
{ # output block

echo "`date` ----------------Beginning of Script------------"
echo "Script name: $0"

echo 
echo   "RMAN: $RMAN"
echo   "ORACLE_SID: $ORACLE_SID"
echo   "ORACLE_USER: $ORACLE_USER"
echo   "ORACLE_HOME: $ORACLE_HOME"
echo   "BACKUP_HOME: $BACKUP_HOME"
echo   "NB_ORA_SCRIPTS: $NB_ORA_SCRIPTS"
echo   "NBADMIN_MAIL: $NBADMIN_MAIL"
echo   "LSM_SAVECTL: $LSM_SAVECTL"
echo

case "$1" in
    *logs*) # backup archivelogs
    echo "archivelog backup requested"
    BACKUP_TYPE="archivelogs"
    CMDFILE=${NB_ORA_SCRIPTS}/archivelog_backup.rcv
    ;;

    *incr*)
    echo "hot database differential incremental backup requested"
    BACKUP_TYPE="differentional level 1"
    CMDFILE=${NB_ORA_SCRIPTS}/hot_database_backup_level1_differential.rcv
    ;;

    *cum*)
    echo "hot database cumulative incremental backup requested"
    BACKUP_TYPE="cumulative level 1"
    CMDFILE=${NB_ORA_SCRIPTS}/hot_database_backup_level1_cumulative.rcv
    ;;

    *full*)
    echo "hot database backup requested (incremental level 0)"
    BACKUP_TYPE="full"
    CMDFILE=${NB_ORA_SCRIPTS}/hot_database_backup_level0.rcv
    ;;

    *)
        echo "Usage: `basename $0` full|incr|cum|logs"
        exit 1
    ;;
esac

echo
echo "% ${ORACLE_HOME}/bin/$RMAN $TARGET $RCVCAT cmdfile '$CMDFILE'"
echo

su - $ORACLE_USER -c "
ORACLE_SID=$ORACLE_SID
export ORACLE_SID
${ORACLE_HOME}/bin/$RMAN $TARGET $RCVCAT cmdfile "$CMDFILE"
"
RETURN_STATUS=$?

if [ "$RETURN_STATUS" != "0" ]; then
    echo
    echo "Check for ignored errors:"
    if find_errors $OUTF "RMAN-20242"
    then
        RETURN_STATUS=0
    fi
    echo "Check done."
fi

echo
echo "% $LSM_SAVECTL"
echo

[ -n "$LSM_SAVECTL" ] && $LSM_SAVECTL

echo
echo "% $LSM_SAVEBOOT"
echo

[ -n "$LSM_SAVEBOOT" ] && $LSM_SAVEBOOT

echo
echo "`date` ----------------End of Script------------------"
echo
echo "exit $RETURN_STATUS"

if [ "$RETURN_STATUS" != "0" -o "$BACKUP_TYPE" = "full" ]; then
    [ "$RETURN_STATUS" != "0" ] && STAT="FAILED" || STAT="SUCCESSED"
    cat $OUTF | \
        mailx -s "RMAN(`hostname`)  sid: $ORACLE_SID  backup: $BACKUP_TYPE  status: $STAT" $NBADMIN_MAIL
fi

if [ "$RETURN_STATUS" = "0" ]; then
    rm -f $OUTF
fi

exit $RETURN_STATUS

} >> $OUTF 2>&1





archivelog_backup.rcv


run {
    allocate channel t1 type 'SBT_TAPE';
    allocate channel t2 type 'SBT_TAPE';

    backup
        filesperset 5
        format 'DB.LOGS.%d.s%s.p%p'
        (archivelog all delete input);

    release channel t1;
    release channel t2;

    allocate channel d1 type disk;
    copy
        current controlfile
            to '?/admin/backup/ctl/controlfile.bk';
    release channel d1;
}
 

---------------------------------------------------------------------------------------------

run {
    allocate channel t1 type 'SBT_TAPE';

    backup
        filesperset 5
        format 'DB.LOGS.%d.s%s.p%p'
                (archivelog from logseq = 2913 like '/arch/testdb_%' delete input);

    release channel t1;

    allocate channel d1 type disk;
    copy
        current controlfile
            to '?/admin/backup/ctl/controlfile.bk';
    release channel d1;
}



--------------------------------------------------------------------------------------------

run {
    allocate channel d1 type disk format '/backup/db/DB.LOGS.%d.s%s.p%p';
    allocate channel d2 type disk format '/backup/db/DB.LOGS.%d.s%s.p%p';
    set limit channel d1 kbytes 1048576;
    set limit channel d2 kbytes 1048576;

    backup
        (archivelog all delete input);

   copy
        current controlfile
            to '/oracle/admin/backup/ctl/controlfile.bk';
 release channel d1;
 release channel d2;
}




hot_database_backup_level1_differential.rcv

run
{
    allocate channel t1 type 'SBT_TAPE';
    allocate channel t2 type 'SBT_TAPE';

    backup incremental level 1
    skip offline
    skip readonly
    skip inaccessible
    filesperset 1
        database format 'DB.INC1.%d.s%s.p%p'
        include current controlfile;
   
    sql 'alter system archive log current';

    backup
        filesperset 5
        format 'DB.LOGS.%d.s%s.p%p'
        (archivelog all delete input);

    release channel t1;
    release channel t2;

    allocate channel d1 type disk;
    copy
        current controlfile
            to '?/admin/backup/ctl/controlfile.bk';
    release channel d1;
}



hot_database_backup_level1_cumulative.rcv

run
{
    allocate channel t1 type 'SBT_TAPE';
    allocate channel t2 type 'SBT_TAPE';

    backup incremental level 1
    cumulative
    skip offline
    skip readonly
    skip inaccessible
    filesperset 1
        database format 'DB.CUM1.%d.s%s.p%p'
        include current controlfile;

    sql 'alter system archive log current';

    backup
        filesperset 5
        format 'DB.LOGS.%d.s%s.p%p'
        (archivelog all delete input);
   
    release channel t1;
    release channel t2;

    allocate channel d1 type disk;
    copy
        current controlfile
            to '?/admin/backup/ctl/controlfile.bk';
    release channel d1;
}
 




hot_database_backup_level0.rcv


run
{
    allocate channel t1 type 'SBT_TAPE';
    allocate channel t2 type 'SBT_TAPE';

    backup incremental level 0
    filesperset 4
        database format 'DB.INC0.%d.s%s.p%p'
        include current controlfile;

    sql 'alter system archive log current';

    backup
        filesperset 5
        format 'DB.LOGS.%d.s%s.p%p'
        (archivelog all delete input);
   
    release channel t1;
    release channel t2;

    allocate channel d1 type disk;
    copy
        current controlfile
            to '?/admin/backup/ctl/controlfile.bk';
    release channel d1;
}
 

-------------------------------------------------------------------------------------------

run
{
    allocate channel t1 type 'SBT_TAPE';

    backup incremental level 0
    filesperset 5
        database format 'DB.INC0.%d.s%s.p%p'
        include current controlfile;

    sql 'alter system archive log current';

    backup
        filesperset 20
        format 'DB.LOGS.%d.s%s.p%p'
        (archivelog like '%arch/%' delete input);
   
    release channel t1;

    allocate channel d1 type disk;
    copy
        current controlfile
            to '?/admin/backup/ctl/controlfile.bk';
    release channel d1;
}

-------------------------------------------------------------------------------------------

run
{
    allocate channel d1 type disk format '/backup/db/DB.INC0.%d.s%s.p%p';
    allocate channel d2 type disk format '/backup/db/DB.INC0.%d.s%s.p%p';
    set limit channel d1 kbytes 1048576;
    set limit channel d2 kbytes 1048576;

    backup incremental level 0
    filesperset 2
    database
        include current controlfile;

    sql 'alter system archive log current';
    release channel d1;
    release channel d2;

    allocate channel d1 type disk format '/backup/db/DB.LOGS.%d.s%s.p%p';
    allocate channel d2 type disk format '/backup/db/DB.LOGS.%d.s%s.p%p';
    set limit channel d1 kbytes 1048576;
    set limit channel d2 kbytes 1048576;
    backup
        (archivelog all delete input);
   
    copy
        current controlfile
            to '/oracle/admin/backup/ctl/controlfile.bk';
    release channel d1;
    release channel d2;
}




restore_arch.rcv

run {
     allocate channel t1 type 'SBT_TAPE';
     set archivelog destination to '/tmp/';

     restore archivelog from logseq 200 until logseq 202;
     release channel t1;
}



change.rcv

run {
    change archivelog all validate;
}




[oracle@omega01]$ tail -10000 hot_database_backup.sh

#!/bin/bash
. `dirname ${0}`\/mutex.sh

CUSER=`id |cut -d"(" -f2 | cut -d ")" -f1`

export ORACLE_USER=oracle

export ORAUSER_HOME_DIR=`getent passwd ora|awk -F: '{print $6;}'`

export ORACLE_SID_ENV=`echo $NB_ORA_POLICY|awk -F_ '{print $3;}'|tr "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"`

. $ORAUSER_HOME_DIR/.oraenv $ORACLE_SID_ENV
export TARGET_CONNECT_STR=/
export CATALOG_CONNECT_STRING=rman/pwd@catdb
export RMAN=$ORACLE_HOME/bin/rman
export NB_ORA_CLIENT=$NB_ORA_CLIENT

# ---------------------------------------------------------------------------
# Put output in .out. Change as desired.
# Note: output directory requires write permission.
# ---------------------------------------------------------------------------

RMAN_LOG_FILE=${0}.out
echo >> $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== started on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE
chown ${ORACLE_USER}:dba $RMAN_LOG_FILE

# ---------------------------------------------------------------------------
# Print out the value of the variables set by bphdb.
# ---------------------------------------------------------------------------

echo >> $RMAN_LOG_FILE
echo   "RMAN: $RMAN" >> $RMAN_LOG_FILE
echo   "ORACLE_SID: $ORACLE_SID" >> $RMAN_LOG_FILE
echo   "ORACLE_USER: $ORACLE_USER" >> $RMAN_LOG_FILE
echo   "ORACLE_HOME: $ORACLE_HOME" >> $RMAN_LOG_FILE


echo  >> $RMAN_LOG_FILE
echo   "NB_ORA_FULL: $NB_ORA_FULL" >> $RMAN_LOG_FILE
echo   "NB_ORA_INCR: $NB_ORA_INCR" >> $RMAN_LOG_FILE
echo   "NB_ORA_CINC: $NB_ORA_CINC" >> $RMAN_LOG_FILE
echo   "NB_ORA_SERV: $NB_ORA_SERV" >> $RMAN_LOG_FILE
echo   "NB_ORA_POLICY: $NB_ORA_POLICY" >> $RMAN_LOG_FILE
echo   "NB_ORA_CLIENT: $NB_ORA_CLIENT" >> $RMAN_LOG_FILE

# ---------------------------------------------------------------------------
# NOTE: This script assumes that the database is properly opened. If desired,
# this would be the place to verify that.
# ---------------------------------------------------------------------------

echo >> $RMAN_LOG_FILE
# ---------------------------------------------------------------------------
# If this script is executed from a NetBackup schedule, NetBackup
# sets an NB_ORA environment variable based on the schedule type.
# The NB_ORA variable is then used to dynamically set BACKUP_TYPE
# For example, when:
#     schedule type is                BACKUP_TYPE is
#     ----------------                --------------
# Automatic Full                     INCREMENTAL LEVEL=0
# Automatic Differential Incremental INCREMENTAL LEVEL=1
# Automatic Cumulative Incremental   INCREMENTAL LEVEL=1 CUMULATIVE
#
# For user initiated backups, BACKUP_TYPE defaults to incremental
# level 0 (full).  To change the default for a user initiated
# backup to incremental or incremental cumulative, uncomment
# one of the following two lines.
# BACKUP_TYPE="INCREMENTAL LEVEL=1"
# BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"
#
# Note that we use incremental level 0 to specify full backups.
# That is because, although they are identical in content, only
# the incremental level 0 backup can have incremental backups of
# level > 0 applied to it.
# ---------------------------------------------------------------------------

if [ "$NB_ORA_FULL" = "1" ]
then
        echo "Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"

elif [ "$NB_ORA_INCR" = "1" ]
then
        echo "Differential incremental backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1"

elif [ "$NB_ORA_CINC" = "1" ]
then
        echo "Cumulative incremental backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"

elif [ "$BACKUP_TYPE" = "" ]
then
        echo "Default - Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"
fi


CMD_STR="

. $ORAUSER_HOME_DIR/.oraenv $ORACLE_SID_ENV
export ORACLE_HOME=$ORACLE_HOME
export ORACLE_SID=$ORACLE_SID
export NB_ORA_CLIENT=$NB_ORA_CLIENT

$RMAN target $TARGET_CONNECT_STR catalog $CATALOG_CONNECT_STRING msglog $RMAN_LOG_FILE append << EOF
#$RMAN target $TARGET_CONNECT_STR nocatalog  msglog $RMAN_LOG_FILE append << EOF
RUN {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch02 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch03 TYPE 'SBT_TAPE';

SEND 'NB_ORA_POLICY=$NB_ORA_POLICY, NB_ORA_SERV=$NB_ORA_SERV';

BACKUP
    $BACKUP_TYPE
#    SKIP INACCESSIBLE
#   TAG hot_db_bk_level0
    FILESPERSET 1
    # recommended format
    FORMAT 'bk_%s_%p_%t'
    DATABASE;
RELEASE CHANNEL ch00;
RELEASE CHANNEL ch01;
RELEASE CHANNEL ch02;
RELEASE CHANNEL ch03;
}

#ALLOCATE CHANNEL FOR MAINTENANCE TYPE 'SBT_TAPE';
#DELETE FORCE NOPROMPT OBSOLETE;
#DELETE FORCE NOPROMPT EXPIRED BACKUP;
#RELEASE CHANNEL;
exit;
EOF
"
# Initiate the command string
mutex_enter /tmp/oracle-${ORACLE_SID}
chown $ORACLE_USER:dba /tmp/oracle-${ORACLE_SID}
if [ "$CUSER" = "root" ]
then
    su - $ORACLE_USER -c "$CMD_STR" >> $RMAN_LOG_FILE
    RSTAT=$?
else
    /bin/sh -c "$CMD_STR" >> $RMAN_LOG_FILE
    RSTAT=$?
fi
mutex_exit /tmp/oracle-${ORACLE_SID}
# ---------------------------------------------------------------------------
# Log the completion of this script.
# ---------------------------------------------------------------------------

if [ "$RSTAT" = "0" ]
then
    LOGMSG="ended successfully"
else
    LOGMSG="ended in error"
fi

echo >> $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== $LOGMSG on `date` ======================================================================= >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE
exit $RSTAT




[oracle@omega01]$ tail -10000 archivelog_backup.sh


#!/bin/bash
. `dirname ${0}`\/mutex.sh

CUSER=`id |cut -d"(" -f2 | cut -d ")" -f1`

export ORACLE_USER=oracle

export ORAUSER_HOME_DIR=`getent passwd ora|awk -F: '{print $6;}'`

export ORACLE_SID_ENV=`echo $NB_ORA_POLICY|awk -F_ '{print $3;}'|tr "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"`

# ---------------------------------------------------------------------------
export NLS_DATE_FORMAT='DD-Mon-YYYY HH24:MI:SS'
# ---------------------------------------------------------------------------

. $ORAUSER_HOME_DIR/.oraenv $ORACLE_SID_ENV
export TARGET_CONNECT_STR=/
export CATALOG_CONNECT_STRING=rman/pwd@catdb
export RMAN=$ORACLE_HOME/bin/rman
export NB_ORA_CLIENT=$NB_ORA_CLIENT

# ---------------------------------------------------------------------------
# Put output in .out. Change as desired.
# Note: output directory requires write permission.
# ---------------------------------------------------------------------------

RMAN_LOG_FILE=${0}.out
echo >> $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== started on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE
chown ${ORACLE_USER}:dba $RMAN_LOG_FILE

# ---------------------------------------------------------------------------
# Print out the value of the variables set by bphdb.
# ---------------------------------------------------------------------------

echo >> $RMAN_LOG_FILE
echo   "RMAN: $RMAN" >> $RMAN_LOG_FILE
echo   "ORACLE_SID: $ORACLE_SID" >> $RMAN_LOG_FILE
echo   "ORACLE_USER: $ORACLE_USER" >> $RMAN_LOG_FILE
echo   "ORACLE_HOME: $ORACLE_HOME" >> $RMAN_LOG_FILE


echo  >> $RMAN_LOG_FILE
echo   "NB_ORA_FULL: $NB_ORA_FULL" >> $RMAN_LOG_FILE
echo   "NB_ORA_INCR: $NB_ORA_INCR" >> $RMAN_LOG_FILE
echo   "NB_ORA_CINC: $NB_ORA_CINC" >> $RMAN_LOG_FILE
echo   "NB_ORA_SERV: $NB_ORA_SERV" >> $RMAN_LOG_FILE
echo   "NB_ORA_POLICY: $NB_ORA_POLICY" >> $RMAN_LOG_FILE
echo   "NB_ORA_CLIENT: $NB_ORA_CLIENT" >> $RMAN_LOG_FILE

# ---------------------------------------------------------------------------
# NOTE: This script assumes that the database is properly opened. If desired,
# this would be the place to verify that.
# ---------------------------------------------------------------------------

echo >> $RMAN_LOG_FILE
# ---------------------------------------------------------------------------
# If this script is executed from a NetBackup schedule, NetBackup
# sets an NB_ORA environment variable based on the schedule type.
# The NB_ORA variable is then used to dynamically set BACKUP_TYPE
# For example, when:
#     schedule type is                BACKUP_TYPE is
#     ----------------                --------------
# Automatic Full                     INCREMENTAL LEVEL=0
# Automatic Differential Incremental INCREMENTAL LEVEL=1
# Automatic Cumulative Incremental   INCREMENTAL LEVEL=1 CUMULATIVE
#
# For user initiated backups, BACKUP_TYPE defaults to incremental
# level 0 (full).  To change the default for a user initiated
# backup to incremental or incremental cumulative, uncomment
# one of the following two lines.
# BACKUP_TYPE="INCREMENTAL LEVEL=1"
# BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"
#
# Note that we use incremental level 0 to specify full backups.
# That is because, although they are identical in content, only
# the incremental level 0 backup can have incremental backups of
# level > 0 applied to it.
# ---------------------------------------------------------------------------

if [ "$NB_ORA_FULL" = "1" ]
then
        echo "Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"

elif [ "$NB_ORA_INCR" = "1" ]
then
        echo "Differential incremental backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1"

elif [ "$NB_ORA_CINC" = "1" ]
then
        echo "Cumulative incremental backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"

elif [ "$BACKUP_TYPE" = "" ]
then
        echo "Default - Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"
fi


CMD_STR="

. $ORAUSER_HOME_DIR/.oraenv $ORACLE_SID_ENV
export ORACLE_HOME=$ORACLE_HOME
export ORACLE_SID=$ORACLE_SID
export NB_ORA_CLIENT=$NB_ORA_CLIENT

$RMAN target $TARGET_CONNECT_STR catalog $CATALOG_CONNECT_STRING msglog $RMAN_LOG_FILE append << EOF
#$RMAN target $TARGET_CONNECT_STR nocatalog  msglog $RMAN_LOG_FILE append << EOF
RUN {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE';
SEND 'NB_ORA_POLICY=$NB_ORA_POLICY, NB_ORA_SERV=$NB_ORA_SERV';
BACKUP
filesperset 10
FORMAT 'al_%s_%p_%t'
ARCHIVELOG ALL DELETE INPUT;
RELEASE CHANNEL ch00;
RELEASE CHANNEL ch01;
}
exit;
EOF
"
# Initiate the command string
mutex_enter /tmp/oracle-${ORACLE_SID}-arch
chown $ORACLE_USER:dba /tmp/oracle-${ORACLE_SID}-arch
if [ "$CUSER" = "root" ]
then
    su - $ORACLE_USER -c "$CMD_STR" >> $RMAN_LOG_FILE
    RSTAT=$?
else
    /usr/bin/sh -c "$CMD_STR" >> $RMAN_LOG_FILE
    RSTAT=$?
fi
mutex_exit /tmp/oracle-${ORACLE_SID}-arch
# ---------------------------------------------------------------------------
# Log the completion of this script.
# ---------------------------------------------------------------------------

if [ "$RSTAT" = "0" ]
then
    LOGMSG="ended successfully"
else
    LOGMSG="ended in error"
fi

echo >> $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== $LOGMSG on `date` ======================================================================= >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE
exit $RSTAT



[oracle@omega01]$ tail -10000 mutex.sh

function mutex_message {
        echo `date "+%b %e %T"` "$$" "$*"
}

function mutex_enter {
        mutex_message "Trying to acquire the mutex $1"
        mkdir $1 > /dev/null 2>&1
        if [ $? -eq 0 ]; then
                mutex_message "Acquired mutex $1"
                return
        fi
        mutex_message "Entering spinlock"
        while [ -d $1 ]; do
                sleep 10
        done
        mutex_message "Exited spinlock"
        mutex_enter $1
}

function mutex_exit {
        rmdir $1
        mutex_message "Released mutex $1"
}





[oracle@omega01]$ tail -10000 /usr/openv/netbackup/ext/db_ext/oracle/database_backup_TESTDB1.sh

#!/bin/bash

#----------------------------------------------------
export ORACLE_HOME="/u01/app/oracle/product/12.1.0.2"
export ORACLE_SID=TESTDB1
export ORACLE_USER=oracle
export HOSTNAME=omega01
export NB_ORA_CL_CLIENT=omega01-priv
export NB_ORA_POLICY="ORA-TESTDB"
export NB_ORA_SERV=nbsrv
export PWD="/usr/openv/netbackup/ext/db_ext/oracle"
#----------------------------------------------------
export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
export NLS_DATE_FORMAT=YYYY-MM-DD:HH24:MI:SS
export LIBPATH=$ORACLE_HOME/lib:/usr/lib
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/lib
#----------------------------------------------------

if [ "$NB_ORA_FULL" = "1" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-full_backup.out"

elif [ "$NB_ORA_INCR" = "1" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-incremental_backup.out"

elif [ "$NB_ORA_CINC" = "1" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-archivelogs_backup.out"

elif [ "$BACKUP_TYPE" = "" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-full_backup.out"
fi


TARGET_CONNECT_STR=/
RMAN=$ORACLE_HOME/bin/rman
CUSER=`id |cut -d"(" -f2 | cut -d ")" -f1`


echo >> $RMAN_LOG_FILE
chmod 666 $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== started on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE

echo >> $RMAN_LOG_FILE
echo   "RMAN: $RMAN" >> $RMAN_LOG_FILE
echo   "ORACLE_SID: $ORACLE_SID" >> $RMAN_LOG_FILE
echo   "ORACLE_USER: $ORACLE_USER" >> $RMAN_LOG_FILE
echo   "ORACLE_HOME: $ORACLE_HOME" >> $RMAN_LOG_FILE
echo   "NB_ORA_POLICY: $NB_ORA_POLICY" >> $RMAN_LOG_FILE
echo  >> $RMAN_LOG_FILE
echo   "NB_ORA_FULL: $NB_ORA_FULL" >> $RMAN_LOG_FILE
echo   "NB_ORA_INCR: $NB_ORA_INCR" >> $RMAN_LOG_FILE
echo   "NB_ORA_CINC: $NB_ORA_CINC" >> $RMAN_LOG_FILE
echo   "NB_ORA_SERV: $NB_ORA_SERV" >> $RMAN_LOG_FILE
echo   "NB_ORA_POLICY: $NB_ORA_POLICY" >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE

function mutex_message {
        echo `date "+%b %e %T"` "$$" "$*"
}

function mutex_enter {
        mutex_message "Trying to acquire the mutex $1"
        mkdir $1 > /dev/null 2>&1
        if [ $? -eq 0 ]; then
                mutex_message "Acquired mutex $1"
                return
        fi
        mutex_message "Entering spinlock"
        while [ -d $1 ]; do
                sleep 10
        done
        mutex_message "Exited spinlock"
        mutex_enter $1
}

function mutex_exit {
        rmdir $1
        mutex_message "Released mutex $1"
}

if [ "$NB_ORA_FULL" = "1" ]
then
        echo "Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"
        BACKUP_NAME="INC_0"
        export SCHED_NAME="Default-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=1

elif [ "$NB_ORA_INCR" = "1" ]
then
        echo "Differential incremental backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1"
        BACKUP_NAME="INC_1"
        export SCHED_NAME="Default-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=1

elif [ "$NB_ORA_CINC" = "1" ]
then
        echo "Archivelog only backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"
        BACKUP_NAME="INC_1_CUMUL"
        export SCHED_NAME="Archivelog-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=0

elif [ "$BACKUP_TYPE" = "" ]
then
        echo "Default - Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"
        BACKUP_NAME="INC_0"
        export SCHED_NAME="Default-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=1
fi

############################
# Backup name for TAG
############################
BACKUP_NAME=${BACKUP_NAME}_`date +'%Y%m%d_%H%M%S'`
echo "BACKUP_NAME=$BACKUP_NAME"
echo >> $RMAN_LOG_FILE
echo "BACKUP_NAME=$BACKUP_NAME"  >> $RMAN_LOG_FILE


export SEND="'NB_ORA_POLICY=$NB_ORA_POLICY, NB_ORA_SCHED=$SCHED_NAME, NB_ORA_CLIENT=$NB_ORA_CL_CLIENT'"

if [ "$BACKUP_DATABASE" = "1" ] ; then
        BACKUP_DATABASE_TEXT="BACKUP
    $BACKUP_TYPE
    SKIP INACCESSIBLE NOEXCLUDE
    TAG '${BACKUP_NAME}'
    FILESPERSET 25
    FORMAT 'db_%s_%p_%t'
    DATABASE;"
else
        BACKUP_DATABASE_TEXT=""
fi

####################################
# Backup database text
####################################
echo "BACKUP_DATABASE_TEXT={$BACKUP_DATABASE_TEXT}"
echo >> $RMAN_LOG_FILE
echo "BACKUP_DATABASE_TEXT={$BACKUP_DATABASE_TEXT}"  >> $RMAN_LOG_FILE


CMD_STR="
ORACLE_HOME=$ORACLE_HOME
export ORACLE_HOME
ORACLE_SID=$ORACLE_SID
export ORACLE_SID
$RMAN target $TARGET_CONNECT_STR catalog=/@catdb msglog $RMAN_LOG_FILE append << EOF
RUN {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch02 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch03 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch04 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch05 TYPE 'SBT_TAPE';
SEND $SEND;

# backup database
$BACKUP_DATABASE_TEXT

# backup all archive logs
BACKUP
   filesperset 20
   FORMAT 'log_%s_%p_%t'
   ARCHIVELOG ALL DELETE ALL INPUT;

# backup control file
BACKUP
    FORMAT 'cntrl_%s_%p_%t'
    CURRENT CONTROLFILE;
}

###################################################
# Maintenance
###################################################
ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE 'SBT_TAPE' PARMS 'ENV=(NB_ORA_CLIENT=$NB_ORA_CL_CLIENT,NB_ORA_SERV=$NB_ORA_SERV)';
crosscheck archivelog all;
crosscheck backup of database;
crosscheck backup of archivelog all;
crosscheck backup of spfile;
crosscheck backup of controlfile;
crosscheck copy;
delete noprompt expired backup;
delete noprompt expired archivelog all;
delete noprompt expired copy;
delete noprompt obsolete;
restore database preview summary;

###################################################
# Maintenance Report
###################################################
ALLOCATE CHANNEL FOR MAINTENANCE DEVICE TYPE 'SBT_TAPE' PARMS 'ENV=(NB_ORA_CLIENT=$NB_ORA_CL_CLIENT,NB_ORA_SERV=$NB_ORA_SERV)';
LIST DB_UNIQUE_NAME OF DATABASE;
LIST BACKUP OF DATABASE SUMMARY;
LIST BACKUP OF DATABASE SUMMARY FOR DB_UNIQUE_NAME 'TESTDB_OMEGA01';
REPORT UNRECOVERABLE;


EOF
"
# Initiate the command string

mutex_enter /tmp/oracle-${ORACLE_SID}

if [ "$CUSER" = "root" ]
then
#echo su - $ORACLE_USER -c "$CMD_STR" >> $RMAN_LOG_FILE
su - $ORACLE_USER -c "$CMD_STR" >> $RMAN_LOG_FILE
        RSTAT=$?
else
#echo /bin/sh -c "$CMD_STR" >> $RMAN_LOG_FILE
/bin/sh -c "$CMD_STR" >> $RMAN_LOG_FILE
        RSTAT=$?
fi

mutex_exit /tmp/oracle-${ORACLE_SID}

# ---------------------------------------------------------------------------
# Log the completion of this script.
# ---------------------------------------------------------------------------

if [ "$RSTAT" = "0" ]
then
        LOGMSG="ended successfully"
else
    LOGMSG="ended in error"
fi

echo >> $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== $LOGMSG on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE

exit $RSTAT




[oracle@omega01]$ tail -10000 /usr/openv/netbackup/ext/db_ext/oracle/archivelog_backup_TESTDB1.sh

#!/bin/bash

#----------------------------------------------------
export ORACLE_HOME="/u01/app/oracle/product/12.1.0.2"
export ORACLE_SID=TESTDB1
export ORACLE_USER=oracle
export HOSTNAME=omega01
export NB_ORA_CL_CLIENT=omega01-priv
export NB_ORA_POLICY="ORA-TESTDB"
export NB_ORA_SERV=nbsrv
export PWD="/usr/openv/netbackup/ext/db_ext/oracle"
#----------------------------------------------------
export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
export NLS_DATE_FORMAT=YYYY-MM-DD:HH24:MI:SS
export LIBPATH=$ORACLE_HOME/lib:/usr/lib
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/lib
#----------------------------------------------------

if [ "$NB_ORA_FULL" = "1" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-full_backup.out"

elif [ "$NB_ORA_INCR" = "1" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-incremental_backup.out"

elif [ "$NB_ORA_CINC" = "1" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-archivelogs_backup.out"

elif [ "$BACKUP_TYPE" = "" ]
then
        export RMAN_LOG_FILE="$PWD/$ORACLE_SID-archivelogs_backup.out"
fi


TARGET_CONNECT_STR=/
RMAN=$ORACLE_HOME/bin/rman
CUSER=`id |cut -d"(" -f2 | cut -d ")" -f1`


echo >> $RMAN_LOG_FILE
chmod 666 $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== started on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE

echo >> $RMAN_LOG_FILE
echo   "RMAN: $RMAN" >> $RMAN_LOG_FILE
echo   "ORACLE_SID: $ORACLE_SID" >> $RMAN_LOG_FILE
echo   "ORACLE_USER: $ORACLE_USER" >> $RMAN_LOG_FILE
echo   "ORACLE_HOME: $ORACLE_HOME" >> $RMAN_LOG_FILE
echo   "NB_ORA_POLICY: $NB_ORA_POLICY" >> $RMAN_LOG_FILE
echo  >> $RMAN_LOG_FILE
echo   "NB_ORA_FULL: $NB_ORA_FULL" >> $RMAN_LOG_FILE
echo   "NB_ORA_INCR: $NB_ORA_INCR" >> $RMAN_LOG_FILE
echo   "NB_ORA_CINC: $NB_ORA_CINC" >> $RMAN_LOG_FILE
echo   "NB_ORA_SERV: $NB_ORA_SERV" >> $RMAN_LOG_FILE
echo   "NB_ORA_POLICY: $NB_ORA_POLICY" >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE

function mutex_message {
        echo `date "+%b %e %T"` "$$" "$*"
}

function mutex_enter {
        mutex_message "Trying to acquire the mutex $1"
        mkdir $1 > /dev/null 2>&1
        if [ $? -eq 0 ]; then
                mutex_message "Acquired mutex $1"
                return
        fi
        mutex_message "Entering spinlock"
        while [ -d $1 ]; do
                sleep 10
        done
        mutex_message "Exited spinlock"
        mutex_enter $1
}

function mutex_exit {
        rmdir $1
        mutex_message "Released mutex $1"
}

if [ "$NB_ORA_FULL" = "1" ]
then
        echo "Full backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=0"
        BACKUP_NAME="INC_0"
        export SCHED_NAME="Default-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=1

elif [ "$NB_ORA_INCR" = "1" ]
then
        echo "Differential incremental backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1"
        BACKUP_NAME="INC_1"
        export SCHED_NAME="Default-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=1

elif [ "$NB_ORA_CINC" = "1" ]
then
        echo "Archivelog only backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"
        BACKUP_NAME="LOG"
        export SCHED_NAME="Archivelog-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=0

elif [ "$BACKUP_TYPE" = "" ]
then
        echo "Archivelog only backup requested" >> $RMAN_LOG_FILE
        BACKUP_TYPE="INCREMENTAL LEVEL=1 CUMULATIVE"
        BACKUP_NAME="LOG"
        export SCHED_NAME="Archivelog-Application-Backup"
        echo "SCHED_NAME: $SCHED_NAME" >> $RMAN_LOG_FILE
        export BACKUP_DATABASE=0
fi

############################
# Backup name for TAG
############################
BACKUP_NAME=${BACKUP_NAME}_`date +'%Y%m%d_%H%M%S'`
echo "BACKUP_NAME=$BACKUP_NAME"
echo >> $RMAN_LOG_FILE
echo "BACKUP_NAME=$BACKUP_NAME"  >> $RMAN_LOG_FILE

export SEND="'NB_ORA_POLICY=$NB_ORA_POLICY, NB_ORA_SCHED=$SCHED_NAME, NB_ORA_CLIENT=$NB_ORA_CL_CLIENT'"

if [ "$BACKUP_DATABASE" = "1" ] ; then
        BACKUP_DATABASE_TEXT="BACKUP
    $BACKUP_TYPE
    SKIP INACCESSIBLE NOEXCLUDE
    TAG '${BACKUP_NAME}'
    FILESPERSET 25
    FORMAT 'db_%s_%p_%t'
    DATABASE;"
else
        BACKUP_DATABASE_TEXT=""
fi

CMD_STR="
ORACLE_HOME=$ORACLE_HOME
export ORACLE_HOME
ORACLE_SID=$ORACLE_SID
export ORACLE_SID
$RMAN target $TARGET_CONNECT_STR catalog=/@catdb msglog $RMAN_LOG_FILE append << EOF
RUN {
ALLOCATE CHANNEL ch00 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch01 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL ch02 TYPE 'SBT_TAPE';
#ALLOCATE CHANNEL ch03 TYPE 'SBT_TAPE';
SEND $SEND;

# backup all archive logs
BACKUP
   filesperset 20
   FORMAT 'log_%s_%p_%t'
   ARCHIVELOG ALL DELETE ALL INPUT;

# backup control file
BACKUP
    FORMAT 'cntrl_%s_%p_%t'
    CURRENT CONTROLFILE;
}


EOF
"
# Initiate the command string

mutex_enter /tmp/oracle-${ORACLE_SID}

if [ "$CUSER" = "root" ]
then
#echo su - $ORACLE_USER -c "$CMD_STR" >> $RMAN_LOG_FILE
su - $ORACLE_USER -c "$CMD_STR" >> $RMAN_LOG_FILE
        RSTAT=$?
else
#echo /bin/sh -c "$CMD_STR" >> $RMAN_LOG_FILE
/bin/sh -c "$CMD_STR" >> $RMAN_LOG_FILE
        RSTAT=$?
fi

mutex_exit /tmp/oracle-${ORACLE_SID}

# ---------------------------------------------------------------------------
# Log the completion of this script.
# ---------------------------------------------------------------------------

if [ "$RSTAT" = "0" ]
then
        LOGMSG="ended successfully"
else
    LOGMSG="ended in error"
fi

echo >> $RMAN_LOG_FILE
echo Script $0 >> $RMAN_LOG_FILE
echo ==== $LOGMSG on `date` ==== >> $RMAN_LOG_FILE
echo >> $RMAN_LOG_FILE

exit $RSTAT




[oracle@omega01]$ crontab -l

00 04   * * 6   NB_ORA_FULL=1 /usr/openv/netbackup/ext/db_ext/oracle/database_backup_TESTDB1.sh   >/dev/null 2>&1
00 04   * * 0-5 NB_ORA_INCR=1 /usr/openv/netbackup/ext/db_ext/oracle/database_backup_TESTDB1.sh   >/dev/null 2>&1
00 *    * * *   NB_ORA_CINC=1 /usr/openv/netbackup/ext/db_ext/oracle/archivelog_backup_TESTDB1.sh >/dev/null 2>&1



[oracle@omega01]$ more nmda_oracle_arch.cfg

ORACLE_HOME=/u01/app/oracle/product/12.1.0.2
ORACLE_SID=TESTDB1
ORACLE_USER=oracle
NSR_RMAN_ARGUMENTS="target / nocatalog msglog '/u01/app/oracle/admin/TESTDB1/networker/nw_TESTDB1_arch.log' append"
# NLS_LANG =
# TNS_ADMIN =
# PRECMD =
# POSTCMD =
# NSR_NWPATH =
# NSR_DIRECT_ACCESS =
# NSR_DEBUG_LEVEL =9
# NSR_DIAGNOSTIC_DEST =

[oracle@omega01]$



[oracle@omega01]$ more nmda_oracle_full.cfg

ORACLE_HOME=/u01/app/oracle/product/12.1.0.2
ORACLE_SID=TESTDB1
ORACLE_USER=oracle
NSR_RMAN_ARGUMENTS="target / nocatalog msglog '/u01/app/oracle/admin/TESTDB1/networker/nw_TESTDB1_full.log' append"
# NLS_LANG =
# TNS_ADMIN =
# PRECMD =
# POSTCMD =
# NSR_NWPATH =
# NSR_DIRECT_ACCESS =
# NSR_DEBUG_LEVEL =9
# NSR_DIAGNOSTIC_DEST =

[oracle@omega01]$


[oracle@omega01]$ more nrman_arch

RUN {
ALLOCATE CHANNEL CH1 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL CH2 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL CH3 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL CH4 TYPE 'SBT_TAPE';
SEND DEVICE TYPE 'SBT_TAPE' 'NSR_ENV=(NSR_DIRECT_ACCESS=No)';
sql 'alter system archive log current';
BACKUP
 filesperset 20
 FORMAT 'al_%d-id-%I-%u'
 ARCHIVELOG ALL NOT BACKED UP 1 TIMES delete all input
;
BACKUP
 FORMAT 'cntrl_%d-id-%I-%u'
 CURRENT CONTROLFILE
;
RELEASE CHANNEL CH1;
RELEASE CHANNEL CH2;
RELEASE CHANNEL CH3;
RELEASE CHANNEL CH4;
}

[oracle@omega01]$


[oracle@omega01]$ more nrman_full
RUN {
ALLOCATE CHANNEL CH1 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL CH2 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL CH3 TYPE 'SBT_TAPE';
ALLOCATE CHANNEL CH4 TYPE 'SBT_TAPE';
SEND DEVICE TYPE 'SBT_TAPE' 'NSR_ENV=(NSR_DIRECT_ACCESS=No)';
BACKUP
 FULL
 FILESPERSET 1
 FORMAT 'db_%d-id-%I-%u'
 DATABASE
 INCLUDE CURRENT CONTROLFILE
;
sql 'alter system archive log current';
BACKUP
 filesperset 20
 FORMAT 'al_%d-id-%I-%u'
 ARCHIVELOG ALL NOT BACKED UP 1 TIMES
;
BACKUP
 FORMAT 'cntrl_%d-id-%I-%u'
 CURRENT CONTROLFILE
;
RELEASE CHANNEL CH1;
RELEASE CHANNEL CH2;
RELEASE CHANNEL CH3;
RELEASE CHANNEL CH4;
}

[oracle@omega01]$