Search This Blog

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Sunday, February 12, 2023

Server State using WLST

Hello! Dear Automation focused engineer we have this post about how to work simple server status list for a WebLogic domain. This logic can be build and executed for huge number of WebLogic or FMW Servers in Produciton helps to view all at a time hostnames, their corresponding states.   

Why we needWebLogic Server State? What all those states?

While trouble shooting Middleware/FMW administrator need to check the status of all the WebLogic server instances. This is the basic need when the all the servers are in bounced for production code move. This same script can be applicable for the pre-production or staging environment too. WLST provides the built-in methods, which gives the status of the Server instance or servers in a Cluster. Here we will deal with individual instance wise data.

WebLogic Server Life cycle state diagram

There are several ways to list out the servers. The simple way here you go with interactive way...
In the following example 
  1. We are collecting all the list of servers present in the WebLogic domain
  2. state function applied on each server as item  passed to it
  3. repeat this step 2 until all server list ends
 
wls:/demodomain/serverConfig> x=ls('Servers',returnMap='true')
dr--   demoadm
dr--   demoms1
dr--   demoms2

wls:/demodomain/serverConfig> x
[demoadm, demoms1, demoms2]
wls:/demodomain/serverConfig> for i in x:
... state(i,'Server')
...
Current state of "demoadm" : RUNNING
Current state of "demoms1" : SHUTDOWN
Current state of "demoms2" : SHUTDOWN

Cluster listing
wls:/demodomain/serverConfig> c=ls('Clusters',returnMap='true')
dr--   clstr01

wls:/demodomain/serverConfig> c
[clstr01]
wls:/demodomain/serverConfig> state(c[0],'Cluster')

There are 2 server(s) in cluster: clstr01

States of the servers are
demoms1---SHUTDOWN
demoms2---SHUTDOWN

ServerLIfecycleRuntime Mbean tree


Using above shown MBean hierarchy we can fetch the all WebLogic domain server instance's states. If your production WebLogic domain consists of two digit (eg. 60 instances) or three digit number (eg. 120 instances) of managed server then, it is difficult to see all server’s state at once. Weblogic Administration console is unable to show all the servers in the domain on a single page. Navigating in between also a time eating process so think! think better way!! WLST has the solution.

To get the status of all servers in the domain can be obtained with the following steps
  1. Connect to the WebLogic Admin Server
  2. Fetch the Managed server list from the domainRuntime MBean
  3. Iterate the loop and get the state of each Managed Server with ServerLifeCycle Runtime MBean
  4. Repeat if required the step 3 as per the user input to Continue...
  5. Finally if all desired output is visible then disconnect from the AdminServer and exit.

################################################## 
# This script is used to check the status of all WL instances including the admin
###########################################################

def conn():
    UCF='/path/.AdminScripts/userConfigFile.sec'
    UKF='/path/.AdminScripts/userKeyFile.sec'
    admurl = "t3://hostname:wlport"

    try:
        connect(userConfigFile=UCF, userKeyFile=UKF, url=admurl)
    except ConnectionException,e:
        print '\033[1;31m Unable to find admin server...\033[0m'
        exit()

def ServrState():
    print 'Fetching state of every WebLogic instance'
#Fetch the state of the every WebLogic instance
    for name in serverNames:
        cd("/ServerLifeCycleRuntimes/" + name.getName())
        serverState = cmo.getState()
        if serverState == "RUNNING":
            print 'Server ' + name.getName() + ' is :\033[1;32m' + serverState + '\033[0m'
        elif serverState == "STARTING":
            print 'Server ' + name.getName() + ' is :\033[1;33m' + serverState + '\033[0m'
        elif serverState == "UNKNOWN":
            print 'Server ' + name.getName() + ' is :\033[1;34m' + serverState + '\033[0m'
        else:
            print 'Server ' + name.getName() + ' is :\033[1;31m' + serverState + '\033[0m'
        quit()

def quit():
    print '\033[1;35mRe-Run the script HIT any key..\033[0m'
    Ans = raw_input("Are you sure Quit from WLST... (y/n)")
    if (Ans == 'y'):
        disconnect()
        stopRedirect()
        exit()
    else:
        ServrState()

if __name__== "main":
    redirect('./logs/Server.log', 'false')       
    conn()
    serverNames = cmo.getServers()
    domainRuntime()
    ServrState()

Smart Script

Recently I have online discussion with Dianyuan Wang, state of the Managed servers can be obtained with state() command. This function can be used in two ways: 
  • To get individual managed server status you need to pass arguments as managed server name, type as 'Server'. 
  • Other one is to get individual Cluster wise status. 
This can be achieved by passing two arguments cluster name and type as 'Cluster'. The following script will be illustrate the second option, which I found that shorten code that gives same script outcome as above script. It could be leverage your scripting thoughts it is like a plain vanilla form as shown below:

Note: Hope you follow the WLST Tricks & tips
try:
    connect(url = "t3://adminhostname:adminport")
except:
    print "Connection failed"
state('appclstr','Cluster')
state('web1clstr','Cluster')

...
state('webNclstr','Cluster')
-->

Extra Stroke of this new script is that prints how many servers available in each given cluster.

Server state with redirecting, re in WLST

Wang mailed me his situation clarity of explanation why he chosen state command. And how he resolved with Python script tricks here. Its a great learning for me so sharing with you when I saw same question in StackExchange today(28 April 2014) after 3 years!! "The reason I do not use (for now) domainConfig is because some how few Weblogic domains are not in a good state, and when I run the domainConfig command, it complains that it is not enabled. Hence the alternative way I've selected here is using state command. But it don't return the state. It always return None. But it prints out the state of the server. Here you go, Better way is capture that printing output to a file using WLST command redirect-stopRedirect and then, use the Python regular expression to extract the state of each server. The following is the Python snippet how I use the redirect:
 
# Fill your own connection details 
  serverlist=cmo.getServers()   
  for s in serverlist:   
    server_nm = s.getName()
    urldict[server_nm]='t3s://'+s.getListenAddress()+':'+str(s.getAdministrationPort())   
    #domainRuntime()
    #cd('ServerLifeCycleRuntimes/'+server_nm)
    fileName='/tmp/myserver_state.txt'
    redirect(fileName)
    state(server_nm,'Server')
    stopRedirect()
    f = open(fileName)
    try:
      for line in f.readlines():
        if re.search('Current state',line):
          status[server_nm]=line
    except:
      continue
 
  Ks = status.keys()
  for s in Ks:   
    if re.search('RUNNING',status[s]):
		try:
		connect(username,password,urldict[s])
		except:
		continue
		cd("/Servers/" + s)  


...
best regards! Dianyuan Wang

Here I request you please write back your experiencing with this posting looking ahead for your issues/ suggestions as comments.

Thursday, December 25, 2014

File IO in WLST: How to store output of WLST/Jython?

Hey WLST scripting enthos Guys!!

I was prepared some of industry most reffered WLST monitoring scripts... they are running well and good... Now the need is to store the result of this monitoring script into a FILE. How to make this? how to redirect this output... normally output is coming from print command in the jython/python. I was searching in google for this output storing to a file from WLST not really good outcomes... then I thought better I choose file style as in C programming allows Standard Output to a files with file pointers. This found a jython tutorial which is already available in online...

WLST File input output operations

-->

Standard Out and Error


