Thursday, May 15, 2014

SQL Query Tuning Tips

SQL Query Tuning Tips

Here are some very simple yet powerful SQL tips to remember.

  • Avoid using the following:
  •  Boolean operators >, <, >=, <=, is null,is not null.
  •  Not in, !=
  •  Like '%pattern', not exists
  •  Calculations on unindexed columns or (use union instead)
  •  Having (use a WHERE clause instead)
  •  Do use the following:
• Enable aliases to prefix all columns
• Place indexed columns higher in the WHERE clause
• Use SQL Joins instead of using sub-queries
• Make the table with the least number of rows the driving table by making it first in the FROM clause
Other important points for SQL Tuning:
• Establish a tuning environment that reflects your production  database.
• Establish performance expectations before you begin
• Always Design and develop with performance in mind
• Create Indexes to support selective WHERE clauses and join conditions.
• Use concatenated indexes where appropriate
• Consider indexing more than you think you should, to avoid table lookups.
• Pick the best join method.
• Nested loops joins are best for indexed joins of subsets.
• Hash joins are usually the best choice for "big" joins.
• Pick the best join order.
• Pick the best "Driving" table.
• Eliminate rows as early as possible in the join order
• Use bind variables. Bind variables are key to application scalability.
• Use Oracle hints where appropriate.
• Compare performance between alternative syntax for your SQL statement.
• Consider utilizing PL/ SQL to overcome difficult SQL tuning issues.
• Consider using third party tools to make the job of SQL tuning easier.
• Never do a calculation on an Indexed column (e.g., WHERE salary*5 > :myvalue).
• Whenever possible, use the UNION statement instead of OR conditions.
• Avoid the use of NOT IN or HAVING in the WHERE clause. Instead, use the NOT EXISTS clause.
• Always specify numeric values in numeric form and character values in character form (e.g., WHERE
emp_number = 565, WHERE emp_name = ‘Jones’).
• Avoid specifying NULL in an indexed column.
• Avoid the LIKE parameter if = will suffice. Using any Oracle function will invalidate the index, causing a full-table scan.
• Never mix data types in Oracle queries, as it will invalidate the index. If the column is numeric,
remember not to use quotes (e.g., salary = 50000). For char index columns, always use single quotes (e.g., name = ‘BURLESON’).
• Avoid using subqueries when a JOIN will do the job.
• Use the Oracle “decode” function to minimize the number of times a table has to be selected.
• If your query will return more than 20 percent of the rows in the table, a full-table scan may be better than an index scan.
• Always use table aliases when referencing columns.
• To turn off an index you do not want to use (only with a cost-based optimizer), concatenate a null string to the index column name (e.g., name||') or add zero to a numeric column name (e.g., salary+0).
With the rule-based optimizer, this allows you to manually choose the most selective index to service your query. These rules may seem simplistic but following them in a diligent manner will generally relieve more than half of the SQL tuning problems that are experienced:
Remember that Oracle’s rule-based optimizer looks at the order of table names in the FROM clause to determine the driving table. Always make sure that the last table specified in the FROM clause is the table that will return the smallest number of rows. In other words, specify multiple tables with the largest result set table specified first in the FROM clause.
SQL Query Tuning Tips
Efficient SQL statements play a very important role in maintaining the database. They not only improve the performance of the database but also help in reducing the network traffic. The following can be stated as some of the tips for tuning SQL statements used to retrieve data from the database:
1. Know your application and business data well: Before writing our SQL statements, we need to familiarize ourselves with different business data sources. We must be aware of the data volume and its distribution in the database along with thorough understanding of the business data model – such as relationships among business entities.
2. Test your queries with realistic data: After writing an SQL statement, we must test it in an environment which reflects the production database. The behavior of the SQL statement depends a lot on the environment wherein it is tested.
3. Write identical SQL statements in your applications: Use bind variables, stored procedures and packages whenever possible. The benefits of using identical SQL statements include reduced memory use on the database server and faster execution, as parsing is not done.
4. Use indexes carefully on the table: Be sure of creating the necessary indexes on the table used in the SQL statement. But creating too many of them may result in performance degradation of the server. Try to follow the below rules in creating indexes on a table:
1. Create indexes on the columns which are frequently used in the WHERE clause of the application SQL or the queries given by the end users.
2. Index those columns which are frequently used in joining tables in SQL statements.
3. Use only index columns that select small percent of rows with the same value.
4. Do not index the columns which are used with functions and operators in the WHERE clause of the SQL statement.
5. Do not index those columns which get modified frequently as the index maintenance will become an issue during execution of DML statements on the table.
6. Unique indexes are better than non-unique indexes due to better selectivity. Create unique indexes on PK columns and non-unique indexes on FK columns and the columns frequently used in the WHERE clause.
7. Create index so that the column used in the WHERE clause make up a leading portion of the index.
5. Make an indexed path available to SQL: Sometimes even after creating the indexes, they won’t get used in the execution of the query. One of the different ways of making the indexed path available to the optimizer is to use SQL hints.
6. Use Explain Plan and TKPROF wherever possible: These are the tools that come along with Oracle server and help in understanding the execution of our SQL statements. Explain Plan – helps us to know the access path the optimizer opted. TKPROF – shows the actual performance statistics of the SQL statement.
7. Understand the Optimizer: SQL statement can be executed using rule-based optimizer or cost-based optimizer. In older applications, Oracle has used rule-based approach whereas in newer applications, oracle is promoting more of cost-based approach. If you opt to use cost-based approach, then it is necessary to run ANALYZE schema regularly as doing that stores the recent database statistics in the data dictionary views which are used by the cost-based optimizer. The SQL query can tuned only if cost based approach is opted for.
8. Think globally when acting locally: Keep in mind that the modifications you do to improve the
performance of one SQL statement affects other SQL statements used by applications or other users.
9. The WHERE clause is crucial: The following can be said to be some of the cases where the WHERE
clause will not use index even if it is created on a column. The index is created on column COL1 but it
wont be used in the below illustrated examples.
1. COL1 < COL2
2. COL1 > COL2
3. COL1 <= COL2
4. COL1 >= COL2
5. COL1 is null – The index does not store null values hence when queries for null values index won’t get
used
6. COL1 is not null – The index does not store null values hence when queries for null values index won’t
get used.
7. COL1 not in (value1, value2...)
8. COL1 != expression1
9. COL1 like ‘%pattern1’ – index is not used in this case as the leading edge of the index is suppressed;
but whereas if queried as COL1 like ‘pattern1%’, then index is used as they would result in a bounded
range index scan
10. Not exists (subquery)
11. Expression1 = expression2 – All expressions, functions or calculations involving indexes column
would prohibit using the index on that column.
10. Use WHERE clause instead of HAVING clause to filter the records : Using an indexed column in
HAVING clause of the query to filter records will result in full table scan and avoid the usage on the index
on that column. Instead first filter the records using WHERE clause to filter the records which makes use
of the index on the column. Below queries illustrate the usage of index, if an index is created on DEPTID
column of EMP table.
1. Select dept_id, sum(salary) from emp group by dept_id having dept_id = 100;
2. Select dept_id, sum(salary) from emp where  dept_id = 100 group by dept_id;
In case a) Query will not use the index created on dept_id column whereas case b) query makes use of
it.
11. Specify the leading index columns: In case of a compound index, it is used in an SQL query only if the
leading column of it is used. Below queries are used to illustrate the same with an assumption of a
compound index (PART_NUM, PRODUCT_ID) existing on the table PARTS.
1. Select * from parts where part_num = 2;
2. Select * from parts where product_id = 1002;
Case a) would use the index as the column used in the query WHERE clause is a leading column of the
compound index; whereas case b) query would not use the index. If incase of case b), you want to make
use of index we can re-write the query in the following way:
Select * from party where part_num > 0 and product_id = 1002;
12. Evaluate index scan v/s full table scans: If selecting more than 15 percent of the records from a table, it is better to use/force a full table scan on the table for such query. When using an index does more harm than good to the query, we can use techniques the following to suppress the usage of
index.
1. Select /*+ full(a)*/ * from emp where salary = 5000;
A full hint forces the full table scan on the table and avoids the usage of index on salary column.
2. Select * from emp where salary + 0 = 5000;
The salary column in WHERE clause is modified to an expression which results in avoiding the usage of index on the column.
3. Select * from emp where salary = ‘5000’;
An implicit conversion on the indexed column results in avoiding the index usage.
4. Select * from emp where ss# ||’  ‘|| = ‘111-222-333’;
When the percentage of table rows accessed is 15 percent or less, an index scan will work better because it results in multiple logical reads per row accessed, whereas a full table scan can read all the rows in a block in one logical read. Thus, the performance of full table scan is better when accessing a large percentage of rows from a table.
            To illustrate this point, say the ANALYZE command is issued against the EMP table and all its indexes. Oracle generates the following statistics in the data dictionary table USER_TABLES and
