Showing posts with label Steps. Show all posts
Showing posts with label Steps. Show all posts

Saturday, October 20, 2012

Steps - Blackout OS level

--.>To know blockout status:
. oemagent  (connecting to oem env file)
>emctl status blackout

---> complete server blackout
. oemagent
>emctl start blackout "maintenance" -nodelevel    ----> To start blackout
-- emctl stop blackout "maintenance"   ----> To stop blackout
maintenance --- Blackout name
-->To know the perticular db is configured or not in OEM
. oemagent
>emctl config agent listtargets

[xxxx, oracle_database]
....
....

-->To start perticular database blackout
>emctl start blackout "<name>" xxxx:oracle_database  ### to start blackout
>emctl status blackout "<name>"

--> To stop blackout
> emctl stop blackout "<name>"

Steps - OEM Blackout


OEM Blackouts from the GUI and Command Line

Oracle Enterprise Manager provides you with the ability to monitor your environments and alert you once specified thresholds have been reached.  Blackouts allow you to suspend monitoring so you do not get notified.   This is useful for scheduled maintenance windows, such as cold backups, where the application and/or database may not be available.

As well, blackouts also suspends data collection for the given targets.  This means that certain metrics such as availability will not be affected.

To create a blackout from the GUI, login to Enterprise Manager, navigate to the target you would like to blackout and at the bottom of the page under Related Links you will see a Blackouts link.  You will be brought to the following page:



clip_image002

On the screen above you can view any blackouts that may currently be in effect as well as create new ones.  To create a new blackout click on the create button.

clip_image002[8]

On this page you can create a name for the blackout, with the default being “Blackout-<timestamp>”.  You can also select the targets you wish to set the blackout for.   As you can see from the screenshot I am going to set a blackout for an infrastructure application server (infra10g).

You can also provide a reason for the blackout by click on the Reason drop down list.  Quite a few are available, from Server Bounce to Security Patch.    Jobs can be disabled by deselecting the Run jobs during the blackout checkbox.  If your applying a security patch then you may not want a scheduled backup to run as it will either error or cause problems.

clip_image002[10]

The next screen allows you to select which components within the target will be blacked out.  I selected a full blackout but you can select certain members if the outage will only affect specific components.

clip_image002[12]

This screen allows you to schedule the blackout.  It can either start immediately or you can choose a date along with a duration.  Blackouts can be repeating as well, so you only have to create one for that monthly maintenance window for example.

clip_image002[14]

The last screen provides a summary and once you have finished reviewing click on the Finish button.

You can also set blackouts from the command line, which is useful if you have some maintenance scripts which are not executed from Enterprise Managers job system.   I’ve only tested this on linux but it should be the same for windows.

To set a blackout for a list of targets:

emctl start blackout <Blackoutname> [<Target_name>[:<Target_Type>]]…. [-d Duration]

To set a blackout for all targets on a host:

emctl start blackout <Blackoutname> [-nodeLevel] [-d <Duration>]

-nodeLevel tells the agent to stop monitoring all targets on the server.

-d Duration allows you to set a duration in the format of [days] hh:mm.   ex. 1 02:05 means the blackout will last for 1 day, 2 hours and 5 minutes.

For example, to use this in a script in which all targets will be unavailable you would start a blackout at the beginning of the script and stop it at the end:

cd $AGENT_HOME/bin
./emctl start blackout alltargets-myserver –nodeLevel
<Perform Maintenance Tasks>
cd $AGENT_HOME/bin
./emctl stop blackout alltargets-myserver


Troubleshooting

In case you hit issues with blackouts take a look at the following notes:

Subject:     Agent Blackout Initiated By Emctl Command Not Ending      Doc ID:     559577.1

Subject:     EMDiagkit Download and Master Index   Doc ID:     421053.1

Subject:     How to Troubleshoot the EM 10gR1 Blackout Sub-system      Doc ID:     284024.1

Subject:     Troubleshooting Blackouts in EM 10g Grid Control using EMDiag Kit      Doc ID:     300671.1

They provide alot of information and solutions to different scenarios.   I hit an issue over the weekend in which the blackout didn’t end properly.  When I tried to stop it from the command line:

[oracle@myserver ~]$ /u01/app/oracle/product/agent10g/bin/emctl stop blackout alltargets-myserver
Oracle Enterprise Manager 10g Release 3 Grid Control 10.2.0.3.0.
Copyright (c) 1996, 2007 Oracle Corporation.  All rights reserved.
Blackout stop Error : Blackout name alltargets-myserver is invalid


When trying to end the blackout via Enterprise Manager:

Error stopping the blackout on "infra10g": ORA-20710: Agent-side blackouts cannot be edited or stopped ORA-06512: at "SYSMAN.MGMT_BLACKOUT_ENGINE", line 501 ORA-06512: at "SYSMAN.MGMT_BLACKOUT_ENGINE", line 3262 ORA-06512: at "SYSMAN.MGMT_BLACKOUT", line 74 ORA-06512: at "SYSMAN.MGMT_BLACKOUT_UI", line 1167 ORA-06512: at line 1 .

