Search This Blog

Monday, May 31, 2010

JDBC datasource monitoring

"JDBC Monitoring" script, which I was published 2 days back works good for simple single data source and also multi datasources on a domain. But, there is an inadquate information about targeted servers that script doesn't have the flexibility for displaying those managed server mapping with a DataSource.

One of blog follower(Mr. Venkatesh Durai) asked me for the same, A script works for managed server wise display for the Datasource performance monitoring with WLST. It was already discussed by Srikanth Sonti and Vijay Bheemaneni in Oracle WLST ORKUT forums.


Orkut link
Here we go with the latest script, HTH scriptors...

#========================================================
# ScriptFile: DSMonitor.py 
# Author : Pavan Devarakonda
# Purpose : Multi Datasource monitoring with Server wise
#========================================================
urldict={}
def conn():
try:
    print 'Connecting to Admin server....'
    connect(username, password, adminurl)
except:
    print 'Admin Server NOT in RUNNING state....'


def initialize():
    conn()
    try:
        serverlist=['app01','app02','app03'...]
        for s in serverlist:
            cd("/Servers/"+s)
            urldict[s]='t3://'+get('ListenAddress')+':'+str(get('ListenPort'))
            JDBCStat()
     except:
          print 'issue in accessing JDBC Pool'

def printline():
    print '------------------------------------------------------------'

def printHeadr():
    print 'JDBC CONNECTION POOLS STATISTICS'
    print ' '
    print 'Name      Max      Active  Active   WaitSecs Waiting  State'
    print '          capacity Current HighCnt  HighCnt  Count'
    printline()

def getJDBCDetails():
    pname=get("Name")
    pmcapacity=get("CurrCapacityHighCount")
    paccc = get("ActiveConnectionsCurrentCount")
    pachc = get("ActiveConnectionsHighCount")
    pwshc = get("WaitSecondsHighCount")
    pwfccc = get("WaitingForConnectionCurrentCount")
    pstate = get("State")
    print '%10s %7d %7d %7d %7d %7d %10s' % (pname,pmcapacity,paccc,pachc, pwshc,pwfccc,pstate)
    print ' '

def JDBCStat():
    Ks = urldict.keys()
    Ks.sort()
    printHeadr() 
    for s in Ks:
    try:
        connect(user, passwd,urldict[s])
        serverRuntime()
        cd('JDBCServiceRuntime/'+s+'/JDBCDataSourceRuntimeMBeans/')
        print ' '+s
        printline()
        DSlist=ls(returnMap='true')
        for ds in DSlist:
            cd(ds)
            getJDBCDetails()
            cd('..')
    except:
 #pass
        print 'Exception'
        quit()

def quit():
    print ' Hit any key to Re-RUN this script ...' 
    Ans = raw_input("Are you sure Quit from WLST... (y/n)")
    if (Ans == 'y'):
        disconnect()
        stopRedirect()
    else:
        JDBCStat() 

if __name__== "main":
    redirect('./logs/JDBCCntwlst.log', 'false')
    initialize()
    print 'done'




How to run this Script??
Recently one of my blog follower wrote to me " What is the right way for running this monitoring scripts?". Here I am editing my blogs for more readable and flexible for novice WLA.

You need to update with your environment details at line 5, 11, 14. Create this script in a separate folder where you should maintain logs folder, this is expected by line 67.

To run the above script you need to use regular WLST invoking command as follows:
prompt> java weblogic.WLST DSMonitor.py

This is universal way of running WLST I mean on UNIX flavours, on Windows, on Mac OS too.

Friday, May 28, 2010

Mail from WLST when abnormal state for Server

In most of production environments there could be possibility of a WebLogic server instances go on overload and crash or it could reach to a non RUNNING state due to many reasons. But if we know the state of that WebLogic server instance then we can act immediately for further harm to be predicated and confidently control that could happen  in that WebLogic domain.


Python network library smtplib in WLST

WLST supports multiple the network libraries such as

  1. ftplib 
  2. poplib 
  3. imaplib 
  4. smtplib 
  5. telnetlib 
these are  network capabilities in their process, scripting we need to import the libraries and you can use the built-in functions. Before using this smtp libraries you need to check the SMTP service enabled on the machine.

Here I am trying to send the alert mail message when one of the WebLogic Managed Server goes to SHUTDOWN state or UNKNOWN state or some other state which is not RUNNING.

-->

Assuming that your machine have SMTP mail service must enabled. Check before creating this script on the box. Here in the following script you can replace the 'To' address value given as  pavanwla@MAILSERVER.com with mailing address of your supporting WebLogic Administrators (WLA) list by comma separation.
#======================================================
# Script File : StatusMail.py
# Author      : Pavan Devarakonda
# Updated on  : 29th April 2010
#======================================================
import smtplib
import time

From = "wla@WLSERVER.com"
To   =["pavanwla@MAILSERVER.com"]
Date = time.ctime(time.time())
URL='t3://'+get('ListenAddress')+':'+str(get('ListenPort'))

def getServerNames():
   domainConfig()
   return cmo.getServers()

def mailing(name, stat):
    serverRuntime()
    serverConfig()
    if stat == 'SHUTDOWN':
        Subject = ' major: '
    else:
        Subject= 'Critical:'
    Subject= Subject + 'The Weblogic server instance ' +name + ' is ' + stat

    Text='The Server ' +name +'   in the '+ stat+'  Listening at URL ' + URL
    Msg = ('From: %s\r\nTo: %s\r\nDate: \%s\r\nSubject: %s\r\n\r\n%s\r\n' %(From, To, Date, Subject, Text))
    s = smtplib.SMTP('YOURSMTP.DOMAIN.COM')
    rCode = s.sendmail(From, To, Msg.as_string())
    s.quit()

    if rCode:
        print 'Fail to send message...'

def serverStatus(server):
    cd('/ServerLifeCycleRuntimes/' +server)
    return cmo.getState()

def checkStatus():
    try:
        connect('username','******','t3://adminIP:AdminPort')
        serverNames= getServerNames()
        domainRuntime()
        for name in serverNames:
            print name        
            serverState = serverStatus(name)
            if serverState == "SHUTDOWN": 
                mailing(name, serverState)
            elif serverStat == 'UNKNOWN':
                mailing(name, serverState)
    except:
        mailing('AdminServer','Connection Fail')

if __name__== "main":
    redirect('./logs/status.log', 'false')
    checkStatus()
    print 'done'
To make you more comfortable here you need to update few lines 7, 8 10, 27, and 40. Hope you have idea what need to replace in these lines! for your environment.

Cronjob schedule

If you need this script need to run for every 30 mins you can schedule the following line into a shell script. map the shell script to crontab by giving the -e option. If got any trouble please write back to me :)

To test run this script in UNIX/Windows/MacOS/anyother...
prompt> java weblogic.WLST StatusMail.py

Keep posting your valuable comments and suggestions on this post.

References:

  1. http://docs.python.org/library/smtplib.html
  2. http://uthcode.sarovar.org/pyconindia2010/presentation.html

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.

Popular Posts