Standard output and standard error (commonly abbreviated stdout and stderr) are pipes that are built into every unix-like platform. The stdout (fileObject) is defined in the Python standard sys module, and it is a stream object. Calling its write() function which will print out whatever string you pass as argument to it, then return the length of the output. In fact, this is what the print function really does; it adds a carriage return to the end of the string that you’re printing, and calls sys.stdout.write function.
##############################################
# This program is to illustrate sys fileojects
# Standard Output stdout
# Standard Error stderr
##############################################
print "Normal print..."
for i in range(3):
        print "WLST is awesome!!!"

import sys
print "sys.stdout...."
for i in range(5):
        l=sys.stdout.write('WLST By Examples\n')

print "sys.stderr...."
for i in range(4):
        errline=sys.stderr.write('WLST in 12.1.3 Wonderful!! ')

Here it shows the difference of print, write function with/without carriage return example.
$ wlst fileObj_sys.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Normal print...
WLST is awesome!!!
WLST is awesome!!!
WLST is awesome!!!
sys.stdout....
WLST By Examples
WLST By Examples
WLST By Examples
WLST By Examples
WLST By Examples
sys.stderr....
WLST in 12.1.3 Wonderful!! WLST in 12.1.3 Wonderful!! WLST in 12.1.3 Wonderful!!

In the simplest case, sys.stdout and sys.stderr send their output to the same place. In Python, standard output, standard error does not add carriage returns for you. If you want carriage returns. you’ll need to write manually include the carriage return characters. sys.stdout and sys.stderr are stream objects, but they are write-only. Here important fact is that when you attempting to call their read() method will always raise an IOError.

Redirecting output with file descriptor is fine worked good... 
now one more thing... need a timestamp for everytime when you run the monitoring script...
Solution again available in the same tutorial...
jython is going to support Java internally... Java's Date utility gives you the facility to have a time stamp redirect this print to the same file descriptor ... your job is done!!
fileObj = open('test.txt', 'w')
writeList=["I am an Indian", "I love my India", \
"I want to go to USA", "I want to earn dollars", \
"I want to die in India"]

for i in writeList:
 print >>fileObj, i

fileObj.close()

# Default file mode is read (r)
fileObj = open('test.txt')

# We can move fileObj position here it is 0
fileObj.seek(0)

for lines in fileObj.readlines():
 print lines

fileObj.close()
Creates test.txt with lines in list and then will read lines from same file.
wls:/offline> execfile('filereadWrite.py')
I am an Indian

I love my India

I want to go to USA

I want to earn dollars

I want to die in India


The file attributes

Following table have the list of the file object attributes. Which we can directly access them public.
AttributeDescription
file.closedReturns true if file is closed, false otherwise.
file.modeReturns access mode with which file was opened.
file.nameReturns name of the file.
# This program illustrates the file attributes

f=open('fileattr.py')
print "mode:",f.mode
print "name:",f.name

if f.closed:
        print f.name, " is closed"
else:
        print f.name," is not closed"

Its execution gives the output as follows
wls:/offline> execfile('fileattr.py')
mode: r
name: fileattr.py
fileattr.py  is not closed

Testing

with-as operation on Files

Following example shows how to use with

How do I test a simple Jython script at Jython prompt?

You can use the following lines to invoke Jython Shell on your WebLogic environment. This is possible because WLST is based on Jython Shell, obviously you can get a Jython prompt in the WebLogic environment.
Normally you can get with
$ java  org.python.util.jython

Otherwise use the following way to skip caching:
$ java -Dpython.cachedir.skip=true org.python.util.jython

Remember that, WebLogic 9.2 supports Jython 2.1 featured shell, The new Oracle Fusion middleware, WebLogic 11g supports Jython 2.2 features.

In many capacity planning analysis you need the statistcs of day or hour by hour etc., These statistics can be for JVM monitoring or for JMS or JDBC DataSource or Thread Count of a WebLogic domain.
Simply printing to standard output you can redirect them to your desired filenames which you specify in the Jython script. To do print to a file use:
f = open("JVMStat.txt", "w")
# JVM monitoasring Script loop
       print >>f, "JVM Status Line here"
f.close()
And to add to the end of a existing file use:
f = open("JVMStat.txt", "a")
       print >>f, "Added lines comes here"
f.close()

Hope this will give you hint for your need in WLST and file usage. For any issue keep writing back to me.

Enjoy with Jython!!! in WLST !!!

Thursday, April 11, 2013

Home

Do you know this fun thing about Python scripting sing a poem of quotations just by by importing 'this' module.
wls:/offline> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
wls:/offline>

Content

You are invited for the contribution of WLST scripts and articles.

Technorati Claim token code JDU3DCFE66EH

Sunday, June 10, 2012

JDBC Monitoring

JDBC Monitoring with LWLST script
One fine morning we (WLA support Team) got an assignment, The summary of the assignment was to find "How the WebLogic server instance performing for a DataSource?". WebLogic 9.x onwards a DataSource is associated with a ConnectionPool (a pool of connections to the DB). If we monitor ConnectionPool, inturn it is nothing but monitoring a DataSource.

Of-course the task is not that easy, I have gone through various WebLogic forums to find a appropriate solution for this task.

Oracle WebLogic provides two ways to Monitor a Datasource
1. Monitoring Datasource server wise
2. Testing the Connection Pool

Here I am publishing the same script which Madan Noru/Satya prepared in the old bea fourms or ObjectMix forums. Only one thing is difference is that displaying pattern, I had created a separate header, so that output looks good to see in a table form. To make this possible I have used C-Style print command from Python Language. This format you can change as per your screen display size.

The script will retrieve the JDBC Connection Pool MBean using adminHome, which is deprecated object in WLST. The output of the script will gives you the values of the following attributes:
  • DataSource Name
  • Maximum Capacity of the Connection Pool at Run-time
  • Active Connections Current Count
  • Active Connections High Count
  • Wait Seconds High Count
  • Waiting For Connection Current Count
  • State of the Connection Pool

#=======================================================
# This script will monitor the JDBC CONNECTION POOL
# more details on this script contact: Pavan Devarkonda
#=======================================================
connect("username","passwd","t3://AdminIP:AdminPort")
try:
 poolrtlist=adminHome.getMBeansByType('JDBCConnectionPoolRuntime')
 print ' '
 print ' '
 print 'JDBC CONNECTION POOLS'
 print ' '
 print 'Name Max Active Active WaitSecs Waiting State'
 print ' capacity Current HighCnt HighCnt Count'

 for poolRT in poolrtlist:
  pname = poolRT.getName()
  pmaxcapacity = poolRT.getAttribute("MaxCapacity")
  paccc = poolRT.getAttribute("ActiveConnectionsCurrentCount")
  pachc = poolRT.getAttribute("ActiveConnectionsHighCount")
  pwshc = poolRT.getAttribute("WaitSecondsHighCount")
  pwfccc = poolRT.getAttribute("WaitingForConnectionCurrentCount")
  pstate = poolRT.getAttribute("State")
  print '%10s %7d %7d %7d %7d %7d %10s' % (pname,pmaxcapacity,paccc,pachc, pwshc,pwfccc,pstate)
  print ' '
except:
  print 'Error:'
  dumpStack()
  pass
disconnect()

In Year 2012 revisting the same script