USER_INDEXES:
          Table Statistics:
NUM_ROWS = 1000
BLOCKS = 100
Index Statistics:
BLEVEL = 2
AVG_LEAF_BLOCKS_PER_KEY = 1
AVG_DATA_BLOCKS_PER_KEY = 1
            Based on these statistics, the following would be the logical reads (block accessed) for different types of scans:        
  Use of index to return one row = 3
(BLEVEL+(AVG_LEAF_BLOCKS_PER_KEY - 1) + AVG_DATA_PER_KEY)
Use of index to return all rows = 3000
                                        (NUM_ROWS * Blocks accessed to return one row using index)
 Full table scan = 100(BLOCKS)
13. Use an ORDER BY clause for index scan: Oracle optimizer uses an index scan if the ORDER BY clause is used on an indexed column. The query would retrieve ROWID from index and access the table using the ROWID.
14. Know thy data: You need to know the data and its distribution in your database server in order to understand the usage of indexes on the columns and their execution. You need to keep in mind that the SQL query performance varies as the database grows and data distributions changes.
15. Know when to use large-table scans: A full table scan provides better performance when compared to an index scan on a very small table or a very large table. An index scan on a very large table may require scanning of many indexes and table blocks. When these blocks are brought to database buffer cache, they are kept as long as possible. But as these are not needed for other queries, the hit ratio of the database buffer declines resulting in performance degradation. The blocks read by a full table scan are removed from database buffer cache much earlier does not hamper the performance as an index scan on a very large table.
16.   Minimize the table access (passes): Usually by reducing the number of table passes in a SQL statement improves the performance.
     Here’s an example to illustrate the same:
            The STUDENT table has four columns named NAME, STATUS, PARENT_INCOME, and SELF_INCOME. The name is the primary key. The values of the STATUS column are 0 for independent students and 1 for dependent students.
            The following query returns the name and income for dependent as well as independent
