Search This Blog

Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Wednesday, August 31, 2022

JMS Module with ConnectionFactory and Queue configuration using WLST

After almost three and half years again revisited to the JMS module script. This time the project needs are quite different. Where the Oracle WebLogic domains classified environments  but they are standalone server domains. That is only AdminServer will be there in the domain and that would be target for the JMS module, JMS Destinations.



Lets begin the experimenting now, the prerequisites for this are:

  1. A WebLogic Domain configured with single AdminServer
  2. AdminServer should be up and RUNNING
  3. To execute the WLST script required PATH, alias should be defined in the profile as shown below:
  4. export MW_HOME=/u01/app/oracle/fmw
    export WL_HOME=$MW_HOME/wls/wlserver
    export USER_MEM_ARGS="-Djava.security.egd=file:/dev/./urandom"
    alias wlst="$MW_HOME/oracle_common/common/bin/wlst.sh -skipWLSModuleScanning"
    

    You can use this freshly created alias wlst at any directory to invoke WLST shell.  The option -skipWLSModuleScanning is easy, faster learnt while working on docker containers and simple way to use.

  5. Execute the configure JMS Servers
  6. The WLST Script for JMS configurations and all frequently changing values are moved into the properties file.


#========================================
# WLST Script purpose: Configuring JMS Module
# Author: Pavan Devarakonda
# Update date: 3rd Aug 2017
#========================================
from java.util import Properties
from java.io import FileInputStream
from java.io import File
from java.io import FileOutputStream
from java import io
from java.lang import Exception
from java.lang import Throwable
import os.path
import sys

envproperty=""
if (len(sys.argv) > 1):
        envproperty=sys.argv[1]
else:
        print "Environment Property file not specified"
        sys.exit(2)

propInputStream=FileInputStream(envproperty)
configProps=Properties()
configProps.load(propInputStream)

##########################################
# Create JMS Moudle will take the 
# arguments as name, subdeployment name
# target can be on admin or managed server or cluster
##########################################
def createJMSModule(jms_module_name, adm_name, subdeployment_name):
        cd('/JMSServers')
        jmssrvlist=ls(returnMap='true')
        print jmssrvlist
        cd('/')
        module = create(jms_module_name, "JMSSystemResource")
        #cluster = getMBean("Clusters/"+cluster_target_name)
        #module.addTarget(cluster)
        #adm_name=get('AdminServerName')
        adm=getMBean("Servers/"+adm_name)
        module.addTarget(adm)
        cd('/SystemResources/'+jms_module_name)

        module.createSubDeployment(subdeployment_name)
        cd('/SystemResources/'+jms_module_name+'/SubDeployments/'+subdeployment_name)
        list=[]
        for j in jmssrvlist:
                s='com.bea:Name='+j+',Type=JMSServer'
                list.append(ObjectName(str(s)))
        set('Targets',jarray.array(list, ObjectName))


def getJMSModulePath(jms_module_name):
        jms_module_path = "/JMSSystemResources/"+jms_module_name+"/JMSResource/"+jms_module_name
        return jms_module_path

def createJMSTEMP(jms_module_name,jms_temp_name):
        jms_module_path= getJMSModulePath(jms_module_name)
        cd(jms_module_path)
        cmo.createTemplate(jms_temp_name)
        cd(jms_module_path+'/Templates/'+jms_temp_name)
        cmo.setMaximumMessageSize(20)

##########################################
# JMS Queu configuration function 
# arguments are : JMS module name, Queue jndiname
# Queue name, jndi name hu
##########################################
def createJMSQ(jms_module_name,jndi,jms_queue_name):
        jms_module_path = getJMSModulePath(jms_module_name)
        cd(jms_module_path)
        cmo.createQueue(jms_queue_name)
        cd(jms_module_path+'/Queues/'+jms_queue_name)
        cmo.setJNDIName(jndi)
        cmo.setSubDeploymentName(subdeployment_name)

adminUser=configProps.get("adminUser")
adminPassword=configProps.get("adminPassword")
adminURL=configProps.get("adminURL")

connect(adminUser,adminPassword,adminURL)
#adm_name=get('AdminServerName')
adm_name=ls('Servers',returnMap='true')[0]
print adm_name
edit()
startEdit()