We have trouble in the produciton environment with JDBC Connection pool overloaded. All the ActiveConnectionCount reaching the MaxCapacity of the Connection pool. As a temprory workaround we need to reset the Connection pool for that movement. Permanent cure is tuning the Connection pool. For both solutions we need active monitoring the JDBC Connection pool.
To monitor this we have revisited the same script. Now adding more saus to the script we need to find that ActiveConnectionCount reaching 85% as threshold limit. Once it reaches 85 or greater then monitoring tool like HP OV/some other tool will reads log file generated by the script and then sends warns message to supporting Middleware Admin when threshold crossed. If you have sendmail service on your machine you can send message fromt he script itself.
To do this we had manupulated the above script according to the requirements
  1. We have specified DataSource that are causing this trouble
  2. Used separate properties file for user credentials.
  3. The output of script is redirected to a file
  4. Managed Server name opposite to the monitor values it is tricky but resolved The new script is

#=======================================================
# This script will monitor the JDBC CONNECTION POOL
# Date :  18 Apr 2012
#=======================================================
import sys
import time
try:
        loadProperties('./DBcheck.properties')
        fp=open('ActiveConn.log','a+')
        Date = time.ctime(time.time())
        admurl='t3://'+admAdrs+':'+admPort
        connect(userConfigFile=UCF, userKeyFile=UKEY, url=admurl)
        poolrtlist=adminHome.getMBeansByType('JDBCConnectionPoolRuntime')
        print ' '
        print 'JDBC CONNECTION POOLS'
        print>>fp, '================================================ '

 for poolRT in poolrtlist:
                pname = poolRT.getName()
                pmaxcapacity = poolRT.getAttribute("MaxCapacity")
                paccc = poolRT.getAttribute("ActiveConnectionsCurrentCount")
        
  if pname == 'myDataSource1' or pname == 'myDS2'' or pname == 'myDS3':
                        server= str(poolRT).split(',')[2].split('=')[1]
                        p=(paccc /(pmaxcapacity * 1.0)) * 100 
                        if p >= 85:
                                print >>fp, 'WARNING: The Active connections are Greater than Threshold 85%'
                        print>>fp, '%24s %15s %18s %7d %7d' % (Date,server,pname,pmaxcapacity,paccc)

except Exception, e:
        sys.stderr.write('ERROR: %s\n' % str(e))
        print 'Error:', e
        dumpStack()
        pass
fp.close()
disconnect()


-->

Post script actions

  1. Prepare a Shellscript that will let you know howmuch time it will counsume to run py script.
    clear
    date
    $JAVA_HOME/bin/java weblogic.WLST /path/urscript/jdbcmon.py
    date
    
  2. Schedule a scheduler to run this script autosys or crontab that invokes above shell script.
  3. Configure a monitoring tool frequently lookup the logs and send alert messages such as HP OVO or smpt mailing also fine.
What do you think about this new version of script? Write back your comments and suggestions to deliver better. Refernce Object Mix discussion:
http://objectmix.com/weblogic/549153-weblogic-monitoring-script-wlst-2.html -->

Sunday, March 20, 2011

WLST Tricks & Tips

Here I prepared few of the "Tips" and some commonly useful "Tricks" for developing the huge WLST scripts. These are all the learnings which I have came across in my daily working experiments with Programming Python commands for WLST scripts. These WLST commands can be applicable from WebLogic 9.x to WebLogic 10.3.6 and latest trending WebLogic 12c as well.
  1. Tip 1: Know about Where are you in WLST?


  2. On some situations you might need a clarity about which WebLogic version you are using. WebLogic 11g (10.3) has different subsequent versions 10.3.1,10.3.2,10.3.3 and 10.3.4, for all these the directory structure is ~/Oracle/Middleware/wlserver_10.3 which does not tells you about sub versions. Here WLST  is having a solution for this problem,

    You can find the current WebLogic version to which WLST is connected.

    wls:/offline> print version
    WebLogic Server 10.3.3.0  Fri Apr 9 00:05:28 PDT 2010 1321401
    

    How do you know that the WLST Shell running on which JVM version? The simple solution is you this following Python command that will gives you:

    wls:/offline> sys.platform
    'java1.6.0_21'

  3. Tip 2. How to know Jython version is used by WLST?


  4. To get the Jython version you can use sys.version_info method that will returns. or you can use sys.version exact version.

    wls:/offline> import sys
    wls:/offline> sys.version_info
    (2, 2, 1, 'final', 0)
    
    

    Tip 3. Introspection in WLST


    You might understand that using WLST provided help() sometimes you cannot reach your desired level of script code. Some thing that won't be documented but you might need it to develop the prototype in your WLST script. Often I found this could be a need, most helpful way to reach depth of WLST classes, modules, functions. Best way is we need to use Python introspection methods. It is a wonderful way to resolve your coding clues to use best performing script as outcome.

    In some of the situations, I felt using Jython (Java method) is lengthy than using Python. When Python giving you desired outcome in two lines of code why do you choose Java imports and classes and code become 6-10 lines.

    You might be confused sometimes, brain storm about something why a MBean not working or giving the value of an attribute etc. In your mind there could be a question "what is this actually??" Best solution for this is using Python introspection built-in methods.

    dir([WLST/Python Object])
    
    
    If your WLST MBean or module or a function has documented then you use the following to get that:
    _doc__
    

    In Jython there could be classes or interfaces
    __class__
    

    Tip 4. Naming Rules for WLST


    WLST script can have names are case sensitive and cannot start with a number.  They can contain letters, numbers, and underscore symbols. Let us see few examples here:
     state  State  _state  _2_state_  state_2  StatE

    Most of us face an issue what name makes sense for a variable, module or classwhile writing the WLST scripts. Just like Java Language you can follow specific naming rules, we can also find keyword list available in WLST with the following commands

    wls:/offline> import keyword
    wls:/offline> keyword.kwlist
    ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield']
    

    Modules, packages: use lowercase
    Classes: use Capitalized first letters in the Words also follow for exceptions that you create
    Methods, attributes: use lowercase_words
    Local variables: use alphanumeric i, j, sum, x0, etc.
    Globals: use alphanumeric long_descriptive_names

    wls:/offline> sys.modules
    {'weblogic.store.admintool.CommandDefs.CommandType': , ...'sys': sys module, 'weblogic.management.scripting.utils': }
    
    
    
    

    Introspection reveals useful information about your program's objects

    Tip 4 Write a readable script


    While writing a script think about the human readers, Question yourself can you still read your own code ???
    next month?
    next year?
    • Be consistent (but not too consistent!)
    • Use white-space judiciously
    • Write appropriate comments
    • Write helpful doc strings -- not stories or novels
    • Confirm to the existing style even if it’s not your favorite style!
    • local consistency overrides global
    • Update the comments!!and the doc strings!!!

    """Brief one-line description.
    
    Longer description, documenting
    argument values, defaults,
    return values, and exceptions.
    """
    

    When to use classes in WLST? (...and when not!)
    If your script objective is going to have multiple object creation then go for Object-Orientation.

      • You could choose class members or attribute  at the first time
      • name clashes between attribute

    Tip 5 Convene print statement with str()


Most of us from Java/JEE development background common attitude is that using the + operator overloading for strings. Sometimes your WLST script might need to have a print statement, that could include values from a variable or some mathematical expression that might be int type or some other object type. Then such cases, better to use that variable type must be converted to string type by using Python built-in function str() as shown :

print 'Heap Size' + str(totalHeap)

