May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Automation of Monitoring Weblogic Server Runtime using WLST


Automation of Monitoring Weblogic Server Runtime using WLST

In a production environment, the health and the runtime of the Weblogic server instances must be pro-actively monitored in order to prevent the outage/interruption of the service to customers.In this post I am explaining how theWLST (WebLogic Scripting Tool) can be used to automate the monitoring of Weblogic Domains. WLST is based on Jython which is a Java implementation of Python.Since WLST is using the syntax of Python, indentation must be strictly followed.Here in the below script, we are using WLST Online mode to connect to the Admin Server of the Weblogic domain and then interact with the servers’ MBeans. Weblogic server stores the Runtime information in a hierarchical data model called MBean. Its like UNIX file system and you can use cd(), ls() and pwd() commands to navigate to the directories of Weblogic instances which are part of the domain and then you can read various Runtime attributes using the cmo.getXXXX() function. cmo stands for the Current Management Object. Below is an example statement to get the state of a Weblogic server instance.

cd(‘domainRuntime:/ServerLifeCycleRuntimes/’+serverName)
serverState=cmo.getState()

Connect() function can be used to connect to the admin server and then the serverRuntime() function can be used to switch to the domain’s runtime MBean tree. Following is the syntax for the connect function.

connect(“username”,”password”,”admin_server_url”)

Following Weblogic domain runtime attributes are monitored by this wlst script.

  • Server State
  • Server Health
  • Idle Thread Count
  • Application Status
  • JDBC Datasouce State
  • JMS Pending Messages
 
####################################################################################
# Name : weblogic_report.py
# Author  : T.Sivashanker
# Purpose   : To generate a report of various weblogic runtime attributes
####################################################################################
import thread
import sys
import string
import java.util.Date as Date
import reusername=’weblogic’
password=’admin123′
admin_url=’t3://localhost:7001’#Connect to the admin server.
try:
connect(username,password,admin_url)
except:
#Disconnect from the admin server.
disconnect()
#Exit the wlst scripting tool.
exit()
#Exit the python program.
sys.exit(0)reportStatus=’GREEN’#To get the names of all the servers in the weblogic domain.
servers = [‘admin_server’,’Managed_Server-01′,’Managed_Server-02′,’Managed_Server-03′]# Open the html file
fo = open(‘/usr/siva/reportContent.html’,’w+’);########################################################################################
###                      To get the State  of the servers                            ###
########################################################################################
for server in servers:stateColor=’lime’try:
cd(‘domainRuntime:/ServerLifeCycleRuntimes/’+server)
serverState=cmo.getState()
if(serverState != ‘RUNNING’):
stateColor=’red’
except:
serverState=’UNKNOWN’
stateColor=’red’
reportStatus=’RED’########################################################################################
###                      To get the Health of the servers                            ###
########################################################################################
for server in servers:healthColor=’lime’

try:
cd(‘domainRuntime:/ServerRuntimes/’+server)
serverStateX=cmo.getState()
tempHealthState=cmo.getHealthState().getState()
if (tempHealthState == 0):
serverHealthState=’OK’
except:
serverHealthState=’FAILED’
healthColor=’red’
reportStatus=’RED’

########################################################################################
###                          To get the Idle Thread count                            ###
########################################################################################
domainRuntime()

for server in servers:

if( string.find(server,’admin’) != -1):
continue
color=’lime’

try:
cd(‘domainRuntime:/ServerRuntimes/’+server+’/ExecuteQueueRuntimes/weblogic.kernel.Default’)
idlecount=get(‘ExecuteThreadCurrentIdleCount’)

except:
idlecount=0
color=’red’
reportStatus=’RED’

if (idlecount < 10):
color=’red’
elif(idlecount >= 10 and idlecount <20):
color=’#F8A136′
reportStatus=’AMBER’
else:
color=’lime’

########################################################################################
###                          To get the Application status                           ###
########################################################################################
domainRuntime()

cd(‘domainRuntime:/AppRuntimeStateRuntime/AppRuntimeStateRuntime’)
AppList = cmo.getApplicationIds()

for App in AppList:
color=’lime’
AppState=cmo.getIntendedState(App)

if (AppState!=’STATE_ACTIVE’):
color=’red’
reportStatus=’RED’

if( AppState == None ):
#continue
AppState=’None’

########################################################################################
###                          To get JDBC DataSource status                           ###
########################################################################################
totalCount1=0
currentCount1=0
highCount1=0
jdbcstate1=”

