Search This Blog

Showing posts with label WebLogic 10. Show all posts
Showing posts with label WebLogic 10. Show all posts

Saturday, October 4, 2014

WLST Issues

NoClassDefFoundError: weblogic.WLST issue

While starting WLST Script you might encounter this issue
Exception in thread "main" java.lang.NoClassDefFoundError: weblogic.WLST
   at gnu.java.lang.MainThread.run(libgcj.so.7rh)
Caused by: java.lang .ClassNotFoundException: weblogic.WLST not found in gnu.gcj.runtime.SystemClassLoader{urls=[file:./], parent=gnu.gcj.runtime.ExtensionClassLoader{urls=[], parent=null}}
   at java.net.URLClassLoader.findClass(libgcj.so.7rh)
   at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
   at java.lang.ClassLoader.loadClass(libgcj.so.7rh)
   at gnu.java.lang.MainThread.run(libgcj.so.7rh)


What to do? What is the fix? searched in google but they all said run setWLSEnv.sh or cmd. Here my way is setup two environment variable availble to your shell.

  1. WL_HOME your weblogic installation path
  2. CLASSPATH with WL_HOME/server/lib/weblogic.jar
You can update these environment variables in your .bash_profile or .bashrc or .profile in the Home directory.

One more alternative method is use the wlst.sh script with absolute path.


alias wlst='${MW_HOME}/oracle_common/common/bin/wlst.sh'

Now you can directly use wlst mypthon.py my.properties

Still have problem in invoking WLST?
$ java weblogic.WLST

Initializing WebLogic Scripting Tool (WLST) ...

Problem invoking WLST - java.lang.NoClassDefFoundError: weblogic.management.scripting.WLScriptContext
Solution for this issue is set the JAVA_HOME properly. that means don't use Linux provided Java instead you have to use Oracle JDK or Jrockit as follows:

export JAVA_HOME=/apps/softwares/weblogic/jdk160_05
or 
export JAVA_HOME=/apps/softwares/weblogic/jrockit_160_05
export PATH=$JAVA_HOME/bin:$PATH

Update these lines in your .bash_profile or .profile check in new Window/Terminal or execute your .bash_profile by placing dot.
$ . .bash_profile

Permission Denied issue

Today when I have tried to workout on WLST it was throwing error.It was shocked me! till yesterday it was working why it is not working now. This is common sentence for every issue :) Need to analyze the problem.
pavanbsd@ubuntu:~$ wlst

Initializing WebLogic Scripting Tool (WLST) ...

Jython scans all the jar files it can find at first startup. Depending on the system
, this process may take a few minutes to complete, and WLST may not return a prompt
right away.

*sys-package-mgr*: can't create package cache dir, '/tmpWLSTTemppavanbsd/packages'
java.io.IOException: Permission denied
        at java.io.UnixFileSystem.createFileExclusively(Native Method)
        at java.io.File.createNewFile(File.java:1006)
        at java.io.File.createTempFile(File.java:1989)
        at java.io.File.createTempFile(File.java:2040)
        at com.oracle.cie.domain.script.jython.WLST_offline.getWLSTOfflineInitFilePath(WLST_offline.java:239)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at weblogic.management.scripting.utils.WLSTUtil.getOfflineWLSTScriptPathInternal(WLSTUtil.java:104)
        at weblogic.management.scripting.utils.WLSTUtil.setupOfflineInternal(WLSTUtil.java:300)
        at weblogic.management.scripting.utils.WLSTUtil.setupOffline(WLSTUtil.java:277)
        at weblogic.management.scripting.utils.WLSTUtilWrapper.setupOffline(WLSTUtilWrapper.java:29)
        at weblogic.management.scripting.utils.WLSTInterpreter.(WLSTInterpreter.java:168)
        at weblogic.management.scripting.WLST.main(WLST.java:130)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at weblogic.WLST.main(WLST.java:29)
Problem invoking WLST - java.lang.NullPointerException

Problem here is OS Permission denied to create files in /tmp path. I've remmebered that when I want to try re-install the Weblogic software encountered not enough space in /tmp path. So I had removed all the files forcefully using root user. That makes in accessable to weblogic user to write into the /tmp path.
Here is the solution
sudo chmod 1777 /tmp


Issues in WLST 2 :


This again While Starting with the WLST Shell, we were facing the below issue, offcourse this is common for the first time WLST users:

bash-3.00$ java weblogic.WLST
Initializing WebLogic Scripting Tool (WLST) ...
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/rt.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/weblogic92/server/lib/weblogic.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/rt.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/jsse.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/jce.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/charsets.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/ext/sunjce_provider.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/ext/sunpkcs11.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/ext/dnsns.jar'
*sys-package-mgr*: can't write cache file for '/HomeServerInstancepath/bea/jdk150_10/jre/lib/ext/localedata.jar'
*sys-package-mgr*: can't write index file
Welcome to WebLogic Server Administration Scripting Shell
Type help() for help on available commands
wls:/offline>

animations
-->

To Fix the above issue, we have two options:

1) This problem I had encountered in Solaris machine, We need to change the permissions of /var/tmp/wlstTemp directory content must be accessed by all users means to use "chmod 777"
or
2) we need to define the cache directory path using open for every user path as /tmp/wlstTemp