Tip 6: Create single properties file

Every Middleware admin whoever uses this WLST in their environment builds, they must create/use a single properties file where you can have:

  1. Domain properties - username, password, admin url, cluster list
  2. Database configuration properties
  3. JMS configuration properties
  4. WorkManager properties
  5. Monitoring Threshold properties

Tip 7: Using time in WLST


In my daily news updates from social medias I found in reddit.com in the Python community doing excellent there is lots of news about the changes happening with Python programming. One of the blog found very nice examples with date and time functions in Python this can be applicable for our WLST too.

Setting UTC time zone in Python

WLST Tricks


We have come across many situations where it is simple trick works faster to work with WLST scripting. some of them collected here and future also we will update this WLST tricks

Trick 1. Multiple Assignment

In WLST you can assign multiple variables with corresponding multiple values at the same statement or command line.

wls:/offline> cl, ms = ['appclstr','webclstr'], ['app01','app02','web01','web02']
wls:/offline> cl
['appclstr', 'webclstr']
wls:/offline> ms
['app01', 'app02', 'web01', 'web02']


Trick 2. Connect admin without Credentials

When you use storeUserConfig() command for your WebLogic domain environment, the trick here is when you don't specifying any arguments such as user security file, key file paths. WebLogic system automatically generates the following two files:
1. username-WebLogicConfig.properties
2. username-WebLogicKey.properties

For example, Let us assume your user name is 'padmin' then storeUserConfig() command will generates two files as:
* padmin-WebLogicConfig.properties
* padmin-WebLogicKey.properties

Once you got this auto-generated files in you home ($HOME in Unix) directory, WLST Shell automatically detects its existance from this location. You don't need to give the userConfig, Key file paths while connecting. Simply you can connect by giving the adminurl as url value.

wls:/offline> connect(url='t3://myapp.host.com:8756')
Connecting to t3://myapp.host.com:8756 with userid weblogic ...
Successfully connected to Admin Server 'wadmn' that belongs to domain 'mydomain'.

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Trick 3: Command Trials

The interactive mode is great for getting instant feedback on the behavior of each WLST command. Having the whole startup, connection, session-init is time-consuming and the interactive mode of WLST avoids this.

First time if you are making a script better idea is have duplicate windows of the host. In one window you can edit and save according to your required changes, on the other hand you can execute the file with execfile('urScript.py').

Trick 4: Using loadProperties

One of my blog follower Raghu asked me how to use properties in the WLST script. Though I had used different types of properties from properties file, but his requirement is something different he want to reuse the WLST script only by changing the properties file.

cat mys.properties
SERVERS=myser1,myser2,myser3
ADMINSERVER=demoAdmin


Here is the WLST script snippet that uses above defined properties using loadProperties() built-in function call
loadProperties('path/mys.properties')
print SERVERS
serverlsit=SERVERS.split(',')
print serverlist[1]

for i in serverlist:
    print i

Remember that properties are just like Java language properties or C/C++ define constants, which holds name, and corresponding the string values. So when you store portno in properties file better convert using int().
Hope this is useful for your reusable scripts.

Trick 5: How to debug WLST script?

The best way to identify the WLST script bugs using dumpStack(). This works only when you are running interactive mode. If you found a script (such as my blog) or from somewhere after you update all properties you wish to test and it doesn't works! then you wish to debug it.

1. Using simple print variable values
2. Using Python exception values
3. Double check indentations
4. Casting values (converting values str to int or str to bool)

Some of the cases you need to understand that casting fails the values are not allowed to change because WLST variables are created in Runtime. The datatypes are strong type like Java and C++ languages and dynamic type while running it will be assigned to a datatype.

You can enable debug flag at the time of invocation of WLST shell.

java -Dpython.verbose=debug weblogic.WLST

Also you have one more option using debug("true") or set('DebugEnabled', 'true') in the starting of WLST script that will force debug output

If you are using OEPE (Eclipse for developing WLST) then you have much scope to debug every variable content. Right click on the WLST script select 'Debug As', choose 'WLST run' from the list Menu. Please check the screenshot that give you more clear idea on this Oracle link.

Trick Cancel the Edit in WLST

Today while working on WLST in interactive mode to fix the JMS configuration issue, sometime you start editing the configuration you might need to undo the changes you did on the edit tree. This is possible using cancelEdit() give the answer y to confirm when it prompts you. Else you can use cancelEdit('y') as a trick.

Trick 6: Suppress Junk Output in WLST

There is junk when you capture the list from ls(returnMap='true') command execution.
If you are running WLST in *nix based environment you can use /dev/null path for suppressing the junk outputs as shown below redirect command.

redirect('/dev/null','false')
ls()
redirect('/dev/null','true')


Trick 7: Resolve indentation/dedent issue with vi setting


WLST Code copied from NotePad++ to vi editor tabspace issue
when you write few lines in the notepad++ it takes 4 spaces as tabspace, but in the vi editor it is 8 it mismatches and cannot fit into the block. So when run the script it throws 'dedent' issue. To resolve this in vi editor you can set the tabspace=4

: set tabspace=4

Keep writing your valuable comments and great suggestions to improve this blog tutorial ...

References:
  1. 1. Dive into Python
  2. Python Library link
  3. http://forums.oracle.com/forums/thread.jspa?messageID=9416182&tstart=0

Thursday, February 17, 2011

OEPE the best WLST Editor


Now we have, Oracle given a nice GUI editor for WLST scripts. I started looking about it one of my blog commenter Lukas was asked me about it. Oracle released two versions of this Eclipse editor:
  1. Eclipse 3.6 (Helios) Edition
  2. Eclipse 3.5.2 (Galileo) Edition
It has built support for Python scripts and PyDev. Recently I had downloaded new OEPE-Galileo-All-In-One-11.1.1.6.0.201007221355-Win32.Zip. It is really “All in One” why because it has connectivity to WebLogic Server Local/Remote options with all categories of versions supported by WLST. It is included WLST MBean Explorer, built-in WLST Help provided in one of tab.

Here I am going to tell about that what you need to look in this because introductory blog already given by Edwin Biemond from Oracle
OEPE for WLST 

Video blog...
There is nothing to know about much about hidden MBean hierarchies. WLST on OEPE (Eclipse) makes more fun in creating new scripts. More over the OEPE Templates are awesome!! God bless this template creator.  Oracle WLST people given commonly used scripts as templates. Which makes you no efforts to write the line-by-line script writing. GUI makes more work in less time meaning increasing productivity and performance!!!

Ready made Templates
OEPE gave us the following templates as ready-made script templates. You need to change the values or parameters to whatever you want to name for your environment or WebLogic domain. 

  1. Default: WLST online
  2. Create Basic WebLogic Domain
  3. Create WebLogic Cluster
  4. Create WebLogic Domain with JMS and JDBC Resources
  5. Configuring JMS System Resource
  6. Configuring JDBC DataSource Delete  JDBC Data Source
  7. Delete JMS System Resource
  8. Delete WebLogic Cluster
You might be using WebLogic portal or WebLogic Integration or some other WebLogic domain these are core common scripts templates can be applicable to any of them.



Most of the developers requires the Deleting JDBC resources and want to create a fresh DataSource with changed database parameters.