for server in servers:

if( string.find(server,’admin’) != -1):
continue
#currentcolor1=’lime’
jdbccolor1=’lime’

totalCount1=0
currentCount1=0
highCount1=0
jdbcstate1=”

try:
cd(‘domainRuntime:/ServerRuntimes/’+server+’/JDBCServiceRuntime/’+server+’/JDBCDataSourceRuntimeMBeans/<jdbc_name>’)

totalCount1=get(‘ConnectionsTotalCount’)
currentCount1=get(‘ActiveConnectionsCurrentCount’)
highCount1=get(‘ActiveConnectionsHighCount’)
jdbcstate1=get(‘State’)

except:
currentcolor=’red’
reportStatus=’RED’

if(jdbcstate1 != ‘Running’):
jdbcstate1=’FAILED’
jdbccolor1=’red’

########################################################################################
###                          To get JMS Pending Messages                             ###
########################################################################################
runningServers = domainRuntimeService.getServerRuntimes();
count=0

#To get the count of JMS Destinations
for server in runningServers:
tempname=str(server)
if( string.find(tempname,’admin’) != -1):
continue
jmsRuntime = server.getJMSRuntime();
jmsServers = jmsRuntime.getJMSServers();
for jmsServer in jmsServers:
destinations = jmsServer.getDestinations();

for destination in destinations:
count=count+1

break

x=0
while (x < count):
x = x + 1
print(“\
Destination”+str(x)+”\
\
“);

pendingColor=’lime’

for server in runningServers:
tempname=str(server.getName())
if( string.find(tempname,’admin’) != -1):
continue
fo.write(“\
<tr>\n\
<td>”+tempname+”</td>\n\
“);
jmsRuntime = server.getJMSRuntime();
jmsServers = jmsRuntime.getJMSServers();
for jmsServer in jmsServers:
destinations = jmsServer.getDestinations();
for destination in destinations:
pendingMessages=destination.getMessagesPendingCount()
if(pendingMessages != 0):
pendingColor=’red’
print str(pendingMessages)

for server in runningServers:
tempname=str(server.getName())
if( string.find(tempname,’admin’) != -1):
continue
jmsRuntime = server.getJMSRuntime();
jmsServers = jmsRuntime.getJMSServers();
for jmsServer in jmsServers:
destinations = jmsServer.getDestinations();

for destination in destinations:

x=destination.getName()
x = x[x.find(‘@’)+1:len(x)]

fo.write(“\
<li>\n\
“+str(x)+”\
</li>\n\
“);
break

#Disconnect from the admin server.
disconnect()
#Exit the wlst scripting tool.
exit()
#Exit the python program.
sys.exit(0)
print “the END”

Above wlst script can be run using the command javac by specifying the classpath of the weblogic.jar.

java -cp /<MIDDLE_WARE_HOME>/server/lib/weblogic.jar weblogic.WLST wls_report.py
weblogic wlst workmanager monitoring
import thread
from java.util import Date
from java.text import SimpleDateFormat
# Configured user credentials with storeUserConfig