To fix this problem I performed the following:
1. Shutdown the agent on the target server myserver
2. Removed the blackouts.xml file under $AGENT_HOME/sysman/emd
3. Used note 421053.1 to install the EMDiag kit
4. Logged in as sysman on the Enterprise Managers repository database and executed the following query:

select blackout_guid, blackout_name
from mgmt_blackouts;


BLACKOUT_GUID                    BLACKOUT_NAME
-------------------------------- ----------------------
30E2956CA329F0E59FBDF50951F2578E alltargets-myserver


5. Then executed:

exec mgmt_diag.KillBlackout(HEXTORAW(‘30E2956CA329F0E59FBDF50951F2578E’));

6. Restarted the agent on myserver and when I looked in Enterprise manager the blackout had cleared.

I have seen the command used above for some other scenarios but not this one specifically.   Before executing any commands in your environment please test first.

Saturday, July 14, 2012

STEPS - UPGRADING


UPGRADING

Manual upgrade which involves the following steps:

1.Backup the database.
2.In UNIX/Linux environments, set the $ORACLE_HOME and $PATH variables to point to the new 11g Oracle home.
3.Analyze the existing instance using the "$ORACLE_HOME/rdbms/admin/utlu111i.sql" script.
4.Start the original database using the STARTUP UPGRADE command and proceed with the upgrade by running the "$ORACLE_HOME/rdbms/admin/catupgrd.sql" script.
5.Recompile invalid objects.
6.Restart the database.
7.Run the "$ORACLE_HOME/rdbms/admin/utlu111s.sql" script and check the result of the upgrade.
8.Troubleshoot any issues or abort the upgrade.


STEPS - PATCH DOWNLOAD & APPLY


Patch Download
==============
If you are using latest support.oracle.com then after login to metalink Dashboard
- Click on Patches and Updates tab
- On the left sidebar under "Oracle Server/Tools" click on "Latest Patchsets".
- A new window will appear.
- Just mouseover on your product in the "Latest Oracle Server/Tools Patchsets" page.
- Corresponding oracle platform version will appear. Then simply choose the patchset version and click on that.
- You will go the download page. From the download page you can also change your platform and patchset version.

REFERENCES:
http://docs.oracle.com/cd/E11857_01/em.111/e12255/e_oui_appendix.htm
Oracle® Universal Installer and OPatch User's Guide
11g Release 2 (11.2) for Windows and UNIX
Part Number E12255-11

Patch Applying
==============
1. You MUST read the Readme.txt file included in opatch file, look for any prereq. steps/ post installation steps or and DB related changes. Also, make sure that you have the correct opatch version required by this patch.
2.Make sure you have a good backup of database.
3. Make a note of all Invalid objects in the database prior to the patch.
4. Shutdown All the Oracle Processes running from that Oracle Home , including the Listener and Database instance, Management agent etc.
5. You MUST Backup your oracle Home and Inventory
tar -cvf $ORACLE_HOME $ORACLE_HOME/oraInventory | gzip > Backup_Software_Version.tar.gz
6. Unzip the patch in $ORACLE_HOME/patches
7. cd to the patch direcory and do opatch -apply to apply the patch.
8. Read the output/log file to make sure there were no errors.

Patching Oracle Software with OPatch
opatch napply <patch_location> -skip_subset -skip_duplicate
OPatch skips duplicate patches and subset patches (patches under <patch_location> that are subsets of patches installed in the Oracle home).

STEPS - OPATCH Utility


OPATCH Utility (Oracle RDBMS Patching)

1. Download the required Patch from Metalink based on OS Bit Version and DB Version.
2. Need to down the database before applying patch.
3. Unzip and Apply the Patch using ”opatch apply” command.On successfully applied of patch you will see successful message “OPatch succeeded.“, Crosscheck your patch is applied by using “opatch lsinventory” command .
4. Each patch has a unique ID, the command to rollback a patch is “opatch rollback -id  <patch no.>” command.On successfully applied of patch you will see successful message “OPatch succeeded.“, Crosscheck your patch is applied by using “opatch lsinventory” command .
5. Patch file format will be like, “p<patch no.>_<db version>_<os>.zip”
6. We can check the opatch version using “opatch -version” command.
7. Generally, takes 2 minutes to apply a patch.
8. To get latest Opatch version download “patch 6880880 - latest opatch tool”, it contains OPatch directory.
9. Contents of downloaded patches will be like “etc,files directories and a README file”
10. Log file for Opatch utility can be found at $ORACLE_HOME/cfgtoollogs/opatch
11. OPatch also maintains an index of the commands executed with OPatch and the log files associated with it in the history.txt file located in the <ORACLE_HOME>/cfgtoollogs/opatch directory.
12. Starting with the 11.2.0.2 patch set, Oracle Database patch sets are full installations of the Oracle Database software. This means that you do not need to install Oracle Database 11g Release 2 (11.2.0.1) before installing Oracle Database 11g Release 2 (11.2.0.2).
13. Direct upgrade to Oracle 10g is only supported if your database is running one of the following releases: 8.0.6, 8.1.7, 9.0.1, or 9.2.0. If not, you will have to upgrade the database to one of these releases or use a different upgrade option (like export/ import).
14.Direct upgrades to 11g are possible from existing databases with versions 9.2.0.4+, 10.1.0.2+ or 10.2.0.1+. Upgrades from other versions are supported only via intermediate upgrades to a supported upgrade version.