In production environment some of the sites you might need to remove the machines due to their utter performance. “Delete WebLogic Cluster” is the wonderful script for you. You need to give the managed servers list, cluster(s) you want to remove from the domain.
Cons of OEPE
  1. To run OEPE on your desktop requires good amount of MEMORY (RAM).
  2. Sometimes iexplorer stuck you cannot open OEPE anyway it is Windows issue.
  3. JVM Settings of eclipse.ini file need to be updated according to your operating environment. Anyway I found the best reference to solve JVM settings issue at stackoverflow.com
Expecting more exciting things from WLST users so…keep writing your comments, updates about OEPE using WLST.




In these amazon ads you can click on 'Look inside' give you some idea about the above books. And don't forget to enjoy the sample chapters of these books.

While working on eclipse there could be need to pass arguments to your WLST script. Yes!! You can do that goto Run As options select Run Configuration. In the Run Configuration window select the Arguments tab,  you can give Program Arguments.

Good References:
1. http://www.oracle.com/technetwork/developer-tools/eclipse/downloads/index.html
2. http://biemond.blogspot.com/2010/08/wlst-scripting-with-oracle-enterprise.html
3. http://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse

Wednesday, December 22, 2010

My way of deployment with WLST

This Script has ultimate goal to automate to one-step process for deploying the code onto WebLogic Development environments. Usually the development environments are going to have multiple time deployments than other environments. Some of the WebLogic environments creates the persistances objects stores into the servers logs path. To avoid previous object references we need to clean up the cache directory that holds this persistance objects. We have developed a python module for clearCache that will do this task automatically.

There could be dependency on application archive files order. Some of the deployments does not requires the shared libraries deployments. Changes in the web application requires Only web app re-deployment. Changes in the enterprise application needs only EAR file deployments. Considering all these dependencies the script is developed in modular structure.

 The following shell script is developed for the environment which I have used to. The domain path you can specify in the DHOME.

#AppDeployment.sh [Optional]
echo '***** WELCOME TO DEPLOYMENT SCRIPT *****'
user=`echo $LOGNAME`
echo 'APPLICATION DEPLOYMENT IS STARTING IN INSTANCE:' $user
DHOME=/Home/domains/wd$LOGNAME/config
WLHOST=`hostname`
cd $DHOME
WLPORT=`cat config.xml |grep listen-port|tr -s [:blank:] |tr " " "\n" |grep listen-port |cut -c14-17`
URL='t3://'$WLHOST':'$WLPORT
DENV=$HOME/domains/wd$LOGNAME/bin/setDomainEnv.sh
. $DENV $*
echo $CLASSPATH
#calling the paniDeployment.py file
java weblogic.WLST -loadProperties /Home/$user/.Admin/deploy.properties /Home/$user/.Admin/paniDeployment.py $user $URL$CLASSPATH 

Now let me give you what I did in my experiment with deployment script, assume that 'a_ejb.jar','a_adapter.jar','b_adapter.jar','c.war' are the deployable archive file components. You may have different components may be target to different WebLogic server instances or clusters it is your choice of targetting.

Well this might be very lengthy you might feel too much!! but bear with me! this is my first time trial which I made ...

On our WebLogic, there are many logics works hahaaaaaaaaaaaaaaaa!! here I am using Python core library modules such as 'os', 'time' etc.

#======================================================================
# FileName: AppDeployment.py
# Author  : Sarangapani Matoori
#======================================================================
import os
import time
import sys
from java.util import Date
from java.text import SimpleDateFormat
t = Date()
today=SimpleDateFormat("dd_MMM_HH:mm").format(Date())
user=sys.argv[1]
URL=sys.argv[2]
src="/home/"+user+"/CODE/"
bksrc="/home/"+user+"/CODE_"
dpath="/home/domains/wd"+user
ECODE='\033[0m \n'
G='\033[1;40;32m'
R='\033[1;40;31m'
deploylist=['a_ejb.jar','a_adapter.jar','b_adapter.jar','c.war']
def backup():
    try:
         #Creating the Backup with Date And Time 
         command = "cp -R "+src+" "+bksrc+today
         os.system(command)
    except:
          print R+'   Code Backup FAILED!! '+ECODE
          print dumpStack()

def getCode():
        try:
                # GETTING THE Fresg Code from build location 
                os.system('scp user@hostname:/home/user/Code_Ioc/*.*ar '+src)
                print G+'    THE CODE COPIED SUCCESSFULLY  '+ECODE
        except:
                print R+'   THE CODE COPYING FAILED?!?!?'+ECODE
                print dumpStack()
                exit()
def conn():
        try:
                # CONNECTING TO THE SERVER .... 
                connect(userConfigFile=UCF, userKeyFile=UKF, url=URL)
        except:
                print R+'  CONNECTION FAILED....',+ECODE
                print dumpStack()
                exit()
def editing():
        edit()
        startEdit()

def activating():
    save()
    activate()

def stoppingApp():
    deploylist.reverse()
    for s in deploylist:
        try:
            editing()
            progress=stopApplication(s,timeout=360000)
            progress.printStatus()
            activating()
       except:
            print R+'  FAILED TO STOP THE APPLICATION  '+ECODE
            print dumpStack()
  
    print G+'  APPLICATION STOPPED  '+ECODE

def pUndeploy():
     deploylist.reverse()
     for s in deploylist:
        try:
                editing()
                progress=undeploy(s, timeout=360000)
                progress.printStatus()
                activating()
        except:
                print R+'  FAILED TO UNDEPLOY THE APPLICATION  '+ECODE
                print dumpStack()
     print G+'  APPLICATION UNDEPLOYED   '+ECODE

# This module is optional 
def clearCache():
        try:
                print G+'  CLEARING THE CACHE  '+ECODE
                command = "rm -rf "+dpath+"/servers/"+user+"/tmp/*.*"
                os.system(command)
                print G+'  CLEARED THE CACHE   '+ECODE
        except:
                print R+'  FAILED TO CLEAR CACHE '+ECODE

def pDeploy():
     for s in deploylist:
        try:
            editing()
            progress=deploy(s,src+s,target=user,timeout=360000)
            progress.printStatus()
            activating()
        except:
            print R+'FAILED TO DEPLOY THE APPLICATION'+ECODE
            print dumpStack()
     print G+'  APPLICATION DEPLOYED  '+ECODE

def startingApp():
     for s in deploylist:
        try:
                editing()
                startApplication(s,timeout=360000)
                activating()
        except:
            print R+'FAILED TO START THE APPLICATION '+ECODE
     print G+'APPLICATION STARTED SUCCESSFULLY '+ECODE

if __name__== "main":
        backup()
        getCode()
        conn()
        stoppingApp()
        pUndeploy()
        clearCache()
        pDeploy()
        startingApp()
        print G+' ....DEPLOYMENET DONE...'+ECODE
###### End of pani Deployment.py file ###########
We have gone thru the Satya blog, Satya (the original author of WLST) already wrote os.system usage in the following link:
http://ghattus.com/2007/01/01/wlst-startserver-re-visited/

Following comments archived from "WLSTBYPANI" post:



prasanth vasireddy said...
what are the argument to pass through this script..what are the deploy.properties file?. References:

Tuesday, August 24, 2010

Configuring Multi DataSource

Introducing Problem Statement for this post is WLST which enables us to configure any kind of resource on a WebLogic domain. Here I am with new attempt to configuring Multi Datasource. In most of new domain configurations you need to work separately for configuring Datasource. We are already seen how to configure a Dynamic Datasource with customized property file, Adding to the same topic now we are going to work on Multi Datasource configuration.