def monitorThrds():
connect(“weblogic”, “pwd”, “t3://IP:Port”);
serverNames = getRunningServerNames()
domainRuntime()

for i in range(10000):
print ‘[‘ + SimpleDateFormat(‘d MMM yyyy HH:mm:ss’).format(java.util.Date()) + ‘]’
for sname in serverNames:
try:
cd(“domainRuntime:/ServerRuntimes/” + sname.getName() + “/MaxThreadsConstraintRuntimes/MaxThreadConstraint-oms”)
automaxexecnt=get(‘ExecutingRequests’)
automaxdefcnt = get(‘DeferredRequests’)
cd(“domainRuntime:/ServerRuntimes/” + sname.getName() + “/MaxThreadsConstraintRuntimes/MaxThreadsConstraint-oms.ws.jms”)
jmsmaxexecnt=get(‘ExecutingRequests’)
jmsmaxdefcnt = get(‘DeferredRequests’)
cd(“domainRuntime:/ServerRuntimes/” + sname.getName() + “/MinThreadsConstraintRuntimes/MinThreadsConstraint-oms.automation”)
autominexecnt=get(‘ExecutingRequests’)
autominpendcnt = get(‘PendingRequests’)
cd(“domainRuntime:/ServerRuntimes/” + sname.getName() + “/MinThreadsConstraintRuntimes/MinThreadsConstraint-oms.ws.jms”)
jmsminexecnt=get(‘ExecutingRequests’)
jmsminpendcnt = get(‘PendingRequests’)
print ‘%8s %10s  Min = ( E:%4d    P:%4d )    Max = ( E:%4d        D:%4d )’ %  (“(auto)”, sname.getName(), autominexecnt, autominpendcnt, automaxexecnt, automaxdefcnt)
print ‘%8s %10s  Min = ( E:%4d    P:%4d )    Max = ( E:%4d        D:%4d )’ %  (“(jms)”, sname.getName(), jmsminexecnt, jmsminpendcnt, jmsmaxexecnt, jmsmaxdefcnt)
except WLSTException,e:
# this typically means the server is not active, just ignore
pass
print ‘======================================================================’
print ”
import time
time.sleep(3)
def getRunningServerNames():
domainConfig()
return cmo.getServers()
if __name__== “main”:
monitorThrds()
disconnect()

weblogic wlst jms monitoring
import thread
from java.util import Date
from java.text import SimpleDateFormat
# Configured user credentials with storeUserConfig

def monitorJMS():
connect(“weblogic”, “pwd”, “t3://IP:Port”);
servers = domainRuntimeService.getServerRuntimes();
for i in range(10000):
print ‘[‘ + SimpleDateFormat(‘d MMM yyyy HH:mm:ss’).format(java.util.Date()) + ‘]’
if (len(servers) > 0):
for server in servers:
print ‘  Server Name           ‘ , server
jmsRuntime = server.getJMSRuntime();
jmsServers = jmsRuntime.getJMSServers();
for jmsServer in jmsServers:
destinations = jmsServer.getDestinations();
for destination in destinations:
print destination.getName()
print ‘  MessagesCurrentCount        ‘ ,  destination.getMessagesCurrentCount()
print ‘  MessagesHighCount           ‘ ,  destination.getMessagesHighCount()
print ‘  MessagesMovedCurrentCount   ‘ ,  destination.getMessagesMovedCurrentCount()
print ‘  MessagesPendingCount        ‘ ,  destination.getMessagesPendingCount()
print ‘  MessagesReceivedCount       ‘ ,  destination.getMessagesReceivedCount()
print ”
import time
time.sleep(10)
if __name__== “main”:
monitorJMS()
disconnect()

weblogic wlst thread monitoring
from java.util import Date
from java.text import SimpleDateFormat
# Configured user credentials with storeUserConfig

def monitorThrds():
connect(“weblogic”, “pwd”, “t3://IP:Port”);
serverNames = getRunningServerNames()
domainRuntime()

for i in range(10000):
print ‘[‘ + SimpleDateFormat(‘d MMM yyyy HH:mm:ss’).format(java.util.Date()) + ‘]’
print ‘======================================================================’
print ‘| Execute     Total    Idle    Pending     Hogging    Queue     StdBy’
print ‘| QueueName   Count    Count    Count       Count     Length    Count’
print ‘======================================================================’
for sname in serverNames:
try:
cd(“domainRuntime:/ServerRuntimes/” + sname.getName() + “/ThreadPoolRuntime/ThreadPoolRuntime”)
totcnt=get(‘ExecuteThreadTotalCount’)
idlecnt = get(‘ExecuteThreadIdleCount’)
pndcnt =get(‘PendingUserRequestCount’)
sevcnt = get(‘HoggingThreadCount’)
queuelength = get(‘QueueLength’)
stdbycnt = get(‘StandbyThreadCount’)
print ‘| %10s  %4d    %4d       %4d        %4d     %4d      %4d’ %  (sname.getName(), totcnt, idlecnt, pndcnt, sevcnt, queuelength, stdbycnt)
except WLSTException,e:
# this typically means the server is not active, just ignore
pass
print ‘======================================================================’
print ”
import time
time.sleep(3)
def getRunningServerNames():
domainConfig()
return cmo.getServers()
if __name__== “main”:
monitorThrds()
disconnect()

weblogic wlst SAF monitoring
from java.util import Date
from java.text import SimpleDateFormat
# Configured user credentials with storeUserConfig

def monitorThrds():
connect(“weblogic”, “pwd”, “t3://IP:Port”);
serverNames = getRunningServerNames()
serverRuntime()
for i in range(10000):
print ‘[‘ + SimpleDateFormat(‘d MMM yyyy HH:mm:ss’).format(java.util.Date()) + ‘]’
print ‘======================================================================’
for sname in serverNames:
try:
cd(“domainRuntime:/ServerRuntimes/” + sname.getName() + “/SAFRuntime/” +sname.getName() + “.saf/Agents”)
try:
agents=cmo.getAgents()
for agName in agents:
#print agName.getName()
cd(agName.getName())
msgpend=cmo.getMessagesPendingCount()
msgcur=cmo.getMessagesCurrentCount()
msgtot=cmo.getMessagesReceivedCount()
#print ‘%s messages received %s  = %d  %d  %d’ % (agName.getName(), sname.getName(), msgcur, msgpend, msgtot)
#print ‘%-30s %s  CUR:%5d   PEND:%5d   RECV:%5d’ % (agName.getName(), sname.getName(), msgcur,msgpend,msgtot )
print ‘%-30s  CUR:%5d   PEND:%5d  RECV:%8d’ % (agName.getName(),  msgcur,msgpend,msgtot )
cd(“..”)
except WLSTException,e:
pass
except WLSTException,e:
# this typically means the server is not active, just ignore
pass
print ‘======================================================================’
print ”
import time
time.sleep(10)
def getRunningServerNames():
domainConfig()
return cmo.getServers()
if __name__== “main”:
monitorThrds()
disconnect()

 

 

weblogic wlst jms monitoring

import thread
from java.util import Date
from java.text import SimpleDateFormat
# Configured user credentials with storeUserConfigdef monitorJMS():
connect(“weblogic”, “pwd“, “t3://IP:Port”);
servers = domainRuntimeService.getServerRuntimes();
for i in range(10000):
print ‘[‘ + SimpleDateFormat(‘d MMM yyyy HH:mm:ss’).format(java.util.Date()) + ‘]’
if (len(servers) > 0):
for server in servers:
print ‘  Server Name           ‘ , server
jmsRuntime = server.getJMSRuntime();
jmsServers = jmsRuntime.getJMSServers();
for jmsServer in jmsServers:
destinations = jmsServer.getDestinations();
for destination in destinations:
print destination.getName()
print ‘  MessagesCurrentCount        ‘ ,  destination.getMessagesCurrentCount()
print ‘  MessagesHighCount           ‘ ,  destination.getMessagesHighCount()
print ‘  MessagesMovedCurrentCount   ‘ ,  destination.getMessagesMovedCurrentCount()
print ‘  MessagesPendingCount        ‘ ,  destination.getMessagesPendingCount()
print ‘  MessagesReceivedCount       ‘ ,  destination.getMessagesReceivedCount()
print ”
import time
time.sleep(10)
if __name__== “main”:
monitorJMS()
disconnect()

WLST to monitor all Datasources on all Managed Servers by connecting only to the Admin

#connect to the admin server

domainRuntime()
allservers=ls('/ServerRuntimes/', returnMap='true')
for server in allservers:
    allds = ls('/ServerRuntimes/' + server + '/JDBCServiceRuntime/' + server + '/JDBCDataSourceRuntimeMBeans', returnMap='true')
    for ds in allds:
        cd ('/ServerRuntimes/' + server + '/JDBCServiceRuntime/' + server + '/JDBCDataSourceRuntimeMBeans/' + ds)
        print server, ds, cmo.getActiveConnectionsCurrentCount()



WLST to dump free heap memory

from java.io import FileWriter
from java.io import BufferedWriter
from java.util import Date
connect(eval('username'),eval('password'),eval('url'))
domainRuntime()
cd('/ServerRuntimes/' + eval('managedServerName') + '/JVMRuntime/' + eval('managedServerName'))
heapFreeCurrentPerOld = str(cmo.getHeapFreePercent())
heapFreeCurrentValOld = str(cmo.getHeapFreeCurrent())
cmo.runGC()
java.lang.Thread.sleep(int(eval('sleepTime')))

heapFreeCurrentPerNew = str(cmo.getHeapFreePercent())
heapFreeCurrentValNew = str(cmo.getHeapFreeCurrent())
newDate = Date()
fstream = FileWriter(eval('outputFile'),true)
out =  BufferedWriter(fstream)
out.write(eval('managedServerName') + "," + str(newDate.getTime()) + "," + heapFreeCurrentPerOld + "," + heapFreeCurrentValOld + "," + heapFreeCurrentPerNew + "," + heapFreeCurrentValNew + "\n");
out.close();
disconnect()
exit()

There is also a property file which contains the configuration information

managedServerName=<MANAGED>
username=<USER>
password=<PASSWORD>
url=<URL>
sleepTime=<PAUSE>
outputFile=<PathToFile.csv>

And finally to run

$WL_SERVER_HOME/common/bin>wlst -loadProperties

 

 

 

 

Monitoring the JCA Adapter’s through WLST script – Oracle SOA 11g

Sometimes we may need to monitor the runtime performance of the JCA adapters, the monitoring is possible through EM console for limited details, the below WLST script will help us to monitor the required details of the JCA adapter (the scrip should be extended to monitor more details).

The below script can be used for monitoring only the DBAdapter’s and MQAdapter’s; the same can be extended to monitor other JCA Adapters (like FileAdapter) .

Before executing the script change the below condition according to your server name.

if server.getName().strip().startswith(‘S’) | server.getName().strip().startswith(‘O’)

The Adapters are only available in SOA and OSB servers so that I am filtering the other servers  based on the name(AdminServer or MS servers) .The exception will be thrown if we are trying to cd the MBean related to Adapters in others servers.

 

 

 

def monitorDBAdapter(serverName):
cd(“ServerRuntimes/”+str(serverName)+”/ApplicationRuntimes/DbAdapter/ComponentRuntimes/DbAdapter/ConnectionPools”)
connectionPools = ls(returnMap=’true’)
print ‘————————————————————————————–‘
print ‘DBAdapter Runtime details for ‘+ serverName
print ‘                                                                                      ‘
print ‘                                                                                      ‘
print ‘————————————————————————————–‘

print ‘%10s %13s %15s %18s’ % (‘Connection Pool’, ‘State’, ‘Current’, ‘Created’)
print ‘%10s %10s %24s %21s’ % (”, ”, ‘Capacity’, ‘Connections’)
print ‘                                                                                      ‘
print ‘————————————————————————————–‘
for connectionPool in connectionPools:
if connectionPool!=’eis/DB/SOADemo’:
cd(‘/’)
cd(“ServerRuntimes/”+str(serverName)+”/ApplicationRuntimes/DbAdapter/ComponentRuntimes/DbAdapter/ConnectionPools/”+str(connectionPool))
print ‘%15s %15s %10s %20s’ % (cmo.getName(), cmo.getState(), cmo.getCurrentCapacity(), cmo.getConnectionsCreatedTotalCount())

print ‘                                                                                      ‘
print ‘————————————————————————————–‘

def monitorMQAdapter(serverName):
cd(“ServerRuntimes/”+str(serverName)+”/ApplicationRuntimes/MQSeriesAdapter/ComponentRuntimes/MQSeriesAdapter/ConnectionPools”)
connectionPoolsMQ = ls(returnMap=’true’)
print ‘————————————————————————————–‘
print ‘MQAdapter Runtime details for ‘+ serverName
print ‘                                                                                      ‘
print ‘                                                                                      ‘
print ‘————————————————————————————–‘

print ‘%15s %17s %15s %18s’ % (‘Connection Pool’, ‘State’, ‘Current’, ‘Created’)
print ‘%15s %15s %24s %21s’ % (”, ”, ‘Capacity’, ‘Connections’)
print ‘                                                                                      ‘
print ‘————————————————————————————–‘
for connectionPoolMQ in connectionPoolsMQ:
cd(‘/’)
cd(“ServerRuntimes/”+str(serverName)+”/ApplicationRuntimes/MQSeriesAdapter/ComponentRuntimes/MQSeriesAdapter/ConnectionPools/”)
cd(connectionPoolMQ)
print ‘%15s %20s %10s %20s’ % (cmo.getName(), cmo.getState(), cmo.getCurrentCapacity(), cmo.getConnectionsCreatedTotalCount())

print ‘                                                                                      ‘
print ‘————————————————————————————–‘

def main():
#connect(username, password, admurl)
connect(‘weblogic’,’password’,’t3://<<SOA Host>>:<<SOA Port>>’)
servers = cmo.getServers()
domainRuntime()
for server in servers:
cd(“/ServerLifeCycleRuntimes/” + server.getName())
if cmo.getState() == ‘RUNNING’:
if server.getName().strip().startswith(‘S’) | server.getName().strip().startswith(‘O’) :
monitorDBAdapter(server.getName())
for server in servers:
cd(‘/’)
cd(“/ServerLifeCycleRuntimes/” + server.getName())
if cmo.getState() == ‘RUNNING’:
if server.getName().strip().startswith(‘S’) | server.getName().strip().startswith(‘O’) :
monitorMQAdapter(server.getName())
disconnect()

main()

 

 

 

 

 

 

Server State using WLST

While trouble shooting administrator need to check the status of all 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.

ServerLifeCycle

 

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 Admin Server
2. Fetch the server list from the domain runtime MBean
3. Iterate the loop and get the state of each managed server with Server Life Cycle Runtime MBean 
4. Repeat if required the step 3 as per the user input
5. Finally disconnect 

##################################################
# 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()

 

 

Monitor Weblogic using WLST in java

Here is the code i used to monitor the weblogic server details written in java using WLST. At times the weblogic console doesnt respond or is very slow. The script helps getting the important data needed during issues and help monitoring the server.Main parameters that we normally want to monitor :
– JVM Stats
– JMS stats
– JTA stats
– Thread Pool
– Deployed Application stateHere goes the java file , it fetches this data and writes to a text file.

Utility method to write the data to file
   public static void writeFile(StringBuffer data) {
     try {
       FileWriter outFile = new FileWriter(“C:\\ServerStats\\serverinfo.txt”);
       BufferedWriter out = new BufferedWriter(outFile);
       out.write(data.toString());
       out.close();
     }catch(Exception e){e.printStackTrace();}
  }
Main code to fetch server info :
The code is pretty simple and additional code for other parameters can be added easily.
  StringBuffer data= new StringBuffer(“Data”);
            MBeanHome home = null;
           String url = “t3://serverurl:port”;
           String username = “weblogic”;
           String password = “welcome1”;
            try {
                Environment env = new Environment();
                env.setProviderUrl(url);
                env.setSecurityPrincipal(username);
                env.setSecurityCredentials(password);
                Context ctx = env.getInitialContext();
                home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
            } catch (Exception e) {System.out.println(“Exception caught: ” + e);}
            try {
                data.append(“DOMAIN NAME :  ” +  home.getActiveDomain().getName() +”\n”);
            } catch (Exception e) {System.out.println(“Exception: ” + e);}
           Set mbeanSet = home.getMBeansByType(“ServerRuntime”);
           data.append(“Number of servers in the domain: ” + mbeanSet.size() +”\n”);
            Iterator mbeanIterator = mbeanSet.iterator();
            int cls=1;
            while(mbeanIterator.hasNext()) {
                ServerRuntimeMBean serverRuntime =  (ServerRuntimeMBean)mbeanIterator.next();
              if(cls==1)
              {
              try{
              ClusterRuntimeMBean clusterruntime = serverRuntime.getClusterRuntime();
              data.append(“————- CLUSTER INFORMATION—————” + “\n”);
              data.append(“1. Cluster Name :  “+clusterruntime.getName()+”\n”);
              data.append(“2. Cluster MulticastMessagesLostCount : “+clusterruntime.getMulticastMessagesLostCount()+”\n”);
              data.append(“3. Cluster Server Names  “+”\n”);
                  for(int j=0;j<clusterruntime.getServerNames().length;j++) {
                    data.append(” Server :  “+(clusterruntime.getServerNames())[j] + “\n”);
                  }
              data.append(“—————————————————————————- “+”\n”);
              }catch(Exception e){e.printStackTrace();}
              }
              //if(cls==1)
              //{
              try{
                data.append(“————- WEB SERVER INFORMATION—————” + “\n”);
              WebServerRuntimeMBean[] webserverruntime = serverRuntime.getWebServerRuntimes();
              for(int j=0;j<webserverruntime.length;j++) {
                data.append(“1. Web server info : Web server Names  “+webserverruntime[j].getWebServerName()+”\n”);
              }
                data.append(“—————————————————————————- “+”\n”);
              }catch(Exception e){e.printStackTrace();}
            if(serverRuntime.getState().equals(ServerStates.RUNNING)){
              data.append(“—————————————————————————- “+”\n”);
              data.append(” INFO STARTS FOR SERVER “+serverRuntime.getName()+” ******”+”\n”);
              data.append(“—————————————————————————- “+”\n”);
                     data.append(“1. Server Name = ” + serverRuntime.getName()+”\n”);
                     data.append(“2. Server ListenAddress = ” +  serverRuntime.getListenAddress()+”\n”);
                     data.append(“3. Server ListenPort = ” +  serverRuntime.getListenPort()+”\n”);
                     data.append(“4. Admin server Host = ” +  serverRuntime.getAdminServerHost()+”\n”);
                     data.append(“5. Health state = ” +  serverRuntime.getHealthState()+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  data.append(” JVM Parameters For SERVER “+serverRuntime.getName()+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  JVMRuntimeMBean jvmruntime = serverRuntime.getJVMRuntime();
                  data.append(“1. JVM Current Heap size = ” + jvmruntime.getHeapSizeCurrent()+”\n”);
                  data.append(“2. JVM  Heap free Current  = ” + jvmruntime.getHeapFreeCurrent()+”\n”);
                  data.append(“3. JVM  Heap free Percent = ” + jvmruntime.getHeapFreePercent()+”%”+”\n”);
                  data.append(“4. JVM  Heap size max = ” + jvmruntime.getHeapSizeMax()+”\n”);
                  data.append(“5. JVM  JavaVersion = ” + jvmruntime.getJavaVersion()+”\n”);
                  data.append(“6. JVM  JavaVendor = ” + jvmruntime.getJavaVendor()+”\n”);
                  try{
                    ExecuteQueueRuntimeMBean[] executeQueueRuntime =serverRuntime.getExecuteQueueRuntimes();
                    data.append(“—————————————————————————- “+”\n”);
                    data.append(” Execute Queue Runtime parameters “+”\n”);
                    data.append(“—————————————————————————- “+”\n”);
                      for(int j =0;j<executeQueueRuntime.length;j++)
                      {
                        data.append(“1. Execute Queue ThreadTotalCount =  “+executeQueueRuntime[j].getExecuteThreadTotalCount()+”\n”);
                        data.append(“2. Execute Queue ThreadCurrentIdleCount =  “+executeQueueRuntime[j].getExecuteThreadCurrentIdleCount()+”\n”);
                        data.append(“3. Pending RequestCurrentCount =  “+executeQueueRuntime[j].getPendingRequestCurrentCount()+”\n”);
                        data.append(“4. PendingRequestOldestTime =  “+executeQueueRuntime[j].getPendingRequestOldestTime()+”\n”);
                      }
                  }catch(Exception e){e.printStackTrace();}
                  data.append(“—————————————————————————- “+”\n”);
                  data.append(”  JTA STATS FOR SERVER “+serverRuntime.getName() +”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  JTARuntimeMBean jtaruntime= serverRuntime.getJTARuntime();
                   data.append( “1. Total Trx = ” + jtaruntime.getActiveTransactionsTotalCount()+”\n”);
                   data.append( “2. Total Abondened Trx = ” + jtaruntime.getTransactionAbandonedTotalCount()+”\n”);
                   data.append( “3. Total Commited Trx = ” + jtaruntime.getTransactionCommittedTotalCount()+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  data.append(” JMS Parameters FOR SERVER  “+serverRuntime.getName()+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  JMSRuntimeMBean jmsruntime= serverRuntime.getJMSRuntime();
                  JMSServerRuntimeMBean[] jmsservers= jmsruntime.getJMSServers();
                  for(int i=0;i<jmsservers.length;i++)
                  {
                     data.append( “1. JMS Server Name = “+jmsservers[i].getName()+”\n”);
                     data.append( “2. MessagesHighCount = “+jmsservers[i].getMessagesHighCount()+”\n”);
                     data.append( “3. MessagesPendingCount = “+jmsservers[i].getMessagesPendingCount()+”\n”);
                     data.append( “3. DestinationsCurrentCount = “+jmsservers[i].getDestinationsCurrentCount()+”\n”);
                  }
                  data.append(“4. JMS Health : ” + jmsruntime.getHealthState()+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                  data.append(” Application Runtime Data FOR SERVER  “+serverRuntime.getName()+”\n”);
                  data.append(“—————————————————————————- “+”\n”);
                 ApplicationRuntimeMBean[] appruntime = serverRuntime.getApplicationRuntimes();
                 for(int j=0;j<appruntime.length;j++)
                 {
                   if(appruntime[j].isEAR())
                   {
                    data.append(“Application Name : ” +appruntime[j].getApplicationName() +”\n”);
                    data.append(“Application Name : ” +appruntime[j].getHealthState() +”\n”);
                   }
                 }
                 // ThreadPoolRuntimeMBean tpoolruntime=serverRuntime.getThreadPoolRuntime();
                    data.append(” INFO ENDS FOR SERVER “+serverRuntime.getName() +”\n”);
                }
              cls++;
            }//while ends
            writeFile(data);

 

 

WEBLOGIC MONITORING SCRIPT in WLST Tool

Web Logic Monitoring Script in WLST which would monitor JVM, Execute Queue, JDBC and JMS resources of all the Web Logic instances running in a domain. Please feel free to modify the script as necessary.

WLST Script:


# WLST WebLogic Server Monitoring Scriptusername=’wxyz’
password=’******’
urldict={}
connect(username,password,’t3://kyarpt5q:9001′)
serverlist=adminHome.getMBeansByType(‘Server’)
for svr in serverlist:
urldict[svr.getName()]=’t3://’+svr.getListenAddress()+’:’+str(svr.getListenPort())
disconnect()

for svr,url in urldict.items():
try:
connect(username,password,url)
jvmrtlist=home.getMBeansByType(‘JVMRuntime’)
print ‘ ‘
print ‘ ‘ 
print ‘The Runtime Stats of Server: ‘+svr 
print ‘ ‘
print ‘JVM’
print ‘ ‘
print ‘FreeJVM TotalJVM UsedJVM’ 
print ‘ ‘
for jvmRT in jvmrtlist:
freejvm = jvmRT.getAttribute(“HeapFreeCurrent”)
totaljvm = jvmRT.getAttribute(“HeapSizeCurrent”)
usedjvm = (totaljvm – freejvm)
print freejvm,’ ‘,totaljvm,’ ‘,usedjvm
print ‘ ‘

eqrtlist=home.getMBeansByType(‘ExecuteQueueRuntime’)
print ‘ ‘
print ‘ ‘
print ‘EXECUTE QUEUES’
print ‘ ‘
print ‘ExecuteQueueName TotalCount CurrIdleCount PendRequestCurrCount ServicedRequestTotalCount’
print ‘ ‘
for eqRT in eqrtlist:
eqname = eqRT.getAttribute(“Name”)
eqtthreads = eqRT.getAttribute(“ExecuteThreadTotalCount”)
eqithreads = eqRT.getAttribute(“ExecuteThreadCurrentIdleCount”)
eqqc = eqRT.getAttribute(“PendingRequestCurrentCount”)
eqthrougp = eqRT.getAttribute(“ServicedRequestTotalCount”)
print eqname,’ ‘,eqtthreads,’ ‘,eqithreads,’ ‘,eqqc,’ ‘,eqthrougp
print ‘ ‘

poolrtlist=home.getMBeansByType(‘JDBCConnectionPoolRuntime’)
print ‘ ‘
print ‘ ‘
print ‘JDBC CONNECTION POOLS’
print ‘ ‘
print ‘Name Maxcapacity ActiveCurrent ActiveHighCount WaitSecondsHighCount WaitingCurrentCount State’
print ‘ ‘
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 pname,’ ‘,pmaxcapacity,’ ‘,paccc,’ ‘,pachc,’ ‘, pwshc,’ ‘,pwfccc,’ ‘,pstate
print ‘ ‘

jmsrtlist=home.getMBeansByType(‘JMSDestinationRuntime’)
print ‘ ‘
print ‘ ‘
print ‘JMS DESTINATIONS’
print ‘ ‘
print ‘Name ByteCurr Pending Received High MsgCurr Pending High Received ConsumersTotal’ 
print ‘ ‘
for jmsRT in jmsrtlist:
jmsname = jmsRT.getAttribute(“Name”)
jmsbcc = jmsRT.getAttribute(“BytesCurrentCount”)
jmsbpc = jmsRT.getAttribute(“BytesPendingCount”)
jmsbrc = jmsRT.getAttribute(“BytesReceivedCount”)
jmsbhc = jmsRT.getAttribute(“BytesHighCount”)
jmsmcc = jmsRT.getAttribute(“MessagesCurrentCount”)
jmsmpc = jmsRT.getAttribute(“MessagesPendingCount”)
jmsmhc = jmsRT.getAttribute(“MessagesHighCount”)
jmsmrc = jmsRT.getAttribute(“MessagesReceivedCount”)
jmsctc = jmsRT.getAttribute(“ConsumersTotalCount”)
print jmsname,’ ‘,jmsbcc,’ ‘,jmsbpc,’ ‘,jmsbrc,’ ‘,jmsbhc,’ ‘,jmsmcc,’ ‘,jmsmpc,’ ‘,jmsmhc,’ ‘, jmsmrc,’ ‘,jmsctc
print ‘ ‘

disconnect()
except:
print “Skipping “+svr
continue

 

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>