Pages

Tuesday, December 30, 2014

Linux crontab by example

=====================
crontab quick reference
=====================
crontab entries
crontab entries are stored in a file: /var/spool/cron/$USER
The actual path may very per Linux distribution.
For example:
root@my_host:/var/spool/cron>% ls -l
-rw------- 1 oracle   root  77 May 17  2011 oracle
-rw------- 1 root     root 236 Jun 27  2012 root
-rw------- 1 shdaemon root 424 Mar  5  2014 shdaemon


The crontab files are owned by root.

The proper way to access these files is via crontab CLI.
crontab -l - view 
crontab -e - edit 

Entry example:
00 05 * * *   . $HOME/.profile_for_awr; 

00 - min. 00-59
05 - hour. 00-23
* - Day of month. 1-31
* - Month. 1-12
* - Day of week (0 - 6) (Sunday=0)

crontab log 

/var/log/cron
for example:
Jul 23 04:04:01 my_server crond[2167]: (root) CMD (/usr/local/etc/my_user/load_alarm/loadalarmer > /dev/null 2>&1)
Jul 23 04:04:01 my_server crond[2169]: (root) CMD (/usr/local/etc/my_user/load_stats/bin/load_stats)
Jul 23 04:05:01 my_server crond[3720]: (root) CMD (/usr/local/etc/my_user/load_stats/bin/load_stats)
Jul 23 04:05:01 my_server crond[3721]: (root) CMD (/usr/local/etc/my_user/load_alarm/loadalarmer > /dev/null 2>&1)
Jul 23 04:06:01 my_server crond[5295]: (root) CMD (/usr/local/etc/my_user/load_stats/bin/load_stats)
Jul 23 04:06:01 my_server crond[5296]: (root) CMD (/usr/local/etc/my_user/load_alarm/loadalarmer > /dev/null 2>&1)

=======================
Examples:
=======================
# To run at 00:00, 08:00, 16:00
00 0,8,16, * * * /run/something.sh



=======================
Example 1.
=======================
Remove multiple files, older than 5 days with one command from crontab
Run on 23:15 every day.

15 23 * * * find . -type f -name "FILE-TO-FIND" -mtime +5 -exec rm {} \;


=======================
Example 2.
=======================
Delete *.trc and *.trm files older than 7 days, run every day at 04:00.

crontab -l
0 4 * * * /usr/local/etc/userA/oracle_purge/delete_old_trace_files.sh

less /usr/local/etc/userA/oracle_purge/delete_old_trace_files.sh

#!/bin/bash

export ORA_INST=orainst
export DAYS_TO_KEEP=2

find /software/oracle/diag/rdbms/${ORA_INST}/${ORA_INST}/trace -type f -name "*.trc" -mtime +${DAYS_TO_KEEP} -exec rm {} \;
find /software/oracle/diag/rdbms/${ORA_INST}/${ORA_INST}/trace -type f -name "*.trm" -mtime +${DAYS_TO_KEEP} -exec rm {} \;

=======================
Example 3.
=======================
Keep only last hour of listener.log file.


crontab -l

1 * * * * /software/oracle/oracle/scripts/clean_files.sh

less /software/oracle/oracle/scripts/clean_files.sh
#!/bin/bash

#!/bin/bash
MY_SERVER=zaf-vod-7-aps-1
MY_INST=igt
mv -f /software/oracle/diag/tnslsnr/${MY_SERVER}/lsnr_${MY_INST}/trace/lsnr_${MY_INST}.log /software/oracle/diag/tnslsnr/${MY_SERVER}/lsnr_${MY_INST}/trace/lsnr_${MY_INST}_last_hour.log

==================================
crontab log
==================================
under /var/log/
cron file.
older files are cron.1, crom2, etc.


==================================
Example of crontab task to run sql
==================================
Just put this task inside oracle crontab