bash-3.00$ java -Dpython.cachedir=/tmp/wlstTemp weblogic.WLST
Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell
Type help() for help on available commands

wls:/offline>
I found very good referrence blog who always talks technically :) that 'Techtalks'
http://www.prasannatech.net/2009/02/jython-sys-package-mgr-processing-jar.html

Now your turn to comment on this issue how do you feel when you see this on your Solaris machine or Linux machine :)
Keep posting your suggestions too...

Related Posts

Thursday, October 27, 2011

WLST Errors and Exceptions

When first time you started using WLST you might get many of these Python based WLST Errors. Here I had collected few of them which are very simple to handle them with care. Only thing you need to understand when what kind of errors raises, and what need to do to handle them. When there is error on your flow of WLST Script or prompt don't be panic, relax for a moment then after a while take a deep breath and focus on your error and map with one of the following and do the required workaround.


In Jython we have issubclass() to check superclass, subclass relation we can verify class relationship. You can find parent-child relationship with it. As per my understanding the Error hierarchy can be defined in WLST(Jython) as follows:

This WLST(Jython) Error tree I prepared and posted for your reference, so that you can make your script in perfect manner, here you can find what is going wrong why it is happen while working out your script.
try:
 # WLST code Block 
 # perform some tasks that may throw an exception
except ExceptionType, ExceptionVar:
 # WLST code or
 # perform some exception handling
finally:
    # perform tasks that must always be completed (Will be performed before the exception is # raised.)
else:
 # execute code that must always be invoked

The pass statement in WLST

While writing WLST scripts, there are some situations where you need ‘do nothing’ statement syntactically. That is provided by the pass statement. When you start working on Exception handling this statement will be the first experimenting statement for you.

WLST raise statement

In WLST raise is used to generate or invoke an exception condition. The syntax of this statement allows three comma separated expressions which are optional. If no expression is present, WLST attempt to re-raise the last exception that was raised. This raise statement we can use when we need exception handling with robust scripts. When you pass the expressions to the raise statement, the first two expressions are evaluated to get the objects. These objects are then used to determine the type and value of the exception. Omitted expressions are treated as None. The third expression could be used for traceback objects.

wls:/offline> try:
...     raise Exception('SituationalResponse')
...except Exception, e:
...     print e
...
java.lang.Exception: SituationalResponse

SyntaxError

This you cannot be handled with the try-except block, because it will be thrown when your syntax is not in properly arranged, that is in the statement missing indentation or improper arguments. SyntaxError could be raised when the script lines are given for parsing, it will do token by token parsing wherever the improper syntax given WLST Shell points with cap char under the token.


Now let us see the sample indentation issue that raises the Syntax Error.
wls:/offline>; try:
...connect('system','weblogic103','t3://adminhost:adminport')
Traceback (innermost last):
(no code object)
at line 0
File
"", line 2
connect('system','weblogic103','t3://adminhost:adminport')
^
SyntaxError: invalid syntax

Another option for Syntax Error
This Error I have observed when I tried to migrate the WebLogic domain with createDomain() command.

