среда, 25 февраля 2009 г.

Solaris Service Management Facility

svcadm export > all_smf_export

To see all running services
svcs

To see all services, including not-running
svcs -a

To check for services having problems (“in maintenance mode”)
svcs -x

NAME : svc:/network/smtp:sendmail

get detail about any one service.
svcs -l NAME

To see what processes a service is running:
svcs -p NAME

Controlling existing services

svcadm -t enable NAME # Start service
svcadm -t disable NAME # Stop service
svcadm enable NAME # Start service (persists over reboots)
svcadm disable NAME # Start service (persists over reboots)
svcadm restart NAME # (only if defined in manifest?)
svcadm refresh NAME # usually does a "kill -HUP" if defined



mv /etc/rc2.d/S75cron /etc/rc2.d/s.S75cron
svcadm disable system/cron:default

edit /etc/inet/inetd.conf, uncomment the finger line
svcadm enable network/finger:default

/etc/init.d/sshd stop
svcadm disable -t network/ssh:default

/etc/init.d/sshd start
svcadm enable -t network/ssh:default

/etc/init.d/sshd stop; /etc/init.d/sshd start
svcadm restart network/ssh:default

kill -HUP `cat /var/run/sshd.pid`
svcadm refresh network/ssh:default

ok boot -m verbose
svcs -x
svcs -x -v

svcs -p network/smtp:sendmail
svcs -d network/smtp:sendmail
svcs -D network/smtp:sendmail

edit /etc/inittab
svcadm milestone -d milestone/single-user:default
svcadm milestone milestone/multi-user-server:default


boot -m milestone=
milestone (single-user, multi-user, multi-user-server)


Логи смотреть тут:
/var/adm/messages
/var/svc/log
/etc/svc/volatile


svccfg export postfix > my.smf
svccfg validate
svccfg import

Краткий план миграции на 12R1

1.Уведомление о начале работ.

2.Остановка приложений

3.Создание точки отката

sql>SELECT flashback_on, log_mode FROM v$database;
sql> alter database flashback on;  -- если режим flashback не включен

Смотрим место во fra:

sql>select name, round(space_limit/1048576),round(space_used/1048576),round ((space_used/space_limit)*100) as "% used"
from  v$RECOVERY_FILE_DEST;

sql>create restore point RP_1 guarantee flashback database;


4.Проверка целостности исходной БД перед миграцией
cd /oracle/distr/pre

$ sqlplus / as sysdba
sql> alter session set nls_language='American';
sql> @dbupgdiag.sql
sql> exit


5.Проверка БД с помощью hcheck и hout

cd /oracle/distr/pre
$ sqlplus / as sysdba
sql> alter session set nls_language='American';
sql> @hout.sql
sql> @hcheck4.sql
sql> execute hcheck.full
sql> exit


6.Очистить корзину перед обновлением

$ sqlplus /as sysdba
SQL> PURGE DBA_RECYCLEBIN;


7.Проверка версий компонентов:

select substr(comp_id,1,15) comp_id,substr(comp_name,1,30) comp_name, substr(version,1,10) version,status
from dba_registry order by modified;


8.Удалить EM DB Control

$ emctl stop dbconsole
$ sqlplus / as sysdba
SQL> @?/rdbms/admin/emremove.sql


9.Pre Upgrade Steps

cd  /u01/app/oracle/distr/pre
$ unzip preupgrade_12.1.0.2.0_15_lf.zip
$ sqlplus / as sysdba
SQL> alter session set nls_language='American';
SQL> @utluppkg.sql
SQL> @preupgrd.sql


10.Анализ логов и запуск скрипта preupgrade_fixups.sql

$ tail -1000 /u01/app/oracle/cfgtoollogs/testdb/preupgrade/preupgrade.log
SQL>@/u01/app/oracle/cfgtoollogs/testdb/preupgrade/preupgrade_fixups.sql
SQL> exit


