31 December 2010

Standby Switchover/Failover Mode

Database Switchover

A database can be in one of two mutually exclusive modes (primary or standby). These roles can be altered at runtime without loss of data or resetting of redo logs. This process is known as a Switchover and can be performed using the following statements:
-- Convert primary database to standby
CONNECT sys/change_on_install@prim1 AS SYSDBA
ALTER DATABASE COMMIT TO SWITCHOVER TO STANDBY;

-- Shutdown primary database
SHUTDOWN IMMEDIATE;

-- Mount old primary database as standby database
STARTUP NOMOUNT PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora
ALTER DATABASE MOUNT STANDBY DATABASE;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE;


-- Convert standby database to primary
CONNECT sys/change_on_install@stby1 AS SYSDBA
ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY;

-- Shutdown standby database
SHUTDOWN IMMEDIATE;

-- Open old standby database as primary
STARTUP PFILE=C:\Oracle\Admin\TSH1\pfile\init.ora
This process has no affect on alternative standby locations. The process of converting the instances back to their original roles is known as a Switchback. The switchback is accomplished by performing another switchover.

Database Failover

Graceful Database Failover occurs when database failover causes a standby database to be converted to a primary database:
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;
ALTER DATABASE ACTIVATE STANDBY DATABASE;
This process will recovery all or some of the application data using the standby redo logs, therefore avoiding reinstantiation of other standby databases. If completed successfully, only the primary database will need to be reinstatiated as a standby database.

Forced Database Failover changes one standby database to a primary database. Application data may be lost neccessitating the reinstantiation of the primary and all standby databases.

18 November 2010

Change location for RMAN backupset

Execute commands below:


crosscheck backup;
delete noprompt expired;

catalog backuppiece ; {repeat this for each backup file}

01 November 2010

How to edit /etc/fstab when at Fedora “Repair filesystem”


I created a separate partition while installing the operating system and mounted it on ‘/data’. Fedora installation does not let you go without specifying the mount point while creating partitions as OS installation time so i did using ‘/data’. I did this for both the machines for cluster and when I configured DRBD for this partition, mount point has been changed.

22 October 2010

ORA-00600: INTERNAL ERROR CODE, ARGUMENTS: [KELTNFY-LDMINIT]

OS: OEL 5.5
RDBMS: Oracle 10.2.0
Before installing Oracle server do all the jobs with server network (ip, host_naming, etc.) in order to avoid getting error above.

21 October 2010

27 September 2010

Standby log errors

Error
FAL[client]: Failed to request gap sequence 
 GAP - thread 1 sequence 2-101
 DBID 2236488982 branch 665833900
FAL[client]: All defined FAL servers have been attempted.

Solution
crosscheck archivelog all;

22 September 2010

SGA exceeds 2GB on Linux 32bit

1. edit init.ora

use_indirect_data_buffers=true 
db_block_size=8192 
db_block_buffers=1048576 # 8Gb
shared_pool_size=1415577600 #2831155200 - 2G

Grant/Revoke object privileges

begin
  for cur in (select do.owner || '.' || do.object_name obj
                from dba_objects do
               where do.owner = 'user1'
                 and do.object_type = 'TABLE') loop
    execute immediate 'grant select on ' || cur.obj || ' to user2';
    --execute immediate 'revoke select on '||cur.obj ||' from user2';
    dbms_output.put_line(cur.obj);
  end loop;
end;

21 September 2010

OEL Installation options

Packages selection
Applications
- Grafical Internet
Development Tools
- Development Libraries
- Development Tools
- GNOME Software Development
- Java Development
- Legacy Software Development
- X Software Development
   Optional Packages
   - libXP-devel
   - openmotif-devel
Base System
- Legacy Software Support
   Optional packages
   - compat-db
- System Tools
   Optional packages
   - sysstat

14 September 2010

Linux kernel parameters for Oracle installation