5 01,13 * * * . /etc/profile ; echo "TRUNCATE TABLE MY_SCHEMA.MY_TABLE;" | sqlplus /

==================================
crontab and environment variables
==================================
cron is started by the system, so it has a minimal environment. 
It knows nothing about your shell and the local shell environment variables.

Thus need to set the environment variables before running the script, by:
 . $HOME/.set_env;

Note the ";" at the end of the source command.


or to source  . $HOME/.set_env from inside the shell script.

Which variables need to be set?
PATH

LD_LIBRARY_PATH

For example :
env | grep PATH > .set_env
and inside the main script:
.set_env

==================================
crontab and absolute path vs relative path

==================================
In cron - ALWAYS use absolute path.

This will not work in cron:
write to ./my_file

This will work:
write to /usr/my_user/my_path/my_file.txt
==================================
Checklist for crontab task is not running. 
==================================
A. Is crond service working?
Run ps ax | grep cron and look for crond process.

B. is cron working?
* * * * * /bin/echo "cron works" >> /path/test_cron.log

C. Is the script working?
Try to run the job from $HOME

D. Check cron log for possible errors
Check /var/log/cron.log or /var/log/messages

E. Check the Environment variables from inside the script
just put:
echo "PATH = " $PATH >>/path/test_cron.log
echo "ORACLE_HOME = " $ORACLE_HOME >>/path/test_cron.log



=======================
Appendix
=======================
Crontab – Quick Reference
Crontab Examples


Thursday, December 25, 2014

SPFILE issues by example

==============================
SPFILE
==============================
SPFILE stands for Server Parameters File.
SPFILE is a binary file that exist only on the server and is used to start up the database.

==============================
SPFILE and PFILE priority upon Startup
==============================
Upon Startup, Oracle would use the SPFILE from default location, with default name.
$ORACLE_HOME/dbs/spfile<SID>.ora

If this file is not present, Oracle would use the init.ora file:
$ORACLE_HOME/dbs/init<SID>.ora

For Oracle 11.2
INIT.ORA location: /software/oracle/112/dbs
SPFILE location:   /software/oracle/112/dbs
PFILE location:    /software/oracle/admin/igt/pfile

==============================
SPFILE location
==============================
Default location for spfile and for init_ora is ${ORACLE_HOME}/dbs

It would actually be specified inside ${ORACLE_HOME}/dbs/init<SID>.ora
less init<SID>.ora

spfile='/software/oracle/admin/igt/pfile/spfileigt.ora'


The SPFILE can be placed anywhere as long as the path is specified in init.ora file.

If SPFILE is created in a non default location, first need to create a traditional parameter file containing only the following single line:
SPFILE=/full/path/to/spfile.ora

For example:
>less /software/oracle/111/dbs/initorainst.ora

SPFILE=/software/oracle/admin/orainst/pfile/spfileorainst.ora


==============================
SPFILE in RAC
==============================
All instances in an Real Application Clusters environment must use the same server parameter file. 
When permitted, individual instances can have different settings of the same parameter within this one file. 
The syntax: SID.parameter = value, where SID is the instance identifier.

==============================
CREATE PFILE
==============================
PFILE would be located here: /software/oracle/admin/igt/pfile

It is possible to create PFILE in a several ways.

Best Option: CREATE PFILE FROM SPFILE.
CREATE PFILE command exports binary SPFILE into a text initialization parameter file. CREATE PFILE = '$ORACLE_HOME/dbs/orainst_init_ver01.ora
 FROM SPFILE = 'spfile.ora';

Alternative I.
What if CREATE PFILE FROM SPFILE fails?
There is an option CREATE PFILE FROM MEMORY.
CREATE PFILE ='$ORACLE_HOME/dbs/mem_pfile.ora
FROM MEMORY;

Alternative II.
use the strings command to transfer binary file to a text file.
cd $ORACLE_HOME/dbs
strings spfile_name > temp_pfile.ora

