Chapter 13. WLST: Makes an Administrator's Life Easier

For the past few months now, you have made yourself familiar with all the different aspects and concepts of your Oracle WebLogic Server environments. You have installed, configured, and deployed applications and used all your gained knowledge to have perfectly working environments.

One day, you were we're asked by the project team to work on a solution to script deployment tasks. Until now, the deployment was done using the Administration Console, but the team was looking for a better solution for automating this.

However, you are now trying to find a way to ease up administration work, and also be repetitive in the way you create WebLogic environments, do deployments, and so on.

One way to meet this requirement is embedded in Oracle WebLogic Server the WebLogic Scripting Tool.

The WebLogic Scripting Tool explained

From Version 8x, a new and powerful tool was introduced, called WLST. WLST is a command-line tool that you can use to create, manage, and monitor WebLogic domains. WLST is a tool which is based on the Python programming language and uses the Jython feature to act as an administrator interface of the WebLogic Server. In addition to supporting standard Jython features such as local variables, conditional variables, and flow control statements WLST provides a set of scripting functions and commands that are specific to the WebLogic Server.

The Python language

WebLogic Scripting Tool, or let's call it WLST, is based on a programming language called Python. Python is an interpreted, interactive, object-oriented programming language. Interpreted means that the code is executed by a program that translates it into machine-code at runtime. It is interactive because it writes parts while it is already active. It uses modules, exceptions, dynamic typing, very high-level dynamic data types, and classes. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface, in our case for Jython/WLST. Python is portable, that is it runs on many UNIX variants and all kinds of Windows versions.

Sometimes when using WLST, it's useful to use some pure Python functions to get information about operating system-specific information.

The Jython module

Jython is an implementation of the Python language in Java. It compiles Python code into Java bytecode and uses the JVM for this purpose. WLST uses Jython to access various objects within the WebLogic Server domain. These objects are called MBeans (Managed beans), that is Java objects that represent resources to be managed.

JMX

JMX or Java Management Extensions is the management interface to access the MBeans structure. MBeans must follow the design patterns and interfaces defined in the JMX specification. There are various ways to connect to the MBeans, for example a protocol connector such as the JMX RMI connector exposes the MBeans as they are, so a remote client sees the same model as a local client. Another way of connecting can be by using a protocol adaptor such as an SNMP adaptor or HTML adaptor. In fact, WLST is a JMX client that uses the HTML adaptor.

MBeans

An MBean is a simple Java object that is used to provide a management interface for an underlying resource.

  • It is registered in the WebLogic MBean Server under a unique name under which it can be looked up and accessed
  • It has named and typed attributes that can be read and/or written
  • It has named and typed operations that can be invoked
  • It has typed notifications that can be emitted by the MBean

The available MBean trees are:

  • domainConfig
    • Configuration hierarchy of the entire domain; it represents the configuration MBeans in RuntimeMBeanServer
    • Is read only
  • serverConfig
    • Configuration hierarchy (configuration MBeans) of the server you are connected to
    • Is read only
  • domainRuntime
    • Hierarchy of runtime MBeans for the entire domain
    • Is read only
  • serverRuntime
    • Hierarchy of runtime MBeans for the server you are connected to
    • Is read only
  • edit
    • Writable domain configuration with pending changes; it represents the configuration MBeans in the EditMBeanServer
  • jndi
    • Read-only JNDI tree for the server you are connected to
  • custom
    • List of custom MBeans
    • Can be hierarchical/grouped if MBeans use namespaces appropriately

WLST wraps MBean access for popular operations, supports 'basic' JMX access for all MBeans, and allows direct interaction with MBeans.

The modes of WLST

WLST can be used in several modes:

  • Offline: Analogous to the Configuration domain wizard
  • Online: Analogous to the Administration Console
  • Interactive: Command-line mode to prototype/verify scripts
  • Scripted: Running Jython scripts sequentially without entering input
  • Embedded: Use WLST interpreter from within your Java code

Offline mode