11.Создание файла параметров и паролей в новом OH: 

SQL> create pfile from spfile;
$ cp /u01/app/oracle/product/11.2.0.4/db/dbs/inittestdb.ora  /u01/app/oracle/product/12.1.0.2/dbs/
$ cd /u01/app/oracle/product/12.1.0.2/dbs/
vi  inittestdb.ora

Пересоздание файла паролей в новом формате 12с
orapwd file=< fname > entries=< users > force=< y/n > password=< SYS password > format=12

Миграция старого файла паролей на новый формат 12c


orapwd file=< fname > entries=< users > force=< y/n > password=< SYS password > format=12 input_file=< input-fname >

Проверка
orapwd describe file=< passwordfile name with location >


<- br="" testdb="">su – oracle
. oraenv  <  - TESTDB
$ cd $ORACLE_HOME/dbs

$ ls -al orapw*

$ orapwd describe file=orapwtestdb
Password file Description : format=LEGACY ignorecase=N

$ orapwd file=orapwTESTDB entries=10 force=y password=< ... > format=12 input_file=orapwTESTDB

$ orapwd describe file=orapwtestdb
Password file Description : format=12 ignorecase=N
 



12.Upgrade Steps

$ export  ORACLE_HOME=/u01/app/oracle/product/12.1.0.2
cd $ORACLE_HOME/rdbms/admin

sqlplus / as sysdba
SQL> startup UPGRADE
SQL> exit

cd $ORACLE_HOME/rdbms/admin
$ORACLE_HOME/perl/bin/perl catctl.pl -n 4 -l $ORACLE_BASE/cfgtoollogs/testdb catupgrd.sql


13.Анализ логов и запуск базы:

tail -1000 $ORACLE_BASE/cfgtoollogs/testdb/catupgrd0.log
tail -1000 $ORACLE_HOME/cfgtoollogs/testdb/upgrade/upg_summary.log

Запуск базы
$ sqlplus / as sysdba
SQL> startup


14.Post Upgrade Steps

cd $ORACLE_HOME/rdbms/admin

$ sqlplus / as sysdba
SQL> @utlu121s.sql
SQL> @catuppst.sql
SQL>@/u01/app/oracle/cfgtoollogs/testdb/preupgrade/postupgrade_fixups.sql
SQL> @utlrp.sql  4
SQL> @utluiobj.sql
SQL> exit


15.Сбор статистики по фиксированным объектам словаря базы данных:

SQL> exec DBMS_STATS.GATHER_FIXED_OBJECTS_STATS;


16.Запускаем datapatch

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

cd $ORACLE_HOME/OPatch
./datapatch -verbose


17.Перекомпиляция инвалидных объектов.

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


18.Проверка:

select action,
       version||'.'||bundle_id as version_id,
       description,
       status,
       ACTION_TIME,
       patch_id
from DBA_REGISTRY_SQLPATCH;


19.Проверка версий компонентов:

select substr(comp_id,1,15) comp_id,
substr(comp_name,1,30) comp_name,
substr(version,1,10) version,status
from dba_registry order by modified;


20.Сетевые настройки

cd $ORACLE_HOME/network/admin
$ vi listener.ora
$ vi sqlpnet.ora
$ lsnrctl start
$ lsnrctl status


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

!!!  Новый параметр compatible пока не выставляем

Устранить известные критические ошибки для версии 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='*';


Дополнительно можно установить следующие параметры:

alter system set db_files=2048  scope=spfile sid='*';
alter system set processes=1024 scope=spfile sid='*';
alter system set control_file_record_keep_time=30 scope=spfile sid='*';
alter system set cursor_sharing='EXACT' scope=spfile sid='*';
alter system set filesystemio_options='SETALL' scope=spfile sid='*';

alter system set fast_start_mttr_target       = 1200 scope=spfile sid='*';
alter system set fast_start_parallel_rollback = LOW scope=spfile sid='*';

