Search This Blog

Showing posts with label sample. Show all posts
Showing posts with label sample. Show all posts

Thursday, December 25, 2014

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

Hey WLST scripting enthos Guys!!

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

WLST File input output operations

-->

Standard Out and Error


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

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

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

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

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

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

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

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

for i in writeList:
 print >>fileObj, i

fileObj.close()

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

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

for lines in fileObj.readlines():
 print lines

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

I love my India

I want to go to USA

I want to earn dollars

I want to die in India


The file attributes

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

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

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

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

Testing

with-as operation on Files

Following example shows how to use with

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

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

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

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

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

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

Enjoy with Jython!!! in WLST !!!

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.

Saturday, November 14, 2009

JMS Monitoring using WLST

Let me walk through the script, The script is referring to a secure way of user credential usage in the WLST that is given here .

storeUserConfig() command in WLST can generates 2 file suserKeyFile, userConfigFile. These we can use multiple times in the script so I declared it on the top, Global scope variables, which can be used by any method in the script.
Coming to downside of the script, where you can find the main program logic. We need to understand from the main program onwards that is the good programmer reading habit :).

In the main module we don't want to see unnecessary data while running the script just want to see , so redirect useless data. first connect to the admin server in the domain.

Initialization of the URL dictionary for multiple server instances domain. The JmsStat module will tell you the actual status of each JMSRumtime Mbeans.

Here I got two hurdles the all script output is not from same MBean. I need to display the JMS statics from JMSRuntime MBean and need to navigate to the instance's specific JMS.

The list (ls) content need to store in variable and need to cding (cd)
myJmsls=ls(returnMap='true')

This makes turning point for the following script we surf for this found Satya Gattu Answer in ObjectMix.

Here (myJmsls) variable holds the value into list datastructure. Just by pointing index the value will be returned.

################################################################# 
# This script will  get the jms attributes
# Author : Prasanna Yalam
# Updated by: Pavan Devarakonda
################################################################# 

from java.util import Date

ucf='ursec'
ukf='urkey'
admurl='t3://url'
urldict={}

def conn():
try:
 connect(userConfigFile=ucf, userKeyFile=ukf, url=admurl)
except ConnectionException,e:
 print 'Unable to find admin server...'
 exit()
def initalize():
 serverlist= ['app010','app011',...]
 for svr in serverlist:
 cd("/Servers/"+svr)
 urldict[svr]='t3://'+get('ListenAddress')+':'+str(get('ListenPort'))

def JmsStat():
 d = Date() # now
 print  d 

 print 'Instance         ConCur ConHi ConTot High  MsgCur MsgPnd'
 print 'Name             Count  Count Count  Count Count  Count'
 print '===========**=======**==================================' 
 Ks = urldict.keys()
 Ks.sort()

 for key in Ks:
  try:
   connect(userConfigFile=ucf, userKeyFile=ukf,url=urldict[key])
   serverRuntime()
   cd('JMSRuntime/'+key+'.jms/JMSServers')
   curCnt= get('ConnectionsCurrentCount')
   cHiCnt=get('ConnectionsHighCount')
   cTotCnt=get('ConnectionsTotalCount')

   myJmsls=ls(returnMap='true')
   x=myJmsls[0]
   cd(x)

   hiCnt= get('MessagesHighCount')
   currCnt= get('MessagesCurrentCount')
   pendCnt= get('MessagesPendingCount')
   print '%14s   %4d   %4d  %4d  %4d  %4d  %4d' %  (key, curCnt, cHiCnt, cTotCnt,  hiCnt, currCnt, pendCnt) 
  except:
   print 'Exception...in server:', key
   pass
 quit()

def quit():
 d = Date() # now
 print  d
 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() 
  exit()
else:
 JmsStat()

if __name__== "main":
 redirect('./logs/jmsCnt.log', 'false')
 conn()
 initalize()
 JmsStat()
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. #################################################################
  2. # This script will  get the jms attributes
  3. # Author : Prasanna Yalam
  4. # Updated by: Pavan Devarakonda
  5. #################################################################
  6.  
  7. from java.util import Date
  8.  
  9. ucf='ursec'
  10. ukf='urkey'
  11. admurl='t3://url'
  12. urldict={}
  13.  
  14. def conn():
  15. try:
  16.     connect(userConfigFile=ucf, userKeyFile=ukf, url=admurl)
  17. except ConnectionException,e:
  18.     print 'Unable to find admin server...'
  19.     exit()
  20. def initalize():
  21.     serverlist= ['app010','app011',...]
  22.     for svr in serverlist:
  23.     cd("/Servers/"+svr)
  24.     urldict[svr]='t3://'+get('ListenAddress')+':'+str(get('ListenPort'))
  25.  
  26. def JmsStat():
  27.     d = Date() # now
  28.     print  d
  29.  
  30.     print 'Instance         ConCur ConHi ConTot High  MsgCur MsgPnd'
  31.     print 'Name             Count  Count Count  Count Count  Count'
  32.     print '===========**=======**=================================='
  33.     Ks = urldict.keys()
  34.     Ks.sort()
  35.  
  36.     for key in Ks:
  37.         try:
  38.             connect(userConfigFile=ucf, userKeyFile=ukf,url=urldict[key])
  39.             serverRuntime()
  40.             cd('JMSRuntime/'+key+'.jms/JMSServers')
  41.             curCnt= get('ConnectionsCurrentCount')
  42.             cHiCnt=get('ConnectionsHighCount')
  43.             cTotCnt=get('ConnectionsTotalCount')
  44.  
  45.             myJmsls=ls(returnMap='true')
  46.             x=myJmsls[0]
  47.             cd(x)
  48.  
  49.             hiCnt= get('MessagesHighCount')
  50.             currCnt= get('MessagesCurrentCount')
  51.             pendCnt= get('MessagesPendingCount')
  52.             print '%14s   %4d   %4d  %4d  %4d  %4d  %4d' %  (key, curCnt, cHiCnt, cTotCnt,  hiCnt, currCnt, pendCnt)
  53.         except:
  54.             print 'Exception...in server:', key
  55.             pass
  56.     quit()
  57.  
  58. def quit():
  59.     d = Date() # now
  60.     print  d
  61.     print 'Hit any key to Re-RUN this script ...'
  62.     Ans = raw_input("Are you sure Quit from WLST... (y/n)")
  63.     if (Ans == 'y'):
  64.         disconnect()
  65.         stopRedirect()
  66.         exit()
  67. else:
  68.     JmsStat()
  69.  
  70. if __name__== "main":
  71.     redirect('./logs/jmsCnt.log', 'false')
  72.     conn()
  73.     initalize()
  74.     JmsStat()

Popular Posts