REFERENCES:
OPATCH Utility (Oracle RDBMS Patching)
http://avdeo.com/2008/08/19/opatch-utility-oracle-rdbms-patching/

How to apply Database Patches
http://rafioracledba.blogspot.in/search/label/Database%20Patches

Critical Patch Updates, Security Alerts and Third Party Bulletin
http://www.oracle.com/technetwork/topics/security/alerts-086861.html

Oracle: Quick Guide to Opatch - (Oracle Database Patching utility)
http://www.dbalifeline.com/content/oracle-quick-guide-opatch-oracle-database-patching-utility

How to Design an Effective Patch Management Process
http://www.computing.net/howtos/show/how-to-design-an-effective-patch-management-process/744.html

Oracle Database 11.2.0.2 Patch Set (English)
http://www.dbacomp.com.br/blog/?p=69

Apply Oracle CPUApr2010 – 9352191 for Oracle10.2.0.4 in Aix5L
http://hendrydasan.com/2010/05/21/apply-oracle-cpuapr2010-9352191-for-oracle10-2-0-4-in-aix5l/

Monday, June 25, 2012

Steps - Adding Space to Temporary Tablespace


STEPS - Adding Space to Temporary Tablespace


Set Environment
---------------
export ORACLE_SID=
export ORACLE_HOME=
export PATH=$PATH:$ORACLE_HOME/bin:.


To Check Database
-----------------
set pages 200 lines 170
col HOST_NAME for a15
select instance_name,name db_name,host_name,version db_version from gv$instance,v$database;


TEMP TABLESPACE REPORT
----------------------
SET LINESIZE 145
SET PAGESIZE 9999
SET VERIFY   off


COLUMN tablespace_name       FORMAT a18               HEAD 'Tablespace Name'
COLUMN tablespace_status     FORMAT a9                HEAD 'Status'
COLUMN tablespace_size       FORMAT 999,999,999,999   HEAD 'Size'
COLUMN used                  FORMAT 999,999,999,999   HEAD 'Used'
COLUMN used_pct              FORMAT 999               HEAD 'Pct. Used'
COLUMN current_users         FORMAT 9,999             HEAD 'Current Users'


SELECT
    d.tablespace_name                      tablespace_name
  , d.status                               tablespace_status
  , NVL(a.bytes, 0)                        tablespace_size
  , NVL(t.bytes, 0)                        used
  , TRUNC(NVL(t.bytes / a.bytes * 100, 0)) used_pct
  , NVL(s.current_users, 0)                current_users
FROM
    sys.dba_tablespaces d
  , ( select tablespace_name, sum(bytes) bytes
      from dba_temp_files
      group by tablespace_name
    ) a
  , ( select tablespace_name, sum(bytes_cached) bytes
      from v$temp_extent_pool
      group by tablespace_name
    ) t
  , v$sort_segment  s
WHERE
      d.tablespace_name = a.tablespace_name(+)
  AND d.tablespace_name = t.tablespace_name(+)
  AND d.tablespace_name = s.tablespace_name(+)
  AND d.extent_management like 'LOCAL'
  AND d.contents like 'TEMPORARY'
/


To Find the free space in Temp:
-------------------------------
SELECT   A.tablespace_name tablespace, D.mb_total,
         SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
         D.mb_total - SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_free
FROM     v$sort_segment A,
         (
         SELECT   B.name, C.block_size, SUM (C.bytes) / 1024 / 1024 mb_total
         FROM     v$tablespace B, v$tempfile C
         WHERE    B.ts#= C.ts#
         GROUP BY B.name, C.block_size
         ) D
WHERE    A.tablespace_name = D.name
GROUP by A.tablespace_name, D.mb_total;


Temp Free Space:
----------------
SELECT tablespace_name, SUM(bytes_used)/1024/1024/1024 "used(GB)", SUM(bytes_free)/1024/1024/1024 "free(GB)" FROM V$temp_space_header GROUP BY tablespace_name;


Tempfile location:
------------------
col tablespace_name for a15
col file_name for a35
select TABLESPACE_NAME,file_name,bytes/1024/1024 Size_MB,autoextensible,maxbytes/1024/1024 MAX_MB from dba_temp_files where tablespace_name='TABLESPACENAME' order by 1,2;


Filesystem
----------
$ df -h /tempfile/path/
or
$ df -g /tempfile/path/


Filesystem    GB blocks      Free %Used    Iused %Iused Mounted on


set pages 200 lines 160
spool ./resize.log
set echo on feed on time on term on