The offline mode can be used to create domains from a template shipped with WebLogic Server or by using your own created template. It's in fact the configuration wizard in command or scripted mode. In this mode, you need not connect to a running WebLogic Server, which sounds plausible. When you want to create a domain, there is no running server instance yet. During offline mode, one cannot view runtime performance or modify security data.

The offline mode is not recommended to do configuration changes because they can be overwritten by JMX clients, such as WLST online or the Administration Console. Also, you need to be running WLST locally for offline mode. You need filesystem access to the domain''s config folder.

The following script is a very simple example of an offline script to create a domain:

wl_home='/app/oracle/Middleware/wlserver_10.3'
# Open a domain template.
readTemplate (wl_home + '/common/templates/domains/wls.jar')
cd('Servers/AdminServer')
set('ListenPort', 7001 )
set('ListenAddress','10.0.0.12')
create('AdminServer','SSL')
cd('SSL/AdminServer')
set('Enabled', 'True')
set('ListenPort', 7002)
cd('/')
cd('Security/base_domain/User/WebLogic')
cmo.setName('WebLogic')
cmo.setPassword('webl0gic ')
setOption('OverwriteDomain', 'true')
setOption('ServerStartMode', 'prod')
writeDomain(domaintarget)
closeTemplate()
  • Creating a domain (offline)
    • Create a new domain using a specified template: createDomain(domainTemplate, domainDir, user, password)
    • Open an existing domain template for domain creation: readTemplate(templateFileName)
    • writeDomain (domainDirName)
    • closeTemplate ()
  • Updating an existing domain (offline)
    • Open an existing domain for update: readDomain(domainDirName)
    • Extend the current domain: addTemplate(templateFileName)
    • Save the domain: updateDomain()

Online mode

When connecting WLST to a running Administration Server, you can manage the configuration of an active WebLogic domain and view performance data about resources in the domain. You can also use WLST to connect to Managed Servers, but you cannot modify configuration data from Managed Servers; because this should only be done by the Administration Server since it is responsible for maintaining, updating, and storing the configuration data. During online mode, one cannot create a domain.

Example of an online mode:

WLST online: Connecting to a domain

  • Setup the environment:
    • Set WLSEnv.sh(in WL_HOME/server/bin)
    • Add WebLogic server classes to classpath and WL_HOME/server/bin to path
  • Invoke WLST:
    • java weblogic.WLST
  • Starts in offline mode
  • Connect to a domain:
    • wls:/offline> connect('weblogic','weblogic','localhost:7001')

Interactive mode

In the interactive mode, you can enter a command and view the response at the command-line prompt; it is useful for learning the tool, command syntax, and verifying configuration options before creating a script. When using WLST interactively, you will get immediate feedback after making a critical configuration change. The WLST shell keeps a connection with an instance of the WebLogic Server.

With the interactive mode you can browse through the complete MBean structure, navigating with certain commands.

WebLogic Server runtime MBeans are arranged in a hierarchical data structure. When connected to an Administration Server, you access the runtime MBean hierarchy by entering the serverRuntime or the domainRuntime command. The serverRuntime command places WLST at the root of the server runtime management object, ServerRuntimeMBean; the domainRuntime command places WLST at the root of the domain-wide runtime management objects called the DomainRuntimeMBean. When connected to a Managed Server, the root of the runtime MBeans is ServerRuntimeMBean. The domain runtime MBean hierarchy exists on the Administration Server only; you cannot use the domainRuntime command when connected to a Managed Server.

Using the cd command, you can navigate to any of the runtime child MBeans. The navigation model for runtime MBeans is the same as the navigation model for configuration MBeans. However, runtime MBeans exist only on the same server instance as their underlying managed resources (except for the domain-wide runtime MBeans on the Administration Server). Also, they are all uneditable.

Browsing with the WLST command-line needs a specific syntax such as:

  • ls(), ls('c'), ls('a')
  • cd('/')