wls:/offline/wdomain>createDomain('/home/backup/olddomain.jar', '/home/otherusr/domains/newdomain',’system', 'weblogic103')
Traceback (innermost last):
  (no code object) at line 0
  File "", line 1
        createDomain('/home/backup/olddomain.jar', '/home/otherusr/domains/newdomain',?system', 'weblogic103')
                                                                                                          ^
SyntaxError: Lexical error at line 1, column 99.  Encountered: "\ufffd" (65533), after : ""

This "Lexical error" got due to the copying from the webpage which has single quotes in different unicode value. When I retype the single quotes it was resolved.

Here in the above sample after issuing try block starting we must use a tab or 4 spaces before connect() command. When it found that is not
having proper indentation it raised the SyntaxError.

NameError


When the name used to do something like print or use in some other expression without assigning the value before it was defined then WLST will raises NameError. When first time scripting most of the time user encounters this unknowingly.

The following example might give you an idea how to resolve your issue.

wls:/offline> var1=100
wls:/offline> var3=var1+var2
Traceback (innermost last):
  File "", line 1, in ?

You can handle this kind of error with our try-except block
wls:/offline> try: var3=var1+var2
...except NameError, e:
...     print "Please check there is: ", sys.exc_info()[0], sys.exc_info()[1]
...
Please check there is:  exceptions.NameError var2

The beauty of handling your Exception/Error more transparent and easy to understand with sys.exc_info() list.

KeyError


This error can be raised by the WLST while using the dictionary objects or map objects accessed with non-matching key.
wls:/offline> urls['b']
Traceback (innermost last):
File
"", line 1, in ?
KeyError: b

ValueError

The ValueError is raised by the WLST shell when there is a inappropriate element is accessed in a list or a variable, that is such as the value specified for searching in the list with index() method. Removing the element which is not really exists in the list.
wls:/offline> L.index('web2')
Traceback (innermost last):
File
"<console>", line 1, in ?
ValueError: list.index(x): x not in list
I was working on thread and JVM monitoring script, encountered with the ValueError in different way. After storing the ThreadPool values, JVM values into local variables I was using C type of formatting to display the data in a row of Table. Some of the attribute values are Long integers, some of them plain integers some of them are strings.
 cd('/ServerRuntimes/'+ svr +'/ThreadPoolRuntime/ThreadPoolRuntime')
 thtot=`get('ExecuteThreadTotalCount')`
 thid= `get('ExecuteThreadIdleCount')`
 hog= `get('HoggingThreadCount')`
 sbth= `get('StandbyThreadCount')`
 cr =`get('CompletedRequestCount')`
 pr =`get('PendingUserRequestCount')`
 ql =`get('QueueLength')`
 th= `get('Throughput')`
 
 cd('/ServerRuntimes/'+svr+'/JVMRuntime/'+svr)
        freejvm = long(get('HeapFreeCurrent'))/(1024*1024)
        totaljvm = long(get('HeapSizeCurrent'))/(1024*1024)
        usedjvm = (totaljvm - freejvm)
      

When I ran with all numbered values with format as %5d it was shouted as follows:
ValueError: unsupported format character ' ' (0x20) at index 23
Don't know what attribute requires which format ... Initially to resolve this display without any format for all attributes values from the MBean.
print svr, thtot, thid, hog, sbth, cr, pr, ql, th, hs, totaljvm, freejvm, usedjvm
But still ValueError was exists, when I updated with formatter it was stuck with CompletedRequestCount that was not integer type, it is actually Long integer type and that was causing the Error. So, changed the format for that attribute it resolved one issue. Now the issue with different index number came... I have an idea that, if I found all the attributes and their data types then it will be easy to fix the right format for each. I tried the following way
print type(thtot),type(thid), type(hog), type(sbth), type(cr), type(pr), type(ql), type(th),type(freejvm), type(totaljvm), type(usedjvm)
formatted accordingly the ValueError is resolved.
print '%14s %10s %5s %5s %5s %5s %8s %5s %5s %8s %5dMB %5dMB %5dMB' %  (svr, hs, thtot, thid, hog, sbth, cr, pr, ql, th, totaljvm, freejvm, usedjvm) 
So now you can take care of Values of variables for your WLST code before use them for any operation!!

AttributeError


You might be on MBean tree where there is no such attribute defined and you tried to access it then WLST Shell raises AttributeError. Let us see an Example you can easily understand.

wls:/demodom/serverConfig> cmo.State()
Traceback (innermost last):
  File "", line 1, in ?
AttributeError: State
 
 

IndexError

The IndexError will be raised by the WLST shell, when thelist object is accessed with a out of range index value.

Let us see the example a list is defined with 5 elements

wls:/offline> L['app1', 'app2', 'app3', 'app4', 'web1']
when it is accessed with out of range index value say 7 then you get the IndexError.
wls:/offline> L[7]
Traceback (innermost last):
File
"<console>", line 1, in ?
IndexError: index out of range: 7

TypeError

The basic python object types int, str assignments or expressions or print statements with
concatenation does not allows you, raises the TypeError.

wls:/offline> print 'Number of servers:', 5
Number of servers: 5
 
wls:/offline>print 'Number of servers:'+ 5
Traceback (innermost last):
File
"<console>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects


Thanks for reading this post, Give your feedback in comments. cheers!!

Good References:
  1. http://www.doughellmann.com/articles/how-tos/python-exception-handling/
  2. http://www.jython.org/jythonbook/en/1.0/ExceptionHandlingDebug.html
  3. http://www.tutorialspoint.com/python/python_strings.htm

Monday, July 25, 2011

Wanna get the status of the applications in domain


In most of WebLogic domain environments we might have seen multiple applications deployed on WebLogic servers. It is difficult to check their status when server uses high CPU utilization. We can get the complete details by giving one input i.e., target-name.

We use navigate MBean tree more frequently while using interactive mode of WLST and in scripting. Here we can call any attribute from any MBean tree by using colon ':' at the MBean tree root. Here we go with a sample of  for you who struggling to understand navigate each and every time.

Please check the below code snippet and you can change as per your requirement.

#############################################################
"""
 This script will get you status of the applications which are deployed 
 in your WebLogic Domain.         
 script get you the colorful output                         
 NOTE : You need to give target name as an input to the script                
 Author: Krishna Sumanth Naishadam                         
"""
##############################################################
import sys

connect('username','password','t3://wl_admin_host:wl_admin_port')
targetName=sys.argv[1]
domainConfig()
apps=cmo.getAppDeployments()
for i in apps:
    navPath1=getMBean('domainConfig:/AppDeployments/'+i.getApplicationName())
    appID=navPath1.getApplicationIdentifier()
    navPath=getMBean('domainRuntime:/AppRuntimeStateRuntime/AppRuntimeStateRuntime')
    sts=navPath.getCurrentState(appID,targetName)
    if(sts == "STATE_ACTIVE"):
        print "\033[1;32m Status of " + i.getApplicationName() + ": " + sts + "\033[1;m"
    else:
        print "\033[1;31m Status of " + i.getApplicationName() + ": " + sts + "\033[1;m"
disconnect()
exit()
 

domain_app_status.sh
********************

WL_HOME="
# set up common environment
. "${WL_HOME}/server/bin/setWLSEnv.sh"

CLASSPATH="${CLASSPATH}:${WL_HOME}/common/eval/pointbase/lib/pbembedded51.jar:${WL_HOME}/common/eval/pointbase/lib/pbtools51.jar:${WL_HOME}/common/eval/pointbase/lib/pbclient51.jar"
read -p "Enter Target Name : " value1

"${JAVA_HOME}/bin/java" -Xmx124m -Dprod.props.file=${WL_HOME}/.product.properties weblogic.WLST domain_app_status.py $value1 $*

The lifecycle of deployment process happen in the following way:



The following Colors I had chosen for reflecting what state for a application on a server.
======
Status of APPNAME1: STATE_ACTIVE (Green Color)
Status of APPNAME2: STATE_FAILED (Red Color)
Status of APPNAME3: STATE_NEW (Red Color)


Please see below screenshot for exact output

References:

Sunday, September 5, 2010

NodeManager Experiments using WLST

Create Machine configure NodeManager using WLST

This blog post is renovated with latest WebLogic 12.2.1 version execution output here. We have more generic reusable functions, three different functions each one has independent task. Where the pre condition for this is you must have a domain configured and admin server is running.

  1. create a machine and setup the Nodemanager 
  2. delete machine from the domain
  3. show all machines in the domain


 

#==========================================================================
# FileName      : createMachine.py
# Updated       : 11/22/2015
# Description:
# This simple script will create multiple machines
# and also set the NodeManager properties
# use demo.properties file loadProperties command line argument expected
#
# You can add this function block to full domain
#==========================================================================

def createMachine(machineName, machineIP,nmPort=5556):
        """
        This function takes three arguments machineName, machineIP, nmPort
        The default nmPort is 5556 and nmType as Plain
        """
        cd('/')
        cmo.createUnixMachine(machineName)

        cd('/Machines/'+machineName+'/NodeManager/'+machineName)
        cmo.setNMType('Plain')
        cmo.setListenAddress(machineIP)
        cmo.setListenPort(nmPort)
        cmo.setDebugEnabled(false)

def deleteMachine(machineName):
        """
        This function takes machineName as argument
        It will delete the Machine MBean from the Domain
        """
        cd('/')
        editService.getConfigurationManager().removeReferencesToBean(getMBean('/Machines/'+machineName))
        cmo.destroyMachine(getMBean('/Machines/'+machineName))

def printMachineList():
        """
        This function will display the machines configured on a domain
        No arguments required
        """
        cd('/')
        redirect('/dev/null', toStdOut='false')
        machineslist=ls('Machines',returnMap='true')
        for m in machineslist: print m
        stopRedirect()

def main():
        """
        Here we can expect ConnectionException, WLSTException
        and also BeanAlreadyExist for createMachine function
        """
        connect(ADMINUSER,ADMINPASSWD, ADMINURL)

        print "Before machines creation..."
        printMachineList()

        edit()
        startEdit()

        for i in range(1,5):
                try:
                        createMachine('machine'+str(i), '192.168.33.'+str(100+i),5566)
                except:
                        print 'Machine creation failed...'+'machine'+str(i)
        activate()

        print "After creation..."
        printMachineList()

        HitKey=raw_input('Press any key to continue...')

        startEdit()
        for i in range(1,5):
                try:
                        deleteMachine('machine'+str(i))
                except:
                        print 'Unable to remove machine...'
        activate()

        print "After removing machines..."
        printMachineList()
main()

Excecution of the Machine configuration is as follows....


java weblogic.WLST  -loadProperties demo.properties createMachine.py

create, delete and show machines in WebLogic 12.2.1 domain

Double confirmation with Admin console

Machine in WebLogic Domain configured with WLST


Start n Stop the Server using NodeManager by WLST

Manage the Server Life Cycle continues...
[2] Configure a NodeManager to start WebLogic Server instances (using console and command-line)

Start n Stop Server using NodeManager by WLST:

In the sun Solaris environment we need to change few nodemanager.properties to run the NodeManager. There are two kinds of Node Managers available
Java based Node manager
Script based Node manager

while connecting to nodemanager we have received an error as below:

Error encounter when the java native
bash-3.00$ tail -100f nodemanager.log


weblogic.nodemanager.common.ConfigException: Native version is enabled but node manager native library could not be loaded
at weblogic.nodemanager.server.NMServerConfig.initProcessControl(NMServerConfig.java:239)
at weblogic.nodemanager.server.NMServerConfig.(NMServerConfig.java:179)
at weblogic.nodemanager.server.NMServer.init(NMServer.java:177)
at weblogic.nodemanager.server.NMServer.(NMServer.java:142)
at weblogic.nodemanager.server.NMServer.main(NMServer.java:327)
at weblogic.NodeManager.main(NodeManager.java:31)
Caused by: java.lang.UnsatisfiedLinkError: no nodemanager in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1682)
at java.lang.Runtime.loadLibrary0(Runtime.java:822)
at java.lang.System.loadLibrary(System.java:993)
at weblogic.nodemanager.util.UnixProcessControl.(UnixProcessControl.java:16)
at weblogic.nodemanager.util.Platform.getProcessControl(Platform.java:108)
at weblogic.nodemanager.server.NMServerConfig.initProcessControl(NMServerConfig.java:237)
... 5 more

java weblogic.WLST startAdmin.py wcludomNM

connect('weblogic', 'weblogic', 't3://wlhost:7913')
nmEnroll('/home/wluser/domains/WLclsnm')
CLASSPATH to set for NodeManager:
export NM_HOME = $WL_HOME/common/nodemanager

CLASSPATH=/export/home/wladmin/wl813/bea/jdk142_04/jre/lib/rt.jar:/export/home/wladmin/wl813/bea/jdk142_04/lib/rt.jar:/export/home/wladmin/wl813/bea/patches/CR204958_810sp3_v1.jar:/export/home/wladmin/wl813/bea/weblogic81/server/lib/weblogic.jar

startNodeManager(verbose='true',NodeManagerHome='/home/wluser/bea/weblogic92/common/nodemanager')

To Check the log of nodemanager.log
tail -100f /home/wluser/bea/weblogic92/common/nodemanager/nodemanager.log

/home/wluser/bea/weblogic92/common/nodemanager/nodemanager.domains>

nmConnect('weblogic', 'weblogic', 'wlshostname','5556', 'WLclsnm', '/home/wluser/domains/WLclsnm')

prps = makePropertiesObject('weblogic.ListenPort=9013')
wls:/WLclsnm/serverConfig>
wls:/WLclsnm/serverConfig> nmStart('app01',props=prps)
Starting server app02 ...
Error Starting server app02: weblogic.nodemanager.NMException:
Exception while starting server 'app02': java.io.IOException: Server failed to start up. See server output log for more details.

prps = makePropertiesObject('weblogic.ListenPort=9013')

start('wlctr', 'Cluster')

nmStart('app02',props=prps)
Starting server AdminServer...
Server AdminServer started successfully

nmConnect('weblogic', 'weblogic', 'remotehostnameofmanagedserver' '5556','WLclsnm', '/home/wluser/domains/','plain')

Still workin progress to start the remotemanaged server by using wlst
(I am getting some errors when I tried ...will update this site Once it will done successfully if anybody is done plz post it as comment.)
Posted by Pani at 9:44 AM 1 comments:


Archana said...
Hi,
We are also facing the same issue. Not able to start managed servers using makepropertiesobject.

Did u get any solution.
Yes, Archana, We found the Solution as using PLAIN type for NodeManager is good to go.

Wednesday, August 25, 2010

Get Options for command line in WLST script

Problem Statement

Required a Python script for check if the WebLogic admin server is 'Running' or Not recursively
To execute this you have 2 options
1. Executing forever
2. timeout, interval as aruguments

If it isn't keep checking forever or as long as is passed on the command- line with the -t parameter. The wait between checks can be modified with the -i parameter on the command line.

There could be your environemnt also need such options for a Python script. This script will be a example for such requirements.

Script Logic
Hey Smart WLAs what do you think the solution for the above problem statement?? Got any idea? I know you guys are very intelligents!! hope you got idea about getting options at command-line. Yes, it is possible for our WLST Script too, getopt is a python capability which allows us to accept the command line arguments with options -t, -i. Of-course my buddy struggle to find this clues on the Google almost took 2 days.
  1. To read the command line values as dictionary and split as key, value pair and compare the key with desired options then performing the script according to user choice.
  2. If the user failed to enter the options at commandline exception handling with usage funcation.
  3. WLST connect to admin server regular function.
  4. Using sleep method for stopping the WLST execution for some time interval. Repeating this process till given timeout or run this above steps for forever.


#!/usr/bin/python
# Author : Raghunath
# Save Script as : checkAdmin.py 

import time
import getopt
import sys

# ========= connecting to Admin server ==================
def connectAdmin():
   r=1
   try:
        # Update the following line as per your environment
        connect(url='t3://AdminHost:AdminPort')
        print "*** Connected sucessesfully ***"
        r=0
        sys.exit(r)
    except:
        return r
 
def usage():
    print "Usage:"
    print "checkAdmin.py [-t timeout] [-i interval]"
    print "exit with 0 if find Admin Server"
    print "exit with 1 if do not find Admin Server"
    print "if no timeout is given, look for Admin Server until it is found"


# ===== Default settings ===================
Timeout = 0 
Interval = 25000
forever = 1

#====== Main program ===============================
try:
    opts, args = getopt.getopt( sys.argv[1:], "t:i", ["Timeout","Interval"] )
except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)