To resize a datafile:-
----------------------
alter database tempfile '/tempfile/path/tempfilename.dbf' resize 4096m;
To resize a datafile:-(ASM)
----------------------
ALTER DATABASE TEMPFILE '&FILE_NAME' RESIZE 4096M;


spool off


BEFORE ADDING A DATAFILE WE SHOULD CHECK FOR DUPLICATE DATAFILE
---------------------------------------------------------------
SQL> Select file_name from dba_temp_files where file_name like '%&tempdatafilename%';


set pages 200 lines 160
spool ./add.log
set echo on feed on time on term on


Adding space in temp tablespace:
--------------------------------
ALTER TABLESPACE <temptablespacename> ADD TEMPFILE '/tempfile/path/tempfilename.dbf' SIZE 4096M;


Adding space in temp tablespace:(ASM)
--------------------------------
ALTER TABLESPACE <temptablespacename> ADD TEMPFILE '+DATA' SIZE 64G;


spool off


Take Table Space Report.


"Hope for the best, prepare for the worst"
-Dharmendra

STEPS - Adding Space to Tablespace


Set Environment
-----------------
export ORACLE_SID=
export ORACLE_HOME=
export PATH=$PATH:$ORACLE_HOME/bin:.

To Check Database
---------------------
set pages 200 lines 170
col HOST_NAME for a15
select instance_name,name db_name,host_name,version db_version from gv$instance,v$database;

Table Space Report
---------------------
col tablespace_name format a15
col TABLESPACE_NAME heading "Tablespace|Name"
col Allocated_size heading "Allocated|Size(MB)" form 99999999.99
col Current_size heading "Current|Size(MB)" form 99999999.99
col Used_size heading "Used|Size(MB)" form 99999999.99
col Available_size heading "Available|Size(MB)" form 99999999.99
col Pct_used heading "%Used(vs)|(Allocated)" form 99999999.99
select a.tablespace_name
        ,a.alloc_size/1024/1024 Allocated_size
        ,a.cur_size/1024/1024 Current_Size
        ,(u.used+a.file_count*65536)/1024/1024 Used_size
        ,(a.alloc_size-(u.used+a.file_count*65536))/1024/1024 Available_size
        ,((u.used+a.file_count*65536)*100)/a.alloc_size Pct_used
from     dba_tablespaces t
        ,(select t1.tablespace_name
                ,nvl(sum(s.bytes),0) used
          from  dba_segments s
               ,dba_tablespaces t1
          where t1.tablespace_name=s.tablespace_name(+)
          group by t1.tablespace_name) u
        ,(select d.tablespace_name
                ,sum(greatest(d.bytes,nvl(d.maxbytes,0))) alloc_size
                ,sum(d.bytes) cur_size
                ,count(*) file_count
          from dba_data_files d
          group by d.tablespace_name) a
where t.tablespace_name=u.tablespace_name
  and t.tablespace_name=a.tablespace_name
order by t.tablespace_name;

Datafiles of a particular TableSpace
-------------------------------------
set pages 200
set lines 175
col tablespace_name for a27
col file_name for a70
select tablespace_name,file_name,bytes/1024/1024 Size_MB,autoextensible,maxbytes/1024/1024 MAX_MB from dba_data_files  where tablespace_name='TABLESPACENAME' order by 1,2;

ASM Space Report
--------------------
SET LINESIZE 150
SET PAGESIZE 9999
SET VERIFY off
COLUMN group_name             FORMAT a20           HEAD 'Disk Group|Name'
COLUMN sector_size            FORMAT 99,999        HEAD 'Sector|Size'
COLUMN block_size             FORMAT 99,999        HEAD 'Block|Size'
COLUMN allocation_unit_size   FORMAT 999,999,999   HEAD 'Allocation|Unit Size'
COLUMN state                  FORMAT a11           HEAD 'State'
COLUMN type                   FORMAT a6            HEAD 'Type'
COLUMN total_mb               FORMAT 999,999,999   HEAD 'Total Size (MB)'
COLUMN used_mb                FORMAT 999,999,999   HEAD 'Used Size (MB)'
COLUMN pct_used               FORMAT 999.99        HEAD 'Pct. Used'

SELECT
    distinct name                                     group_name
  , sector_size                              sector_size
  , block_size                               block_size
  , allocation_unit_size                     allocation_unit_size
  , state                                    state
  , type                                     type
  , total_mb                                 total_mb
  , (total_mb - free_mb)                     used_mb
  , ROUND((1- (free_mb / total_mb))*100, 2)  pct_used
FROM
    gv$asm_diskgroup
ORDER BY
    name;
/

OTHER ASM QUERIES
--------------------------
select distinct name, total_mb/1024 , (total_mb-free_mb)/1024 , free_mb/1024, SYSDATE from GV$ASM_DISKGROUP;

select GROUP_NUMBER,NAME,TOTAL_MB,FREE_MB from gv$asm_diskgroup order by NAME;
select table_name from dict where table_name like '%ASM%';
select GROUP_NUMBER,DISK_NUMBER,TOTAL_MB,FREE_MB,NAME,MOUNT_STATUS from v$asm_disk;
select INST_ID,GROUP_NUMBER,DISK_NUMBER,TOTAL_MB,FREE_MB,NAME,MOUNT_STATUS from gv$asm_disk;