The steps involved in multi datasource confiuration are as follows:
1. Configure individual datasource
2. Configure a new multidatasource
3. Add the datasources created in steip 1

Keeping more flavor (Object-Orientation) to your script we will create a Class in WLST this time. Are you ready??? I know you guys very intelligents and know all WLST tricks how they works and all!! Lets dive into the process of configuration.
-->


#==========================================
# File name: ConfigMDS.py
# Please change the code (line 38) as per your environment and needs
# Author : Inteligent WLA :)
#=============================================

class MDS:          
 def __init__(self, nam):
  self.nam  = nam 

 def configMDS(self):
  n=self.nam
  try:
   cd('/')
   cmo.createJDBCSystemResource(n)
   cd('/JDBCSystemResources/'+n+'/JDBCResource/'+n)
   cmo.setName(n)
   cd('JDBCDataSourceParams/'+n)
   set('JNDINames',jarray.array([String(n)], String))
 
   cmo.setAlgorithmType('Failover')
   dslist=raw_input('Please enter comma separating Datasources for MDS:')
   cmo.setDataSourceList(dslist)
   cd('/JDBCSystemResources/'+n)
   targetType=raw_input('Target to (C)luster or (S)erver: ')
   if targetType in ('C','c') :
           clstrNam=raw_input('Cluster Name: ')
               set('Targets',jarray.array([ObjectName('com.bea:Name='+clstrNam+',Type=Cluster')], ObjectName))
          else:
               servr=raw_input('Server Name: ')
               set('Targets',jarray.array([ObjectName('com.bea:Name='+servr+',Type=Server')], ObjectName))
   print 'Succesfully configured MultiDataSource...'
   activation()
  except BeanAlreadyExistsException:
   print 'Error: '+n+' BeanAlreadyExists...'
       cancelEdit('y')
   exit()

#===== main program===============
if __name__== "main":
 connect('wlusr','paswd','t3://AdminUrl:AdminPort')
 edit()
 startEdit()
 
 mdsName = raw_input("Please enter MultiDataSource name: ")
  # create object, call configMDS
 MDS(mdsName).configMDS()
 print('Exiting...')
 exit() 

Here you can templatise more by creating the a properties file where you need to store Multidatasoruce name, JNDIName, WebLogic Admin user, Password, AdminURL, the datasource names you wish to add to the multidatasource.

Use the same steps as followed in the Generic Data Source Creation.

# http://unni-at-work.blogspot.com/2009/03/multi-data-source-using-wlst.html
# http://edocs.bea.com/wls/docs100/wlsmbeanref/mbeans/JDBCDataSourceParamsBean.html#AlgorithmType

Monday, March 22, 2010

Side by Side Deployment with WLST



One of my online buddy requested me Python script help for developing Side by Side(SBS) deployment using WLST.

Automate Python Script for Side By Side deployment.

The project is in developing stage, the client need deploying the same applications with different versions must be available for development and testing teams, an automated handy WLST script is requested to develop by buddy WLA.
Add caption

To do this interesting  task, the plan for execution is prepared as following while doing the deployment criteria:
1. If the application is New and the version is new i.e no other version is in the ACTIVE state with the given appName, the script will deploy the application
2. If one of the version of given application is in ACTIVE state visible in the console, then the developer is try to deploy the next version, the script should do DeActivate the old version and deploy the new version.
3. Now already have two versions deployed on the domain one is : ACTIVE state and other is in RETIERED State then undeploy the REITRED versioned application with a timeout interval or deploy the new version so that it will make current ACTIVE application to RETIERED and new deployment to ACTIVE.

Sample Video demonstration from Oracle Weblogic

For implementing the above logic in chronological way. The real challenge lies in the ISSUE with iterations. it was controlled by 'break' statement usually that we do in any C program. And I have used here a flag variable 'appFlags' to indicate the status of the Application status, like that we are able to maintained two version max in the console of the same app.

-->

import sys
#======================================================= 
# Function for fresh plain deployment
#======================================================= 
def newDeploy(appName,ver):
    print 'Deploying .........'
    deploy(appName,'/path/applications/'+appName+'/'+ver , targets='AdminServer')
    startApplication(appName)

#======================================================= 
# Function for finding the  Application Status
#=======================================================  
def appstatus(appName, serverName):
    cd('domainRuntime:/AppRuntimeStateRuntime/AppRuntimeStateRuntime')
    #get current real state for app in specific server
    currentState = cmo.getCurrentState(appName, serverName)
    return currentState
#======================================================  
# Undeploy the given application 
# Target we can change according to domain and application deployed on
#====================================================== 
def unDeploy(appName):
    print 'stopping and undeploying ....'
    stopApplication(appName, targets='AdminServer')
    undeploy(appName, targets='AdminServer')


#======================================================== 
# Main program here...
# Target you can change as per your need
#========================================================  
appName=sys.argv[1]
ver=sys.argv[2]
connect(user, passwd, adminurl)
cd('AppDeployments')
appflag=0
y=ls(returnMap='true')
for i in y :
 if i.startswith(appName )  ==1:
  #Checking for the application existence)
  print i
  print appstatus(i,'AdminServer')
 if appstatus(i,'AdminServer')=='STATE_RETIRED' :
  appflag=1
  break
 elif appstatus(i,'AdminServer')=='STATE_ACTIVE':
  appflag=2
 else:
  print ' other Applications are Running '
  pass


if appflag == 1 :
    print 'application having RETIERED STATE ..'
    unDeploy(i)
    print appstatus(i,'AdminServer')
    newDeploy(appName,ver)
    print appstatus(i,'AdminServer')
elif appflag== 2:
    print 'Application exists in ACTIVE state...'
    newDeploy(appName,ver)
    print appstatus(i,'AdminServer')
else:
    print 'new application'

How to execute the Side by Side deployment script?
Dear novice WLA, you can execute this script by re-defining your connection parameters at line 36. Remember one more thing is the application targeted to AdminServer this may vary for your environment as managed servers or clusters.
prompt$ java weblogic.WLST SBSDeploy.py

If you like the ideas implemented in this script, useful to your environment please share this article.

Reference URLs:

Friday, February 12, 2010

Restarting 24 x 7 Domain with WLST

Here I have little bit struggle to reach a conclusion that, what all servers need to stop? when to stop? the preparing script I did with my analysis that stated that few sites requires 24x7 HA. Few of them don't need the HA, that is site can have sometime outage where it doesn't have request for the application.

Me and Prasanna Yalam discussed about a strategy where every time you run few servers can be stopped from different physical locations. when starting them up then only next round of managed servers can be stopped. This strategy implementation firstly thought with 2 scripts then I made it 2 phases one by one can be done with user input. This module named as 'regularStop()', which supports 24x7 HA domain.

One more thing we need to consider here is most of the Production deployments are in nostage mode, when new version release of application code requires complete domain down option requirement. This is another module take cares where it will stop all clusters in the domain should be passed. The module named as 'releaseStop()'. This you can use for any WebLogic domain.


After composing whole script ran it then found that there is need of server state or cluster state when it is given shutdown command. So every shutdown command is followed by state command given that gives more confidence on script how it is executing.

Finally by performing releaseStop() or RegularStop() we can go for stopping the Admin Server.