students. It results in two passes through the STUDENT table, creates a temporary table for processing, and initiates a sort to eliminate duplicates:
          SELECT NAME, PARENT_INCOME
FROM STUDENT
WHERE STATUS = 1
UNION
SELECT NAME, SELF_INCOME
FROM STUDENT
WHERE STATUS = 0;
The same request can be fulfilled by this query, which results in only one pass through the table:
          SELECT NAME, PARENT_INCOME*STATUS + SELF_INCOME (1-STATUS)
FROM STUDENT;
17. Join tables in the proper order: The order in which the tables are joined in a multiple table join is crucial. Perform the most restrictive search first in order to filter out the maximum number of rows and only a few records are processed in further levels. You need to make sure that the driving table (master table in a master-detail join) returns the least number of rows. For cost-based optimizer, the order in which the tables appear in WHERE clause is irrelevant as it picks the best execution plan on its own. We can use the ORDERED hint to control the order in which
the tables are accessed in the execution plan.
18. Use index-only searches whenever possible: If possible, write the queries that use index-only searches. The optimizer will have to search only index and not the full table to satisfy the SQL resulting in improving the performance. For example, a compound index exists on L_NAME and F_NAME columns
in EMP table.
1. Select f_name from emp where l_name = ‘Smith’;
2. Select f_name, salary from emp where l_name = ‘Smith’;
In Case a) query, the optimizer performs an index-only search whereas in case b) query, the optimizer performs a table search in order to get the data for a column – salary which is not a part of the compound index. Hence we need to observe the column list considered in the SELECT clause as well while writing a query.
19. Redundancy is good: Provide as much information as possible in the WHERE clause of the query. If in
a WHERE clause of a query, there is COL1 = Col2 and Col1 = 10 then the optimizer infers that COL2 = 10.
But at if there is a condition like COL1 = COL2 and COL2 = COL3, then the optimizer does not infer it as
COL1 = COL3.
20. Keep it simple, stupid: Make your SQL statements as simple as possible as simple statements yield better performance than a single complex SQL statement. The lower the Explain Plan Cost of an SQL, the better the performance of the query. Hence we need to try to tune our queries to reduce the cost as much as possible.
21. You can reach the same destination in different ways: In many cases, more than one SQL can provide with the same desired results. Each query uses a different plan and performs differently. For example,
the use of MINUS operator may perform faster than the use of NOT IN or NOT EXISTS predicates. If an
SQL involves an OR in the WHERE clause, we can re-write the same by using a UNION. Hence we need to evaluate all the possible queries for a requirement and choose the best access path query.
22. Use the special columns: Make use of the special columns like ROWID and ROWNUM in your queries. ROWID searches are faster than searches performed on any columns. A ROWID is not a constant in the database; hence do not hard-coded the value in your SQLs and applications.
23. Use explicit cursors over implicit cursors: Implicit cursors are opened by Oracle for DELETE, UPDATE,
SELECT and INSERT and use an extra fetch. Explicit cursors are opened by developers using DECLARE,
PEN, FETCH and CLOSE cursor statements.
24. Explore and take advantage of the oracle parallel query option: Using the parallel query option, you can execute SQL in parallel for faster performance. This parallel query option can be used only in SMP and MPP systems containing multiple disk drivers. The Oracle database has to be configured for this feature to be used and SQLs specific for that feature should be written.
25. Reduce the network traffic and increase throughput: Using array processing and PL/SQL blocks can achieve better performance and reduce the network traffic. Array processing allows a single SQL to process multiple rows. Using arrays in an insert, we can insert 1000 rows in a table. Significance performance gain can be achieved in client/servers and batch systems using this technique. Multiple
SQL statements can cause heavy network traffic. However, if the SQL statements are in a  single PL/SQL block, the entire block can be sent to Oracle server, processed there and results returned to the application running on the client.

Saturday, March 22, 2014

EBS R12.2: Add Managed Servers (oacore, oafm, forms, forms-c4ws)


EBS R12.2 : add managed server oacore,oafm,forms,forms-c4ws

By default there is single Web Application Services in EBS 12.2



If you want to increase number of server either oacore, oafm, forms or forms-c4ws then below instruction need to follow. In below example we are adding one more oacore server.

To check current edition:
echo $FILE_EDITION

Follow below steps to add oacore services

Step 1: Take backup of $CONTEXT_FILE from both edition

Step 2: Run script on run edition:
[applmgr@ebs122 ~]$ perl $AD_TOP/patch/115/bin/adProvisionEBS.pl ebs-create-managedserver 
-contextfile=/apps01/applmgr/TEST/fs2/inst/apps/TEST_ebs122/appl/admin/TEST_ebs122.xml 
-managedsrvname=oacore_server2 -servicetype=oacore -managedsrvport=7203 -logfile=/tmp/oacore2.log
Enter the APPS Schema password:
Enter the WebLogic AdminServer password:

The logfile for this session is located at /tmp/oacore2.log

Check the logfile for any error message.

[applmgr@ebs122 ~]$ vi /tmp/oacore2.log

Step 3: Run autoconfig on run edition 

[applmgr@ebs122 ~]$ adautocfg.sh
Enter the APPS user password:
AutoConfig completed successfully.

Step 4: [applmgr@ebs122 ~]$ perl $FND_TOP/patch/115/bin/txkSetAppsConf.pl -ctxfile=$CONTEXT_FILE -outfile=/tmp/txkSetAppsConf.log
mod_wl_ohs.conf generated successfully

apps.conf generated successfully


Step 5: Stop/start http services on run edition
[applmgr@ebs122 ~]$ cd $ADMIN_SCRIPTS_HOME
[applmgr@ebs122 scripts]$ adapcctl.sh stop

You are running adapcctl.sh version 120.0.12020000.2

Stopping OPMN managed Oracle HTTP Server (OHS) instance ...
opmnctl stopproc: stopping opmn managed processes...

adapcctl.sh: exiting with status 0

[applmgr@ebs122 scripts]$ adapcctl.sh start

You are running adapcctl.sh version 120.0.12020000.2

Starting OPMN managed Oracle HTTP Server (OHS) instance ...
opmnctl start: opmn is already running.
opmnctl startproc: starting opmn managed processes...

adapcctl.sh: exiting with status 0


Now add oacore server info intoPATCH edition:

Step 6: Set patch edition env
[applmgr@ebs122 ~]$ echo $FILE_EDITION

patch

Step 7:
Start up the WebLogic Administration Server of the PATCH file system by executing the below command on the PATCH file system 

[applmgr@ebs122 scripts]$ adadminsrvctl.sh start forcepatchfs                   
You are running adadminsrvctl.sh version 120.10.12020000.2

Enter the WebLogic Admin password:
Enter the APPS Schema password:
Starting WLS Admin Server...
Refer /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/logs/appl/admin/log/adadminsrvctl.txt for details

adadminsrvctl.sh: exiting with status 0

adadminsrvctl.sh: check the logfile /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/logs/appl/admin/log/adadminsrvctl.txt for more information 

Step 8: From Run Addition execute below script with service name and port number

[applmgr@ebs122 scripts]$ perl $AD_TOP/patch/115/bin/adProvisionEBS.pl ebs-create-managedserver 
-contextfile=$CONTEXT_FILE -managedsrvname=oacore_server2 -servicetype=oacore -managedsrvport=7204 -logfile=\tmp\oacore2_2.log
Enter the APPS Schema password:
Enter the WebLogic AdminServer password:

Step 9: 
[applmgr@ebs122 scripts]$ perl $AD_TOP/bin/adSyncContext.pl 
-contextfile=/apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/appl/admin/TEST_ebs122.xml
Enter the APPS user password:
Enter the WebLogic AdminServer password:
The log file is /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/logs/appl/rgf/Sun_Jan_5_15_14_03_2014/adSyncContext.log

Step 10: 
Instantiate the fsclone_config.txt file on the PATCH file system of all Application tier nodes by running the following command after sourcing the RUN file system:

java oracle.apps.ad.autoconfig.InstantiateFile -e -tmpl  \
/admin/template/fsclone_config_txt.tmp -out  \
/appl/admin/fsclone_config.txt
[applmgr@ebs122 scripts]$ java oracle.apps.ad.autoconfig.InstantiateFile -e /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/appl/admin/TEST_ebs122.xml -tmpl  /apps01/applmgr/TEST/fs1/EBSapps/appl/ad/12.0.0/admin/template/fsclone_config_txt.tmp -out  /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/appl/admin/fsclone_config.txt
Enter the APPS password : APPS

Step 11:
Execute below script from RUN file system
On the node containing the Oracle HTTP Server, execute the following script from the RUN file system, passing the context file from the PATCH file system. This will update the Oracle HTTP Server configuration files on the PATCH file system with the new managed server port number.

[applmgr@ebs122 scripts]$ perl $FND_TOP/patch/115/bin/txkSetAppsConf.pl -ctxfile=/apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/appl/admin/TEST_ebs122.xml \
> -outfile=/tmp/oacore2_3.log
mod_wl_ohs.conf generated successfully

apps.conf generated successfully

Step 12: Stop weblogic services from PATCH file system:
[applmgr@ebs122 scripts]$ adadminsrvctl.sh stop

You are running adadminsrvctl.sh version 120.10.12020000.2

Enter the WebLogic Admin password:
Enter the APPS Schema password:
Stopping WLS Admin Server...
.Refer /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/logs/appl/admin/log/adadminsrvctl.txt for details

adadminsrvctl.sh: exiting with status 0

adadminsrvctl.sh: check the logfile /apps01/applmgr/TEST/fs1/inst/apps/TEST_ebs122/logs/appl/admin/log/adadminsrvctl.txt for more information 

Step 13: Start newly added managed server from run edition:

admanagedsrvctl.sh start oacore_server2

Step 14: Check the status of server weblogic console:

Saturday, January 4, 2014

WebLogic Startup Mode: Development or Production


Differences

