Managing Oracle Weblogic with WLST

Oracle WebLogic server ships with a set of tools for server administration and management. In the second chapter, we have learnt how to use the browser-based Administration console, which remains the first choice for WLS administrator. In this chapter we will learn about the WebLogic Scripting Tool (WLST) which is a command-line scripting environment that you can use to create, manage and monitor Oracle WebLogic Server domains.

Getting started with Oracle WLST

Oracle WebLogicScripting Tool (WLST) is an advanced management tool, based on the Java scripting interpreter, Jython. In addition to supporting standard Jython features, such as local variables, conditional variables and flow control statements, WLST provides a set of scripting functions (commands) that are specific to WebLogic Server. You can even extend the WLST to suit your needs by following the Jython language syntax.

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.

WLST modes

WLST can be used in several modes; we can however group them in the following main three categories:

  • Offline: Mostly used to create new domains like the configuration domain wizard
  • Online: Used to perform online administration tasks just like the Administration console
  • Embedded: Invoked directly from Java code

Launching the WLST tool

The WebLogic scripting tool can be located into the $MW_HOME/wlserver/common/bin folder of your distribution. It can be launched using the wlst command as shown here:

Running WLST in offline mode

Oracle recommends using the offline mode to create domain templates, new domains based on existing templates, or extend an existing, inactive domain. It is discouraged to use this mode on a running domain of server since changes can be overwritten by other administration tools like the Web console or the WLST on line shell.

Running WLST in offline mode can be achieved with few little steps: at first set your environment by running the setWLSEnv script (the following example assumes you are running a Windows Machine):

$MW_HOME\wlserver\server\bin>setWLSEnv.cmd

Then you can launch your scripts in offline mode by passing them as argument to WLST:

java weblogic.WLST samplescript.py

Initializing WebLogic Scripting Tool (WLST) ...

starting the script ...

...

Alternatively, you can just connect to the WLST by launching the wlst command (as shown in the former picture), and use the execfile command passing as parameter the script to execute:

wls:/(offline)>execfile('c:/temp/ samplescript.py')

starting the script ...

Example: creating an Oracle WLS domain using a script:

Here is a sample WLST script which can be used to create a new WLS domain:

 

middleware_home=' /usr/weblogic/wlserver '

# Open a domain template.

readTemplate (middleware_home + '/common/templates/domains/wls.jar')

cd('Servers/AdminServer')

set('ListenPort', 7001 )

set('ListenAddress','192.168.10.1')

create('AdminServer','SSL')

cd('SSL/AdminServer')

set('Enabled', 'True')

set('ListenPort', 7002)

cd('/')

cd('Security/base_domain/User/WebLogic')

cmo.setName('WebLogic')

cmo.setPassword('secretPassword123 ')

setOption('OverwriteDomain', 'true')

setOption('ServerStartMode', 'prod')

writeDomain(domaintarget)

closeTemplate()

In this script, we are opening an existing domain template for domain creation, using the readTemplate command. Please note that, once you open a domain template, WLST is placed into the configuration bean hierarchy for that domain template, and the prompt is updated to reflect the current location in the configuration hierarchy.

You can traverse the hierarchical structure of configuration beans using commands such as cd, ls, and pwd in a similar way that you would navigate a file system in a UNIX or Windows command shell.

In this example, we are navigating first to the “Servers/AdminServer” location where we perform some administrative tasks (creation of Administration server); then we are heading for “Security/base_domain/User/WebLogic” bean hierarchy where we set some basic security settings.

If you specify a backslash character (\) in a string (e.g. Windows systems), for example when specifying a file pathname, you should precede the quoted string by “r” to instruct WLST to interpret the string in its raw form and ensure that the backslash is taken literally. This format represents standard Jython syntax.

 

 

Running WLST in online mode

Online WLST provides simplified access to Managed Beans (MBeans) which are Java objects that provide a management interface for an underlying resource that you can manage through JMX. Since WLST is a JMX client, all the tasks you can do using WLST online, can also be done programmatically using JMX. Start by connecting to your running Administration server:

wls:/(offline)> connect('username','password', 't3://localhost:7001')

Connecting to weblogic server instance running at t3://localhost:7001 as username weblogic ...

Successfully connected to Admin Server 'myserver' that belongs to domain 'mydomain'.

wls:/mydomain/serverConfig>

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 which is solely responsible for maintaining, updating, and storing the configuration data.

Once you are connected to your WebLogic server instance, you can start navigating and querying MBeans. There are two main paths which can be traversed once you are connected to a WebLogic server instance: Configuration MBeans and RuntimeMBeans.

Entering Configuration MBeans

Configuration MBeans are used to explore the basic server configuration. You can navigate to configuration MBeans by using serverConfig or domainConfig (the latter one if you are connecting through the administration server):

wls:/base_domain/serverConfig> serverConfig()

Location changed to serverConfig tree.

With ls() you can have a look though this MBean structure:

wls:/mydomain/serverConfig> ls()

dr--   AppDeployments

dr--   BridgeDestinations

dr--   Clusters

dr--   DeploymentConfiguration

dr--   Deployments

dr--   EmbeddedLDAP