Note: Don't forget proper indentations, while editing my script it might be disturbed here.
#====================================
# Script File: StopWLDomain.py
# This module is for 24x7  Domain****
# First phase stops few managed servers of few sites
# Second phase will be used for stop remaining servers
# Note that Second phase allowed only when you press 'y'
# before that you need to Start all the Phase 1 stopped servers.
#====================================
def conn():
 try:
  connect(user, passwd, adminurl)
 except ConnectionException,e:
  print '\033[1;31m Unable to find admin server...\033[0m'
  exit()

#====================================
# Stop all instances of a Cluster 
#====================================
def stopClstr(clstrName):
 try:
  shutdown(clstrName,"Cluster")
  state(clstrName,"Cluster")
 except Exception, e:
  print 'Error while shutting down cluster ',e
  dumpStack()
  return

#====================================
# All the instances of all Clusters will be down for release
#====================================
def releaseStop():
 clstrList=["webclstr1", "webclstr2'..."ejbclstr"]
 for clstr in clstrList:
  stopClstr(clstr) 

#====================================
# Stop a instances given as parameter 
#====================================
def stopInst(iservr):
 try:
  state(str(iservr))
  shutdown(str(iservr), 'Server',force="true")
  state(str(iservr))
 except Exception, e:
  print iservr, 'is having error in shutting down'
  pass

#====================================
# Regular Rstart is 24x7 supported for :SITE1, SITE2, SITE3
#====================================
def regularStop():
 clstrList=["non247clstr1", "non247clstr2"]
 for clstr in clstrList:
  stopClstr(clstr) 
 servrList=servrList=["app1","app2","app3"... "web1","web2"] #sitewise list of servers need to stop
 for inst in servrList:
  stopInst(inst)
 print 'Now, please start the instances exclude the phase 2 instances ...'
 phase2=raw_input("Want to proceed for Phase 2...(y/n)")
 if phase2 == 'y':
  serverList=["app4","web3"...] # remaining Managed Servers to stop after phase servers UP n Running
  for inst in serverList:
   stopInst(inst)

#====================================
# Exiting the script
#====================================
def quit():
 disconnect()
 exit()

#====================================
# The main script starts here...
#====================================
if __name__ == "main":
 conn()
 print ' 1. Regular Stop (24x7)\n 2. Release Stop\n 0. Quit\n'
 sAns=raw_input('Enter your choice: ')
 if int(sAns) == 1:
 regularStop()
 elif int(sAns) == 2:
 releaseStop()
 elif int(sAns)== 0:
 quit()
 else:
 print 'Warning: Invalid option...'
 exit()
 print 'Finally stopping admin now...'
 shutdown()

#========WLST=BY=EXAMPLES==============

You can run this script with java in your PATH and weblogic.jar in the CLASSPATH.
java weblogic.WLST StopWLDomain.py

Wednesday, February 3, 2010

Configuring a Generic Datasource

Configuring the datasource is one time activity for any project in production environment but where as for development or testing environment there is always need for change the datasource as per the demand. These changes makes interrupt majority of the development process. To improve this process we can have a Generic JDBC Data source configuring script in your utilities space.

Creating the data source using a python script makes 100% reusable. Here my perception is that if we don’t hard code the JDBC parameters it will be easy to use for all environments as well as for any kinds of database platforms and their respective driver param values to replace also.

Initially lets go with single Data source creation with targeting to the user input Server it can be Managed Server or AdminServer (basic domain), later on we can go for improve further to target to a Cluster.

JDBC Datasource in offline vs Online WLST


This scripting we can write in two ways offline and in online. In the offile mode we need to navigate the MBean and create, configure parameter and finally do assign() them to a Server or Cluster of a domain. For the online script we need to set the target using setTarget() command. To do this we must connect to the Admin server and acquire lock on configuration repository by edit() or startEdit() commands.


assign('JDBCSystemResource', ‘myds', 'Target', demoCluster')
# -- or --
assign('JDBCSystemResource', ‘myds', 'Target', demoServer')

Datasource MBean in WebLogic
JDBCSystemResourceMBean tree


Oracle WebLogic supports jDriver for various DBMS. And also WebLogic supports XA drivers for distributed transactions. Supporting Third-Party Drivers also available from DBMS vendors. Note the following are the WebLogic supports Drivers for DBMS:

Cloudscape DB2 PostgreSQL
Oracle  Ms SQL Progress
MySQL  PointBase Sybase

Configuring new data source custom properties
Now let us try to configure a new data source with a custom properties for Connection Pool parameters, weblogic console connecting parameters into a same file or you can specify with different properties files. When the properties file is used it must be loaded before first line of processing statement in the script. We have two options to load the properties one is using command line and other one is using loadProperties() method.

###################****##############****########################
# Generic script applicable on any Operating Environments (Unix, Windows)
# ScriptName    : ConfigDS.py
# Properties    : ConfigDS.properties
# Author        : Srikanth Panda
# Updated by    : Pavan Devarakonda
###############     Connecting to Start     #################################
def connectAdmin() :
 try:
  connect(CONUSR,CONPWD, CONURL)
  print('Successfully connected')
 except:
  print 'Unable to find admin server...'
  exit()
################### Configuring Connection Pool #############################
def connPool(DSnam) :
 DRVPARM='/JDBCSystemResources/'+DSnam+'/JDBCResource/'+DSnam+'/JDBCDriverParams/'+DSnam
 cd(DRVPARM)
 set('Url',DBURL)
 set('DriverName',DBDRV)
 set('Password',DBPASS)
 cd(DRVPARM+'/Properties/'+DSnam)
 cmo.createProperty('user')
 cd(DRVPARM+'/Properties/'+DSnam+'/Properties/user')
 set('Value',DBUSR)

############         Creating Data source    ###############################
def createDS() :
 print('Naming the datasource')
 DSnam = DSName
 cmo.createJDBCSystemResource(DSnam)
 RESOURCE='/JDBCSystemResources/'+DSnam+'/JDBCResource/'+DSnam
 cd(RESOURCE)
 set('Name',DSnam)

 #Setting JNDI name
 cd(RESOURCE+'/JDBCDataSourceParams/'+DSnam)
 print RESOURCE+'/JDBCDataSourceParams/'+DSnam
 set('JNDINames',jarray.array([String(DSnam)], String))

 connPool(DSnam)

 #Set Connection Pool specific parameters
 cd(RESOURCE+'/JDBCConnectionPoolParams/'+DSnam)
 cmo.setTestConnectionsOnReserve(true)
 cmo.setTestTableName('SQL SELECT 1 FROM DUAL')
 cmo.setConnectionReserveTimeoutSeconds(25)
 cmo.setMaxCapacity(15)
 cmo.setConnectionReserveTimeoutSeconds(10)
 cmo.setTestFrequencySeconds(120)

 cd(RESOURCE+'/JDBCDataSourceParams/'+DSnam)
 cmo.setGlobalTransactionsProtocol('TwoPhaseCommit')
 cd('/JDBCSystemResources/'+DSnam)

 # targets the DS to Servers(Cluster or Server)
 targetType=raw_input('Target to (C)luster or (S)erver: ')
 if targetType in ('C','c') :
  clstrNam=raw_input('Cluster Name: ')
  set('Targets',jarray.array([ObjectName('com.bea:Name='+clstrNam+',Type=Cluster')], ObjectName))
 else:
  servr=raw_input('Server Name: ')
  set('Targets',jarray.array([ObjectName('com.bea:Name='+servr+',Type=Server')], ObjectName))

###############     Main Script   #####################################
if __name__== "main":
 print('This will enable you to create or update a Datasource')
 connectAdmin()
 edit()
 startEdit()
 # Create a new JDBC resource)
 cd('/')
 createDS()
 save()
 activate()
 disconnect()
####################################


You can configure as many as datasource but you need to provide the responding properties file. The base script will remain unchanged only the properties files will be varies when you move to different database environment.

Derby datasource using WLST on Weblogic 12.1.2

Here I have experimented the above datasource creation script with Apache Derby Database which is a default database part of Oracle WebLogic 12c. You don't need to run the database externally. When you run the WebLogic instance it automatically runs this Derby database instance.

The sample derby database properties are as follows:
DBURL= jdbc:derby://localhost:1527/demodbs
DBDRV=org.apache.derby.jdbc.ClientXADataSource
#oracle.jdbc.OracleDriver
DBPASS=welcome1
DBUSR=weblogic
DSName=myDs
CONUSR=weblogic
CONPWD=welcome1
CONURL=192.168.56.101:8100

Lets execute the script and see...
~/pybin$ wlst -loadProperties createDS.properties createDS.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

This will enable you to create or update a Datasource
Connecting to t3://192.168.56.101:56001 with userid weblogic ...
Successfully connected to Admin Server "demoadm" that belongs to domain "demodomain".

Warning: An insecure protocol was used to connect to the
server. To ensure on-the-wire security, the SSL port or
Admin port should be used instead.

Successfully connected
Location changed to edit tree. This is a writable tree with
DomainMBean as the root. To make changes you will need to start
an edit session via startEdit().

For more help, use help('edit')
You already have an edit session in progress and hence WLST will
continue with your edit session.

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
Naming the datasource
/JDBCSystemResources/myDs/JDBCResource/myDs/JDBCDataSourceParams/myDs
Target to (C)luster or (S)erver: C
Cluster Name: clstr01
Saving all your changes ...
Saved all your changes successfully.
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed
Disconnected from weblogic server: demoadm

Oracle Datasource using WLST

The customized properties file "configDS.properties" goes like this:
#==========================
# FileName : ConfigDS.properties
#==========================
DBURL=jdbc:oracle:thin:@dbhostname:dbport:dbschema
DBDRV=oracle.jdbc.OracleDriver
DBPASS=dbpasswd
DBUSR=dbuser
DSName=myDs
CONUSR=system
CONPWD=*********
CONURL=hostname:adminport

General WLST execution instructions


Now to execute the custom properties datasource script the command will be given as follows:
java weblogic.WLST –loadProperties ConfigDS.properties ConfigDS.py

Sunday, January 31, 2010

Configuring WorkManager using WLST


The WorkManager configuration can be possible only when you navigate on SelfTuning tree. After navigating with cding to SelfTuning MBean hierarcy. You can list out the SelfTuning tree that consists of the following branch trees, which are allowed us to created new MBeans using create command.
  1. ContextRequestClasses
  2. FairShareRequestClasses
  3. ResponseTimeRequestClasses
  4. Capacities
  5. MaxThreadsConstraints
  6. MinThreadsConstraints
  7. WorkManagers
WebLogic WorkManager Threadpool configurations
Here I am with few examples of my experiments with WorkManager and its constraints or Request Classess. To configure a new Global or Server instances wise or Cluster-wide Workmanager using online WLST you need to follow the below steps:

1. connect to the Administration Server.
2. switch to edit tree
3. configure a class or constraint for the WorkManager.
4. set the target as per your need to a server or to a cluster.
5. configure a new workmananger
6. navigate to the newly configured WorkManager MBean and set the constraint or class which created in the step 3.
7. target the workmanager to a server instance or to a cluster as per the need.
8. Save the changes and activate them.
9. While performing the above steps the script can throw WLST Exceptions such as BeanAlreadyExistsException handle them

We can configure a WorkManager and its related constraint or Request classes in two modes 1. online WLST 2. offline WLST The only difference here is targeting the WorkManger instance to a Server or a cluster, Online WLST requires
set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
set('Targets',jarray.array([ObjectName('com.bea:Name=app1,Type=Server')], ObjectName))

WLST MaxThreadsConstraints

Now let us see the example for configuring a MaxThreadsConstraints using Online WLSTHere we are going to set the Count value as per the need in the runtime for the MaxThreadConstraint. Better you can also chance to target to Server instance instead of Cluster.
#********************************************************************************
# Configure a WorkManager with  MaxThreadsConstrain
#********************************************************************************
from weblogic.descriptor import BeanAlreadyExistsException


try:
  connect('adminuser','adminpasswd','t3://adminHost:adminPort')
  
  edit()
  startEdit()
  c=input('Enter the Max Thread Count: ')
  mtc='MaxThreadsConstraint'+str(c)
  cd('/SelfTuning/wd1')
  cmo.createMaxThreadsConstraint(mtc)
  cd('/SelfTuning/wd1/MaxThreadsConstraints/'+mtc)
  cmo.setCount(c)
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cd('/SelfTuning/wd1')
  wm = cmo.createWorkManager('pwm1')
  cd('/SelfTuning/wd1/WorkManagers/pwm1')
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cmo.setMaxThreadsConstraint(getMBean('/SelfTuning/wd1/MaxThreadsConstraints/'+mtc))
  save()
  activate()
except (WLSTException, BeanAlreadyExistsException), e:
  print 'Error in script:', e
  cancelEdit('y')
else:
 disconnect()
 

Then the outcome looks like below:
wls:/offline> execfile('ConfigWM1.py')
Connecting to t3://adminHost:port with userid system ...
Successfully connected to Admin Server 'padmin' that belongs to domain 'wd1'.
...


You already have an edit session in progress and hence WLST will
continue with your edit session.

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
Enter the Max Thread Count: 45
Saving all your changes ...
Saved all your changes successfully.
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed
Disconnected from weblogic server: padmin

Capacity Constraint

Now let us see the example for configuring a capacity constraint using online WLST


#Capacity constraint
#********************************************************************************
from weblogic.descriptor import BeanAlreadyExistsException

try:
  # replace following values 
  connect('adminuser','adminpasswd','t3://adminHost:adminPort')
  edit()
  startEdit()
  cd('/SelfTuning/wd1')
  cmo.createCapacity('pcap2')
  cd('Capacities/pcap2')
  set('Count',10)
  set('Notes','This will set Capacity constraint')
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cd('/SelfTuning/wd1')
  wm = cmo.createWorkManager('pwm2')
  cd('/SelfTuning/wd1/WorkManagers/pwm2')
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cmo.setCapacity(getMBean('/SelfTuning/wd1/Capacities/pcap2'))
  save()
  activate()
except (WLSTException, BeanAlreadyExistsException), e:
  print 'Error in script:', e
  cancelEdit('y')
else:
 disconnect()

The output will be like this:
wls:/offline>  execfile('ConfigWM2.py')
Connecting to t3://adminHost:port with userid system ...
Successfully connected to Admin Server 'padmin' that belongs to domain 'wd1'.
....

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
Saving all your changes ...
Saved all your changes successfully.
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed
Disconnected from weblogic server: padmin
Double check your changes for WorkManager done success on Admin Console. Please write back your feedback and comments on this post... -->

Popular Posts