#===== Handling get options  ===============
for opt, arg in opts:
    if opt == "-t":
        Timeout = arg
        forever = 0
    elif opt == "-i":
        Interval = arg

while (forever == 1) or  (Timeout > 0):
     if connectsave() == 1:
         print 'Now, Sleeping  15 sec *************'
         java.lang.Thread.sleep( Interval )
         print 'Waking up after 15 sec ...'
     
      
print 'done'



To run the above script you can make a small shell script as follows:
# checkAdmin.sh

. $WL_HOME/server/bin/setWLSEnv.sh
java weblogic.WLST checkAdmin.py "$@"

Run this shell script as :
$ checkAdmin.sh -t 100 -i 20

or you call directly python script as follows
$ java weblogic.WLST checkAdmin.py -t 100 -i 20

Note that indentation is must for every Python script, please double check before you run the script.
Write back for any issues ariases when you execute the script in your environment.
Referneces:

# email functionality base on http://docs.python.org/library/email-examples.html

Tuesday, August 24, 2010

Configuring Multi DataSource

Introducing Problem Statement for this post is WLST which enables us to configure any kind of resource on a WebLogic domain. Here I am with new attempt to configuring Multi Datasource. In most of new domain configurations you need to work separately for configuring Datasource. We are already seen how to configure a Dynamic Datasource with customized property file, Adding to the same topic now we are going to work on Multi Datasource configuration.