alter system set open_cursors=2000                        scope=spfile sid='*';
alter system set session_cached_cursors = 200             scope=spfile sid='*';
alter system set open_links=255                           scope=spfile sid='*';
alter system set resumable_timeout=120                    scope=spfile sid='*';
alter system set job_queue_processes=1000                 scope=spfile sid='*';

-- LOG_BUFFER
alter system set log_buffer=67108864 scope=spfile sid='*';

-- deferred_segment_creation
alter system set deferred_segment_creation=FALSE  scope=both sid='*';

--
-- Configure to Protect from Data Corruption
--
alter system reset DB_ULTRA_SAFE                 scope=spfile sid='*';
alter system set db_block_checking="MEDIUM"      scope=spfile sid='*';
alter system set db_block_checksum="TYPICAL"     scope=spfile sid='*';
alter system set db_lost_write_protect="TYPICAL" scope=spfile sid='*';

sql> SHUTDOWN IMMEDIATE
sql>STARTUP
sql> exit


22.Проверка работы приложений.

Проверка работы приложений на новой версии бд


23.Удаление точки отката

Удаляем только если миграция прошла успешно.

sql> SELECT name, scn, time, database_incarnation#, guarantee_flashback_database, storage_size FROM gv$restore_point;
sql>drop restore point RP_1;
SELECT name, scn, time, database_incarnation#, guarantee_flashback_database, storage_size FROM gv$restore_point;


24.Установка нового compatible

-- 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='*';

sql> SHUTDOWN IMMEDIATE
sql>STARTUP
sql> exit


25.Уведомление о завершении работ.

Завершение работ:
Работы считаются завершенными после успешного выполнения всех пунктов плана работ.


План отката: 

Точку отката не должна быть удалена
Возврат  к RESTORE POINT
sql> shutdown immediate;
sql>startup mount;
sql> flashback database to restore point RP_1;
Flashback complete.

Окончательно откроем базу
SQL> alter database open resetlogs;
sql>drop restore point RP_1;




Listener

Настройка листенера для не кластерных конфигураций

По умолчанию сетевая служба Oracle Listener должна использовать порт 1521.

Файл sqlnet.ora должен содержать:


NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
SQLNET.EXPIRE_TIME = 10
ADR_BASE = /u01/app/oracle

Файл listener.ora должен содержать:

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = .domain)(PORT = 1521))
    )
  )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = DB_UNIQUE_NAME)
      (ORACLE_HOME   = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME = SID)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = DB_UNIQUE_NAME_DGMGRL)
      (ORACLE_HOME   = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME = SID)
    )
  )

#################################
# standard parameters
#################################
ADR_BASE_LISTENER = /u01/app/oracle
ENABLE_GLOBAL_DYNAMIC_ENDPOINT_LISTENER=ON
VALID_NODE_CHECKING_REGISTRATION_LISTENER=SUBNET

#################################
# extended parameters
#################################
TRACE_LEVEL_LISTENER       = OFF
STARTUP_WAIT_TIME_LISTENER = 0
CONNECT_TIMEOUT_LISTENER   = 120
INBOUND_CONNECT_TIMEOUT_LISTENER = 120
SUBSCRIBE_FOR_NODE_DOWN_EVENT_LISTENER=OFF

#################################
# 1453883.1 CVE-2012-1675
#################################
SECURE_REGISTER_LISTENER = (TCP,IPC)


Настройка листенера для кластерных конфигураций

Файл listener.ora – по умолчанию никакие изменения не вносятся. Вносятся только параметры для устранения уязвимостей , ошибок и работы сервиса Data Guard Broker.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = DB_UNIQUE_NAME)           # для создания Standby БД
      (ORACLE_HOME   = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME      = SID)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = DB_UNIQUE_NAME_DGMGRL)    #для операций Switchover
      (ORACLE_HOME   = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME      = SID)
    )
  )
 