1) Edit file /etc/sysctl.config
example RAM8Gb
kernel.shmmax = 2147483648 #max RAM
kernel.shmall = 2097152
kernel.shmmni = 4096
kernel.sem = 250 32000 100 128
fs.file-max = 65536
net.ipv4.ip_local_port_range = 1024 65000
net.core.rmem_default=1048576
net.core.rmem_max=1048576
net.core.wmem_default=262144
net.core.wmem_max=262144

06 August 2010

LDAP essentials

LDAP is an acronym that stands for Lightweight Directory Access Protocol.


Oracle is beginning to support and use LDAP. Release 8.1.6 contain an LDAP naming adaptor for Net8. This allows you to define net service names in an LDAP directory instead of the traditional tnsnames.ora file. Another planned use for LDAP in the Oracle world is to support single sign-on. Instead of defining the same user over-and-over again in different databases, you will be able to define a user once in an LDAP directory. Information about a user's roles and privileges will be stored in the directory. The user will authenticate to the directory, and once that has been done, the user will be able to connect to any Oracle database that he has been authorized to use without having to supply a database-specific username and password.

03 August 2010

30 July 2010

Parametrized view

Following is an example which shows use of parametrized view:

CREATE OR REPLACE VIEW test_vw AS
SELECT empno,ename,sal
FROM emp
WHERE empno = to_number(userenv('client_info')) ;

In Stored Procedure, will have to call following procedure before executing the View query, as in following example:

exec dbms_application_info.set_client_info(7934);

select * from test_vw ;

And the output is:

EMPNO ENAME SAL
---------- ---------- ----------
7934 MILLER 13040

05 July 2010

Installation Oracle 10g on Slackware 13.1 Linux

The reason for this actions could be an error has been gotten while installing Oracle on Slackware.
Error description: Failure OS verification
Action: create a file - /etc/redhat-release for OS verification and add something like "Red Hat Enterprise Linux AS release 3 (Taroon)".

09 June 2010

Changing the Database Archiving Mode

1)See the current archiving mode of the database.

select log_mode from v$database;

2)Perform clean shutdown of the database.
shutdown immediate or,
shutdown transactional or,
shutdown normal

You cannot change the mode from ARCHIVELOG to NOARCHIVELOG if any datafiles need media recovery.

How to Enable Flashback Database

To enable flashback database the following operations is needed.


1)Configure the Database in archivelog mode.

To change archiving read, Change Archival Mode

2)Configure Flash Recovery Area.
To configure flash recovery area,
Set up Flash Recovery Area

Set Up a Flash Recovery Area for RMAN

Flash recovery area simplifies the ongoing administration of your database by automatically naming recovery-related files, retaining them as long as they are needed for restore and recovery activities, and deleting them when they are no longer needed to restore your database and space is needed for some other backup and recovery-related purpose.


To see up flash recovery follow below steps.

03 June 2010

Quiescing mode of database state

Quiesced state
Aim: perform DBA actions (compile objects, alter tables ...)
Conditions:
Active non-DBA sessions go on until they are becoming inactive. No active sessions are allowed to be active, but they will be hung. When the database is unquiesced, all hung sessions are resumed and blocking actions are processed. Issued command will wait  for active sessions to become inactive.
RAC: Quiesce affects all instances.
Command:
ALTER SYSTEM QUIESCE RESTRICTED;
ALTER SYSTEM UNQUIESCE;
Control:
V$BLOCKING_QUIESCE - view where DBA can check the info about sessions that are blocking.

02 June 2010

English dictations and listening