Filesystem
-----------
$ df -h /datafile/path/
or
$ df -g /datafile/path/

Filesystem    GB blocks      Free %Used    Iused %Iused Mounted on

set pages 200 lines 160
spool ./resize.log
set echo on feed on time on term on

To resize a datafile
-------------------
alter database datafile '/datafile/path/datafilename.dbf' resize 4096m;

To resize a datafile  (ASM)
----------------------------
ALTER DATABASE DATAFILE '&FILE_NAME' RESIZE 4096M;

spool off;

BEFORE ADDING A DATAFILE WE SHOULD CHECK FOR DUPLICATE DATAFILE
------------------------------------------------------------------------------------------------
For datafile
-----------
select file_name from dba_data_files where file_name like '%&datafilename%';

set pages 200 lines 160
spool ./add.log
set echo on feed on time on term on

To add a new datafile in a tablespace
--------------------------------------
alter tablespace <TABLESPACE NAME> add datafile '/datafile/path/datafilename.dbf' size 4096m;

To add a new datafile in a tablespace  (ASM)
-----------------------------------------------
ALTER TABLESPACE <TABLESPACE NAME> ADD DATAFILE '+DATA' SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE UNLIMITED;

To Create a new tablespace
-----------------------------
create tablespace <TABLESPACE NAME> datafile '/datafile/path/datafilename.dbf' size 4096m;

To Create a new tablespace  (ASM)
--------------------------------------
CREATE TABLESPACE <TABLESPACE NAME> DATAFILE '+DATA' SIZE 100M AUTOEXTEND ON NEXT 100M MAXSIZE UNLIMITED;

To Create a new tablespace with multipple datafiles
----------------------------------------------------
create tablespace <TABLESPACE NAME> datafile '/datafile/path/datafilename_01.dbf' size 4096m;
alter tablespace <TABLESPACE NAME> add datafile '/datafile/path/datafilename_02.dbf' size 4096m;

spool off;

Take Table Space Report.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Tablespaces that are >=80% full, and how much to add to make them 80% again
---------------------------------------------------------------------------
set pages 999 lines 100
col    "Tablespace"    for a50
col    "Size MB"     for 999999999
col    "%Used"     for 999
col    "Add (80%)"     for 999999
select    tsu.tablespace_name "Tablespace"
,    ceil(tsu.used_mb) "Size MB"
,    100 - floor(tsf.free_mb/tsu.used_mb*100) "%Used"
,    ceil((tsu.used_mb - tsf.free_mb) / .8) - tsu.used_mb "Add (80%)"
from    (select tablespace_name, sum(bytes)/1024/1024 used_mb
    from    dba_data_files group by tablespace_name) tsu
,        (select ts.tablespace_name
    ,       nvl(sum(bytes)/1024/1024, 0) free_mb
    from    dba_tablespaces ts, dba_free_space fs
    where   ts.tablespace_name = fs.tablespace_name (+)
    group by ts.tablespace_name) tsf
where    tsu.tablespace_name = tsf.tablespace_name (+)
and    100 - floor(tsf.free_mb/tsu.used_mb*100) >= 80
order    by 3,4
/

"Hope for the best, prepare for the worst"
-Dharmendra

Tuesday, June 19, 2012

Monday, June 18, 2012

STEPS - SCHEMA REFRESH


@ Source

========
connect to Putty
enter the hostname
select load

enter userid and pwd

set the environment for the database
$ uname
AIX
$ cat /etc/oratab
export ORACLE_SID=DBNAME
export ORACLE_HOME=/usr/app/oracle/product/10.2.0/
export PATH=$PATH:$ORACLE_HOME/bin

$ uname
SunOS
$ cat /var/opt/oracle/oratab
export ORACLE_SID=DBNAME
export ORACLE_HOME=/usr/app/oracle/product/10.2.0/
export PATH=$PATH:$ORACLE_HOME/bin

To Check Database

---------------------
sqlplus "/as sysdba"
set pages 200 lines 170
col HOST_NAME for a15
select instance_name,name db_name,host_name,version db_version from gv$instance,v$database;


select username from dba_users where username=upper('&username');
select sum(bytes)/1024/1024/1024 from dba_segments where owner=upper('&owner');
select object_type,count(*) from dba_objects where owner=upper('&username') group by object_type;


Table Space Report
---------------------
col tablespace_name format a15
col TABLESPACE_NAME heading "Tablespace|Name"
col Allocated_size heading "Allocated|Size(MB)" form 99999999.99
col Current_size heading "Current|Size(MB)" form 99999999.99
col Used_size heading "Used|Size(MB)" form 99999999.99
col Available_size heading "Available|Size(MB)" form 99999999.99
col Pct_used heading "%Used(vs)|(Allocated)" form 99999999.99
select a.tablespace_name
        ,a.alloc_size/1024/1024 Allocated_size
        ,a.cur_size/1024/1024 Current_Size
        ,(u.used+a.file_count*65536)/1024/1024 Used_size
        ,(a.alloc_size-(u.used+a.file_count*65536))/1024/1024 Available_size
        ,((u.used+a.file_count*65536)*100)/a.alloc_size Pct_used