##########################################
#   JMS CONFIGURATION## 
##########################################
total_conf=configProps.get("total_conf")
tot_djmsm=configProps.get("total_default_jms_module")
#subdeployment_name=configProps.get("subdeployment_name")

a=1
while(a <= int(tot_djmsm)):
        i=int(a)
        jms_mod_name=configProps.get("jms_mod_name"+ str(i))
        #cluster=configProps.get("jms_mod_target"+ str(i))
        subdeployment_name=configProps.get("subdeployment_name"+ str(i))
        createJMSModule(jms_mod_name,adm_name,subdeployment_name)
        total_q=configProps.get("total_queue"+str(i))
        j=1
        while(j <= int(total_q)):
                queue_name=configProps.get("queue_name"+ str(i)+str(j))
                queue_jndi=configProps.get("queue_jndi"+ str(i)+str(j))
                createJMSQ(jms_mod_name,queue_jndi,queue_name)
                j = j + 1
        i=i+1
        a = a+1
save()
activate(block="true")
disconnect() 


Now see this is a sample of properties file that could help you to build the JMS Module, be read by the WLST script at the run time:
###################################################
# JMS SUBDEPLOY CONFIGURATION
###################################################
total_subdply=2
total_default_jms_module=2
total_conf=0
subdeployment_name1=DemoJMSFAServer1
subdeployment_name2=DemoJMSFAServer2

###################################################
# JMS MODULE CONFIGURATION
###################################################
jms_mod_name1=Demo-SystemModule1
jms_mod_name2=Demo-SystemModule2

###################################################
# JMS CONNECTION FACTORY CONFIGURATION
###################################################
conf_jndi1=demoCF
conf_name1=jms/demoCF

###################################################
#   JMS QUEUE CONFIGURATION
###################################################

total_queue1=2
queue_name11=Q1
queue_jndi11=Q1

queue_name12= BQ1
queue_jndi12= BQ1


total_queue2=2
queue_name21=Q2
queue_jndi21=Q2

queue_name22= BQ2
queue_jndi22= BQ2

#========== ADMIN DETAILS =========================
adminUser=weblogic
adminPassword=welcome1
adminURL=t3://192.168.33.100:8100
output
$ wlst jms_module.py jms_module.properties

let's see what happen when you apply this logic on your project? Did you notice any errors? Please write back 🔙 with your error screen shot. 

How do you know everything went well? Open the WebLogic Administration console to check the JMS Module Configuration has successfully created a new JMS resource or not.

You may be intrested to learn more WLST scripting for JMS you can also visit the Uniform Distributed Queue configuration post. Thanks for being with us in this post, Please write to us your errors and exceptions when you run this script.

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 !!!

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, January 31, 2013

JMS Module Uniform Distributed Queue using WLST


This post is continous series of JMS configurations experimenting with Python. Here the JMS module configuration changes for the JMS will be stored to config.xml repository and its sub-deployment module descriptor in a separate file. JMS system module can be defined with name, target to servers or cluster, its related sub-deployments such as Queue or publisher/Subscriber topics.

The WebLogic JMS related Mbeans are constructed as follows :
  • JMSBean
  • JMSSystemReourceMBean
  • QueueBean
  • JMSConnectionFactoryBean
  • DistributedQueueBean
  • UniformDistributedQueueBean
  • SubdeploymentMBean

While configuring you need to understand that JMS system module, that consists of ConnectionFactory that give access to the JMS services, and there could be a different scenario on demand. The machines are high-powered, low powered are in the same cluster then JMS destinations must be distributed destinations with ‘Allocate members Uniformly’ option set to false and manually select more physical destination from the high powered machines.The configuring JMS module is going to have various sub-deployment components in it. First we need to configure the JMS Module name, target to the advanced deployment as sub-deployment. 


Now you need brainstrom, and provide your customized domain with JMS module details in the properties file, let me give you sample :
############################################################################### 
# JMS MODULE CONFIGURATION
############################################################################### 
total_default_jms_module=1
jms_mod_name1=jmsSystemModule
jms_mod_target1=my_cluster