...

-r--   AdminServerName                              myserver

-r--   AdministrationMBeanAuditingEnabled           false

-r--   AdministrationPort                           9002

-r--   AdministrationPortEnabled                    false

-r--   AdministrationProtocol                       t3s

-r--   ArchiveConfigurationCount                    5

Entering Runtime MBeans

Similar to the configuration information, WebLogic Server Runtime MBeans are arranged in a hierarchical data structure. When connected to an Administration Server, you can 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 objects - ServerRuntimeMBean;

The domainRuntime command places WLST at the root of the domain-wide runtime management objects - DomainRuntimeMBean. (The domain runtime MBean hierarchy exists on the Administration Server only).

Here’s for example how you can check health state information about one application deployed on WebLogic Server:

wls:/base_domain/domainRuntime> serverRuntime()

Location changed to serverRuntime tree. This is a read-only tree with ServerRuntimeMBean as the root.

And now let’s issue a directory listing:

wls:/base_domain/serverRuntime> ls()

dr--   ApplicationRuntimes

dr--   AsyncReplicationRuntime

dr--   ClusterRuntime

dr--   ConnectorServiceRuntime

. . . . .

-r--   MiddlewareHome                               C:\Weblogic

-r--   Name                                         AdminServer

-r--   OpenSocketsCurrentCount                      2

-r--   OracleHome                                   C:\Weblogic

-r--   RestartRequired                              false

-r--   SSLListenAddress                             192.168.1.109

-r--   SSLListenPort                                7002

-r--   SSLListenPortEnabled                         true

-r--   ServerClasspath                              C:\Weblogic\wlserver/endorse

. . . .

wls:/base_domain/serverRuntime> cd ('ApplicationRuntimes');

wls:/base_domain/serverRuntime/ApplicationRuntimes> ls()

dr--   SystemModule-0

dr--   WLSDemo

. . . .

wls:/base_domain/serverRuntime/ApplicationRuntimes> cd ('WLSDemo');

wls:/base_domain/serverRuntime/ApplicationRuntimes/WLSDemo> ls()

. . . .

 

-r--   ActiveVersionState                           2

-r--   ApplicationName                              WLSDemo

-r--   HealthState                                  Component:null,State:HEALTH_

OK,MBean:null,ReasonCode:[]

. . . .

A special variable, named cmo, is set as a pointer to the bean instance you are navigate into. You can use this variable to perform any get, set, or invoke a method on the current bean instance.

wls:/base_domain/serverConfig> cmo

[MBeanServerInvocationHandler]com.bea:Name=base_domain,Type=Domain

wls:/base_domain/serverConfig> cd ('Servers')

wls:/base_domain/serverConfig/Servers> ls()

dr--   AdminServer

dr--   WLSNode1

dr--   WLSNode2

. . . . .

wls:/base_domain/serverConfig/Servers> cd ('WLSNode1');

wls:/base_domain/serverConfig/Servers/WLSNode1> cmo

[MBeanServerInvocationHandler]com.bea:Name=WLSNode1,Type=Server

Editing MBeans

Inspecting the values of MBeans is just half of your administrator activities. Within the Administration Server, there is a set of configuration MBeans in a single, editable hierarchy that contains an editable copy of all configuration MBeans in the domain and it is used only as part of the change management process.

 

The change management process is a controlled procedure for distributing configuration changes in a domain; a change process that loosely resembles a database transaction.

You start the editing process by obtaining a lock on the editable configuration hierarchy to prevent other people from making changes. When you finish making changes, you save and distribute them to all server instances in the domain. When you distribute changes, each server determines whether it can accept the change. If all servers are able to accept the change, they update their working hierarchy of configuration MBeans and the change is completed.

Here’s for example, how you can modify the ‘FileCount’ logging attribute

wls:/base_domain/serverConfig/Servers/AdminServer/Log/AdminServer> edit()

wls:/base_domain/edit !> startEdit()

wls:/base_domain/edit !> cd('Servers/AdminServer/Log/AdminServer')

wls:/base_domain/edit/Servers/AdminServer/Log/AdminServer !> set('FileCount', '8

')

wls:/base_domain/edit/Servers/AdminServer/Log/AdminServer !> save()

wls:/base_domain/edit/Servers/AdminServer/Log/AdminServer !> activate()

Activating all your changes may take a while; however the edit lock associated with this edit session is released once the activation is completed.

Notice the usage of thestartEdit command that initiates the editing process. Changes will not be committed to the repository until you enter the save command. The activate command initiates the distribution of the changes and releases the lock; finally notice that you can make additional changes, without re-entering the startEdit command, or undo changes you have made by entering the undo command.

 

 

Running WLST in Embedded mode

In embedded mode, you instantiate the WLST interpreter in your Java code and use it to run WLST commands and scripts. All WLST commands and variables that you use in interactive and script mode can be also run in embedded mode.

The following example shows how to connect WLST to a running server, create two servers, assign them to a newly created cluster and exit.

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','welcome1')");

    interpreter.exec(buffer.toString());

  }

 