Настройка технологических дескрипторов соединения с БД для сервиса DGMGRL

Для Primary + Standby серверов добавить следующее описание дескрипторов:


vi $ORACLE_HOME/network/admin/tnsnames.ora

DB_UNIQUE_NAME_1 =
  (DESCRIPTION =
    (ENABLE=BROKEN)
    (ADDRESS_LIST=
        (ADDRESS = (PROTOCOL = TCP)(HOST = <имя_хоста_1>)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = DB_UNIQUE_NAME_1)
    )
  )

DB_UNIQUE_NAME_2 =
  (DESCRIPTION =
    (ENABLE=BROKEN)
    (ADDRESS_LIST=
        (ADDRESS = (PROTOCOL = TCP)(HOST = <имя_хоста_2>)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = DB_UNIQUE_NAME_2)
    )
  )

  

Пример конфигурации листенера:


oracle@omega:$  more listener.ora

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = omega.domain)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = TESTDB_OMEGA)
      (ORACLE_HOME = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME = testdb)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = TESTDB_OMEGA_DGMGRL)
      (ORACLE_HOME   = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME = testdb)
    )
    (SID_DESC =
      (GLOBAL_DBNAME = TESTDB)
      (ORACLE_HOME = /u01/app/oracle/product/12.1.0.2)
      (SID_NAME = testdb)
    )
  )


#################################
# standard parameters
#################################
ADR_BASE_LISTENER = /u01/app/oracle
ENABLE_GLOBAL_DYNAMIC_ENDPOINT_LISTENER=ON
VALID_NODE_CHECKING_REGISTRATION_LISTENER=SUBNET

#################################
# extended parameters
#################################
TRACE_LEVEL_LISTENER       = OFF
STARTUP_WAIT_TIME_LISTENER = 0
CONNECT_TIMEOUT_LISTENER   = 120
INBOUND_CONNECT_TIMEOUT_LISTENER = 120
SUBSCRIBE_FOR_NODE_DOWN_EVENT_LISTENER=OFF

#################################
# 1453883.1 CVE-2012-1675
#################################
SECURE_REGISTER_LISTENER = (TCP,IPC)


oracle@omega:$



oracle@omega:$  more sqlnet.ora

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
SQLNET.EXPIRE_TIME = 10
ADR_BASE = /u01/app/oracle


oracle@omega:$  more tnsnames.ora

TESTDB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.7)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = testdb)
    )
  )

RCAT =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = alpha)(PORT = 1521)))
      (CONNECT_DATA = (SID = RCAT)
    )
  )

oracle@omega:$ 







Настройка дескрипторов соединений на клиентской стороне

Подключение к тестовым БД 

Non-RAC конфигурация

<имя_дескриптора> =
  (DESCRIPTION =
    (ENABLE=BROKEN)
    (ADDRESS_LIST=
        (ADDRESS = (PROTOCOL = TCP)(HOST = <имя_хоста>)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = <имя_сервиса>)
    )
  )


RAC конфигурация

<имя_дескриптора> =
  (DESCRIPTION =
     (ENABLE=BROKEN)
     (CONNECT_TIMEOUT=30)
     (TRANSPORT_CONNECT_TIMEOUT=10)
     (RETRY_COUNT=3)
     (ADDRESS_LIST=
       (LOAD_BALANCE=on)
       (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = 1521))
     )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = <имя_сервиса>)
    )
  )

 

Подключение к боевым БД

Non-RAC конфигурация

<имя_дескриптора> =
  (DESCRIPTION =
    (ENABLE=BROKEN)
    (TRANSPORT_CONNECT_TIMEOUT=10)
    (ADDRESS_LIST=
      (LOAD_BALANCE=OFF)
      (FAILOVER=ON)
        (ADDRESS = (PROTOCOL = TCP)(HOST = <имя_хоста_1>)(PORT = 1521))
        (ADDRESS = (PROTOCOL = TCP)(HOST = <имя_хоста_2>)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = <имя_сервиса>)
    )
  )