strings command comment
By default strings command will be looking for sequences of at least 4 printable characters, that are terminated by a NULL character. 
To change the total number of characters that needs to be searched in the binary files, use option -n.
For example:
strings -n 1 spfile_name
Alternative III.
What if CREATE PFILE FROM MEMORY fails?
It possible to manually edit the pfile:
- open the alert_<sid> log.
- locate the  last successful DB startup.
- This section of the file shows all non-default parameters & their values.
- Copy/Paste these lines to pfile.

==============================
CREATE SPFILE 
==============================
CREATE SPFILE FROM PFILE = '$ORACLE_HOME/work/orainst_init.ora';

==============================
Oracle startup from PFILE
==============================
init.ora file would be located here:
${ORACLE_HOME}/dbs/

This is an example of creating a text pfile, and then string Oracle from that text pfile.


Create PFILE from SPFILE, as described above.

SHUTDOWN;
vi init<SID>.ora //Edit the text parameters file.
#spfile='/software/oracle/admin/igt/pfile/spfileigt.ora'


Rename the spfile, so it would not be used upon Oracle startup.

/software/oracle/admin/igt/pfile>% mv spfileigt.ora spfileigt.ora_orig_bak


STARTUP PFILE=
'/home/oracle/product/10.1.0/db1/dbs/init<SID>.ora';

CREATE SPFILE FROM PFILE;

===========================================
Database Won’t Start due to invalid parameter in spfile.
===========================================
The flow:
A. Create pfile from SPFILE
B. Startup Oracle using PFILE
C. Create SPFILE
D. Startup Oracle using SPFILE

Step 1 - Shutdown the database, if not already down, and backup existing SPFILE and PFILE files.
SHUTDOWN IMMEDIATE;

Step 2. - Find the pfile
Default path is for pfile is:
$ORACLE_HOME/dbs/init<SID>.ora

If this file not found, continue to Step 3:

Step 3. - Generate text file from binary SPFILE
See above section, "CREATE PFILE"
CREATE PFILE = '$ORACLE_HOME/dbs/orainst_init_ver01.ora
FROM SPFILE = 'spfile.ora';

Step 4.
Edit the temp_pfile.ora, to resolve the issue that prevented Oracle from starting.

Step 5.
Startup Oracle by:
STARTUP PFILE=$ORACLE_HOME/dbs/temp_pfile.ora

SQL>STARTUP PFILE=/software/oracle/admin/igt/pfile/spfileigt.ora_strings
ORACLE instance started.

Total System Global Area 2147481656 bytes
Fixed Size                  8898616 bytes
Variable Size            1291845632 bytes
Database Buffers          838860800 bytes
Redo Buffers                7876608 bytes
Database mounted.

Database opened.



Step 6
Create a valid SPFILE
CREATE SPFILE FROM PFILE;

spfileigt.ora File created under /software/oracle/193/dbs/

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

Changing SYSTEM Parameter with SCOPE=<SCOPE>
===========================================
To make SYSTEM parameter changes persistent, use SCOPE=<PARAMETER>.
For example:
ALTER SYSTEM SET MAX_SEESIONS=25 SCOPE=SPFILE;

The syntax:
ALTER SYSTEM SET <parameter>=<value> 
                  SCOPE=<memory/spfile/both> 
                  COMMENT=<'comments'> 
                  DEFERRED
                  SID=<sid,*>

SCOPE options:

MEMORY - Changes are active for the current instance only and are lost on restart.

SPFILE - Changes are stored in the SPFILE and are activated on the next startup, the presently active instance is not affected. 
                    This is the way to change static parameters.

BOTH  -     Default.
                  Changes are effective immediately for the present instance and are stored in SPFILE for future startups. 

COMMENT Optional. Free text.

