Search This Blog

Showing posts with label Jython. Show all posts
Showing posts with label Jython. Show all posts

Sunday, February 12, 2023

Server State using WLST

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

Why we needWebLogic Server State? What all those states?

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

WebLogic Server Life cycle state diagram

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

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

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

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

There are 2 server(s) in cluster: clstr01

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

ServerLIfecycleRuntime Mbean tree


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

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

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

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

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

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

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

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

Smart Script

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

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

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

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

Server state with redirecting, re in WLST

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


...
best regards! Dianyuan Wang

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

Thursday, December 25, 2014

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

Hey WLST scripting enthos Guys!!

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

WLST File input output operations

-->

Standard Out and Error


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

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

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

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

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

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

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

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

for i in writeList:
 print >>fileObj, i

fileObj.close()

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

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

for lines in fileObj.readlines():
 print lines

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

I love my India

I want to go to USA

I want to earn dollars

I want to die in India


The file attributes

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

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

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

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

Testing

with-as operation on Files

Following example shows how to use with

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

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

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

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

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

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

Enjoy with Jython!!! in WLST !!!

Thursday, April 11, 2013

Home

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

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

Content

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

Technorati Claim token code JDU3DCFE66EH

Sunday, March 20, 2011

WLST Tricks & Tips

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


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

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

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

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

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

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


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

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

    Tip 3. Introspection in WLST


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

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

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

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

    In Jython there could be classes or interfaces
    __class__
    

    Tip 4. Naming Rules for WLST


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

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

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

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

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

    Introspection reveals useful information about your program's objects

    Tip 4 Write a readable script


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

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

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

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

    Tip 5 Convene print statement with str()


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

print 'Heap Size' + str(totalHeap)

Tip 6: Create single properties file

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

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

Tip 7: Using time in WLST


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

Setting UTC time zone in Python

WLST Tricks


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

Trick 1. Multiple Assignment

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

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


Trick 2. Connect admin without Credentials

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

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

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

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

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

Trick 3: Command Trials

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

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

Trick 4: Using loadProperties

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

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


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

for i in serverlist:
    print i

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

Trick 5: How to debug WLST script?

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

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

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

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

java -Dpython.verbose=debug weblogic.WLST

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

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

Trick Cancel the Edit in WLST

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

Trick 6: Suppress Junk Output in WLST

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

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


Trick 7: Resolve indentation/dedent issue with vi setting


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

: set tabspace=4

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

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

Wednesday, December 22, 2010

My way of deployment with WLST

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

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

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

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

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

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

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

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

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

def activating():
    save()
    activate()

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

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

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

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

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

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

Following comments archived from "WLSTBYPANI" post:



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

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

Popular Posts