Startup Mode
Development                    Production
Auto deployment
(to admin server only)
YesNo
Automatically created
boot.properties for Admin server only under
$DOMAIN_HOME/servers/$SERVER_NAME/security 
YesNo
Nodemanger username and password
default admin
credentials
randomly
generated
SSL demo certificates cause warning in log files
NoYes
Log file are rotated at server startup
YesNo
On demand deployment of internal applications as default
YesNo
Availability of web service test client
YesNo
Availability of Classloader Analysis Tool
YesNo
Availability of Fast Swap
YesNo
Change Center Enabled
NoYes
Default start parameters
when using Sun JDK and the default
startWebLogic script 
java
-client
-Xms256m
-Xmx512m
-XX:CompileThreshold=
8000
-XX:PermSize=128m
-XX:MaxPermSize=256m
java
-server
-Xms256m
-Xmx512m
-XX:MaxPermSiz=256m
The following settings in the weblogic.xml deployment descriptors default to -1:
NoYes
Differences in previous WebLogic versions:
Up to WebLogic 11:
Default JDK used for new domain
SunJRockit
Up to WebLogic 8 only:
Default number of execute threads
1525
Up to WebLogic 8 only:
maximum number of JDBC connections default setting
1525




Configuration

There is different ways to configure the WebLogic startup mode:
  1. The startup mode can be configured with the admin console, as shown on the screenshot below (requires a restart). Once it’s set to production mode it cannot be reverted with the admin console.
  2. Supply the -Dweblogic.ProductionModeEnabled=true switch as startup parameter
  3. Set the PRODUCTION_MODE variable in the setDomainEnv script in the directory DOMAIN_NAME/bin.

What you should know

Some issues to be aware of:
  • The differences between the two settings depend on the WebLogic version. This can be a bit confusing when you are running different environments with different versions. See the table above: For WebLogic 8 the maximum number of connections in a JDBC connection pool defaults to 25 in production mode (but 15 in development mode); for WebLogic 12c it defaults to 15 in both cases.
  • You cannot revert to development mode from the WebLogic admin console. It’s like the child-proof lock in the back of your car. I understand that is makes sense to protect the children in the back seat your car from themselves but you are are logged with the admin role – still you cannot revert to development mode using the admin console.
  • Autodeployment is not used that much anymore since it only deploys to the admin server – so it doesn’t make sense for a production domain. What if you are a developer? Then your IDE is deploying to the admin server, that is correct – but your IDE is typically not using autodeployment.
  • Note, that there will be a randomly set user and password for nodemanager when creating your domain in production mode with config.sh (see comments from Jacco).
  • You cannot disable the change center in production mode

HOW TO RECOVER WEBLOGIC ADMIN PASSWORD


There is another smart way to get past this problem of "lost weblogic admin password" , what it does is

"INSTEAD OF TRYING TO RECOVER THE ORIGINAL PASSWORD,
https://recover-weblogic-password.appspot.com/
   1) ADD ANOTHER ADMIN USER
   2) LOGIN TO CONSOLE
   3) CHANGE THE PASSWORD OF ORIGINAL USER


These three steps are much faster to execute and a smarter approach i would say. Also it involves less user mistakes.

Here is the step by step guide

Note : replace the $DOMAIN_HOME with the actual path in your environment,.


1) shutdown the domain ( All managed servers & then admin)


2) backup your $DOMAIN_HOME/security folder in case u need it


cd $DOMAIN_HOME 
tar cvf security.tar security

3) set the environment

$cd $DOMAIN_HOME/bin
$ . ./setDomainEnv.sh 

Note : dont forget the first dot(.) 

4) change to security folder & Add the new admin user using the below command after setting the environment

$ cd ../security    ( important step, otherwise you will get IO exception) 

$java weblogic.security.utils.AdminAccount adminuser1 welcome1 .

Note : there is a dot (.) at the end of the command
this will add the user adminuser1 as the administrator.

5)  remove the below file from ldap directory


rm $DOMAIN_HOME/servers//data/ldap/DefaultAuthenticatormyrealmInit.initialized
6)  start the server using startWebLogic.sh

Note : do not use the boot.properties file .. or a wrapper script at the first time


7) login to the console and change the password of the original admin user

******************************************************************

How to decrypt WebLogic passwords with WLST

Sooner or later you will find the situation where you do not remember any of the WebLogic Server password’s stored in the configuration files.

Some examples are:
a) The WebLogic Server administrator credentials (username and password) stored in the files config.xml and boot.properties
b) Node Manager password, stored also in the config.xml file (if you still have the default password, don’t wait and change it know!!)
c) Database password used by the JDBC Data Sources and stored in the file [DOMAIN_HOME]/config/jdbc/[datasource_name].xml

So, how to decrypt this data in 3 easy steps. Just follow this techtapa recipe:

Ingredients:
- 1 WLST script
- The path of the WebLogic Server domain
- The encrypted field, for example, username and password from boot.properties

Preparation:
1. Copy this WLST script (you can also download it here).


import os
import weblogic.security.internal.SerializedSystemIni
import weblogic.security.internal.encryption.ClearOrEncryptedService