Subdeployment in JMS Module

Most of the Admins not really aware of the use of subdeployment. We need to configure a subdeployment per JMS Module. While configuring the subdeployment we have to provide the target as JMS servers which are configured in the first section. Why we need a subdeployment is interesting topic  • To avoid network traffic between JMS components communication • It will group Connection factories, queues, topics

 • Easy to migrate
WebLogic - JMS Module configuration using WLST

###############################################################################
# JMS SUBDEPLOY CONFIGURATION
###############################################################################
total_subdply=1
subdeployment_name=aJmssub

JMS Connection Factory

We have configured the ConnectionFactory properties as follows
###############################################################################
# JMS CONNECTION FACTORY CONFIGURATION
##########
conf_jndi1=myConnectionFactory
conf_name1=MyConnectionFactory
Configuring Uniform distributed queue using WLST We have configured the Queue with Distributed option because we have multiple JMS providers. The Uniform Distributed Queue is the one of the best practice when you have Clustered WebLogic Domain. While configuring this you need a name for the Uniform Distributed Queue and a JNDI name for it.
###############################################################################
#   UNIFORM DISTRIBUTED QUEUE CONFIGURATION
###############################################################################
total_udq=3
udq_name1=jmsIncomingChannel
udq_jndi1=jms/incoming/response
The JMS Module configuration with Subdeployment target to JMS Servers configured earlier. ConnectionFactory, Uniform Distributed Queue target to subdeployment.
from java.util import Properties
from java.io import FileInputStream
from java.io import File
from java.io import FileOutputStream
from java import io
from java.lang import Exception
from java.lang import Throwable
import os.path
import sys

envproperty=""
if (len(sys.argv) > 1):
        envproperty=sys.argv[1]
else:
        print "Environment Property file not specified"
        sys.exit(2)
propInputStream=FileInputStream(envproperty)
configProps=Properties()
configProps.load(propInputStream)

def createJMSModule(jms_module_name,cluster_target_name):
        cd('/JMSServers')
        jmssrvlist=ls(returnMap='true')
       # jmssrvlist=['AjmsServer1','AjmsServer2']
        cd('/')
        module = create(jms_module_name, "JMSSystemResource")
        cluster = getMBean("Clusters/"+cluster_target_name)
        module.addTarget(cluster)
        cd('/SystemResources/'+jms_module_name)

        module.createSubDeployment(subdeployment_name)
        cd('/SystemResources/'+jms_module_name+'/SubDeployments/'+subdeployment_name)
        list=[]
        for j in jmssrvlist:
                s='com.bea:Name='+j+',Type=JMSServer'
                list.append(ObjectName(str(s)))
        set('Targets',jarray.array(list, ObjectName))


def getJMSModulePath(jms_module_name):
        jms_module_path = "/JMSSystemResources/"+jms_module_name+"/JMSResource/"+jms_module_name
        return jms_module_path

def createJMSTEMP(jms_module_name,jms_temp_name):
        jms_module_path= getJMSModulePath(jms_module_name)
        cd(jms_module_path)
        cmo.createTemplate(jms_temp_name)
        cd(jms_module_path+'/Templates/'+jms_temp_name)
        cmo.setMaximumMessageSize(20)

def createJMSUDQ(jms_module_name,jndi,jms_udq_name):
        jms_module_path = getJMSModulePath(jms_module_name)
        cd(jms_module_path)
        cmo.createUniformDistributedQueue(jms_udq_name)
        cd(jms_module_path+'/UniformDistributedQueues/'+jms_udq_name)
        cmo.setJNDIName(jndi)
    #    cmo.setDefaultTargetingEnabled(bool("true"))
        cmo.setSubDeploymentName(subdeployment_name)