The steps involved in multi datasource confiuration are as follows:
1. Configure individual datasource
2. Configure a new multidatasource
3. Add the datasources created in steip 1

Keeping more flavor (Object-Orientation) to your script we will create a Class in WLST this time. Are you ready??? I know you guys very intelligents and know all WLST tricks how they works and all!! Lets dive into the process of configuration.
-->


#==========================================
# File name: ConfigMDS.py
# Please change the code (line 38) as per your environment and needs
# Author : Inteligent WLA :)
#=============================================

class MDS:          
 def __init__(self, nam):
  self.nam  = nam 

 def configMDS(self):
  n=self.nam
  try:
   cd('/')
   cmo.createJDBCSystemResource(n)
   cd('/JDBCSystemResources/'+n+'/JDBCResource/'+n)
   cmo.setName(n)
   cd('JDBCDataSourceParams/'+n)
   set('JNDINames',jarray.array([String(n)], String))
 
   cmo.setAlgorithmType('Failover')
   dslist=raw_input('Please enter comma separating Datasources for MDS:')
   cmo.setDataSourceList(dslist)
   cd('/JDBCSystemResources/'+n)
   targetType=raw_input('Target to (C)luster or (S)erver: ')
   if targetType in ('C','c') :
           clstrNam=raw_input('Cluster Name: ')
               set('Targets',jarray.array([ObjectName('com.bea:Name='+clstrNam+',Type=Cluster')], ObjectName))
          else:
               servr=raw_input('Server Name: ')
               set('Targets',jarray.array([ObjectName('com.bea:Name='+servr+',Type=Server')], ObjectName))
   print 'Succesfully configured MultiDataSource...'
   activation()
  except BeanAlreadyExistsException:
   print 'Error: '+n+' BeanAlreadyExists...'
       cancelEdit('y')
   exit()