DEFERRED Used to set parameter values for future connecting sessions. 
                      Currently active sessions are not affected and they retain the 
                      old parameter value. 
                      The option is required for parameters that have the 
                      ISSYS_MODIFIABLE column value in V$PARAMETER set to 'DEFERRED'. 
                      It is optional if the ISSYS_MODIFIABLE value is set to 'IMMEDIATE'. 
                      For static parameters, this option is not allowed and cannot be specified.


SID Only for Real Application Clusters. 
          Setting this to a specific SID value changes the parameter value for that particular instance only. 

==============================
How to see contents of SPFILE
==============================

Use strings Linux command

oracle@isr-sdc-1-cgw-1:/software/oracle/admin/igt/pfile>% strings spfileigt.ora
igt.__db_cache_size=201326592
igt.__java_pool_size=4194304
igt.__large_pool_size=4194304
igt.__shared_pool_size=226492416
*.aq_tm_processes=1
*.archive_lag_target=1800
*.background_dump_dest='/software/oracle/admin/igt/bdump'
*.compatible='10.1.0.5.0'
*.control_files='/oracle_db/db1/db_igt/ora_control_01.ctl','/oracle_db/db1/db_igt/ora_control_02.ctl','/oracle_db/db1/db_igt/ora_control_03.ctl'
*.core_dump_dest='/software/oracle/admin/igt/cdump'
*.db_block_size=8192
*.db_cache_size=167772160
*.db_domain=''
*.db_file_multiblock_read_count=16
*.db_keep_cache_size=33554432
*.db_name='igt'
*.disk_asynch_io=true
*.fast_start_mttr_target=180
*.filesystemio_options='asynch'
*.instance_name='igt'
*.job_queue_processes=30
*.log_archive_dest_1='location=/oracle_db/db3/db_igt/arch'
*.log_archive_format='arch%T_%s_%r.arc'
*.log_buffer=157286400
*.nls_length_semantics='char'
*.open_cursors=300
*.open_links=12
*.os_authent_prefix=''
*.pga_aggregate_target=125829120
*.processes=200
*.remote_dependencies_mode='SIGNATURE'
*.remote_login_passwordfile='EXCLUSIVE'
*.SESSION_CACHED_CURSORS=100
*.sga_max_size=943718400
*.sga_target=629145600
*.undo_management='AUTO'
*.undo_retention=3600
*.undo_tablespace='UNDOTBS'
*.user_dump_dest='/software/oracle/admin/igt/udump'
*.utl_file_dir='/software/oracle/admin/igt/utl_file','/software/oracle/admin/igt/utl_file/tap3/files','/software/oracle/admin/igt/utl_file/tap3','/software/oracle/admin/igt/utl_file/tap3/files/mobilkomfiles'
oracle@isr-sdc-1-cgw-1:/software/oracle/admin/igt/pfile>% strings spfileigt.ora_20151208
igt.__db_cache_size=201326592
igt.__java_pool_size=4194304
igt.__large_pool_size=4194304
igt.__shared_pool_size=226492416
*.aq_tm_processes=1
*.archive_lag_target=1800
*.background_dump_dest='/software/oracle/admin/igt/bdump'
*.compatible='10.1.0.5.0'
*.control_files='/oracle_db/db1/db_igt/ora_control_01.ctl','/oracle_db/db1/db_igt/ora_control_02.ctl','/oracle_db/db1/db_igt/ora_control_03.ctl'
*.core_dump_dest='/software/oracle/admin/igt/cdump'
*.db_block_size=8192
*.db_cache_size=167772160
*.db_domain=''
*.db_file_multiblock_read_count=16
*.db_keep_cache_size=33554432
*.db_name='igt'
*.disk_asynch_io=true
*.fast_start_mttr_target=180
*.filesystemio_options='asynch'
*.instance_name='igt'
*.job_queue_processes=30
*.log_archive_dest_1='location=/oracle_db/db3/db_igt/arch'
*.log_archive_format='arch%T_%s_%r.arc'
*.log_buffer=157286400
*.nls_length_semantics='char'
*.open_cursors=300
*.open_links=12
*.os_authent_prefix=''
*.pga_aggregate_target=125829120
*.processes=200
*.remote_dependencies_mode='SIGNATURE'
*.remote_login_passwordfile='EXCLUSIVE'
*.SESSION_CACHED_CURSORS=100
*.sga_max_size=943718400
*.sga_target=629145600
*.undo_management='AUTO'
*.undo_retention=3600
*.undo_tablespace='UNDOTBS'
*.user_dump_dest='/software/oracle/admin/igt/udump'