def createJMSConnectionFactory(jms_module_name,cfjndi,jms_cf_name):
        jms_module_path = getJMSModulePath(jms_module_name)
        cd(jms_module_path)
        cf = create(jms_cf_name,'ConnectionFactory')
        jms_cf_path = jms_module_path+'/ConnectionFactories/'+jms_cf_name
        cd(jms_cf_path)
        cf.setJNDIName(cfjndi)
        cd (jms_cf_path+'/SecurityParams/'+jms_cf_name)
        #cf.setAttachJMXUserId(bool("false"))
        cd(jms_cf_path+'/ClientParams/'+jms_cf_name)
        cmo.setClientIdPolicy('Restricted')
        cmo.setSubscriptionSharingPolicy('Exclusive')
        cmo.setMessagesMaximum(10)
        cd(jms_cf_path+'/TransactionParams/'+jms_cf_name)
        #cmo.setXAConnectionFactory(bool("true"))
        cd(jms_cf_path)
        cmo.setDefaultTargetingEnabled(bool("true"))

adminUser=configProps.get("adminUser")
adminPassword=configProps.get("adminPassword")
adminURL=configProps.get("adminURL")

connect(adminUser,adminPassword,adminURL)

edit()
startEdit()

 # ====# JMS CONFIGURATION## ##########################################
total_temp=configProps.get("total_temp")
total_udq=configProps.get("total_udq")
total_conf=configProps.get("total_conf")
tot_djmsm=configProps.get("total_default_jms_module")
subdeployment_name=configProps.get("subdeployment_name")

a=1
while(a <= int(tot_djmsm)):
        var1=int(a)
        jms_mod_name=configProps.get("jms_mod_name"+ str(var1))
        cluster=configProps.get("jms_mod_target"+ str(var1))
        createJMSModule(jms_mod_name,cluster)
        i=1

        while(i <= int(total_temp)):
                t_name=configProps.get("temp_name"+ str(i))
                createJMSTEMP(jms_mod_name,t_name)
                i = i + 1

        j=1
        while(j <= int(total_udq)):
                udq_name=configProps.get("udq_name"+ str(j))
                udq_jndi=configProps.get("udq_jndi"+ str(j))
                createJMSUDQ(jms_mod_name,udq_jndi,udq_name)
                j = j + 1
        k = 1
        while(k <= int(total_conf)):
                conf_name=configProps.get("conf_name"+ str(k))
                conf_jndi=configProps.get("conf_jndi"+ str(k))
                createJMSConnectionFactory(jms_mod_name,conf_jndi,conf_name)
                k = k + 1
        a = a+1

save()
activate(block="true")
disconnect()
############################################################

The sample properties listed for helping out how to create here for your projects.
###############################################################################
# JMS SUBDEPLOY CONFIGURATION
###############################################################################
total_subdply=1
total_default_jms_module=1
total_conf=1
subdeployment_name=demoSub

###############################################################################
# JMS CONNECTION FACTORY CONFIGURATION
######################################################
conf_jndi1=demoCF
conf_name1=jms/demoCF

###############################################################################
#   UNIFORM DISTRIBUTED QUEUE CONFIGURATION
###############################################################################
 

total_temp=0
total_udq=2
udq_name1=jmsIncomingChannel
udq_jndi1=jms/incoming/response
temp_name1=jmsIncomingChannel1

udq_name2=jmsOutgoingChannel
udq_jndi2=jms/outgoing/response
temp_name2=jmsOutgoingChannel1

adminUser=weblogic
adminPassword=welcome1
adminURL=t3://192.168.1.106:8100
###############################################################################
# JMS MODULE CONFIGURATION
###############################################################################
total_default_jms_module=1
jms_mod_name1=demo_jmsmod
jms_mod_target1=democlstr

To execute this JMS Module with subdeployments you need to pass the properties file as argument
java weblogic.WLST jms_module.py jms_module.properties
pavanbsd@ubuntu:~/pybin$ wlst jmsmodnq.py jmsmodnq.properties

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

Connecting to t3://192.168.1.106:8100 with userid weblogic ...
Successfully connected to Admin Server "demoadmin" that belongs to domain "demodomain".

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.

Location changed to edit tree. This is a writable tree with
DomainMBean as the root. To make changes you will need to start
an edit session via startEdit().

For more help, use help('edit')
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.
drw-   jms_ms1
drw-   jms_ms2

MBean type JMSSystemResource with name demo_jmsmod has been created successfully.
MBean type ConnectionFactory with name jms/demoCF has been created successfully.
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: demoadmin

Keep writing back 🔙 your error screen shot comments and suggestions on this post. Keep smiling cheers!! 

