Search This Blog

Showing posts with label Weblogic scripting tool. Show all posts
Showing posts with label Weblogic scripting tool. Show all posts

Friday, December 19, 2014

Object Oriented Programming in WLST

I taught Object orientation programming with C++ and Java previously. With that experiance I am  trying to explore more in the Pythonic OOP in WLST.

class definition in WLST Script


In WLST every thing is object as its base scripting language is Python suppose the same. If you create normal variable assignment uses their base objects like int, float, str etc. Each object will be created on JVM with ID, Type (object type) and value. In this post you will get to know about Object orientation for WLST scripts. The four pillars of Object orientation are supported in WLST as well.

  • Encapsulation - How you hide within object
  • Abstraction - How the object make interact with the world
  • Inheritance -Reusing functionalities of a object
  • Polymorphism - Dynamism to your methods

Why should I use OOP in WLST?

The best features identified and designed for object oriented programming mainly following:
  • Object are natural easy to understand and write
  • Objects are more reusable
  • Objects are more maintainable
  • Objects can be extended

What is class in WLST?

A class is a special user defined data type, which defines how to build a certain kind of objects. These classes also stores some common data itms that are shared by all its instances of the class. Instances are objects that are created which follow the definition given inside of the class.

In simple words class is a blue print for constructing the objects. 
Initializer method __init__
The functions that you define within the class are called methods. for all methods must use the first argument as self.

What is 'self' do in WLST?

The Self is object pointer like in C++, Java we have this pointer that refers to the newly created runtime object attributes values.In __init__, self refers to the object currently being created. In WLST classes self used more often than Java. You don't need to give a value for self. When you call the method VM automatically provides the value for self.

What is Instance?

An instance can be created in the main program that is after completing the class block. To create we need the className followed by perantesis.

i=className()

calling the method can be done with instance period followed by method signature with required parameters. 

Magical methods
There are some methods which are executed without calling them! Example initializer method, printing the object into string type using __repr__, and __str__ .When you call the instance in print command it will automaticall invoke these magical methods.

Best practics for class definitons
  • While you defining a class the class name must begin with Capital letter 
  • Explicit inheriting object type give more power to your class
  • Define a method like a function. must have a first argument as self which provide access to current instance attribute values
  • Better to have a DocString for each method you define in the class 
class level methods
static methods
Inheritance 

Multiple Inheritance

# This illustrates the subclassing
# Empty class with pass 
# usage of issubclass function

class Animal(object): pass
class Snake(Animal):
 def __init__(self):
  print "Ssss n a k e!!"
class Python(Snake):
 "I like Python class"
 atr=0
 def __init__(self):
  print "Busssshhhh!!!"
  Snake.__init__(self)
  self.atr+=1
 def __repr__(self):
  return 'This is Python object'

print "issubclass(Animal,object:)",issubclass(Animal,object)
print "issubclass(Snake,Animal:)",issubclass(Snake,Animal)
print "issubclass(Python, Snake:)",issubclass(Python, Snake)

p=Python()
print "Instance printing:", p
print "docString:", p.__doc__
print "p is from class:", p.__class__

print "p type:",type(p)
print "p id:", id(p)
print "p attribute:", p.atr
 

Private variables in class

In Python classes by default everything is public access. to provide encapsulation for the object double underscore represents the private variables(__var1). 

  Exercise for Learners

  1. Create a class for configuring a simple domain with initializer method that will load all properties that required to configure. [managed servers, machines, cluster]
  2. Create a singleton class that would allow single connection object that can be preserved and used for monitoring JVM, Threads etc.

Sunday, June 23, 2013

Socket module using WLST

Network Socket with Python/WLST

Internet protocol libraries for Python can be used in WLST. hostname you can use to make most generic for your automation scripts. Use this idea in build and deployment process.

wls:/offline> import socket
wls:/offline> print(socket.gethostname())
pavanb.wlst.by.examples.com

There are many socket related modules and built-in functions available to check we can run dir command on each to know wha is inside that package.
 