*.utl_file_dir='/software/oracle/admin/igt/utl_file','/software/oracle/admin/igt/utl_file/tap3/files','/software/oracle/admin/igt/utl_file/tap3','/software/oracle/admin/igt/utl_file/tap3/files/mobilkomfiles'

Create SPFILE and PFILE from memory
CREATE PFILE ='/software/oracle/122/dbs/pfile_from_memory.ora' FROM MEMORY;
CREATE SPFILE = '/software/oracle/122/dbs/spfile_from_memory.ora' FROM MEMORY;
-rw-r--r-- 1 oracle dba     9677 Jul  1 14:11 pfile_from_memory.ora
-rw-r----- 1 oracle dba    22016 Jul  1 14:12 spfile_from_memory.ora


=========================
Create PFILE is giving error ORA-01565: error in identifying file
=========================
SQL> CREATE PFILE='/software/oracle/admin/igt/pfile/pfileigt.ora.20210805_A' FROM SPFILE;
CREATE PFILE='/software/oracle/admin/igt/pfile/pfileigt.ora.20210805_A' FROM SPFILE
*
ERROR at line 1:
ORA-01565: error in identifying file
'/software/oracle/admin/igt/pfile/spfileigt.ora'
ORA-27037: unable to obtain file status
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3

SELECT name, value FROM V$PARAMETER WHERE name = 'spfile'

NAME                 VALUE
-------------------- ------------------------------------------------
spfile               /software/oracle/admin/igt/pfile/spfileigt.ora

The path in parameter spfile is not correct
Actual location of spfile is /software/oracle/112/dbs/spfileigt.ora

To work around this issue, specify exact path to spflie
CREATE PFILE='/software/oracle/admin/igt/pfile/pfileigt.ora.20210805_A' FROM SPFILE='/software/oracle/112/dbs/spfileigt.ora';

File created.

Wednesday, December 24, 2014

ksh and perl by Example: crontab task to find and kill Long Running Oracle Jobs.

General.
Every 15 minutes execute a script that would identify and kill sessions that ran longer than 30 minutes.
This script is launched on Oracle server, as oracle user.

steps
A. crontab task - that runs ksh script every 15 minutes
B. ksh script that launches perl script
C. perl script that connects to DB to find long running queries, and then kills the tasks

crontab -l
0-59/15 * * * * /backup/ora_exp/kill_long_running_jobs.sh

kill_long_running_jobs.sh
#!/bin/bash
. /etc/profile
. /etc/sh/orash/oracle_login.sh igt

perl /backup/ora_exp/kill_long_runing_jobs.pl


kill_long_runing_jobs.pl
#! /usr/bin/perl

use DBI;

use Time::gmtime;
use File::Copy;

####################################################################

#####  Subroutine to get the current date  #########################
####################################################################

sub getDate

{
  use Time::gmtime;
  $tm=gmtime;
  ($second,$minute,$hour,$day,$month,$year) = (gmtime) [0,1,2,3,4,5];
  my $locDate=sprintf("%04d%02d%02d%02d%02d%02d",$tm->year+1900,($tm->mon)+1,$tm->mday,$tm->hour,$tm->min,$tm->sec );
  return $locDate;
}

########################

# main start here ######
########################
my $RetCode;
my $myDate=getDate;
my $logLocation="/backup/ora_exp/";
my $logFile=$logLocation."runLog-".$myDate.".txt";
#unlink $logFile;
my @mailArg;
my $sql;
my $db="orainst";
my $db_driver="dbi:Oracle:".$db;