Sunday, June 10, 2012

JDBC Monitoring

JDBC Monitoring with LWLST script
One fine morning we (WLA support Team) got an assignment, The summary of the assignment was to find "How the WebLogic server instance performing for a DataSource?". WebLogic 9.x onwards a DataSource is associated with a ConnectionPool (a pool of connections to the DB). If we monitor ConnectionPool, inturn it is nothing but monitoring a DataSource.

Of-course the task is not that easy, I have gone through various WebLogic forums to find a appropriate solution for this task.

Oracle WebLogic provides two ways to Monitor a Datasource
1. Monitoring Datasource server wise
2. Testing the Connection Pool

Here I am publishing the same script which Madan Noru/Satya prepared in the old bea fourms or ObjectMix forums. Only one thing is difference is that displaying pattern, I had created a separate header, so that output looks good to see in a table form. To make this possible I have used C-Style print command from Python Language. This format you can change as per your screen display size.

The script will retrieve the JDBC Connection Pool MBean using adminHome, which is deprecated object in WLST. The output of the script will gives you the values of the following attributes:
  • DataSource Name
  • Maximum Capacity of the Connection Pool at Run-time
  • Active Connections Current Count
  • Active Connections High Count
  • Wait Seconds High Count
  • Waiting For Connection Current Count
  • State of the Connection Pool

#=======================================================
# This script will monitor the JDBC CONNECTION POOL
# more details on this script contact: Pavan Devarkonda
#=======================================================
connect("username","passwd","t3://AdminIP:AdminPort")
try:
 poolrtlist=adminHome.getMBeansByType('JDBCConnectionPoolRuntime')
 print ' '
 print ' '
 print 'JDBC CONNECTION POOLS'
 print ' '
 print 'Name Max Active Active WaitSecs Waiting State'
 print ' capacity Current HighCnt HighCnt Count'

 for poolRT in poolrtlist:
  pname = poolRT.getName()
  pmaxcapacity = poolRT.getAttribute("MaxCapacity")
  paccc = poolRT.getAttribute("ActiveConnectionsCurrentCount")
  pachc = poolRT.getAttribute("ActiveConnectionsHighCount")
  pwshc = poolRT.getAttribute("WaitSecondsHighCount")
  pwfccc = poolRT.getAttribute("WaitingForConnectionCurrentCount")
  pstate = poolRT.getAttribute("State")
  print '%10s %7d %7d %7d %7d %7d %10s' % (pname,pmaxcapacity,paccc,pachc, pwshc,pwfccc,pstate)
  print ' '
except:
  print 'Error:'
  dumpStack()
  pass
disconnect()

In Year 2012 revisting the same script

We have trouble in the produciton environment with JDBC Connection pool overloaded. All the ActiveConnectionCount reaching the MaxCapacity of the Connection pool. As a temprory workaround we need to reset the Connection pool for that movement. Permanent cure is tuning the Connection pool. For both solutions we need active monitoring the JDBC Connection pool.
To monitor this we have revisited the same script. Now adding more saus to the script we need to find that ActiveConnectionCount reaching 85% as threshold limit. Once it reaches 85 or greater then monitoring tool like HP OV/some other tool will reads log file generated by the script and then sends warns message to supporting Middleware Admin when threshold crossed. If you have sendmail service on your machine you can send message fromt he script itself.
To do this we had manupulated the above script according to the requirements
  1. We have specified DataSource that are causing this trouble
  2. Used separate properties file for user credentials.
  3. The output of script is redirected to a file
  4. Managed Server name opposite to the monitor values it is tricky but resolved The new script is