private static void createServers() {

    StringBuffer buf = new StringBuffer();

    buf.append(startTransaction());

    buf.append("man1=create('msEmbedded1','Server')\n");

    buf.append("man2=create('msEmbedded2','Server')\n");

    buf.append("clus=create('clusterEmbedded','Cluster')\n");

    buf.append("man1.setListenPort(8001)\n");

    buf.append("man2.setListenPort(9001)\n");

    buf.append("man1.setCluster(clus)\n");

    buf.append("man2.setCluster(clus)\n");

    buf.append(endTransaction());

    buf.append("print 'Script ran successfully ...' \n");

    interpreter.exec(buf.toString());

  }

private static String startTransaction() {

    StringBuffer buf = new StringBuffer();

    buf.append("edit()\n");

    buf.append("startEdit()\n");

    return buf.toString();

  }

private static String endTransaction() {

    StringBuffer buf = new StringBuffer();

    buf.append("save()\n");

    buf.append("activate(block='true')\n");

    return buf.toString();

  }

public static void main(String[] args) {

    new EmbeddedWLST();

    connect();

    createServers();

  }

}

As you can see, the embedded mode consists in passing WLST commands as String to the weblogic.management.scripting.utils.WLSTInterpreter class. This kind of mode can be useful for developers that want to spice their application with some administration tasks, although it is discouraged for system administrators as it will be harder to maintain.

 

 

Controlling Servers through WLST

WLST can be used as well to manage server life cycle and can be pretty useful, for example, if you have to start/stop a domain consisting in lots of servers. There are basically two modes to manage your servers:

  • Using the Node Manager interface
  • Without Node Manager (via the Admin Server).

Let’s shortly illustrate both approaches

Controlling servers using Node Manager

WLST can connect to a Node Manager that is running on any machine and start one or more WebLogic Server instances on the machine.

A WebLogic domain's Administration Server does not need to be running in order to start servers using this technique.

Start by launching WLST at first:

java weblogic.WLST

In case the Node Manager process is not already running, you can log on to the host computer and use WLST to start it:

wls:/offline> startNodeManager()

Next, connect WLST to a Node Manager by entering the nmConnect command:

nmConnect('weblogic','password123','localhost','5556','mydomain','c:/bea/user_projects/domains/mydomain','SSL')

You can now use the nmStart command to start a server:

wls:/nm/mydomain>nmStart('WLSNode1')

Monitor the status of Managed server by entering the nmServerStatus command:

wls:/nm/mydomain>nmServerStatus('WLSNode1')

Finally, you can stop the server by entering the nmKill command:

wls:/nm/mydomain>nmKill('WLSNode1')

Controlling servers without Node Manager

In the latter option, we will use the WLST startServer command to start the Administration Server. Here’s an example:

wls:offline/>startServer('AdminServer','mydomain','t3://localhost:7001','weblogic','welcome1','c:/weblogic/user_projects/domains/mydomain','true',60000,'false')

After WLST starts a server instance, the server runs in a separate process from WLST; exiting WLST does not shut down the server. So, once you have started the administration server, you can simply connect to it and issue commands to control life cycle of servers:

connect("username","password","t3://localhost:8001")

# First enable the Administration Port. This is not a requirement.

# After you enable the Administration Port in a domain, WebLogic Server

# persists the setting in its configuration files. You do not need to repeat

# the process in future WLST sessions.

edit()

startEdit()

cmo.setAdministrationPortEnabled(1)

activate(block="true")

# check the state of the server

state("myserver")

# now move the server from RUNNING state to ADMIN

suspend("myserver", block="true")

# check the state

state("myserver")

# now resume the server to RUNNING state

resume("myserver",block="true")

 

 

Deploying applications using WLST

This recipe will show you how to deploy/undeploy applications using WLST online mode.

As an example, we will deploy the sampleApp application located at c:\home\sample and create a default deployment plan for it:

progress= deploy(appName='sampleApp',path='c:/home/sample',createplan='true')

The above command will return a WLSTProgress object. You can then use the progress variable to print the status of the deploy command. For example:

wls:/mydomain/serverConfig/Servers> progress.printStatus()

    Current Status of your Deployment:

    Deployment command type: deploy

    Deployment State       : completed

    Deployment Message     : null

The next command, removes the sampleApp application from all target servers. WLST waits 60,000 ms for the process to complete:

wls:/mydomain/serverConfig> undeploy('sampleApp', timeout=60000)

 

 

Creating a cluster with WLST

We will complete the WLST section by providing a ready-to-cook recipe for creating a cluster made up of three Managed Servers (serverA, serverB, serverC). The script is self-descriptive and it uses the createCluster command on the root of the MBean hierarchy in order to create the Cluster which will be later assigned to the Managed Servers via the setCluster command:

connect('myuser','mypass','myhost:7001')

edit()

startEdit()

cd('/')

cmo.createCluster('SampleCluster')

cd('/Clusters/HRWebCluster')

cluster = getMBean('/Clusters/SampleCluster')

cd('/Servers/serverA')

cmo.setCluster(cluster)

cd('/Servers/serverB')

cmo.setCluster(cluster)

cd('/Servers/serverC')

cmo.setCluster(cluster)

activate()

disconnect()

exit()

Francesco Google+