RAC конфигурация

<имя_дескриптора> =
  (DESCRIPTION_LIST=
     (LOAD_BALANCE=OFF)
     (FAILOVER=ON)
       (DESCRIPTION=
          (ENABLE=BROKEN)
          (CONNECT_TIMEOUT=30)
          (TRANSPORT_CONNECT_TIMEOUT=10)
          (RETRY_COUNT=3)
          (ADDRESS_LIST=
            (LOAD_BALANCE=ON)
            (ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=1521))
          )
            (CONNECT_DATA=
              (SERVER = DEDICATED)
              (SERVICE_NAME=<имя_сервиса>)
            )
       )
       (DESCRIPTION=
          (ENABLE=BROKEN)
          (CONNECT_TIMEOUT=30)
          (TRANSPORT_CONNECT_TIMEOUT=10)
          (RETRY_COUNT=3)
          (ADDRESS_LIST=
            (LOAD_BALANCE=ON)
            (ADDRESS=(PROTOCOL=TCP)(HOST=)(PORT=1521))
          )
            (CONNECT_DATA=
              (SERVER = DEDICATED)
              (SERVICE_NAME=<имя_сервиса>)
            )
       )
  )







Profile

Файл  .bashrc  или  .profile  должен содержать следующие строки:

##################################################
# Setup Oracle standard env
##################################################

export ORACLE_SID=SID
export ORACLE_BASE=/u01/app/oracle
export PATH=$PATH:/usr/local/bin
ORAENV_ASK=NO
. /usr/local/bin/oraenv > /dev/null 2>&1
ORAENV_ASK=YES

##################################################
# Setup Oracle extended env
##################################################
#export NLS_LANG=AMERICAN_AMERICA.CL8MSWIN1251
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
export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:/sbin:/usr/sbin:/bin:/usr/local/bin:/usr/bin:$PATH

umask 022
unset TMOUT


if [ `uname` = "Linux" ]; then
unset LS_COLORS
fi

if [ `uname` = "AIX" ]; then
export AIXTHREAD_SCOPE=S
fi

if [ `uname` = "SunOS" ]; then
export AWT_TOOLKIT=XToolkit
# Preventing Installation Errors Caused by Terminal Output Commands
if [ -t 0 ]; then
   stty intr ^C
fi
fi


где SID – указать идентификатор экземпляра БД


Для корректной установки переменных окружений из профайла необходимо следить
за заполнением информации в файле /etc/oratab, где регистрируется информация об используемых экземплярах баз данных.

oracle@omega:~$ more /etc/oratab

# This file is used by ORACLE utilities.  It is created by root.sh
# and updated by either Database Configuration Assistant while creating
# a database or ASM Configuration Assistant while creating ASM instance.

# A colon, ':', is used as the field terminator.  A new line terminates
# the entry.  Lines beginning with a pound sign, '#', are comments.
#
# Entries are of the form:
#   $ORACLE_SID:$ORACLE_HOME::
#
# The first and second fields are the system identifier and home
# directory of the database respectively.  The third filed indicates
# to the dbstart utility that the database should , "Y", or should not,
# "N", be brought up at system boot time.
#
# Multiple entries with the same $ORACLE_SID are not allowed.
#
#
+ASM:/u01/app/grid/product/11.2.0.4:N
TESTDB:/u01/app/oracle/product/11.2.0.4:N         # line added by Agent
 

oracle@omega:~$




В  .bash_profile  можно поместить следующие строки:


oracle@omega:~$ cat .bash_profile

# .bash_profile

# Source global definitions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

if [ "$BASH" = "" ]; then

echo Hello Bourne or K shell ....
PS1=$LOGNAME@`uname -n`"# "
else
echo Hello Bash ...
PS1="\u@\h:\w$ "
fi