#===== main program===============
if __name__== "main":
 connect('wlusr','paswd','t3://AdminUrl:AdminPort')
 edit()
 startEdit()
 
 mdsName = raw_input("Please enter MultiDataSource name: ")
  # create object, call configMDS
 MDS(mdsName).configMDS()
 print('Exiting...')
 exit() 

Here you can templatise more by creating the a properties file where you need to store Multidatasoruce name, JNDIName, WebLogic Admin user, Password, AdminURL, the datasource names you wish to add to the multidatasource.

Use the same steps as followed in the Generic Data Source Creation.

# http://unni-at-work.blogspot.com/2009/03/multi-data-source-using-wlst.html
# http://edocs.bea.com/wls/docs100/wlsmbeanref/mbeans/JDBCDataSourceParamsBean.html#AlgorithmType

Monday, March 22, 2010

Side by Side Deployment with WLST



One of my online buddy requested me Python script help for developing Side by Side(SBS) deployment using WLST.

Automate Python Script for Side By Side deployment.

The project is in developing stage, the client need deploying the same applications with different versions must be available for development and testing teams, an automated handy WLST script is requested to develop by buddy WLA.
Add caption

To do this interesting  task, the plan for execution is prepared as following while doing the deployment criteria:
1. If the application is New and the version is new i.e no other version is in the ACTIVE state with the given appName, the script will deploy the application
2. If one of the version of given application is in ACTIVE state visible in the console, then the developer is try to deploy the next version, the script should do DeActivate the old version and deploy the new version.
3. Now already have two versions deployed on the domain one is : ACTIVE state and other is in RETIERED State then undeploy the REITRED versioned application with a timeout interval or deploy the new version so that it will make current ACTIVE application to RETIERED and new deployment to ACTIVE.

Sample Video demonstration from Oracle Weblogic

For implementing the above logic in chronological way. The real challenge lies in the ISSUE with iterations. it was controlled by 'break' statement usually that we do in any C program. And I have used here a flag variable 'appFlags' to indicate the status of the Application status, like that we are able to maintained two version max in the console of the same app.

-->

import sys
#======================================================= 
# Function for fresh plain deployment
#======================================================= 
def newDeploy(appName,ver):
    print 'Deploying .........'
    deploy(appName,'/path/applications/'+appName+'/'+ver , targets='AdminServer')
    startApplication(appName)

#======================================================= 
# Function for finding the  Application Status
#=======================================================  
def appstatus(appName, serverName):
    cd('domainRuntime:/AppRuntimeStateRuntime/AppRuntimeStateRuntime')
    #get current real state for app in specific server
    currentState = cmo.getCurrentState(appName, serverName)
    return currentState
#======================================================  
# Undeploy the given application 
# Target we can change according to domain and application deployed on
#====================================================== 
def unDeploy(appName):
    print 'stopping and undeploying ....'
    stopApplication(appName, targets='AdminServer')
    undeploy(appName, targets='AdminServer')