When you use the easeSyntax() command, all quotes and brackets can be left out. Beware, this is only when you don't have to change a configuration. So this is not recommended for scripted mode and especially when using loop constructs. You can also use the regular Jython syntax with parentheses after you enabled the easy syntax. To leave the easy syntax mode, just execute the easeSyntax() command again.

Scripted mode

When you become an expert in WLST, you'll be able to write your own scripts for administering your WebLogic Server and automate manual tasks. To run in scripted mode, you must invoke the script with the WLST command. This can be done in two ways:

  • Directly on an OS command-line:
    java weblogic.WLST script.py
    
  • Or execute the script in the WLST command-line:
    java weblogic.WLST
    Initializing WebLogic Scripting Tool (WLST) ...
    ...
    ...
    wls:/(offline)> execfile('script.py') starting the script ...
    

Because you always have to start with a connection to a domain , you should embed the connect-string to your WebLogic domain in the following way:

connect('<weblogic username>','<weblogic password>','<weblogic admin url>')

To use weblogic.WLST, you should run the setWLSEnv or the setDomainEnv script.

The setWLSEnv script is in the WebLogic Server Home, that is under the wlserver_10.3/server/bin directory.

The setDomainEnv script is in your Domain Home, that is in the bin directory. You can execute this by running the following code:

. ./setDomainEnv.sh

The same counts for the setWLSEnv.sh script.

Finally, WebLogic Server is shipped with some preconfigured shell-scripts, located in the<WebLogic Server Home> /common/bin/wlst.sh.

Embedded mode

To include WLST in Java programs, you can embed the code. This makes it possible to call the WLST interpreter from within your Java code.

For an administrator, the embedded mode is difficult to maintain, but the following is a small example:

package wlst;
import java.util.*;
import weblogic.management.scripting.utils.WLSTInterpreter;
import org.python.util.InteractiveInterpreter;
public class EmbeddedWLST
{
static InteractiveInterpreter interpreter = null;
EmbeddedWLST() { interpreter = new WLSTInterpreter(); }
private static void connect() { StringBuffer buffer = new StringBuffer(); buffer.append("connect('weblogic','weblogic')"); interpreter.exec(buffer.toString()); }
private static void createServers() { StringBuffer buf = new StringBuffer(); buf.append(startTransaction()); buf.append("man1=create('msEmbedded1','Server')
"); buf.append("man2=create('msEmbedded2','Server')
"); buf.append("clus=create('clusterEmbedded','Cluster')
"); buf.append("man1.setListenPort(8001)
"); buf.append("man2.setListenPort(9001)
"); buf.append("man1.setCluster(clus)
"); buf.append("man2.setCluster(clus)
"); buf.append(endTransaction()); buf.append("print 'Script ran successfully ...' 
"); interpreter.exec(buf.toString()); }
private static String startTransaction() { StringBuffer buf = new StringBuffer(); buf.append("edit()
"); buf.append("startEdit()
"); return buf.toString(); }
private static String endTransaction() { StringBuffer buf = new StringBuffer(); buf.append("save()
"); buf.append("activate(block='true')
"); return buf.toString(); }
public static void main(String[] args) { new EmbeddedWLST(); connect(); createServers(); } }

Operational use of WLST

Of course, you want to use your WLST for operational purposes. As a beginner, you start with some simple commands, and the more knowledge you get, the more advanced is the way you use WLST.

Here are some examples how to use WLST for operational tasks:

Starting WebLogic Server instances

You can use WLST to start, stop, suspend, or manage the lifecycle of your Server instances. This can be accomplished in two ways:

Starting with the Node Manager

The following diagram explains that you can connect to the Node Manager using WLST, and from there you can stop or start your WebLogic Server instances:

Starting with the Node Manager
  1. First, of course you will have to start up WLST, using:
    java weblogic.WLST
    
  2. In the WLST console, notice the 'Offline' in the prompt. Next type the following command to connect the Administration Server:
    connect('weblogic','Welkom123','t3://localhost:7001')
    

    When ready, notice the change in the prompt.

  3. First, if it's necessary, start the Node Manager:
    startNodeManager(verbose='true',
    NodeManagerHome='<Node Manager Directory>', ListenPort='5556')
    
  4. In the WLST shell, execute the following command to connect to the Node Manager:
    nmConnect('weblogic', '<weblogic password>','<weblogic host>','<nodemanager port>','<name of domain>,'<domain dir>','plain')
    

    The 'plain' stands for whether the connection is SSL or not. In this case, it's not.

    Tip

    Type the command help('nmConnect') for detailed information on the void in the function nmConnect(void). If you get syntax errors, review the paths and names in the void; a typo is to be expected.

  5. In the WLST shell, type the following command to view the status of the Managed Server ms_trn_1:
    nmServerStatus('<WebLogic Server Instance>')
    
  6. If the status is running use the following command to stop the Managed Server:
    nmKill('<WebLogic Server Instance>')
    

    Verify that the server is SHUTDOWN using the nmServerStatus command.

  7. Use the following command to restart the Managed Server ms_trn_1 and review the feedback:
    nmStart('<WebLogic Server Instance>')
    
  8. When the Node Manager is done, use the command nmServerStatus to review the current status.

Starting without the Node Manager

In this overview, you will connect via the Admin Server instead of the Node Manager to manipulate the WebLogic Server instances. But this can even be used in offline mode, and can be used to start up the Admin Server:

startServer('AdminServer', '<name of domain>','<Admin URL>', 'weblogic','<password WebLogic>', '>,'<domain dir>','true')

The following is a sample script that checks the status of a specific Server instance and starts it when it is not running:

# Connect WLST to the running server
connect('weblogic','<password WebLogic>','<Admin URL>'),
#The following command will print the state of the servers
print 'Status',state('AdminServer','Server'),
serverRuntime()
a = get('State')
if a == 'RUNNING'
print 'Status',state('<Managed Server Name 1>','Server'),
print 'Status',state('<Managed Server Name 2>','Server'),
startServer('AdminServer','mydomain','<Admin URL>',
'weblogic','<password weblogic>', >,'<domain dir>','true')
# Disconnect the WLST from Adminserver
disconnect();

Using CMO (Current Management Object)

CMO is the WLST inbuilt variable. These are like our Java keywords having a dedicated meaning and functionality. CMO stands for Current Management Object. While using or programming in WLST, you can use cmo to point the current MBean (object) instance you are navigating to. The cmo value changes when you navigate to a different hierarchy of MBeans under different MBean trees in WebLogic (except for the JNDI tree).

When WLST first connects to an instance of WebLogic Server, cmo is initialized to the root of all configuration management objects which are of the DomainMBean.MBean type, the value of cmo reflects the parent MBean. MBean name gives the name of the MBean object.

wls:/mydomain/edit> cmo.setAdministrationPort(9005)

If you log in using WLST, cmo gives you the root MBean:

wls:/forms11g_domain/serverConfig> cmo
[MBeanServerInvocationHandler]com.bea:Name=forms11g_domain,Type=Domain

WLST deployment

WLST has a built-in deployment interface, from which you can deploy applications or update domain configurations. WLST deploys applications to a WebLogic Server instance similar to the weblogic.Deployer utility. The deploy command returns a WLSTProgress object that can be used to check the status.

In order to build a good deployment script, you should get to know the different editing commands you will have to use during deployment:

The following are the editing commands:

  • edit();: Used to create, delete, get, set
  • startEdit();: Starts new edit session
  • validate();: Validates changes before saving
  • save();: Saves your changes to a pending version
  • activate();: Starts distribution of changes and releases session lock
  • stopEdit();: Stops current editing session and releases session lock
  • isRestartRequired('true'),: Requires change, restart

Using WLST, you will have to use the various statements that contain the following commands in order to deploy an application:

  • deploy: Deploy an application to a WebLogic Server instance
  • distributeApplication: Copy the deployment bundle to the specified targets
  • getWLDM: Return the WebLogic DeploymentManager object
  • loadApplication: Load an application and deployment plan into memory
  • redeploy: Redeploy a previously deployed application
  • startApplication: Start an application, making it available to users
  • stopApplication: Stop an application, making it unavailable to users
  • undeploy: Undeploy an application from the specified servers
  • updateApplication: Updates an application configuration with a new plan

The following is an example of a small deployment statement:

wls:/mydomain/serverConfig/Servers> deploy('App',
'<path of application package>', targets='<server instance>',
planPath='<path to deployment plan>', timeout=120000)

With the progress.getState() command, you can see the status of the deployment.

For more deployment techniques and know-hows, I'd like you to refer to Chapter 6,Deploy Your Applications in Oracle WebLogic.

Using WLST as an ANT task

It is possible to embed WLST commands into your ANT scripting, because Oracle WebLogic provides an ANT task for this, called wlst.

If you want to use the wlst task with your own ANT installation, include the following task definition in your build file:

<taskdef name="wlst"
classname="weblogic.ant.taskdefs.management.WLSTTask" />

To use the ANT command, you will have to run the setWLSEnv.sh script from the WebLogic Server Home or the setDomainEnv.sh script from the Domain Home to run it from command-line and set all environment settings correctly.

When invoking WLST from an ANT script, it is recommended that you fork a new JVM by specifying fork="true". This will ensure a clean environment and prevent the WLST Exit command which calls System.exit(0) from exiting the ANT script.

For deployment, you can use the wldeploy to add it to your ANT task. For this, you will have to include the following code into your build file:

<taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy"/>

Then you can start using the wldeploy tasks as shown in the following example. It shows a wldeploy target that deploys an application to a single WebLogic Server instance:

<target name="deploy"> <wldeploy action="deploy" verbose="true" debug="true" name="DeployExample" source="output/redeployEAR" user="weblogic" password="weblogic" adminurl="t3://localhost:7001" targets="myserver" /> </target>

Using the Console Script Recording feature

If you want to explore the capabilities of WLST and how to build scripts, you could use the Recording feature for the Admin Console:

First log into the Admin Console:

  1. Step 1: Turn on recording
    • Log in to the WLS console and click on 'Record' (in the toolbar near the top of the page). This starts the WLST script recording. When you start recording, the console prints out the name of the WLST script file that it will create.
    • Make some changes and turn off script recording. The recording session has started.
    • Any configuration changes you make will be recorded in this script. Remember the name of this script since you'll be hand editing it later.

    Note

    Deployment plan changes and security data changes (such as adding, deleting, and modifying users, groups, roles, and policies) will not be captured in the script.

  2. Step 2: Use the WLS console to make typical edits
    • Use the WLS console to make some changes to the domain's configuration. For this example, create a new server in 'Cluster', enable SSL for the server, and customize the server's listen address, listen port, and SSL listen port.
  3. Step 3: Turn off recording
    • Click on 'Record' again in the toolbar near the top of the page. This stops WLST script recording. The console will print out the name of the script again.
    Using the Console Script Recording feature
    • You now have a script that shows how to add a new SSL-enabled server named 'MyServer' to the cluster 'MyCluster':
      startEdit()
      cd('/') cmo.createServer('MyServer')
      cd('/Servers/MyServer') cmo.setListenAddress('MyListenAddress') cmo.setListenPort(7777) cmo.setCluster(getMBean('/Clusters/MyCluster'))
      activate()
      startEdit() cmo.setListenPortEnabled(true) cmo.setJavaCompiler('javac') cmo.setClientCertProxyEnabled(false) cmo.setMachine(None)
      cd('/Servers/MyServer/SSL/MyServer') cmo.setEnabled(true) cmo.setListenPort(8888)
      activate()
      startEdit()
      
    • If you look at this script, you'll notice that it isn't ready to use yet because:
      • It doesn't connect to the Admin Server at the beginning or disconnect at the end; this is because the console is already connected to the Admin Server.
      • It doesn't start 'edit' to tell WLST to use the 'edit' MBean Server. The Admin Server has several different MBean Servers. The'edit' MBean Server is the one that lets you view and manage the domain's configuration.
      • There should be extra 'activate' and 'startEdit' commands. This is because 'Automatically Acquire Lock and Activate Changes' is enabled (this preference makes every console page use a separate configuration editing session).
      • The server name, cluster name, listen address, listen port, and SSL listen port values are hardcoded.
  4. Step 4: Edit the script
    • Make a copy of the captured script, then edit the copy to address these issues.
    • Use 'connect' at the beginning of the script to connect to the WebLogic domain. To connect, WLST needs to know the Admin Server URL as well as the Admin username and password. You have two choices on how to get this information.
      • Prompt for them or get the information from the command line, then pass them to the'connect' command. Don''t pass any parameters to the'connect' command. Instead, always run WLST from the domain directory on the Admin Server's machine. When you do this, WLST can automatically figure out the username, password, and URL.
    • Call 'edit' to tell WLST to use the Admin Server's 'edit' JMX Server and use 'disconnect' at the end of the script.
    • Remove the extra 'activate' and 'startEdit' commands.
    • Parameterize the script, specify the server name, listen address, listen port, and SSL listen port. The following sample prompts for them.

    Note

    Since this example wants to show how to add new servers to an existing cluster, it leaves the cluster name hardcoded in the script 'MyCluster'. This is typical. Most scripts want to parameterize some values and hardcode others.

    The following is the edited script:

    connect() edit()
    myServerName = raw_input('Enter server name:') myListenAddress = raw_input('Enter listen address:') myListenPort = int(raw_input('Enter listen port:')) mySSLListenPort = int(raw_input('Enter SSL listen port:'))
    startEdit()
    cd('/') cmo.createServer(myServerName)
    cd('/Servers/' + myServerName) cmo.setListenAddress(myListenAddress) cmo.setListenPort(myListenPort) cmo.setCluster(getMBean('/Clusters/MyCluster'))
    cmo.setListenPortEnabled(true) cmo.setJavaCompiler('javac') cmo.setClientCertProxyEnabled(false) cmo.setMachine(None)
    cd('/Servers/' + myServerName + '/SSL/' + myServerName) cmo.setEnabled(true) cmo.setListenPort(mySSLListenPort)
    activate() disconnect()
    

You now have a parameterized WLST script that your administrator can use to add new SSL-enabled servers to 'MyCluster' as the load goes up.

Now you can run the script and the raw_input statement enables you to fill in your own parameters.

Command-line editing in a UNIX environment

Not a standard WebLogic feature, but one I'd like to discuss as a bonus for your hard work, is the command-line editing feature.

In a UNIX environment, WLST does not provide any command-line editing capabilities. However, you can use a third-party tool, such as JLine, to provide line editing in WLST.

JLine provides the following editing capabilities:

  • Command history
  • Line editing
  • Custom key bindings

For more information about JLine refer to http://jline.sourceforge.net/index.html.

To use JLine with WLST, follow the steps mentioned next:

  1. Download JLine from http://jline.sourceforge.net/downloads.html.
  2. Unzip the file and put the JLine jar into a directory on your machine. Add the JLine jar to the CLASSPATH.
  3. Run JLine as follows:
    java jline.ConsoleRunner weblogic.WLST
    
  4. Alternatively, you can copy the $WL_HOME/common/bin/wlst.sh script and then add jline.ConsoleRunner before weblogic.WLST.

    The default keys in JLine are:

    • UP ARROW and DOWN ARROW to move within the command history
    • Ctrl + N and Ctrl + P to move within the command history
    • LEFT ARROW and RIGHT ARROW to move within a command
    • Ctrl + B moves to the previous character
    • Ctrl + G moves to the previous word
    • Ctrl + A moves to the beginning of the line
    • Ctrl + F moves to the next character
    • Ctrl + E moves to the end of the line
    • Ctrl + U deletes all characters before the cursor
    • Ctrl + W deletes the word before the cursor

On UNIX systems, JLine will execute the stty command to initialize the terminal to allow unbuffered input, using the jline.UnixTerminal class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.174.0