wls:/offline> import smtplib
wls:/offline> dir(smtplib)
['CRLF', 'OLDSTYLE_AUTH', 'SMTP', 'SMTPAuthenticationError', 'SMTPConnectError',
 'SMTPDataError', 'SMTPException', 'SMTPHeloError', 'SMTPRecipientsRefused', 'SM
TPResponseException', 'SMTPSenderRefused', 'SMTPServerDisconnected', 'SMTP_PORT'
, 'SSLFakeFile', 'SSLFakeSocket', '__all__', '__doc__', '__file__', '__name__',
'base64', 'encode_base64', 'hmac', 'quoteaddr', 'quotedata', 're', 'rfc822', 'so
cket', 'types']

FTP library in WLST

wls:/offline> import ftplib
wls:/offline> dir(ftplib)
['CRLF', 'Error', 'FTP', 'FTP_PORT', 'MSG_OOB', 'Netrc', '_150_re', '_227_re', '
__all__', '__doc__', '__file__', '__name__', 'all_errors', 'error_perm', 'error_
proto', 'error_reply', 'error_temp', 'ftpcp', 'os', 'parse150', 'parse227', 'par
se229', 'parse257', 'print_line', 'socket', 'string', 'sys', 'test']

Did you ever thought of using FTP from WLST?

IMAPLIB in WLST

wls:/offline> import imaplib
wls:/offline> dir(imaplib)
['AllowedVersions', 'CRLF', 'Commands', 'Continuation', 'Debug', 'Flags', 'IMAP4
', 'IMAP4_PORT', 'Int2AP', 'InternalDate', 'Internaldate2tuple', 'Literal', 'Mon
2num', 'ParseFlags', 'Response_code', 'Time2Internaldate', 'Untagged_response',
'Untagged_status', '_Authenticator', '__all__', '__doc__', '__file__', '__name__
', '__version__', '_cmd_log', '_cmd_log_len', '_dump_ur', '_log', '_mesg', 'bina
scii', 'print_log', 'random', 're', 'socket', 'sys', 'time']
This is implib

telnet Library in WLST

Just for connectivity before create your database connection pools.
wls:/offline> import telnetlib
wls:/offline> dir(telnetlib)
['AO', 'AUTHENTICATION', 'AYT', 'BINARY', 'BM', 'BRK', 'CHARSET', 'COM_PORT_OPTI
ON', 'DEBUGLEVEL', 'DET', 'DM', 'DO', 'DONT', 'EC', 'ECHO', 'EL', 'ENCRYPT', 'EO
R', 'EXOPL', 'FORWARD_X', 'GA', 'IAC', 'IP', 'KERMIT', 'LFLOW', 'LINEMODE', 'LOG
OUT', 'NAMS', 'NAOCRD', 'NAOFFD', 'NAOHTD', 'NAOHTS', 'NAOL', 'NAOLFD', 'NAOP',
'NAOVTD', 'NAOVTS', 'NAWS', 'NEW_ENVIRON', 'NOOPT', 'NOP', 'OLD_ENVIRON', 'OUTMR
K', 'PRAGMA_HEARTBEAT', 'PRAGMA_LOGON', 'RCP', 'RCTE', 'RSP', 'SB', 'SE', 'SEND_
URL', 'SGA', 'SNDLOC', 'SSPI_LOGON', 'STATUS', 'SUPDUP', 'SUPDUPOUTPUT', 'SUPPRE
SS_LOCAL_ECHO', 'TELNET_PORT', 'TLS', 'TM', 'TN3270E', 'TSPEED', 'TTYLOC', 'TTYP
E', 'TUID', 'Telnet', 'VT3270REGIME', 'WILL', 'WONT', 'X3PAD', 'XASCII', 'XAUTH'
, 'XDISPLOC', '__all__', '__doc__', '__file__', '__name__', 'select', 'socket',
'sys', 'test', 'theNULL']
This is having more functions and variables check it...

httplib in WLST for Sanity check

You can use 'httplib' for checking sanity of an application after deployment.
wls:/offline> import httplib
wls:/offline> dir(httplib)
['BadStatusLine', 'CannotSendHeader', 'CannotSendRequest', 'FakeSocket', 'HTTP',
 'HTTPConnection', 'HTTPException', 'HTTPMessage', 'HTTPResponse', 'HTTPS', 'HTTPSConnection', 'HTTPS_PORT', 'HTTP_PORT', 'ImproperConnectionState', 'IncompleteRead', 'InvalidURL', 'LineAndFileWrapper', 'NotConnected', 'ResponseNotReady', 'SSLFile', 'SharedSocket', 'SharedSocketClient', 'StringIO', 'UnimplementedFileMode', 'UnknownProtocol', 'UnknownTransferEncoding', '_CS_IDLE', '_CS_REQ_SENT', '_CS_REQ_STARTED', '_UNKNOWN', '__all__', '__doc__', '__file__', '__name__', 'errno', 'error', 'mimetools', 'socket', 'test', 'urlsplit']
Here, I fond the HTTPLIB example given by Valdmir blog post->Python: HTTP Basic authentication with httplib. Where in the Python script used to do the Sanity test for a provided application URL, which uses the authentication provided using base64 module.

The xmlrpclib library for WLST

This is xmrpclib can be used while interacting with config.xml file. have a look and decide :)
wls:/offline> import xmlrpclib
wls:/offline> dir(xmlrpclib)

['ArrayType', 'Binary', 'Boolean', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DateTime', 'DictProxyType', 'DictType','DictionaryType', 'EllipsisType', 'Error', 'ExpatParser', 'False', 'FastParser',
 'FastUnmarshaller', 'Fault', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MAXINT', 'MININT', 'Marshaller', 'MethodType', 'ModuleType', 'NoneType',
'ObjectType', 'ProtocolError', 'ResponseError', 'SafeTransport', 'Server', 'ServerProxy', 'SgmlopParser', 'SliceType', 'SlowParser', 'StringType', 'StringTypes', 'TracebackType', 'Transport', 'True', 'TupleType', 'TypeType', 'UnboundMethodT
ype', 'UnicodeType', 'Unmarshaller', 'WRAPPERS', 'XRangeType', '_Method', '__doc__', '__file__', '__name__', '__version__', '_decode', '_stringify', 'binary', 'boolean', 'classDictInit', 'datetime', 'dumps', 'escape', 'getparser', 'loads','operator', 're', 'string', 'time']

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 -->

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

Wednesday, May 19, 2010

WebLogic Scripting Tool (WLST) Overview

-->
There are many newbies into the WebLogic stream ( Development/ Administration). Most of them are novice to WLST. I thought let me found a way to give you best links available on the net.

After being in the development team one of my buddy asked me "your blogs are very nice, I want to learn WLST. But where to start? " My answer for all my blog readers who want to encourage newbies in WLST can pass this post. Currently WLST is supporting Application Servers are listed as follows:
  • WebLogic 8.1
  • BEA WebLogic 9.0
  • BEA WebLogic 9.1
  • BEA WebLogic 9.2
  • BEA WebLogic 10.0
WLST is first initiated in the BEA System Inc., days so it is supported since WebLogic 8.1 onwards with latest service packs till WebLogic version 10.0. After Oracle acquisition following are the versions:

  • Oracle WebLogic 10g R3
  • Oracle WebLogic 11gR1
  • Oracle WebLogic 11gR1 PatchSet 1 (10.3.1)
  • Oracle WebLogic 11gR1 PatchSet 2 (10.3.2)
  • Oracle WebLogic 11gR1 PatchSet 3 (10.3.3)
  • Oracle WebLogic 12c

WLST Features indentation - Clear Sytax


The WLST programming structure follows strict syntax indentation and it is the same structure as in Python programming. As per my experiances with WLST it can be divided into four parts
  1. Importing section
  2. Global variables
  3. Definations - class/function
  4. Main program uses above sections

Import section for Reuse
importing WLST libraries includes Python standard libraries and thousands of new Jython libraries also included. You can have Java packages as module imports which gives you flexible programming.

While writing a WLST script, the file can be store with the extension .py are called python modules. We can reuse the external language such as Java methods into our WLST script you can use import statement for this. Here is the syntaxes that you can use.

import module
from module import submodule
from . import submodule

You can write a WLST script that uses command line aruguments using sys module sys.args.

WLST Datatypes - Global variables

In WLST you can define the global variables on the top of the program that can be used across all the functions defined in the script. On the other hand you can define the variables in the function definitions that can be treated as local to the function, Jython programming language supported datatypes all can be used it supports
  • Base Datatypes: integer, float, long, char, str, bool
  • Collection Types: list, dictionary, tuple, sequances, maps etc
  • Object types: Python objects and Java package objects
Dynamic typing
In WLST supports Python Dynamic typing, we can use same variable for storing different type of data as shown below.
wls:/offline> # VAR CAN CHANGE INTO MANY TYPES
wls:/offline> var=10
wls:/offline> print var
10
wls:/offline> var='Busy in WLST'
wls:/offline> print var
Busy in WLST
wls:/offline> var=[1,2,3]
wls:/offline> print var
[1, 2, 3]

Class in WLST

Object oriented scripting can be defined and can be reusable with creation of objects.
 
class CLASSNAME:
 def __init__():   #like C++ constructor
  self.name
  do something initially
 def function1():
  do some task 
Let’s experiment with class in WLST. In a class we can define attributes and we can assign values to them. And we define functions related to that class that you will make.
wls:/offline> class test:
...     u,p='weblogic','vybhav@28'
...
After this we are able to create instances of the class test. Let us create t as a instance of test class.
wls:/offline> t=test()
wls:/offline> print t.u,t.p
weblogic vybhav@28
There is a difference between class attribute and instance attributes. Let us know about it, The variables u, and p of the instance can be modified by assignment:
wls:/offline> t.u='vasuakka'
wls:/offline> t.u
'vasuakka'
In u attribute value was changed into ‘vasuakka’ instead of ‘weblogic’.

Function definitions in WLST

How to define a Function in WLST? It is simple it starts with keyword ‘def’, you need to give a name of the function followed by number of argument and a colon. After this you need to give a tab space indentation that indicates the function block. You can add text to tell about what this function will do. Then you can add number of WLST statements or control flow statements. At the bottom of the function you can return a value or you leave that line, it is optional.
Now, let’s experiment with function definition for conversion of Kilobytes to megabytes. The logic of this function is that we can get the megabyte value when you pass the argument as kilobyte this will be divided by 1024.
wls:/offline> def kb2MB(kb):
...     mb=kb/1024
...     return mb
...
wls:/offline> print kb2MB(2048)
2

WLST Operators

You WLST commands statements not only JMX accessing functions we need to use some of the Python programming control flows in it. To use the control flow you must know about what kind of operations you can do in WLST. So let us see some of them are:

Comparison operators
This opertators we can use in regular if statements or while statements
==, >, <, <=, =>

Logical Operators
In WLST the variable can be empty or zero values are treated as "", 0, None, 0.0, [], and {}. So you need to be careful when you define a variable and moved the values of variables.

How WLST script Execution works?

Here I am going to explain with the following picture, how the Python script will be interpreted and internally compiled to java code and then Byte code so that it can be executable on JVM.
WLST Execution process
The source code for the WLST script is written in Python code. The WLST program file must have the extension as .py which is the source code consisting a set of Jython instructions for WebLogic domain. This source code is going to use a JVM machine when it is instructed to RUN the script; its invocation internally generates Java byte code to interpret with the JVM to produce the desired output. You might wonder by seeing this Chines WLST link, but it is worthy to see in google chrome. Because the web-page is from china and entire page is in chaineese language. If you have Google Chrome it will give you translate on top of the page you can choose your choice of language and have knowledge on WLST :) Here I am sharing the wonderful presentation about WLST overview. Check this following SlideShare Presentation: it's pretty informative, it was delivered by James Bayer who is the technical expert from Oracle. Especially I more impressed myself to see the 47 slide saying about THIS blog as one of the web reference.
Thankyou for visiting this post, feel free to post your comments after viewing these video links.

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... -->

Sunday, May 24, 2009

Cosmotising your WLST output

Here I am with new idea that colored output according to the state of the Server.
Hope most of you(WLA) knows WLST script for displaying Server status, my idea is when the server state is in SHUTDOWN state let it display in red color, STARTING state in YELLOW, and geen for RUNNING state and so on... colors you can specify as per your choice. 

I ran thru google for searching colors in python... it is simple logic print instruction in python putting UNIX shell code way. The color code need to be prefix in the line where color need to appear in the output.



My choice of WLST is that it should have a provision to rerun the script if user wish to run the script after a while. this makes less time to get output because re-initializing of WLST is not required 

CODE Snippet:
#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'



Thursday, April 30, 2009

WLST Thread Count

WLST Thread Count in WebLogic 9.x and all higher version the Thread model is depends on WorkManager. The WorkManager internally uses self-tuning threads for each WebLogic Server instances.
-->

To get the thread Model and its Idle count as in the WebLogic 8.1 we need to tune the server instance parameter in the config.xml. While changing this you should be cautious,

 make sure you have  a backup copy the config.xml before editing.
Enter the following line in the child element, given same level as element.



Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. <use81-style-execute-queues>true</use81-style-execute-queues>



Full detail description about how to change this parameter is given here...
http://download.oracle.com/docs/cd/E13222_01/wls/docs92/perform/appb_queues.html

The WLST script for Thread count monitoring will be as follows: 



######################################################
# This script is used to monitor all servers
# Author: Pavan Devarakonda
# Date:   28th April 2009
######################################################
import thread
 
# Configured user credentials with storeUserConfig
 
 ucf='keypath/xuserconfig.key'
 ukf='keypath/xkeyfile.key'
 admurl = "t3://hostingdns.com:port"
  
 def monitorThrds():
     connect(userConfigFile=ucf, userKeyFile=ukf, url= admurl )
     serverNames = getRunningServerNames()
     domainRuntime()
     print 'EXECUTE QUEUES'
     print ' '
     print 'Execute   Total  Current   PendRequest ServicedRequest'
     print 'QueueName Count  IdleCount CurrCount   TotalCount '
     print '===========**=======**=================================='
     for snam in serverNames:
         try:
                 cd("/ServerRuntimes/" + snam.getName() + "/ExecuteQueueRuntimes/weblogic.kernel.Default") 
                 totcnt=get('ExecuteThreadTotalCount') 
                 idlecnt = get('ExecuteThreadCurrentIdleCount')
                 pndcnt =get('PendingRequestCurrentCount') 
                 sevcnt = get('ServicedRequestTotalCount') 
                 print '%10s  %4d    %4d    %4d   %16d' %  (snam.getName(), totcnt, idlecnt, pndcnt, sevcnt) 
         except WLSTException,e:
                 # this typically means the server is not active, just ignore
                 pass
  
 def getRunningServerNames():
         domainConfig()
         return cmo.getServers()
  
 if __name__== "main":
     monitorThrds()
     disconnect()

Wednesday, April 22, 2009

JVM Monitoring with WLST

Hey dear WLAs, here I am with a new assignment for JVM monitoring. The fresh production environment setup with Clustered Domain with multiple physical locations with multiple UNIX machines.

The WebLogic capacity planning going on and various low memory or OutOfMemory issues araising when new migration happen from WebLogic 8.1 to 9.2 MP3. To identity how the Garbage Collection working? How much free memory is available for each instance? This can be known with JVM statistics, which inturn tuning the JVM parameters or reset is easy for decide.

I had found a JVM monitoring script that is best suites to my WebLogic environment.

This script is able to get all server instances JVM statistics with a single run. The beauty of WLST is that it runs on single JVM and provides us the required output with the help of domain, server Runtime MBeans, which are supported by WebLogic 9.x and later releases by default supporting JMX 1.2, which has many good features to control and monitor the Runtime Environment of a WebLogic Server instance.


Here have the script which I have modified as per my task there is little C-style customization done with Python language syntax. I mean in Jython which actally used in the WLST.


This could be further refined but ... short of time I am pubishing this
Enjoy!!! Jython/WLST SCRIPTING

#You can create key files
ucf='keypath/xuserconfig.key'
ukf='keypath/xkeyfile.key'
admurl = "t3://hostingdns.com:port"

# This module is for retrieve the JVM statistics
def monitorJVMHeapSize():
     connect(userConfigFile=ucf, userKeyFile=ukf, url=admurl)
     # alternate connect('user', 'passwd', 'adminurl')
     serverNames = getRunningServerNames()
     domainRuntime()

     print '                TotalJVM  FreeJVM  Used JVM' 
     print '=============================================='
     for name in serverNames:
   try:
    cd("/ServerRuntimes/"+name.getName()+"/JVMRuntime/"+name.getName())
    freejvm = int(get('HeapFreeCurrent'))/(1024*1024)
    totaljvm = int(get('HeapSizeCurrent'))/(1024*1024)
    usedjvm = (totaljvm - freejvm)
    print '%14s  %4d MB   %4d MB   %4d MB ' %  (name.getName(),totaljvm, freejvm, usedjvm)
   except WLSTException,e:
     pass

# This module for managed Servers list
def getRunningServerNames():
     domainConfig()
     return cmo.getServers()
 
if __name__== "main":
     monitorJVMHeapSize()
     disconnect()

Here in this program you can add more functionality with getting the HeapFreePercent. It is just a variable assigned with get('HeapFreePercent') . Later, You can print that variable value.

Popular Posts