#======================================================== 
# Main program here...
# Target you can change as per your need
#========================================================  
appName=sys.argv[1]
ver=sys.argv[2]
connect(user, passwd, adminurl)
cd('AppDeployments')
appflag=0
y=ls(returnMap='true')
for i in y :
 if i.startswith(appName )  ==1:
  #Checking for the application existence)
  print i
  print appstatus(i,'AdminServer')
 if appstatus(i,'AdminServer')=='STATE_RETIRED' :
  appflag=1
  break
 elif appstatus(i,'AdminServer')=='STATE_ACTIVE':
  appflag=2
 else:
  print ' other Applications are Running '
  pass


if appflag == 1 :
    print 'application having RETIERED STATE ..'
    unDeploy(i)
    print appstatus(i,'AdminServer')
    newDeploy(appName,ver)
    print appstatus(i,'AdminServer')
elif appflag== 2:
    print 'Application exists in ACTIVE state...'
    newDeploy(appName,ver)
    print appstatus(i,'AdminServer')
else:
    print 'new application'

How to execute the Side by Side deployment script?
Dear novice WLA, you can execute this script by re-defining your connection parameters at line 36. Remember one more thing is the application targeted to AdminServer this may vary for your environment as managed servers or clusters.
prompt$ java weblogic.WLST SBSDeploy.py

If you like the ideas implemented in this script, useful to your environment please share this article.

Reference URLs:

Friday, February 12, 2010

Restarting 24 x 7 Domain with WLST

Here I have little bit struggle to reach a conclusion that, what all servers need to stop? when to stop? the preparing script I did with my analysis that stated that few sites requires 24x7 HA. Few of them don't need the HA, that is site can have sometime outage where it doesn't have request for the application.

Me and Prasanna Yalam discussed about a strategy where every time you run few servers can be stopped from different physical locations. when starting them up then only next round of managed servers can be stopped. This strategy implementation firstly thought with 2 scripts then I made it 2 phases one by one can be done with user input. This module named as 'regularStop()', which supports 24x7 HA domain.

One more thing we need to consider here is most of the Production deployments are in nostage mode, when new version release of application code requires complete domain down option requirement. This is another module take cares where it will stop all clusters in the domain should be passed. The module named as 'releaseStop()'. This you can use for any WebLogic domain.


After composing whole script ran it then found that there is need of server state or cluster state when it is given shutdown command. So every shutdown command is followed by state command given that gives more confidence on script how it is executing.

Finally by performing releaseStop() or RegularStop() we can go for stopping the Admin Server.


Note: Don't forget proper indentations, while editing my script it might be disturbed here.
#====================================
# Script File: StopWLDomain.py
# This module is for 24x7  Domain****
# First phase stops few managed servers of few sites
# Second phase will be used for stop remaining servers
# Note that Second phase allowed only when you press 'y'
# before that you need to Start all the Phase 1 stopped servers.
#====================================
def conn():
 try:
  connect(user, passwd, adminurl)
 except ConnectionException,e:
  print '\033[1;31m Unable to find admin server...\033[0m'
  exit()

#====================================
# Stop all instances of a Cluster 
#====================================
def stopClstr(clstrName):
 try:
  shutdown(clstrName,"Cluster")
  state(clstrName,"Cluster")
 except Exception, e:
  print 'Error while shutting down cluster ',e
  dumpStack()
  return