from     dba_tablespaces t
        ,(select t1.tablespace_name
                ,nvl(sum(s.bytes),0) used
          from  dba_segments s
               ,dba_tablespaces t1
          where t1.tablespace_name=s.tablespace_name(+)
          group by t1.tablespace_name) u
        ,(select d.tablespace_name
                ,sum(greatest(d.bytes,nvl(d.maxbytes,0))) alloc_size
                ,sum(d.bytes) cur_size
                ,count(*) file_count
          from dba_data_files d
          group by d.tablespace_name) a
where t.tablespace_name=u.tablespace_name
  and t.tablespace_name=a.tablespace_name
order by t.tablespace_name;

Datafiles of a particular TableSpace
-------------------------------------
set pages 200
set lines 175
col tablespace_name for a27
col file_name for a70
select tablespace_name,file_name,bytes/1024/1024 Size_MB,autoextensible,maxbytes/1024/1024 MAX_MB from dba_data_files  where tablespace_name='TABLESPACENAME' order by 1,2;



ASM Space Report
--------------------
SET LINESIZE 150
SET PAGESIZE 9999
SET VERIFY off
COLUMN group_name             FORMAT a20           HEAD 'Disk Group|Name'
COLUMN sector_size            FORMAT 99,999        HEAD 'Sector|Size'
COLUMN block_size             FORMAT 99,999        HEAD 'Block|Size'
COLUMN allocation_unit_size   FORMAT 999,999,999   HEAD 'Allocation|Unit Size'
COLUMN state                  FORMAT a11           HEAD 'State'
COLUMN type                   FORMAT a6            HEAD 'Type'
COLUMN total_mb               FORMAT 999,999,999   HEAD 'Total Size (MB)'
COLUMN used_mb                FORMAT 999,999,999   HEAD 'Used Size (MB)'
COLUMN pct_used               FORMAT 999.99        HEAD 'Pct. Used'

SELECT
    distinct name                                     group_name
  , sector_size                              sector_size
  , block_size                               block_size
  , allocation_unit_size                     allocation_unit_size
  , state                                    state
  , type                                     type
  , total_mb                                 total_mb
  , (total_mb - free_mb)                     used_mb
  , ROUND((1- (free_mb / total_mb))*100, 2)  pct_used
FROM
    gv$asm_diskgroup
ORDER BY
    name;
/

OTHER ASM QUERIES
--------------------------
select distinct name, total_mb/1024 , (total_mb-free_mb)/1024 , free_mb/1024, SYSDATE from GV$ASM_DISKGROUP;

select GROUP_NUMBER,NAME,TOTAL_MB,FREE_MB from gv$asm_diskgroup order by NAME;
select table_name from dict where table_name like '%ASM%';
select GROUP_NUMBER,DISK_NUMBER,TOTAL_MB,FREE_MB,NAME,MOUNT_STATUS from v$asm_disk;
select INST_ID,GROUP_NUMBER,DISK_NUMBER,TOTAL_MB,FREE_MB,NAME,MOUNT_STATUS from gv$asm_disk;


col file_name for a70
set linesize 150
set pagesize 100
select file_name,bytes/1024/1024 from dba_data_files where tablespace_name='TABLESPACENAME' order by file_name;
FILE_NAME                                                    BYTES/1024/1024
------------------------------------------------------------ ---------------
/FILE/LOCATION/

Check for the space availability for taking backup:
>! df -h /FILE/LOCATION/

cd /source/backup/location/
mkdir EXPORT_REF_NO
cd EXPORT_REF_NO
$pwd
/source/backup/location/EXPORT_REF_NO

NOTE: If the size is less better to go for EXP/IMP

A. For schema backup (EXPDP/IMPDP)
create or replace directory <EXPDPDIR> as '/directory/location/';
Directory created.

GRANT read,write ON DIRECTORY <EXPDPDIR> to <user>;
Grant succeeded.

nohup expdp <user>/`pwd` logfile=schemaname.log directory=EXPDPDIR dumpfile=schemaname_`date +\%b\%d`_%U.dmp schemas=schemaname exclude=statistics PARALLEL=4 &
For schema backup (EXP/IMP)

B. For schema backup (EXP/IMP)
nohup exp <user>/`pwd` file=source_schemaname_exp.dmp log=source_schemaname_exp.log owner=schemaname statistics=NONE resumable=y resumable_name=continue resumable_timeout=18000 &

Check the status of EXPORT:

$jobs or $ps -ef| grep expdp or $ps -ef| grep exp or ps -ef|grep <processid>
[1]+  Running
[1]+  Done
$ls -lrt
source_schemaname_exp
$cat source_schemaname_exp.log