А все остальное поместить в .bashrc :

oracle@omega:~$ cat .bashrc

# .bashrc
# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

##################################################
# Setup Oracle standard env
##################################################
export ORACLE_SID=TESTDB
export ORACLE_BASE=/u01/app/oracle
export PATH=$PATH:/usr/local/bin
ORAENV_ASK=NO
. /usr/local/bin/oraenv > /dev/null 2>&1
ORAENV_ASK=YES

##################################################
# Setup Oracle extended env
##################################################
#export NLS_LANG=AMERICAN_AMERICA.CL8MSWIN1251
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
export PATH=$ORACLE_HOME/bin:/sbin:/usr/sbin:/bin:/usr/local/bin:/usr/bin:$PATH

umask 022
unset TMOUT

if [ `uname` = "Linux" ]; then
unset LS_COLORS
fi

oracle@omega:~$





Посмотрим что содержится в файле  /usr/local/bin/oraenv :

oracle@omega:~$ more /usr/local/bin/oraenv

#!/bin/sh
#
# $Header: buildtools/scripts/oraenv.sh /linux32/8 2010/03/25 04:17:55 ashrives Exp $ oraenv.sh.pp Copyr (c) 1991 Oracle
#
# Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
#
# This routine is used to condition a Bourne shell user's environment
# for access to an ORACLE database.  It should be installed in
# the system local bin directory.
#
# The user will be prompted for the database SID, unless the variable
# ORAENV_ASK is set to NO, in which case the current value of ORACLE_SID
# is used.
# An asterisk '*' can be used to refer to the NULL SID.
#
# 'dbhome' is called to locate ORACLE_HOME for the SID.  If
# ORACLE_HOME cannot be located, the user will be prompted for it also.
# The following environment variables are set:
#
#       ORACLE_SID      Oracle system identifier
#       ORACLE_HOME     Top level directory of the Oracle system hierarchy
#       PATH            Old ORACLE_HOME/bin removed, new one added
#       ORACLE_BASE     Top level directory for storing data files and
#                       diagnostic information.
#
# usage: . oraenv
#
# NOTE:         Due to constraints of the shell in regard to environment
# -----         variables, the command MUST be prefaced with ".". If it
#               is not, then no permanent change in the user's environment
#               can take place.
#
#####################################
#
# process aruments
#
SILENT='';
for arg in $@
do
    if [ "$arg" = "-s" ]; then
        SILENT='true'
    fi
done

case ${ORACLE_TRACE:-""} in

    T)  set -x ;;
esac

#
# Determine how to suppress newline with echo command.
#
N=
C=
if echo "\c" | grep c >/dev/null 2>&1; then
    N='-n'
else
    C='\c'
fi

#
# Set minimum environment variables
#

# ensure that OLDHOME is non-null
if [ ${ORACLE_HOME:-0} = 0 ]; then
    OLDHOME=$PATH
else
    OLDHOME=$ORACLE_HOME
fi
case ${ORAENV_ASK:-""} in                       #ORAENV_ASK suppresses prompt when set

    NO) NEWSID="$ORACLE_SID" ;;
    *)  case "$ORACLE_SID" in
            "") ORASID=$LOGNAME ;;
            *)  ORASID=$ORACLE_SID ;;
        esac
        echo $N "ORACLE_SID = [$ORASID] ? $C"
        read NEWSID
        case "$NEWSID" in
            "")         ORACLE_SID="$ORASID" ;;
            *)          ORACLE_SID="$NEWSID" ;;
        esac ;;
esac
export ORACLE_SID

ORAHOME=`dbhome "$ORACLE_SID"`
case $? in
    0)  ORACLE_HOME=$ORAHOME ;;
    *)  echo $N "ORACLE_HOME = [$ORAHOME] ? $C"
        read NEWHOME
        case "$NEWHOME" in
            "") ORACLE_HOME=$ORAHOME ;;
            *)  ORACLE_HOME=$NEWHOME ;;
        esac ;;