def decrypt(domainHomeName, encryptedPwd):
    domainHomeAbsolutePath = os.path.abspath(domainHomeName)
    encryptionService = weblogic.security.internal.SerializedSystemIni.getEncryptionService(domainHomeAbsolutePath)
    ces = weblogic.security.internal.encryption.ClearOrEncryptedService(encryptionService)
    clear = ces.decrypt(encryptedPwd)
    print "RESULT:" + clear

try:
    if len(sys.argv) == 3:
        decrypt(sys.argv[1], sys.argv[2])
    else:
  print "INVALID ARGUMENTS"
  print " Usage: java weblogic.WLST decryptPassword.py DOMAIN_HOME ENCRYPTED_PASSWORD"
  print " Example:"
  print " java weblogic.WLST decryptPassword.py D:/Oracle/Middleware/user_projects/domains/base_domain {AES}819R5h3JUS9fAcPmF58p9Wb3syTJxFl0t8NInD/ykkE="
except:
    print "Unexpected error: ", sys.exc_info()[0]
    dumpStack()
    raise

2. Set your environment (CLASSPATH, PATH,..). Open a console, go to [FMW_HOME]/wlserver_10.3/server/bin/ and run the script setWLSEnv.sh:
$ . ./setWLSEnv.sh

3.Run the script. Go to the path where you copied the WLST script ( decryptPassword.py) and run it. You must provide two arguments, the WebLogic Server domain Home full path and the string you want to decrypt, for example:

$ java weblogic.WLST decryptPassword.py /opt/oracle/Middleware/user_projects/domains/base_domain {AES}LU5dLPP0PliNb5Ml1Fo7rD2AbNFwLcyLtYUEDTb+8zY\=

$ java weblogic.WLST decryptPassword.py /XXXXX/applmgr/fs2/FMW_Home/user_projects/domains/EBS_domain_xx122i {AES}Cb3qjo8vUPVBkkxMH3FSiIm4HJXC+RdQ5CjzRoHGPdE=

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

RESULT:weblogic123

Enjoy it!!

Tuesday, May 21, 2013

Oracle RAC Physical Standby DataGuard Creation

Oracle RAC Physical Standby DataGuard Creation


The following article describes how to create an Oracle RAC 11gR2 physical standby database with Active DataGuard real-time apply enabled on Linux. This procedure can easily be modified for any other supported platform. Creating a standby database as RAC directly from primary RAC, rather than standalone, saves time and prevents potential issues, while converting from standalone to RAC. In addition, the following approach ensures the proper placement of database files at the standby ASM disk groups.

Both systems are using ASM for storage. The storage layout is identical between the primary and the standby databases. System, data, redo log, and fast recovery area are located on separate ASM disks for performance and recoverability reasons.
The source and target databases are 2-node Oracle RAC 11gR2. Maintaining standby database as RAC with Active DataGuard and a real-time apply feature allows using it for reading, backup, and testing by converting it over to a snapshot standby database and back after the completion.

The following are the names and their meaning used in this article.

Name
Description
MY_DB_DOMAIN
Database domain name
MYDB
Database name
STNDBY
Unique database name
stndbyhost1, stndbyhost2
Standby hosts
STNDBY1, STNDBY2
Standby instances
PRIMARY1, PRIMARY2
Primary instances
primaryhost1, primaryhost2
Primary hosts
-vip
Host’s virtual IP
primary-grid-scan-name
Primary RAC Grid SCAN
standby-grid-scan-name
Standby RAC Grid SCAN
ASM_diskN
ASM disk name N
Oracle Grid should already be installed and running on all of the standby hosts. Oracle database software should also be installed on all of the standby hosts. All the prerequisites should have been completed for both environments for the Oracle physical standby DataGuard configuration.
The following are the actual steps needed for this process.
1. Prepare the primary database
a. Ensure that the database is in archivelog mode
SQL > SELECT LOG_MODE FROM V$DATABASE;
  LOG_MODE
  ------------
  ARCHIVELOG
b. Enable force logging, so that all database changes are logged
SQL > ALTER DATABASE FORCE LOGGING;
c. Create standby redo logs
SQL > ALTER DATABASE ADD STANDBY LOGFILE THREAD 1 GROUP 5 '' SIZE  GROUP 6 '' SIZE  GROUP 7 '' SIZE ;
SQL > ALTER DATABASE ADD STANDBY LOGFILE THREAD 2 GROUP 8 '' SIZE  GROUP 9 '' SIZE  GROUP 10 '' SIZE ;
 
Where and specify the location and size of log files
Note the following when creating standby redo logs:
  • The quantity is determined by (maximum # of logfile groups +1) * maximum # of threads.
  • Must be the same size as online redo logs.
  • Should not be multiplexed.
2. Create $ORACLE_HOME/dbs/initSTNDBY1.ora on stndbyhost1 to start an auxiliary database instance.
*.db_domain='MY_DB_DOMAIN'
*.db_name='MYDB'
*.db_unique_name='STNDBY'
Note: delete spfileSTNDBY1.ora if one exists.
3. Create adump directory on stndbyhost1 and stndbyhost2.
CMD > mkdir -p $ORACLE_BASE/admin/STNDBY/adump
4. Create and start a temporary listener with static service information on stndbyhost1 in database home.
Edit $ORACLE_HOME/network/admin/listener.ora as follows:
SID_LIST_LISTENER_DBCLONE =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = STNDBY.MY_DB_DOMAIN)
      (ORACLE_HOME = $ORACLE_HOME)
      (SID_NAME = STNDBY1)
    )
  )
    
  LISTENER_DBCLONE =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL=TCP)(HOST = stndbyhost1)(PORT = 1521))
      )
    )
  )