@ Target
========
connect to Putty
enter the hostname
select load

enter userid and pwd

set the environment for the database


To Check Database

---------------------
sqlplus "/as sysdba"
set pages 200 lines 170
col HOST_NAME for a15
select instance_name,name db_name,host_name,version db_version from gv$instance,v$database;


select username from dba_users where username=upper('&username');
select sum(bytes)/1024/1024/1024 from dba_segments where owner=upper('&owner');
select object_type,count(*) from dba_objects where owner=upper('&username') group by object_type;


Check for the space availabilty for taking backup:
df -h
cd /target/backup/location/
mkdir EXPORT_REF_NO
cd EXPORT_REF_NO
$pwd
/target/backup/location/EXPORT_REF_NO

NOTE: If the size is less better to go for EXP/IMP

A. For schema backup (EXPDP/IMPDP)
create or replace directory <EXPDPDIR> as '/directory/location/';
GRANT read,write ON DIRECTORY <EXPDPDIR> to <user>;

nohup expdp <user>/`pwd` logfile=schemaname.log directory=EXPDPDIR dumpfile=schemaname_`date +\%b\%d`_%U.dmp schemas=schemaname exclude=statistics PARALLEL=4 &

B. For schema backup (EXP/IMP)
nohup exp <user>/`pwd` file=target_schemaname_exp.dmp log=target_schemaname_exp.log owner=schemaname statistics=NONE resumable=y resumable_name=continue resumable_timeout=18000 &

Check the status of EXPORT:
$jobs or $ps -ef| grep exp
$ls -lrt
target_schemaname_exp.log
$cat target_schemaname_exp.log

@ Source
========
scp source_schemaname_exp.dmp oracle@target_hostname:/target/backup/location/EXPORT_REF_NO/

@ Target
========
cd /target/backup/location/EXPORT_REF_NO/
ls -lrt
source_schemaname_exp.dmp

sqlplus "/as sysdba"
select name from v$database;

DROP SCHEMA OBJECTS
-------------------
set head off
set pagesize 0
set linesize 100
select 'drop table '||Table_name||' cascade constraints;' from user_tables;

set pagesize 200
select 'drop '||object_type||' '||object_name||';' from user_objects where object_type not in ('DATABASE LINK');

or

spool target_schemaname_drop_obj.sql
select 'drop '||object_type||' '||owner||'.'||object_name||DECODE(OBJECT_TYPE,'TABLE',' CASCADE CONSTRAINTS;',';')
from dba_objects
where owner in ('SCHEMANAME') and OBJECT_TYPE not in ('DATABASE LINK') order by object_type,object_name;
spool off;

OTHERS
------
select 'DROP '||decode(object_type, 'PACKAGE BODY', 'PACKAGE',object_type)|| ' '||owner||'.'||object_name|| decode(object_type,'TABLE',' CASCADE CONSTRAINTS;',';')
from dba_objects
where owner=upper('&Schema')
--and object_type not in ('TABLE');

exit

ls -lrt
target_schemaname_drop_obj.sql
vi target_schemaname_drop_obj.sql
edit and save using :wq

sqlplus "/as sysdba"
select name from v$database;

@target_schemaname_drop_obj.sql

schema object count:
select object_type,count(*) from dba_objects where owner=upper('&username') group by object_type;
exit

pwd
/target/backup/location/EXPORT_REF_NO/

ls -lrt
source_schemaname_exp.dmp

Restore schema backup:
---------------------
A. For schema import (EXPDP/IMPDP)
nohup impdp system/`pwd` logfile=source_schemaname_exp_import.log directory=EXPDPDIR remap_schema=sourceschemaname:targetschemaname dumpfile=source_schemaname_exp.dmp exclude=statistics PARALLEL=4 &

B. For schema import (EXP/IMP)
nohup imp system/`pwd` file=source_schemaname_exp.dmp log=source_schemaname_exp_import.log fromuser=schemaname touser=schemaname ignore=y statistics=NONE commit=y resumable=y resumable_name=continue resumable_timeout=18000 &

Check the status of IMPORT:
$jobs or $ps -ef| grep imp
$ls -lrt
$cat source_schemaname_exp_import.log

sqlplus "/as sysdba"
select name from v$database;
schema object count:
select object_type,count(*) from dba_objects where owner=upper('&username') group by object_type;

NOTE: THE TARGET SCHEMA OBJECT COUNT SHOULD BE SAME AS THE SOURCE SCHEMA OBJECT COUNT CAPTURED

DBLINKS DETAILS
---------------
set pages 100 lines 150
col owner for a15
col username for a15
col host for a35
col created for a20
select owner, db_link, username, host, to_char(created,'dd-mon-yyy hh24:mi:ss') CREATED from dba_db_links order by owner, db_link;
OWNER           DB_LINK                             USERNAME        HOST                                CREATED
--------------- ----------------------------------- --------------- ----------------------------------- --------------------
exit

Gather schema stats after schema refresh
----------------------------------------
set timing on
exec dbms_stats.gather_schema_stats(ownname=>'schemaname',CASCADE=>TRUE,ESTIMATE_PERCENT=>30,degree =>4);