#====================================
# All the instances of all Clusters will be down for release
#====================================
def releaseStop():
 clstrList=["webclstr1", "webclstr2'..."ejbclstr"]
 for clstr in clstrList:
  stopClstr(clstr) 

#====================================
# Stop a instances given as parameter 
#====================================
def stopInst(iservr):
 try:
  state(str(iservr))
  shutdown(str(iservr), 'Server',force="true")
  state(str(iservr))
 except Exception, e:
  print iservr, 'is having error in shutting down'
  pass

#====================================
# Regular Rstart is 24x7 supported for :SITE1, SITE2, SITE3
#====================================
def regularStop():
 clstrList=["non247clstr1", "non247clstr2"]
 for clstr in clstrList:
  stopClstr(clstr) 
 servrList=servrList=["app1","app2","app3"... "web1","web2"] #sitewise list of servers need to stop
 for inst in servrList:
  stopInst(inst)
 print 'Now, please start the instances exclude the phase 2 instances ...'
 phase2=raw_input("Want to proceed for Phase 2...(y/n)")
 if phase2 == 'y':
  serverList=["app4","web3"...] # remaining Managed Servers to stop after phase servers UP n Running
  for inst in serverList:
   stopInst(inst)

#====================================
# Exiting the script
#====================================
def quit():
 disconnect()
 exit()

#====================================
# The main script starts here...
#====================================
if __name__ == "main":
 conn()
 print ' 1. Regular Stop (24x7)\n 2. Release Stop\n 0. Quit\n'
 sAns=raw_input('Enter your choice: ')
 if int(sAns) == 1:
 regularStop()
 elif int(sAns) == 2:
 releaseStop()
 elif int(sAns)== 0:
 quit()
 else:
 print 'Warning: Invalid option...'
 exit()
 print 'Finally stopping admin now...'
 shutdown()

#========WLST=BY=EXAMPLES==============

You can run this script with java in your PATH and weblogic.jar in the CLASSPATH.
java weblogic.WLST StopWLDomain.py

Sunday, January 31, 2010

Configuring WorkManager using WLST


The WorkManager configuration can be possible only when you navigate on SelfTuning tree. After navigating with cding to SelfTuning MBean hierarcy. You can list out the SelfTuning tree that consists of the following branch trees, which are allowed us to created new MBeans using create command.
  1. ContextRequestClasses
  2. FairShareRequestClasses
  3. ResponseTimeRequestClasses
  4. Capacities
  5. MaxThreadsConstraints
  6. MinThreadsConstraints
  7. WorkManagers
WebLogic WorkManager Threadpool configurations
Here I am with few examples of my experiments with WorkManager and its constraints or Request Classess. To configure a new Global or Server instances wise or Cluster-wide Workmanager using online WLST you need to follow the below steps:

1. connect to the Administration Server.
2. switch to edit tree
3. configure a class or constraint for the WorkManager.
4. set the target as per your need to a server or to a cluster.
5. configure a new workmananger
6. navigate to the newly configured WorkManager MBean and set the constraint or class which created in the step 3.
7. target the workmanager to a server instance or to a cluster as per the need.
8. Save the changes and activate them.
9. While performing the above steps the script can throw WLST Exceptions such as BeanAlreadyExistsException handle them

We can configure a WorkManager and its related constraint or Request classes in two modes 1. online WLST 2. offline WLST The only difference here is targeting the WorkManger instance to a Server or a cluster, Online WLST requires
set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
set('Targets',jarray.array([ObjectName('com.bea:Name=app1,Type=Server')], ObjectName))

WLST MaxThreadsConstraints

Now let us see the example for configuring a MaxThreadsConstraints using Online WLSTHere we are going to set the Count value as per the need in the runtime for the MaxThreadConstraint. Better you can also chance to target to Server instance instead of Cluster.
#********************************************************************************
# Configure a WorkManager with  MaxThreadsConstrain
#********************************************************************************
from weblogic.descriptor import BeanAlreadyExistsException


try:
  connect('adminuser','adminpasswd','t3://adminHost:adminPort')
  
  edit()
  startEdit()
  c=input('Enter the Max Thread Count: ')
  mtc='MaxThreadsConstraint'+str(c)
  cd('/SelfTuning/wd1')
  cmo.createMaxThreadsConstraint(mtc)
  cd('/SelfTuning/wd1/MaxThreadsConstraints/'+mtc)
  cmo.setCount(c)
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cd('/SelfTuning/wd1')
  wm = cmo.createWorkManager('pwm1')
  cd('/SelfTuning/wd1/WorkManagers/pwm1')
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cmo.setMaxThreadsConstraint(getMBean('/SelfTuning/wd1/MaxThreadsConstraints/'+mtc))
  save()
  activate()
except (WLSTException, BeanAlreadyExistsException), e:
  print 'Error in script:', e
  cancelEdit('y')
else:
 disconnect()
 

Then the outcome looks like below:
wls:/offline> execfile('ConfigWM1.py')
Connecting to t3://adminHost:port with userid system ...
Successfully connected to Admin Server 'padmin' that belongs to domain 'wd1'.
...


You already have an edit session in progress and hence WLST will
continue with your edit session.

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
Enter the Max Thread Count: 45
Saving all your changes ...
Saved all your changes successfully.
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed
Disconnected from weblogic server: padmin

Capacity Constraint

Now let us see the example for configuring a capacity constraint using online WLST


#Capacity constraint
#********************************************************************************
from weblogic.descriptor import BeanAlreadyExistsException

try:
  # replace following values 
  connect('adminuser','adminpasswd','t3://adminHost:adminPort')
  edit()
  startEdit()
  cd('/SelfTuning/wd1')
  cmo.createCapacity('pcap2')
  cd('Capacities/pcap2')
  set('Count',10)
  set('Notes','This will set Capacity constraint')
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cd('/SelfTuning/wd1')
  wm = cmo.createWorkManager('pwm2')
  cd('/SelfTuning/wd1/WorkManagers/pwm2')
  set('Targets',jarray.array([ObjectName('com.bea:Name=appClstr,Type=Cluster')], ObjectName))
  cmo.setCapacity(getMBean('/SelfTuning/wd1/Capacities/pcap2'))
  save()
  activate()
except (WLSTException, BeanAlreadyExistsException), e:
  print 'Error in script:', e
  cancelEdit('y')
else:
 disconnect()

The output will be like this:
wls:/offline>  execfile('ConfigWM2.py')
Connecting to t3://adminHost:port with userid system ...
Successfully connected to Admin Server 'padmin' that belongs to domain 'wd1'.
....

Starting an edit session ...
Started edit session, please be sure to save and activate your
changes once you are done.
Saving all your changes ...
Saved all your changes successfully.
Activating all your changes, this may take a while ...
The edit lock associated with this edit session is released
once the activation is completed.
Activation completed
Disconnected from weblogic server: padmin
Double check your changes for WorkManager done success on Admin Console. Please write back your feedback and comments on this post... -->

Sunday, May 24, 2009

Cosmotising your WLST output

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

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



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

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



Popular Posts