Start the listener.
CMD > lsnrctl start LISTENER_DBCLONE
5. Add standby database to $ORACLE_HOME/network/admin/tnsnames.ora on primaryhost1.
This entry points to the listener in the previous step.
STNDBY1 =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = stndbyhost1-vip)(PORT = 1521))
    (CONNECT_DATA = (UR=A)
      (SERVER = DEDICATED)
      (SERVICE_NAME = STNDBY.MY_DB_DOMAIN)
    )
  )
Note: (UR=A) is needed to connect to a BLOCKED unmounted database instance.
6. Modify and reload the standby grid listeners with static service information for the standby database.
Edit $GRID_HOME/network/admin/listener.ora on both standby hosts and add the following configuration.
stndbyhost1
LISTENER =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL=IPC)(KEY=LISTENER))
      (ADDRESS = (PROTOCOL = TCP)(HOST = stndbyhost1-vip)(PORT = 1521))
    )
  )
 
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = STNDBY.MY_DB_DOMAIN)
      (ORACLE_HOME = $ORACLE_HOME)
      (SID_NAME = STNDBY1)
    )
  )
stndbyhost2
LISTENER =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = stndbyhost2-vip)(PORT = 1521))
    )
  )
 
SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = STNDBY.MY_DB_DOMAIN)
      (ORACLE_HOME = $ORACLE_HOME)
      (SID_NAME = STNDBY2)
    )
  )
7. Reload the grid listeners on stndbyhost1 and stndbyhost2.
CMD > lsnrctl reload
8. Copy the password file from primaryhost1 to stndbyhost1 and stndbyhost2.
CMD > scp $ORACLE_HOME/dbs/orapwMYDB1 stndbyhost1:$ORACLE_HOME/dbs/orapwSTNDBY1
    CMD > scp $ORACLE_HOME/dbs/orapwMYDB1 stndbyhost2:$ORACLE_HOME/dbs/orapwSTNDBY2
9. Add instance name to /etc/oratab.
Add STNDBY1 instance name to /etc/oratab on stndbyhost1 and STNDBY2 on stndbyhost2 and set the environment. Note that command line starts with dot “.” to make the environment values permanent.
CMD >. oraenv
10. Start the standby database in nomount state on stndbyhost1.
CMD > sqlplus / as sysdba
SQL > startup nomount
SQL > exit
11. Duplicate the database from primaryhost1.
Note: standby database name STNDBY1 matches to the one in step 4.
Parameter notes:
  • db_create_file_dest and db_recovery_file_dest must be reset in order for all the files to be placed at the same location on destination as on the source.
  • cluster_database must be initially disabled, because duplication works with one node only.
  • remote_listener is required to register the database with SCAN listener.
Allocate multiple primary channels, as the primary work is performed by target channels.
CMD > rman target=sys@PRIMARY1 auxiliary=sys@STNDBY1
     
run
{
allocate channel prmy1 type disk;
allocate channel prmy2 type disk;
allocate channel prmy3 type disk;
allocate channel prmy4 type disk;
allocate auxiliary channel stby type disk;
 
DUPLICATE DATABASE FOR STANDBY FROM ACTIVE DATABASE
NOFILENAMECHECK
SPFILE
  PARAMETER_VALUE_CONVERT 'MYDB','STNDBY'
  SET db_unique_name='STNDBY'
  SET db_file_name_convert='/MYDB/','/STNDBY/'
  SET log_file_name_convert='/MYDB/','/STNDBY/'
  SET fal_server='(DESCRIPTION = (LOAD_BALANCE = ON)(ADDRESS = (PROTOCOL = TCP)(HOST = primary-grid-scan-name)(PORT = 1521))(CONNECT_DATA = (SERVICE_NAME = MYDB.MY_DB_DOMAIN)))'
  SET standby_file_management='AUTO'
  SET log_archive_config='dg_config=(STNDBY,MYDB)'
  SET log_archive_dest_1='LOCATION=use_db_recovery_file_dest', 'valid_for=(ALL_ROLES,ALL_LOGFILES)'
  SET log_archive_dest_2='service="(DESCRIPTION = (LOAD_BALANCE = ON)(ADDRESS = (PROTOCOL = TCP)(HOST = primary-grid-scan-name)(PORT = 1521))
(CONNECT_DATA = (SERVICE_NAME = MYDB.MY_DB_DOMAIN)))"',
'LGWR ASYNC NOAFFIRM delay=0 optional compression=disable max_failure=0 max_connections=1 reopen=300 db_unique_name="MYDB" net_timeout=30',
'valid_for=(all_logfiles,primary_role)'
  SET log_archive_dest_state_2='enable'
  SET remote_listener='standby-grid-scan-name:1521'
  SET cluster_database='false'
  RESET db_create_file_dest
  RESET db_recovery_file_dest