#=======================================================
# This script will monitor the JDBC CONNECTION POOL
# Date :  18 Apr 2012
#=======================================================
import sys
import time
try:
        loadProperties('./DBcheck.properties')
        fp=open('ActiveConn.log','a+')
        Date = time.ctime(time.time())
        admurl='t3://'+admAdrs+':'+admPort
        connect(userConfigFile=UCF, userKeyFile=UKEY, url=admurl)
        poolrtlist=adminHome.getMBeansByType('JDBCConnectionPoolRuntime')
        print ' '
        print 'JDBC CONNECTION POOLS'
        print>>fp, '================================================ '

 for poolRT in poolrtlist:
                pname = poolRT.getName()
                pmaxcapacity = poolRT.getAttribute("MaxCapacity")
                paccc = poolRT.getAttribute("ActiveConnectionsCurrentCount")
        
  if pname == 'myDataSource1' or pname == 'myDS2'' or pname == 'myDS3':
                        server= str(poolRT).split(',')[2].split('=')[1]
                        p=(paccc /(pmaxcapacity * 1.0)) * 100 
                        if p >= 85:
                                print >>fp, 'WARNING: The Active connections are Greater than Threshold 85%'
                        print>>fp, '%24s %15s %18s %7d %7d' % (Date,server,pname,pmaxcapacity,paccc)

except Exception, e:
        sys.stderr.write('ERROR: %s\n' % str(e))
        print 'Error:', e
        dumpStack()
        pass
fp.close()
disconnect()


-->

Post script actions

  1. Prepare a Shellscript that will let you know howmuch time it will counsume to run py script.
    clear
    date
    $JAVA_HOME/bin/java weblogic.WLST /path/urscript/jdbcmon.py
    date
    
  2. Schedule a scheduler to run this script autosys or crontab that invokes above shell script.
  3. Configure a monitoring tool frequently lookup the logs and send alert messages such as HP OVO or smpt mailing also fine.
What do you think about this new version of script? Write back your comments and suggestions to deliver better. Refernce Object Mix discussion:
http://objectmix.com/weblogic/549153-weblogic-monitoring-script-wlst-2.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

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.

Wednesday, February 3, 2010

Configuring a Generic Datasource

Configuring the datasource is one time activity for any project in production environment but where as for development or testing environment there is always need for change the datasource as per the demand. These changes makes interrupt majority of the development process. To improve this process we can have a Generic JDBC Data source configuring script in your utilities space.

Creating the data source using a python script makes 100% reusable. Here my perception is that if we don’t hard code the JDBC parameters it will be easy to use for all environments as well as for any kinds of database platforms and their respective driver param values to replace also.

Initially lets go with single Data source creation with targeting to the user input Server it can be Managed Server or AdminServer (basic domain), later on we can go for improve further to target to a Cluster.

JDBC Datasource in offline vs Online WLST


This scripting we can write in two ways offline and in online. In the offile mode we need to navigate the MBean and create, configure parameter and finally do assign() them to a Server or Cluster of a domain. For the online script we need to set the target using setTarget() command. To do this we must connect to the Admin server and acquire lock on configuration repository by edit() or startEdit() commands.


assign('JDBCSystemResource', ‘myds', 'Target', demoCluster')
# -- or --
assign('JDBCSystemResource', ‘myds', 'Target', demoServer')

Datasource MBean in WebLogic
JDBCSystemResourceMBean tree


Oracle WebLogic supports jDriver for various DBMS. And also WebLogic supports XA drivers for distributed transactions. Supporting Third-Party Drivers also available from DBMS vendors. Note the following are the WebLogic supports Drivers for DBMS:

Cloudscape DB2 PostgreSQL
Oracle  Ms SQL Progress
MySQL  PointBase Sybase

Configuring new data source custom properties
Now let us try to configure a new data source with a custom properties for Connection Pool parameters, weblogic console connecting parameters into a same file or you can specify with different properties files. When the properties file is used it must be loaded before first line of processing statement in the script. We have two options to load the properties one is using command line and other one is using loadProperties() method.

###################****##############****########################
# Generic script applicable on any Operating Environments (Unix, Windows)
# ScriptName    : ConfigDS.py
# Properties    : ConfigDS.properties
# Author        : Srikanth Panda
# Updated by    : Pavan Devarakonda
###############     Connecting to Start     #################################
def connectAdmin() :
 try:
  connect(CONUSR,CONPWD, CONURL)
  print('Successfully connected')
 except:
  print 'Unable to find admin server...'
  exit()