my $dbh=DBI->connect($db_driver,'user','password',{RaiseError =>1,AutoCommit=>0})|| die "$DBI::errstr";

print $DBI::errstr;

my $sql="select d.spid, c.serial#, a.job, a.failures, b.what, a.this_date, sysdate,a.sid, ROUND((SYSDATE - a.this_date)

* 24 * 60) from dba_jobs_running a,dba_jobs b,v\$session c,v\$process d  where a.job = b.job and a.sid = c.sid and c.pad
dr = d.addr and ((b.what in ('JOB_A.main;', 'JOB_B.main;','JOB_C.main;') and (SYSDATE - a.this_date) * 24 * 60 > 30) OR (b.what in ('JOB_A1.main;','JOB_B1.main;') AND (SYSDATE - a.this_date) * 24 * 60 > 200))";
my $FNsth=$dbh->prepare($sql);
$FNsth->execute();
my @row;
my @temp;
while (@row=$FNsth->fetchrow())
{
  open (MyLog,">>".$logFile);
  print MyLog "----I---- Startting long runing job process for ".$myDate."\n";
  print MyLog "These are the details of the job that has been running for more than 30 minutes: \n";

  print MyLog "SPID: ".$row[0]." \n";

  print MyLog "Job Num: ".$row[2]." \n";
  print MyLog "Job Description: ".$row[4]." \n";
  print MyLog "Start Time: ".$row[5]." \n";
  print MyLog "SID: ".$row[7]." \n";
  print MyLog "Minutes Running: ".$row[8]." \n";

  ##print MyLog "looking for the SPID in the OS: \n";

  #$temp = "ps -ef | grep ".$row[0]." | grep -v grep |";
  $temp = "ps -fp ".$row[0]." |";
  ##print MyLog "Command: ".$temp." \n";

  open(PS,$temp);

  $i=0;
  while (<PS>) {
     chomp;
     @psarray = split(' ',$_,8);
     $pid[$i] = $psarray[1];
     $pname[$i]=$psarray[7];
     if ($i>0) {
        print MyLog $pid[$i]."-->".$pname[$i];
        print MyLog "\n";
         ##print MyLog "TEST: ".substr($pname[$i],0,5)." \n";
         if (substr($pname[$i],0,5) eq "ora_j") {
            open(PS,"kill -9 ".$pid[$i]." |");
           print MyLog "PID #".$pid[$i]." was killed!!! \n";
         }
         else {
           print MyLog "PID #".$pid[$i]." is not an Oracle job! Process was not killed! \n";
        }
     }
     $i++;
  }

  print MyLog "----I---- Process complete. \n";


  close(PS);

}
$FNsth->finish();
$dbh->disconnect;
close MyLog;


=================================
SQL to identify long running jobs
=================================
SELECT PROCESSES.spid, 
       SESSIONS.serial#, 
      DBA_JOBS_RUNNING.job, 
      DBA_JOBS_RUNNING.failures, 
      DBA_JOBS.what, 
      DBA_JOBS_RUNNING.this_date, 
      SYSDATE,
      DBA_JOBS_RUNNING.sid, 
      ROUND((SYSDATE - DBA_JOBS_RUNNING.this_date)* 24 * 60)
  FROM DBA_JOBS_RUNNING DBA_JOBS_RUNNING,
       DBA_JOBS DBA_JOBS,
      V$SESSION SESSIONS,
      V$PROCESS PROCESSES
 WHERE DBA_JOBS_RUNNING.job = DBA_JOBS.job 
   AND DBA_JOBS_RUNNING.sid = SESSIONS.sid 
   AND SESSIONS.paddr = PROCESSES.addr 


=======================================
profile files, not really important for this example...
=======================================
. /etc/profile

# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