;
}
exit
12. Set standby database parameters.
The following parameters were reset before the duplication and should be set now.
Run the following on the stndbyhost1, while replacing “+ARCH” and “+APP” with your own values:
SQL > ALTER SYSTEM SET db_recovery_file_dest='+ARCH';
SQL > ALTER SYSTEM SET db_create_file_dest='+APP';
SQL > ALTER SYSTEM SET cluster_database=true SCOPE=spfile;
SQL > ALTER SYSTEM RESET db_file_name_convert;
SQL > ALTER SYSTEM RESET log_file_name_convert;
13. Create pfile from spfile on stndbyhost1.
CMD > cd $ORACLE_HOME/dbs
SQL > CREATE pfile='p.ora' FROM spfile;
Edit pfile as follows:
  • Remove parameter local_listener, if one exists.
  • Replace all parameter prefixes MYDB[N] with STNDBY[N], while keeping parameter values.
14. Create spfile on ASM from pfile created in the previous step.
SQL > CREATE spfile='+SYS/STNDBY/spfileSTNDBY.ora' FROM pfile='p.ora';
15. Prepare the standby database on stndbyhost1.
a. Shutdown the standby database and listener LISTENER_DBCLONE on stndbyhost1.
b. Rename or delete $ORACLE_HOME/network/admin/listener.ora, as it was used for duplication only.
16. Create initialization file on the stndbyhost1.
a. Remove spfile from $ORACLE_HOME/dbs.
b. Replace the contents of $ORACLE_HOME/dbs/initSTNDBY1.ora as follows:
SPFILE='+SYS/STNDBY/spfileSTNDBY.ora'
17. Prepare database on primaryhost1 for DataGuard.
SQL > ALTER SYSTEM SET log_archive_config='dg_config=(MYDB,STNDBY)';
SQL > ALTER SYSTEM SET log_archive_dest_1='LOCATION=+ARCH valid_for=(ALL_LOGFILES,ALL_ROLES) db_unique_name=MYDB';
SQL > ALTER SYSTEM SET log_archive_dest_2='service="(DESCRIPTION = (LOAD_BALANCE = ON)
  (ADDRESS = (PROTOCOL = TCP)(HOST = primary-grid-scan-name)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = STNDBY.MY_DB_DOMAIN)))"', 
  'LGWR ASYNC NOAFFIRM delay=0 optional compression=disable max_failure=0 max_connections=1 reopen=300 db_unique_name="STNDBY" net_timeout=30', 
  'valid_for=(all_logfiles,primary_role)';
SQL > ALTER SYSTEM SET log_archive_dest_state_2='enable';
SQL > ALTER SYSTEM SET dg_broker_start=true;
18. Register RAC on the standby.
Run the following commands on stndbyhost1 or stndbyhost2 to register standby RAC with Oracle Grid, while replacing ASM disk groups “ASM_disk” with the actual ones
CMD > srvctl add database -d STNDBY -o $ORACLE_HOME -c RAC -a "ASM_disk1,ASM_disk2,...,
 ASM_diskN" -p "+SYS/STNDBY/spfileSTNDBY.ora" -m "MY_DB_DOMAIN" -r physical_standby -n MYDB
CMD > srvctl add instance -d STNDBY -n stndbyhost1 -i STNDBY1
CMD > srvctl add instance -d STNDBY -n stndbyhost2 -i STNDBY2
19. Startup the standby RAC from any standby node.
CMD > srvctl start database -d STNDBY
20. Enable flashback and start the Managed Recovery Process (MRP) on stndbyhost1.
SQL > ALTER DATABASE FLASHBACK ON;
 SQL > ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
If licensed for Active Dataguard (ADG), then open the Standby Database in READ ONLY mode:
SQL > ALTER DATABASE OPEN READ ONLY;
21. Verify the standby database.
On primaryhost1:
SQL > ALTER SYSTEM ARCHIVE LOG CURRENT;
On stndbyhost1 and primaryhost1:
The sequence number should be the same on both databases.
SQL > SELECT sequence#, first_time, next_time, applied
    FROM v$archived_log ORDER BY sequence#;
22. Create DataGuard configuration on the primaryhost1.
CMD > dgmgrl /
 
CREATE CONFIGURATION 'MYDB.MY_DB_DOMAIN' AS PRIMARY DATABASE IS 'MYDB' CONNECT IDENTIFIER IS '(DESCRIPTION = (LOAD_BALANCE = ON)
 (ADDRESS = (PROTOCOL = TCP)(HOST = primary-grid-scan-name)(PORT = 1521))(CONNECT_DATA = (SERVICE_NAME = MYDB.MY_DB_DOMAIN)))';
 
ADD DATABASE 'STNDBY' AS CONNECT IDENTIFIER IS '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= standby-grid-scan-name) (PORT=1521))
 (CONNECT_DATA=(SERVICE_NAME=STNDBY.MY_DB_DOMAIN)(SERVER=DEDICATED)))';
 
ENABLE CONFIGURATION;
 
EDIT DATABASE 'STNDBY' SET PROPERTY 'Enterprise Manager Name' = 'STNDBY.MY_DB_DOMAIN';
 
EDIT DATABASE 'MYDB' SET PROPERTY 'Enterprise Manager Name' = 'MYDB.MY_DB_DOMAIN';
23. Add the new standby database to Oracle Enterprise Manager (OEM).