Search This Blog

Friday, November 6, 2015

WLST Programming Controls

Effective programming could be developed using right decision making in your scripts. Here I would like to share some basics of Python program controls that would be used in the WLST scripts.


if-else in WLST



This is common decision making control in every programming language same in WLST. Python based program control much simple no braces required when you construct the if condition. There is no complex confusions for string comparisons and numeric value comparisons. As you know there is no semicolons for statements. The relational operators we have to use straight English words and, or, not. 




if-elif-else in WLST : if-else ladder


In normal programming need this would be mostly used in two or three steps on the ladder preferable. Before you enter here you need to check this really required that gives optimizing your WLST script.

if-elif-else in WLST Scripting

Most of the WLST scripts that you develop for reuse with iterative process need to be in the looping structures for more time. If you write the script optimized way means you need to focus on few facts:
clean, faster, better

While loop can be used when you want to pass the iterations with numbers. We need to initialize the iteration variable and within the loop we need to increase or decrease that value to complete the loop. While loop will be entered into its block when the given expression is executed and resulted true.

Iterations in WLST Scripts


We can see the major categories of WLST iterations control flows available such as 'for loop' and 'while loop'. Before iterating important Python function for automatic number list generation is given below.

The range() function

When you are using for-loop best trick to use with range built in Python function. It will take three different optional arguments and gives you different variety of values in the range of list as output.

  • Until the given number
  • From one particular value to another
  • From one value to another with increment by value

Experimenting with range function to understand all its capabilities The range command always start from the 0 if you pass single argument that is considered as number of values you want as output.

wls:/offline> R=range(11)
wls:/offline> R
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
wls:/offline> R=range(2,10,2)
wls:/offline> R
[2, 4, 6, 8]
wls:/offline> R=range(2,10,3)
wls:/offline> R
[2, 5, 8]


While loop control

This loop control works as same as in C programming style loop. The execution of while loop should not have any control on the variable that is used for iterate the loop. You need to initialize, check the termination condition and in the while loop block it should be iterated by increase or decrease as per program needs.
WLST While loop - WLST for loop

wls:/offline> i=0
wls:/offline> while i < 10:
... jms_server="JMSServer"+str(i)
... print jms_server
... i+=1
...

While loop in WLST Script example

The 'for loop' in WLST


Every scripts developer favorite iterator controller is for loop. Let us dive into some of the examples with it. The example of the 'for loop' in WLST is given below

wls:/offline> slist=range(1,11)
wls:/offline> for i in slist:
...     print 'managed'+str(i)+'_server'
...
managed1_server
managed2_server
managed3_server
managed4_server
managed5_server
managed6_server
managed7_server
managed8_server
managed9_server
managed10_server

Now lets get our WebLogic stuff here :) There could be a deployment on specific standalone servers instances which are not part of the cluster. Fetching only the managed servers excluding the adminserver from the server list that we get them from the ServerLifeCycleRuntimes MBean, Here I've considered the AdminServer name can be any name that includes Admin or adm etc. To solve this we can use lower() string function on the server name and check server names not contains 'adm' then it is managed server list!
wls:/offline> connect('weblogic','welcome1','t3://192.168.33.100:7001')
Connecting to t3://192.168.33.100:7001 with userid weblogic ...
Successfully connected to Admin Server 'wappAdmin' that belongs to domain 'wappdomain'.

wls:/wappdomain/serverConfig> domainRuntime()
Location changed to domainRuntime tree. This is a read-only tree with DomainMBean as the root.
For more help, use help(domainRuntime)

wls:/wappdomain/domainRuntime> cd('/ServerLifeCycleRuntimes/')
wls:/wappdomain/domainRuntime/ServerLifeCycleRuntimes> ls()
dr--   wappAdmin
dr--   wappMS1
dr--   wappMS2

wls:/wappdomain/domainRuntime/ServerLifeCycleRuntimes>  x=ls(returnMap='true')
dr--   wappAdmin
dr--   wappMS1
dr--   wappMS2

wls:/wappdomain/domainRuntime/ServerLifeCycleRuntimes> [s for s in x if 'adm' in s.lower()]
['wappAdmin']
wls:/wappdomain/domainRuntime/ServerLifeCycleRuntimes> [s for s in x if 'adm' not in s.lower()]
['wappMS1', 'wappMS2']
The last output is really awesome you will save lines as well because you don't need new line for if condition.

While loop usage vs for loop


While loop
  1.  Takes more time to executed 
  2. initialization, increase/decrease iterator variable  
  3. Easy to construct infinite loops with intervals  
For loop 
  1.  Fastest loop 
  2. depends on range function to iterate on numbers 
  3. Flexible for including single lambda conditions 
 Will update the following soon after sample executions completed. But these control flags works as in C language.

The break statement in WLST

Some of the code scenarios we need to terminate the iteration with a certain conditions. The 'break' statement in WLST will terminates the current loop. This control jump statement could be under if or else block only.
 
# check for prime
n=input("enter a number: ")

i = 2
while i < n:
        if n%i == 0:
                print "Given ", n, " not prime"
                break
        i+=1