pathmunge () {
        if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
           if [ "$2" = "after" ] ; then
              PATH=$PATH:$1
           else
              PATH=$1:$PATH
           fi
        fi
}

# Path manipulation
pathmunge /sbin
pathmunge /usr/sbin
pathmunge /usr/local/sbin
pathmunge /usr/local/bin
pathmunge /usr/X11R6/bin after


# No core files by default
ulimit -S -c 0 > /dev/null 2>&1

USER="`id -un`"
LOGNAME=$USER
MAIL="/var/spool/mail/$USER"

HOSTNAME=`/bin/hostname`
HISTSIZE=1000

if [ -z "$INPUTRC" -a ! -f "$HOME/.inputrc" ]; then
    INPUTRC=/etc/inputrc
fi

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC

for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
        . $i
    fi
done


unset i

. /etc/sh/orash/oracle_login.sh orainst
#!/bin/bash
#
# NAME:
#      oracle_login.sh
# !!!
#
# ABSTRACT:
#           Defining oracle's enironment variables. - Unix version
#
#
# ARGUMENTS:
#           [p1] - oracle sid
#
#       Note - 1) the parameter can be ommitted
#
#
# SPECIAL FILE:
#
# ENVIRONMENT VAR:
#     PROJECT_SID -
#        should be defined in the following way:
#        globaly        - the node run only one oracle instance
#        group login    - there is more than one instance on the current node
#        as a parameter - there is more than one instance per project,
#                         or for system users.
#
# SPECIAL CCC MACROS:
#
# INPUT FORMAT:
#
# OUTPUT FORMAT:
#
# RETURN/EXIT STATUS:
#            1) PROJECT_SID is not defined
#            2) the database PROJECT_SID does not exist
#            3) PROJECT_SID missing from $ORASH/sid.hosts
#            4) ORA_VER missing from $ORASH/sid.hosts
#            5) charcter missing for current sid from $ORASH/charset.dat
#
# LIMITATIONS:
#
# MODIFICATION HISTORY:
# +-------------+-------------------+-----------------------------------------+
# | Date        |     Name          |  Description                            |
# +-------------+-------------------+-----------------------------------------+
# +             +                   +                                         +
# +-------------+-------------------+-----------------------------------------+
if [ "$ORASH" = "" ]; then
   ORASH=$SH_ETC/etc/orash
fi

FACILITY="oracle_login:"
UNAME=`uname | cut -d_ -f1`   #=> Linux

  if [ "$#" -ge 1 ]; then
      PROJECT_SID=$1
   else
      project_sid_def=`set | grep "^PROJECT_SID=" |wc -l`
      if [ "$project_sid_def" -eq 0 ]; then
         echo "<oracle_login> ERROR>> PROJECT_SID is not defined"
         return 1
      fi
   fi

   ORACLE_BASE=/software/oracle
   project_sid_def=`set | grep "^PROJECT_SID=" |wc -l`
   if [ "$project_sid_def" -eq 0 ]; then
         echo "<oracle_login> ERROR>> PROJECT_SID is not defined"
         return 1
   fi

   ORACLE_HOME=`grep ^"$PROJECT_SID": /var/opt/oracle/oratab | awk '{if (NR==1) print $0}' | cut -d: -f2`
   if [ "$ORACLE_HOME" = "" ]; then
      echo "<oracle_login> ERROR>> the database $PROJECT_SID does not exist in /var/opt/oracle/oratab or /etc/oratab"
      return 2
   fi

   ORA_VER=`grep "$PROJECT_SID" $ORASH/sid.hosts | awk '{if (NR==1) print $0}' |cut -d: -f3`
   if [ "$ORA_VER" = "" ]; then
      echo "$FACILITY unable to verify ORA_VER for $PROJECT_SID using $ORASH/sid.hosts"
      return 4
   fi
   DEFAULT_SID=$PROJECT_SID

   ORACLE_SID=$DEFAULT_SID
   TNS_ADMIN=${ORACLE_HOME}/network/admin