NOTE: ONCE TASK COMPLETED AT PRODUCTION SERVER IMMEDIATLY DO EXIT.



"Hope for the best, prepare for the worst"
-Dharmendra

Sunday, June 10, 2012

STEPS - DATABASE REFRESH

Database refresh with EXP/IMP & EXPDP/IMPDP 

===================================
Backup
======
Backup must be taken in the source side at the backup location using EXPORT or EXPDP.If required, at target side too.

EXP/IMP
----------
Full Database export
nohup exp <userid>/<password>  file=filename.dmp log=filename.log CONSISTENT=Y full=y &

Pre-checks
========
SOURCE SIDE & TARGET SIDE (STEP 1 AND STEP2)
============================================
step 1:
------
source and target users must me same.
NOTE: Otherwise, create new user in target side before import

To Check Database
---------------------
sqlplus "/as sysdba"
set pages 200 lines 170
col HOST_NAME for a15
select instance_name,name db_name,host_name,version db_version from gv$instance,v$database;

SQL>select count(*) from dba_users;
SQL>select username from dba_users;

step 2:
------
source and target tablespaces must be same and check the space avilabilty too.
NOTE: Otherwise, need to create new tablespace in target side before import

Tablespace size including pct free
----------------------------------
select
   fs.tablespace_name                          "Tablespace",
  df.totalspace                               "TOT_SIZE",
  fs.freespace                                "TOT_FREE",
  (round(100 * (fs.freespace / df.totalspace))) pct_Free
from
   (select      tablespace_name,
      round(sum(bytes) / 1048576) TotalSpace
   from
      dba_data_files
   group by
      tablespace_name
   ) df,
   (select
      tablespace_name,
      round(sum(bytes) / 1048576) FreeSpace  
   from
      dba_free_space
   group by
      tablespace_name  ) fs
where   (df.tablespace_name = fs.tablespace_name ) ORDER BY pct_free DESC ;

Target side
===========
step 3:
------
passwords bkp:
-------------
select 'alter user '||username||' identified by values '||password||';' from dba_users; --10g

select 'alter user '||name||' identified by values '||password||';' from SYS.USER$;  --11g

Before droping all users take DDL of each user in the target.
set long 100000
select dbms_metadata.get_ddl('USER','USERNAME') from dual;

Before droping user:(super Script---> colecting all grants of user):
--------------------------------------------------------------------
set long 100000

select dbms_metadata.get_ddl('USER',upper('&username')) from dual;
select dbms_metadata.get_granted_ddl( 'SYSTEM_GRANT', upper('&username') ) from dual;
select DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT',upper('&username')) FROM dual;
select GRANTEE,TABLE_NAME from dba_tab_privs where GRANTEE=upper('&username');
select dbms_metadata.get_granted_ddl( 'ROLE_GRANT', upper('&username')) from dual;

Drop the all users except the default users (sys,system,DBSNMP,OUTLN,DIP,TSMSYS,)
DROP USER <USERNAME> CASCADE

OTHER QUERIES
-----------------------
SELECT 'alter system kill session ''' || SID || ',' || serial# || ''' immediate;' FROM v$session where username=upper('&username') and status ='INACTIVE';

SELECT 'alter system kill session ''' || SID || ',' || serial# || ''' immediate;' FROM v$session where username=upper('&username') and status ='ACTIVE';

select sid,username,terminal,program,logon_time,status from v$session where username=upper('&username');

select SID,USERNAME,STATUS from v$session where status='ACTIVE';

step 4:
------
create all users using DDLs taken before.

step 5:
------
EXP/IMP
-------
Full Database import
nohup imp <userid>/<password>  file=filename.dmp log=filename.log buffer=2000000 full=y &

step 6:
------
Take DDL of all users in the target.


Gather schema stats after schema refresh
----------------------------------------
set timing on

set long 100000
select dbms_metadata.get_ddl('USER','USERNAME') from dual;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


EXPDP/IMPDP
-----------------
create or replace directory <EXPDP_DIR> as '/location/of/directory';
grant read,write ON DIRECTORY <EXPDP_DIR> to <USER>;

select * from dba_directories;

Full Database export
nohup expdp <userid>/<password> directory=<EXPDP_DIR> logfile=filename.log dumpfile=dumpfile_`date +\%b\%d`_%U.dmp PARALLEL=6 full=y &

Full Database import
nohup impdp userid=<userid>/<password> directory=<EXPDP_DIR> logfile=filename.log dumpfile=filename.dmp PARALLEL=6 full=y &

Pre-checks
----------
All steps same as EXP/IMP.

NOTE: Before doing Full database refresh with EXP/IMP & EXPDP/IMPDP, need to confirm with requestor whether they need Full database refresh or only some schemas refresh.


NOTE: ONCE TASK COMPLETED AT PRODUCTION SERVER IMMEDIATLY DO EXIT. 

"Hope for the best, prepare for the worst"
-Dharmendra