################### Configuring Connection Pool #############################
def connPool(DSnam) :
 DRVPARM='/JDBCSystemResources/'+DSnam+'/JDBCResource/'+DSnam+'/JDBCDriverParams/'+DSnam
 cd(DRVPARM)
 set('Url',DBURL)
 set('DriverName',DBDRV)
 set('Password',DBPASS)
 cd(DRVPARM+'/Properties/'+DSnam)
 cmo.createProperty('user')
 cd(DRVPARM+'/Properties/'+DSnam+'/Properties/user')
 set('Value',DBUSR)

############         Creating Data source    ###############################
def createDS() :
 print('Naming the datasource')
 DSnam = DSName
 cmo.createJDBCSystemResource(DSnam)
 RESOURCE='/JDBCSystemResources/'+DSnam+'/JDBCResource/'+DSnam
 cd(RESOURCE)
 set('Name',DSnam)

 #Setting JNDI name
 cd(RESOURCE+'/JDBCDataSourceParams/'+DSnam)
 print RESOURCE+'/JDBCDataSourceParams/'+DSnam
 set('JNDINames',jarray.array([String(DSnam)], String))

 connPool(DSnam)

 #Set Connection Pool specific parameters
 cd(RESOURCE+'/JDBCConnectionPoolParams/'+DSnam)
 cmo.setTestConnectionsOnReserve(true)
 cmo.setTestTableName('SQL SELECT 1 FROM DUAL')
 cmo.setConnectionReserveTimeoutSeconds(25)
 cmo.setMaxCapacity(15)
 cmo.setConnectionReserveTimeoutSeconds(10)
 cmo.setTestFrequencySeconds(120)

 cd(RESOURCE+'/JDBCDataSourceParams/'+DSnam)
 cmo.setGlobalTransactionsProtocol('TwoPhaseCommit')
 cd('/JDBCSystemResources/'+DSnam)

 # targets the DS to Servers(Cluster or Server)
 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))

###############     Main Script   #####################################
if __name__== "main":
 print('This will enable you to create or update a Datasource')
 connectAdmin()
 edit()
 startEdit()
 # Create a new JDBC resource)
 cd('/')
 createDS()
 save()
 activate()
 disconnect()
####################################


You can configure as many as datasource but you need to provide the responding properties file. The base script will remain unchanged only the properties files will be varies when you move to different database environment.

Derby datasource using WLST on Weblogic 12.1.2

Here I have experimented the above datasource creation script with Apache Derby Database which is a default database part of Oracle WebLogic 12c. You don't need to run the database externally. When you run the WebLogic instance it automatically runs this Derby database instance.

The sample derby database properties are as follows:
DBURL= jdbc:derby://localhost:1527/demodbs
DBDRV=org.apache.derby.jdbc.ClientXADataSource
#oracle.jdbc.OracleDriver
DBPASS=welcome1
DBUSR=weblogic
DSName=myDs
CONUSR=weblogic
CONPWD=welcome1
CONURL=192.168.56.101:8100

Lets execute the script and see...
~/pybin$ wlst -loadProperties createDS.properties createDS.py

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands

This will enable you to create or update a Datasource
Connecting to t3://192.168.56.101:56001 with userid weblogic ...
Successfully connected to Admin Server "demoadm" that belongs to domain "demodomain".

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.

Successfully connected
Location changed to edit tree. This is a writable tree with
DomainMBean as the root. To make changes you will need to start
an edit session via startEdit().

For more help, use help('edit')
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.
Naming the datasource
/JDBCSystemResources/myDs/JDBCResource/myDs/JDBCDataSourceParams/myDs
Target to (C)luster or (S)erver: C
Cluster Name: clstr01
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: demoadm

Oracle Datasource using WLST

The customized properties file "configDS.properties" goes like this:
#==========================
# FileName : ConfigDS.properties
#==========================
DBURL=jdbc:oracle:thin:@dbhostname:dbport:dbschema
DBDRV=oracle.jdbc.OracleDriver
DBPASS=dbpasswd
DBUSR=dbuser
DSName=myDs
CONUSR=system
CONPWD=*********
CONURL=hostname:adminport

General WLST execution instructions


Now to execute the custom properties datasource script the command will be given as follows:
java weblogic.WLST –loadProperties ConfigDS.properties ConfigDS.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... -->

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

Popular Posts