esac

export ORACLE_HOME

#
# Reset LD_LIBRARY_PATH
#
case ${LD_LIBRARY_PATH:-""} in
    *$OLDHOME/lib*)     LD_LIBRARY_PATH=`echo $LD_LIBRARY_PATH | \
                            sed "s;$OLDHOME/lib;$ORACLE_HOME/lib;g"` ;;
    *$ORACLE_HOME/lib*) ;;
    "")                 LD_LIBRARY_PATH=$ORACLE_HOME/lib ;;
    *)                  LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH ;;
esac

export LD_LIBRARY_PATH

#
# Put new ORACLE_HOME in path and remove old one
#

case "$OLDHOME" in
    "") OLDHOME=$PATH ;;        #This makes it so that null OLDHOME can't match
esac                            #anything in next case statement

case "$PATH" in
    *$OLDHOME/bin*)     PATH=`echo $PATH | \
                            sed "s;$OLDHOME/bin;$ORACLE_HOME/bin;g"` ;;
    *$ORACLE_HOME/bin*) ;;
    *:)                 PATH=${PATH}$ORACLE_HOME/bin: ;;
    "")                 PATH=$ORACLE_HOME/bin ;;
    *)                  PATH=$PATH:$ORACLE_HOME/bin ;;
esac

export PATH

# Locate "osh" and exec it if found
ULIMIT=`LANG=C ulimit 2>/dev/null`

if [ $? = 0 -a "$ULIMIT" != "unlimited" ] ; then
  if [ "$ULIMIT" -lt 2113674 ] ; then

    if [ -f $ORACLE_HOME/bin/osh ] ; then
        exec $ORACLE_HOME/bin/osh
    else
        for D in `echo $PATH | tr : " "`
        do
            if [ -f $D/osh ] ; then
                exec $D/osh
            fi
        done
    fi

  fi

fi

# Set the value of ORACLE_BASE in the environment.
#
# Use the orabase executable from the corresponding ORACLE_HOME, since the ORACLE_BASE of different
# ORACLE_HOMEs can be different.  The return value of orabase will be determined based on the value
# of ORACLE_BASE from oraclehomeproperties.xml as set in the ORACLE_HOME inventory.
#
# If orabase can not determine a value then oraenv returns with ORACLE_BASE unset.
#
# The existing value of ORACLE_BASE is only used to inform the user if the script has changed
# the value of ORACLE_BASE.

ORABASE_EXEC=$ORACLE_HOME/bin/orabase

if [ ${ORACLE_BASE:-"x"} != "x" ]; then
   OLD_ORACLE_BASE=$ORACLE_BASE
   unset ORACLE_BASE
   export ORACLE_BASE
else
   OLD_ORACLE_BASE=""
fi

if [ -w $ORACLE_HOME/inventory/ContentsXML/oraclehomeproperties.xml ]; then
   if [ -f $ORABASE_EXEC ]; then
      if [ -x $ORABASE_EXEC ]; then
         ORACLE_BASE=`$ORABASE_EXEC`

         # did we have a previous value for ORACLE_BASE
         if [ ${OLD_ORACLE_BASE:-"x"} != "x" ]; then
            if [ $OLD_ORACLE_BASE != $ORACLE_BASE ]; then
               if [ "$SILENT" != "true" ]; then
                  echo "The Oracle base has been changed from $OLD_ORACLE_BASE to $ORACLE_BASE"
               fi
            else
               if [ "$SILENT" != "true" ]; then
                  echo "The Oracle base remains unchanged with value $OLD_ORACLE_BASE"
               fi
            fi
         else
            if [ "$SILENT" != "true" ]; then
               echo "The Oracle base has been set to $ORACLE_BASE"
            fi
         fi
         export ORACLE_BASE
      else
         if [ "$SILENT" != "true" ]; then
            echo "The $ORACLE_HOME/bin/orabase binary does not have execute privilege"
            echo "for the current user, $USER.  Rerun the script after changing"
            echo "the permission of the mentioned executable."
            echo "You can set ORACLE_BASE manually if it is required."
         fi
      fi
   else
      if [ "$SILENT" != "true" ]; then
         echo "The $ORACLE_HOME/bin/orabase binary does not exist"
         echo "You can set ORACLE_BASE manually if it is required."
      fi
   fi