else:
        print n, " is prime"

This logic will be applicable in many scenario, When an application is available on a WebLogic instance overall state for the application would be available. So you could break the loop and come out.
The break statement in WLST

The continue statement in WLST

To skip an iteration in the loop that could be for-loop or while-loop the keyword you need to use 'continue'. This continue statement also requires certain condition for skip the loop. So it can be part of either in the if or in the else block. Lets experiment with continue statement, printing the 0-10 numbers except when 5, 6,7 in the sequence.
 
# This script will illustrate for loop skip
r=range(11)
for i in r:
        if i in (5, 6, 7):
                continue
        print i

The continue statement in WLST
The pass statement in WLST

Sunday, July 19, 2015

startNodeManager with WLST in Windows

If you are working on OFMW environments there is a utility script startNMProps.sh/.cmd file present in the ORACLE_COMMON_HOME/common/bin. This script would update the nodemanager.properties file, which is exists in the WL_HOME/common/nodemanger [NM_Home].
When I've used the example command given in the WLST help got the following error:

Caused by: java.lang.UnsatisfiedLinkError: no nodemanager in java.library.path

Here the problem could be solved or workaround with two options:

  1. Check your JAVA_HOME, JAVA_VENDOR values correctly pointed or not.
  2. Change the nodemanager.properties content with the following option

NativeVersionEnabled=false

When you execute the startNodeManager command for the WLST offline you could pass two arguments: DomainRegistrationEnabled, NodeManagerHome.

wls:/offline> startNodeManager(DomainRegistrationEnabled='true',NodeManagerHome='c:/Oracle/product/fmw/wlserver_10.3/common/nodemanager')
Launching NodeManager ...
Removed output here...
Where it displays that generated nodemanager.properties and also shows the domain mapping.
:
:
NMProcess: INFO: Secure socket listener started on port 5556
Successfully launched the Node Manager.
The Node Manager process is running independent of the WLST process.
Exiting WLST will not stop the Node Manager process. Please refer
to the Node Manager logs for more information.
The Node Manager logs will be under c:\Oracle\product\fmw\wlserver_10.3\common\nodemanager
Node Manager starting in the background

You could experiment on NodeManager on Windows share your issues in the comments.


Sunday, July 12, 2015

NodeManager Status from WLST

When you use WebLogic admin console you know the Node manager is 'Reachable' or 'Inactive' state. The same thing if you wish to get it from WLST machine monitoring, this is not available as exposed MBean attribute.



How to find the NodeManager Running from WLST?
Brainstorming...
Found three alternative solutions.

  1. Use jps command to find the NodeManager Pid exist or not
  2. Connect the Nodemanager if it is succeeds then NM Reachable otherwise not.
  3. Use a simple socket module to create the socket object on the host, port

NodeManager Check with jps command

JDK provides jps command to show the list of Java Pids with name of the Java program. provided your JAVA_HOME must be available in os environment variables. So conditions applied here!! anyways lets see the solution :

def nm_status():
        NMstatus=os.system('jps |grep -i nodemanager|grep -v grep')
        if NMstatus==0:
                return 'Reachable'
        else:
                return 'Inactive'
Note: Please check indentations after copying to your editor.
The disadvantage of this method is it is going to work on Linux/Unix environments only, No Windows.

Connect to NodeMnager get State


WLST Command nmConnect() is going to connect if the machine have a Node Manager running, but here it does not returns the output to a variable. The output normally redirecting to standard output stdout. If we can redirect that to a file and check that contians "Connected"word then you can confirm Nodemanager is 'Reachable' otherwise 'Inactive' state.

def NM_status(nmUser, nmPassword, nmHost, nmPort, dName, domainPath,nmTYPE):
 """ This option nmConnect will give that it is reachable or not from stdout """
        redirect('/tmp/mywlst.out')
        nmConnect(nmUser, nmPassword, nmHost, nmPort, dName, domainPath,nmTYPE)
        stopRedirect()
        flag=0
        for line in open("/tmp/mywlst.out"):
         if "Connected" in line:
          flag=1
          break

 nmDisconnect()
        if flag==1:
          return "Reachable"
        else:
         return "Inactive"

Here we met the purpose of knowing about the status of Node manager. Still looking for better alternative than this!

Node manager status by Socket module

In Python we have Socket object and its related methods to check weather a port is available or not. On a machine if we try to create socket object with Node manager ip address, port then it is going to check the port availability that gives us status!

def is_available(address, port):
    import socket
    try:
        s = socket.socket()
        s.connect((address, int(port)))
        return true
    except:
        return false

def nmStatus(machinesList):
 """ This will create global string with Node manager status"
 machine_port=5556
 machine_host=localhost
 global g_str  
 g_str+="NM "+machine+ " -   "
     
 if is_available(machine_host, machine_port):
  g_str+="Reachable"+"\n"
 else:
  g_str+="Inactive"+"\n"
 
In you main script you could call nmStatus to know about the nodemanager status. Do you have any new thoughts, ideas or suggestions are welcome, Thanks for being with me.

Popular Posts