#----------------------------------------------------------------#
# the hostname of the DEFAULT_SID appears first in file sid.hosts
#----------------------------------------------------------------#
   HOST=`grep ^"$PROJECT_SID": $ORASH/sid.hosts | awk '{if (NR==1) print $0}' | cut -d: -f2`
   if [ "$HOST" = "" ]; then
      echo "<oracle_login> ERROR>> the database $PROJECT_SID does not exist in $ORASH/sid.hosts"
      return 3
   fi

#-------------------------------------#
#  TWO_TASK is used for a unix clients
#-------------------------------------#
# Disable TWO_TASK feature eliminating the need to change hostname, after disk replication
#   NODE=`hostname`
#   if [ "$NODE" != "$HOST" ]; then
#      TWO_TASK=${DEFAULT_SID}_remote
#   fi

#-------------------------------------#
# setting up NLS_LANG
#-------------------------------------#
   CHARSET=`grep ^"$PROJECT_SID": $ORASH/charset.dat | awk '{if (NR==1) print $0}' | cut -d: -f2`
   if [ "$CHARSET" = "" ]; then
      echo "<oracle_login> ERROR>> the database $PROJECT_SID does not exist in $
ORASH/charset.dat"
      return 5
   fi

   NLS_DATE_FORMAT="DD-MON-RR"
   ORACLE_LPPROG=lpr
   ORACLE_LPARGS="-P la424"
   NLS_LANG="AMERICAN_AMERICA."${CHARSET}
   ORA_NLS32=$ORACLE_HOME/ocommon/nls/admin/data # for oracle
   ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data # for oracle8

   cleaned_path=$PATH
   for ora_path in `grep -v "^#" /var/opt/oracle/oratab | cut -d: -f2 | uniq` ; do
      cleaned_path=`echo -e "${cleaned_path}\c" | tr ':' '\n' | grep -v "$ora_path" | tr '\n' ':'`
   done
   if [ $UNAME = 'SunOS' ] ; then
      cleaned_path=`echo -e "${cleaned_path}\c" | tr ':' '\n' | grep -v "$ora_path" | tr '\n' ':'`
   done
   if [ $UNAME = 'SunOS' ] ; then
     PATH=$cleaned_path:$ORACLE_HOME/bin:/usr/ccs/bin:/usr/openwin/bin
   else
     PATH=$cleaned_path$ORACLE_HOME/bin
   fi

   shlib_def=`set | grep "^LD_LIBRARY_PATH" |wc -l`
   if [ "$shlib_def" -eq 0 ]; then
      LD_LIBRARY_PATH=$ORACLE_HOME/lib:/usr/lib
   else
      cleaned_shlib_path=$LD_LIBRARY_PATH
      for ora_path in `grep -v "^#" /var/opt/oracle/oratab | cut -d: -f2 | uniq` ; do
         cleaned_shlib_path=`echo -e "${cleaned_shlib_path}\c" | tr ':' '\n' | grep -v "$ora_path" | tr '\n' ':'`
      done

      if [ $UNAME = 'SunOS' ] ; then
         LD_LIBRARY_PATH=$cleaned_shlib_path:$ORACLE_HOME/lib:/usr/lib
      else
         LD_LIBRARY_PATH=$cleaned_shlib_path$ORACLE_HOME/lib:/usr/lib
      fi
   fi

   export PROJECT_SID
   export ORACLE_TERM
   export ORACLE_HOME
   export ORACLE_BASE
   export ORACLE_SID
   export TNS_ADMIN
   export ORACLE_SERVER
   export PATH
   export LD_LIBRARY_PATH
   export NLS_LANG
   export ORA_NLS33
   unset ORA_NLS32
   ORACLE_ENV_DEFINED="yes"
   export ORACLE_ENV_DEFINED

   export ORA_VER