else
   if [ "$SILENT" != "true" ]; then
      echo "ORACLE_BASE environment variable is not being set since this"
      echo "information is not available for the current user ID $USER."
      echo "You can set ORACLE_BASE manually if it is required."
   fi
fi

#
# Install any "custom" code here
#

oracle@omega:~$





А файл  /u01/app/oracle/product/11.2.0.4/bin/dbhome содержит :

oracle@omega:~$ more /u01/app/oracle/product/11.2.0.4/bin/dbhome



#
# $Header: dbhome.sh 24-may-2007.12:10:51 vkolla Exp $ dbhome.sh.pp Copyr (c) 1991 Oracle
#
###################################
#
# usage: ORACLE_HOME=`dbhome [SID]`
# NOTE:  A NULL SID is specified with "" on the command line
#
# The only sane way to use this script is with SID specified on the
# command line or to have ORACLE_SID set for the database you are looking
# for.  The return code will be 1 if dbhome can't find ANY value, 2 if
# it finds a questionable value, 0 if it finds a good one (ie. out of
# oratab).
#
# If ORACLE_SID is set or provided on the command line the script
# will write to the standard output the first of the following that
# it finds:
#       1.  The value of the 2nd field in oratab where the
#           value of the 1st field equals $ORACLE_SID.
#       2.  The home directory for the user 'oracle' in /etc/passwd
#           or in the yellow pages password entries.
#
# If ORACLE_SID is not set and not provided on the command line the
# script will write to the standard output the first of the following
# that it finds:
#       1.  The current value of ORACLE_HOME if not null.
#       2.  The home directory for the user 'oracle' in /etc/passwd
#           or in the yellow pages password entries.
#
# This script currently uses no hard-coded defaults for ORACLE_SID or
# ORACLE_HOME.
#
#####################################

case "$ORACLE_TRACE" in
    T)  set -x ;;
esac

trap '' 1

RET=0
ORAHOME=""
ORASID=${ORACLE_SID-NOTSET}
ORASID=${1-$ORASID}

ORATAB=/etc/oratab

PASSWD=/etc/passwd
PASSWD_MAP=passwd.byname

case "$ORASID" in
    NOTSET)     # ORACLE_SID not passed in and not in environment
                RET=2
                ORAHOME="$ORACLE_HOME" ;;

    *)  # ORACLE_SID was set or provided on the command line
        if test -f $ORATAB ; then
            # Try for a match on ORASID in oratab
            # NULL SID is * in oratab
            case "$ORASID" in
                "")     ORASID='\*' ;;
            esac

            ORAHOME=`awk -F: '{if ($1 == "'$ORASID'") {print $2; exit}}' \
                        $ORATAB 2>/dev/null`

        fi ;;
esac

case "$ORAHOME" in
    "") # Not found in oratab or ORACLE_HOME not set;
        # try /etc/passwd & yp for "oracle"
        RET=2
        ORAHOME=`awk -F: '/^oracle:/ {print $6; exit}' $PASSWD`
        case "$ORAHOME" in

            "") ORAHOME=`(ypmatch oracle $PASSWD_MAP) 2>/dev/null | \
                    awk -F: '/^oracle:/ {print $6; exit}'`

                case "$ORAHOME" in
                    "") echo "Cannot locate ORACLE_HOME." 1>&2
                        exit 1 ;;
                esac ;;
        esac ;;
esac

echo $ORAHOME
exit $RET





oracle@omega:~$