There were three dictations had done. (http://www.fonetiks.org/dictations/)
Elementary 2,7,10
2. - done
7. - ... date of expiry ...
10. - ... not very tall and a bit plump..., ... blond hair ..., ... blue eyes ...


There was one listening test had done (http://www.esl-lab.com)


easy phone  messages man 00:34

Answering Machine
Score 80%

31 May 2010

SQL revise (part 2)

Union/Union all


The UNION operator returns results from both queries after eliminating duplications.
The UNION ALL operator returns results from both queries, including all duplications.


The INTERSECT operator returns rows that are common to both queries.
The MINUS operator returns rows in the first query that are not present in the second query.

30 May 2010

Oracle Advanced Queue

Process below describes how to organize queue
Create queue user
Check parameters job_queue_processes and aq_tm_processes (al least - 4 for each)
Create queue table in user scheme above. (Check free rooms in the tablespace)
Create queue (dbms_aqadm.create_queue). Check created queue (user_queue)

29 May 2010

English Idioms

Idioms with foot (engvid.com)
cold feet - hesitate about your decision on the edge on the event (getting married)
to get your foot in the door - make an opportunity to do something/ to get inside
to put your foot in your mouth - confusing situation where you should apologize for
shoe's on the other foot - now you're filing what I'm filing. change places in bad situation.

27 May 2010

TOAD Cyrillic alphabet

[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Nls\CodePage]
"1252"="c_1251.nls"

Recover database

RECOVER (SQL Plus command) repost
Recover a Database, Tablespace, Data or Log file.

Syntax:
Full recovery:
  
   RECOVER [AUTOMATIC] [FROM 'location']
      [STANDBY] DATABASE 
         [UNTIL CANCEL] | [UNTIL TIME date] | [UNTIL CHANGE int] | [USING BACKUP CONTROLFILE]
              [TEST | ALLOW int CORRUPTION ]

   RECOVER [AUTOMATIC] [FROM 'location']
      [STANDBY] DATABASE 
         CANCEL

Grant privileges on columns

Grant privileges

grant update (column1, column2,column3, ...) on table to user_name

26 May 2010

SQL revise

INNER JOIN - find pair of rows of tables satisfied to join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B are combined into a result row.
  1.  explicit
  2.  implicit
  • Explicit
select * from emp inner join dept on (emp.deptno=dept.deptno)
  • Impicit
select * from emp, dept where emp.deptno=dept.deptno
The result of both queries is the same.


28 April 2010

Renaming an Oracle database

The following log shows how a database name was renamed from ORA9 to CAT.
SQL> select name from v$database;

19 April 2010

Oracle hash function

use of function
select dbms_utility.get_hash_value('your string', 999999, 32768) from dual

05 April 2010

Oracle read/write into file

Write to file
declare
  output utl_file.file_type;
  line   varchar2(20000);
begin
--  execute immediate 'alter session set NLS_CHARACTERSET = CL8MSWIN1251';
  output := utl_file.fopen(location => 'directory_name', filename => to_char(sysdate, 'file_name', open_mode => 'A');
  for rec in
    ()
  loop
    line := rec.field1|| '|' || rec.field2 || '|' || rec.field3 || '|' || rec.field4 || '|' || rec.field5;
    utl_file.put(output, line); 
    utl_file.new_line(file => output);
  end loop;
  utl_file.fclose(file => output);
end;


12 March 2010

Tkprof

TKPROF: Yes, it is still used but the FOREGROUND_DUMP_DEST is no longer
used. There is info in the Oracle docs on this. Here is the syntax:

04 March 2010

Восстановить удаленную процедуру в Oracle и т.п.
select text
from dba_source as of timestamp (systimestamp - interval '3' hour) -- interval '5' minute)
where owner =
   and name =
   and type = 'PACKAGE' --'FUNCTION', 'PROCEDURE'
order by name
        , type
        , line;

01 March 2010

Example of how to trace a session and use tkprof

Enable trace for a user session:
SQLPLUS> exec sys.dbms_system.set_sql_trace_in_session(SID, SERIAL, true);
Use tkprof to analyze the trace file:
tkprof [TRACE FILE] [OUTPUT FILE] explain=/ sort=prsela,exeela,fchela
table=ops\$oracle.plan_table 
 

26 February 2010

DB Link
create link on db1 side to db2
If global_name = true then let's db1 has global_name='db1' and db2 has global_name='db2' then dblink name = 'db2'.

alter system set global_names=True
ALTER DATABASE RENAME GLOBAL_NAME TO db_name

25 February 2010

memorize

CREATE OR REPLACE TRIGGER authorize_users_trig
AFTER LOGON ON DATABASE

-- Description: This trigger helps database administrators to
-- control users logging into the database using various client
-- tools and machines. List of USERNAME, OSUSER, PROGRAM and
-- MACHINE entered in table AUTHORIZE_USERS_TAB will only be
-- permitted to login into the database.
-- Ref Oracle Bug No.2628258 and Doc No.2628258.8 in Metalink for
-- using RTRIM(machine,CHR(0)) in the below code.
-- Caveat: When a user tries to connect via SQL*Plus and if the
-- trigger refuses connection, info about that session is shown
-- as INACTIVE in V$SESSION, unless that user closes the SQL*Plus
-- window/session.

DECLARE
p_count NUMBER(1);
BEGIN
SELECT COUNT(*)
INTO p_count
FROM sys.authorize_users_tab
WHERE UPPER(username || osuser || program || RTRIM(machine, CHR(0))) IN
(SELECT UPPER(username || osuser || program ||
RTRIM(machine, CHR(0)))
FROM v$session !
WHERE au dsid = USERENV('sessionid')
AND logon_time =
(SELECT MAX(logon_time)
FROM v$session
WHERE audsid = USERENV('sessionid')));
IF p_count = 0 THEN
RAISE_APPLICATION_ERROR(-20001, '---> Sorry, Access Denied <---');
END IF;
END;
-----------------------------
Ask Tom variant

create or replace trigger trg_no_sys_logon
after logon
on database
declare
v_machine varchar2(30);
v_count number;
begin
select count(machine) into v_count
from host_machine_list
where SYS_CONTEXT('USERENV','HOST') = MACHINE;
If v_count = 0 then
for check_users in(select username
from v$session
where AUDSID = USERENV('SESSIONID')) loop
if upper(check_users.username) in ('SYSTEM')
then
insert into gdemo.dbas_aud3
(
LOGON_TIME
,TERMINAL
,SESSIONID
,INSTANCE
,ENTRYID
,ISDBA
,CURRENT_USER
,CURRENT_USERID
,SESSION_USER
,SESSION_USERID
,PROXY_USER
,PROXY_USERID
,DB_NAME
,HOST
,OS_USER
,EXTERNAL_NAME
,IP_ADDRESS
,NETWORK_PROTOCOL
,AUTHENTICATION_TYPE)
select
SYSDATE
,SYS_CONTEXT('USERENV','TERMINAL') TERMINAL
,SYS_CONTEXT('USERENV','SESSIONID') SESSIONID
,SYS_CONTEXT('USERENV','INSTANCE') INSTANCE
,SYS_CONTEXT('USERENV','ENTRYID') ENTRYID
,SYS_CONTEXT('USERENV','ISDBA') ISDBA
,SYS_CONTEXT('USERENV','CURRENT_USER') CURRENT_USER
,SYS_CONTEXT('USERENV','CURRENT_USERID') CURRENT_USERID
,SYS_CONTEXT('USERENV','SESSION_USER') SESSION_USER
,SYS_CONTEXT('USERENV','SESSION_USERID') SESSION_USERID
,SYS_CONTEXT('USERENV','PROXY_USER') PROXY_USER
,SYS_CONTEXT('USERENV','PROXY_USERID') PROXY_USERID
,SYS_CONTEXT('USERENV','DB_NAME') DB_NAME
,SYS_CONTEXT('USERENV','HOST') HOST
,SYS_CONTEXT('USERENV','OS_USER') OS_USER
,SYS_CONTEXT('USERENV','EXTERNAL_NAME') EXTERNAL_NAME
,SYS_CONTEXT('USERENV','IP_ADDRESS') IP_ADDRESS
,SYS_CONTEXT('USERENV','NETWORK_PROTOCOL') NETWORK_PROTOCOL
,SYS_CONTEXT('USERENV','AUTHENTICATION_TYPE') AUTHENTICATION_TYPE from
dual;
end if;
commit;
end loop;
END IF;
exception
when others then
NULL;
end trg_no_sys_logon_3;

18 February 2010

Trace ORA-04030
Take a dump by setting this event in the INIT file and analyze the trace file. This will clearly pinpoint the problem
event="4030 trace name errorsatck level 3"

Track ORA-04031. Set parameter in INIT file
event="4031 trace name heapdump forever, level=3"

05 February 2010

Killing an Oracle process from inside Oracle

For memory. I'll translate this article later...

I had a following situation few days ago – I was running a CREATE TABLE AS SELECT over a heterogenous services dblink. However I cancelled this command via pressing CTRL+C twice in Windows sqlplus (this actually just kills the client sqlplus and not the call).

Anyway, when I wanted to drop that table involved, this happened:

SQL> drop table MYTABLE;
drop table MYTABLE
*
ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified

I can’t drop a table as someone is holding a lock on it. Fair enough, this was a dev environment used only by me, so I used DBA_OBJECTS.OBJECT_ID to find out the object ID of that table:

SQL> @o MYTABLE

owner object_name object_type CREATED LAST_DDL_TIME status OID D_OID
------------------------- ------------------------------ ------------------ ----------------- ----------------- --------- ---------- ----------
XYZ_DEV01_OWNER MYTABLE TABLE 20080616 11:08:44 20080616 11:08:44 VALID 63764 63764

…and then I queried what enqueue locks were held on that object:

SQL> select * from v$lock where id1=63764;

ADDR KADDR SID TY ID1 ID2 LMODE REQUEST CTIME BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
40034278 40034290 130 TM 63764 0 6 0 2662 0

Ok, I see session 130 holding a TM lock on that table. I queried the corresponding SERIAL# from v$session as well and killed the session:

SQL> alter system kill session '130,8764';
alter system kill session '130,8764'
*
ERROR at line 1:
ORA-00031: session marked for kill

SQL> select * from v$lock where id1=63764;

ADDR KADDR SID TY ID1 ID2 LMODE REQUEST CTIME BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
40034278 40034290 130 TM 63764 0 6 0 2668 0

After hanging for 60 seconds, my kill command gave up (and marked my session for kill), but my lock was still not released… Now what?

This happens when the victim session is so stuck somewhere in an Oracle call that it never has a chance to receive the message it has been killed. And apparently some resources used can in that call can’t be released (for whatever reason, it may be by design, it may just be a bug).

The below queries against V$SESSION and V$LOCK show that even though the session has been marked to be in killed status, it’s still holding a lock:

SQL> @usid 130

USERNAME SID AUDSID OSUSER MACHINE PROGRAM SPID HASH_VALUE LASTCALL STATUS
----------------------- -------------- ----------- ---------------- ------------------ -------------------- ------------ ----------- ---------- --------
XYZ_DEV01_OWNER '130,8764' 33533 1288249 \XYZHOST001 sqlplus.exe 3872 3564023715 4032 KILLED

SQL> select * from v$lock where id1=63764;

ADDR KADDR SID TY ID1 ID2 LMODE REQUEST CTIME BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
40034278 40034290 130 TM 63764 0 6 0 2695 0

Ok, I tried various other options, like kill immediate and disconnect, which should have higher chance to clean up my session properly:

SQL> alter system kill session '130,8764' immediate;
alter system kill session '130,8764' immediate
*
ERROR at line 1:
ORA-00031: session marked for kill

SQL> alter system disconnect session '130,8764' immediate;
alter system disconnect session '130,8764' immediate
*
ERROR at line 1:
ORA-00031: session marked for kill

SQL> select * from v$lock where id1=63764;

ADDR KADDR SID TY ID1 ID2 LMODE REQUEST CTIME BLOCK
-------- -------- ---------- -- ---------- ---------- ---------- ---------- ---------- ----------
40034278 40034290 130 TM 63764 0 6 0 2710 0

Still no luck, lock is there.

So I found the OS PID of my server process (or actually OS Thread ID inside oracle.exe process as I was on Windows) and used oradebug short_stack to check where that process was stuck (the output is slightly formatted):

SQL> oradebug setospid 3872;
Oracle pid: 18, Windows thread id: 3872, image: ORACLE.EXE (SHAD)

SQL> oradebug short_stack;
_ksdxfstk+14<-_ksdxcb+1481<-_ssthreadsrgruncallback+428<-_OracleOradebugThreadStart@4+819 <-7C80B680<-00000000<-71A557C4<-71AB4376<-6298540C<-6298325E<-60A0D931<-609D005F<-609B073D<-609AF9 endExitAgent+202<-_hoxexit+188<-_hogmdis+890<-_hogdisc+8<-_xupidhs+137<-_upidhs+20<-_kpudtch+305 <-_OCIServerDetach+12<-_ncodncf+268<-_npidr0+2300<-_npifcc+46<-_qerrmFBu+457<-_qerrmFetch+1
+1291<-_opiodr+1099<-_rpidrus+178<-_rpidru+88<-_rpiswu2+426<-_rpidrv+1461<-_psddr0+449 <-_psdnal+283<-_pevm_EXIM+153<-_pfrinstr_EXIM+34<-_pfrrun_no_tool+56<-_pfrrun+781<-_plsql_run+738 <-_pr+1099<-_opidrv+819<-_sou2o+45<-_opimai_real+112<-_opimai+92<-_OracleThreadStart@4+726<-7C80B680

This terse stack shows (start reading from bottom right to left) this process is stuck somewhere “above” qerrmFetch (Remote Fetch). I guess the functions starting with “h” above that are heterogenous services functions. By the way, V$SESSION_WAIT didn’t show any wait state changes either and the session itself was still constantly waiting for “HS message to agent” event. So, being stuck in a HS call was probably the reason why that session could not clean itself up.

Now, in such situations one normally would proceed with ORAKILL on Windows or just killing that server process at Unix level (after carefully thinking what you’re about to do). Killing the process makes PMON to perform the cleanup and PMON usually does clean all resources up ok. However I didn’t have access to that Windows server box, so OS kill was out of question.

So, I used another trick. While being connected to the victim process using oradebug, I issued this:

SQL> oradebug event immediate crash;
ORA-00072: process "Windows thread id: 3872, image: ORACLE.EXE (SHAD)" is not active
SQL>

After waiting for a while (crashdump occurred), sqlplus reported that the target process doesn’t exist anymore. Thanks to the crash, PMON had woken up and performed the cleanup.

Let’s see if it helped:

SQL> oradebug short_stack;
ORA-00072: process "Windows thread id: 3872, image: ORACLE.EXE (SHAD)" is not active

SQL> select * from v$lock where id1=63764;

no rows selected

SQL> @usid 130

no rows selected

SQL> drop table MYTABLE;

Table dropped.

Yippee, I finally got rid of that session, lock and could drop my table!

Note that I would still prefer killing the processes with Unix kill or Windows orakill, however there are some bugs with orakill (search in Metalink) that it doesn’t always succeed killing the thread properly. And in my case I didn’t have OS access anyway.

Ideally, the ALTER SYSTEM KILL session command should do all needed cleanup for us, but there are some corner cases involving loops, hangs and bugs where this approach won’t work. There’s a Metalink note 1020720.102 with a list of ways for killing Oracle processes/threads from OS level.