F WebLogic Scripting Tool Examples

The WebLogic Diagnostics Framework (WLDF) includes examples that show using WLST and JMX to interact with WLDF components.

Note:

The following examples are also included with the WebLogic Server code examples:

These examples are bundled under the title "Configuring the Policies and Actions System and Harvesting Data Using WLST". For information about installing and configuring the WebLogic Server code examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

This appendix includes the following sections:

For information about running WebLogic Scripting Tool (WLST) scripts, see Running WLST from Ant in Understanding the WebLogic Scripting Tool. For information about developing JMX applications, see Understanding JMX in Developing Manageable Applications Using JMX for Oracle WebLogic Server.

WLST Commands for Diagnostics

WLST includes a set of commands that you can use to retrieve diagnostic data and manage diagnostic system resources. These commands are summarized in Table F-1.

Table F-1 WLST Commands Used with WLDF

Command Summary
captureAndSaveDiagnosticImage

Captures a diagnostics image and downloads it locally.

createSystemResourceControl

Creates a diagnostics system resource control using specified descriptor file that is not persisted in the domain configuration. See Using WLST to Activate and Deactivate Diagnostic System Modules.

destroySystemResourceControl

Destroys an external diagnostics system resource control; that is, one that is created in a server or cluster instance but that is not persisted in the domain configuration. See Using WLST to Activate and Deactivate Diagnostic System Modules.

disableSystemResource

Deactivates a diagnostic system resource control that is persisted in the domain configuration. See Using WLST to Activate and Deactivate Diagnostic System Modules.

dumpDiagnosticData

Dumps the diagnostics data from a Harvester to a local file.

enableSystemResource

Activates a diagnostic resource control. See Using WLST to Activate and Deactivate Diagnostic System Modules.

exportDiagnosticData

Execute a query against the specified log file.

exportDiagnosticDataFromServer

Executes a query on the server side and retrieves the exported WLDF data.

getAvailableCapturedImages

Returns a list of the previously captured diagnostic images.

listSystemResourceControls

Lists the diagnostic system modules that are currently configured in the domain. See Using WLST to Activate and Deactivate Diagnostic System Modules.

mergeDiagnosticData

Merges a set of data files that were previously generated by the dumpDiagnosticData() command.

saveDiagnosticImageCaptureFile

Downloads the specified diagnostic image capture.

saveDiagnosticImageCaptureEntryFile

Downloads a specific entry from the diagnostic image capture.

For complete details about each of these commands, including additional examples, see Diagnostics Commands in WLST Command Reference for WebLogic Server.

Example: Dynamically Creating DyeInjection Monitors

You can create a DyeInjection monitor dynamically using WLST. This demonstration script shown in Example F-1does the following:
  • Connects to a server (boots the server first if necessary).

  • Looks up or creates a WLDF System Resource.

  • Creates the DyeInjection monitor.

  • Sets the dye criteria.

  • Enables the monitor.

  • Saves and activates the configuration.

  • Enables the Diagnostic Context feature via the ServerDiagnosticConfigMBean.

The demonstration script in Example F-1 only configures the dye monitor, which injects dye values into the diagnostic context. To fire events, you must implement downstream diagnostic monitors that use dye filtering to fire on the specified dye criteria. An example downstream monitor artifact is shown in Example F-2. This must be placed in a file named weblogic-diagnostics.xml and placed into the META-INF directory of a application archive. It is also possible to create a monitor using a JSR-88 deployment plan. See Deploying Applications to Oracle WebLogic Server.

Example F-1 Example: Using WLST to Dynamically Create DyeInjection Monitors (demoDyeMonitorCreate.py)

# Script name: demoDyeMonitorCreate.py
#########################################################################
# Demo script showing how to create a DyeInjectionMonitor dynamically
# via WLST. This script will:
# - Connect to a server, booting it first if necessary
# - Look up or create a WLDF System Resource
# - Create the DyeInjection Monitor (DIM)
# - Set the dye criteria
# - Enable the monitor
# - Save and activate
# - Enable the Diagnostic Context functionality via the
#   ServerDiagnosticConfig MBean
# Note: This will only configure the dye monitor, which will inject dye
# values into the Diagnostic Context.  To fire events requires the
# existence of "downstream" monitors set to fire on the specified
# dye criteria.
##########################################################################
myDomainDirectory="domain"
url="t3://localhost:7001"
user="weblogic"
password="password"
myServerName="myserver"
myDomain="mydomain"
props="weblogic.GenerateDefaultConfig=true,weblogic.RootDirectory="\
        +myDomainDirectory
try:
  connect(user,password,url)
except:
  startServer(adminServerName=myServerName,domainName=myDomain,
     username=user,password=password,systemProperties=props,
     domainDir=myDomainDirectory,block="true")
  connect(user,password,url)
# Start an edit session
edit()
startEdit()
cd ("/")
# Look up or create the WLDF System resource.
wldfResourceName = "mywldf"
myWldfVar = cmo.lookupSystemResource(wldfResourceName)
if myWldfVar==None:
  print "Unable to find named resource,\
           creating WLDF System Resource: " + wldfResourceName
  myWldfVar=cmo.createWLDFSystemResource(wldfResourceName)
# Target the System Resource to the demo server.
wldfServer=cmo.lookupServer(serverName)
myWldfVar.addTarget(wldfServer)
# create and set properties of the DyeInjection Monitor (DIM). 
mywldfResource=myWldfVar.getWLDFResource()
mywldfInst=mywldfResource.getInstrumentation()
mywldfInst.setEnabled(1)
monitor=mywldfInst.createWLDFInstrumentationMonitor("DyeInjection")
monitor.setEnabled(1)
# Need to include newlines when setting properties 
# on the DyeInjection monitor.
monitor.setProperties("\nUSER1=larry@celtics.com\
                            \nUSER2=brady@patriots.com\n")
monitor.setDyeFilteringEnabled(1)
# Enable the diagnostic context functionality via the
# ServerDiagnosticConfig.
cd("/Servers/"+serverName+"/ServerDiagnosticConfig/"+serverName)
cmo.setDiagnosticContextEnabled(1)
# save and disconnect
save()
activate()
disconnect()
exit()

Example F-2 Example: Downstream Monitor Artifact

<?xml version="1.0" encoding="UTF-8"?>
<wldf-resource xmlns="http://xmlns.oracle.com/weblogic/weblogic-diagnostics"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <instrumentation>
      <enabled>true</enabled>
      <!-- Servlet Session Monitors -->
      <wldf-instrumentation-monitor>
          <name>Servlet_Before_Session</name>
          <enabled>true</enabled>
          <dye-mask>USER1</dye-mask>
          <dye-filtering-enabled>true</dye-filtering-enabled>
          <action>TraceAction</action>
          <action>StackDumpAction</action>
          <action>DisplayArgumentsAction</action>
          <action>ThreadDumpAction</action>
      </wldf-instrumentation-monitor>
      <wldf-instrumentation-monitor>
          <name>Servlet_After_Session</name>
          <enabled>true</enabled>
          <dye-mask>USER2</dye-mask>
          <dye-filtering-enabled>true</dye-filtering-enabled>
          <action>TraceAction</action>
          <action>StackDumpAction</action>
          <action>DisplayArgumentsAction</action>
          <action>ThreadDumpAction</action>
      </wldf-instrumentation-monitor>
   </instrumentation>
</wldf-resource>

Example: Configuring a Policy and a JMX Action

You can use WLST to configure a policy and a JMX action using the WLDF Policies and Actions component. The demonstration script shown in Example F-3 does the following:
  • Connects to a server and boots the server first if necessary.

  • Looks up/creates a diagnostic system module.

  • Creates a policy expression on the ServerRuntimeMBean for the OpenSocketsCurrentCount attribute.

  • Configures the actuion to use a JMXNotification medium.

Note:

This example is also included with the WebLogic Server code examples. For information about installing and configuring these examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

This script can be used in conjunction with the following files and scripts:

To see these files work together, perform the following steps:

  1. To run the policy configuration script (demoWatch.py), type:

      java weblogic.WLST demoWatch.py
    
  2. To compile the JMXWatchNotificationListener.java source, type:

    javac JMXWatchNotificationListener.java
    
  3. To run the JMXWatchNotificationListener.class file, type:

    java JMXWatchNotificationListener

    Note:

    Be sure the current directory is in your class path, so it will find the class file you just created.

  4. To run the demoHarvester.py script, type:

      java weblogic.WLST demoHarvester.py
    

When the demoHarvester.py script runs, it executes the JMXNotification action for the policy configured in step 1.

Example F-3 Example: Policy and JMXNotification (demoWatch.py)

# Script name: demoWatch.py
##########################################################################
# Demo script showing how to configure a policy and a JMXNotification
# using the WLDF Policies and Action framework.
# The script will:
# - Connect to a server, booting it first if necessary
# - Look up or create a WLDF System Resource
# - Create a policy expression on the ServerRuntimeMBean for the
#     "OpenSocketsCurrentCount" attribute
# - Configure the policy to use a JMXNotification medium
#
# This script can be used in conjunction with
# - the JMXWatchNotificationListener.java class
# - the demoHarvester.py script, which registers the
#   "OpenSocketsCurrentCount" attribute with the harvester for collection.
# To see these work together:
# 1. Run the policy configuration script
#       java weblogic.WLST demoWatch.py
# 2. Compile and run the JMXWatchNotificationListener.java source code
#       javac JMXWatchNotificationListener.java
#         java JMXWatchNotificationListener
# 3. Run the demoHarvester.py script
#       java weblogic.WLST demoHarvester.py
# When the demoHarvester.py script runs, it fires the
# JMXNotification for the policy configured in step 1.
#########################################################################
myDomainDirectory="domain"
url="t3://localhost:7001"
user="weblogic"
myServerName="myserver"
myDomain="mydomain"
props="weblogic.GenerateDefaultConfig=true\
       weblogic.RootDirectory="+myDomainDirectory
try:
  connect(user,user,url)
except:
  startServer(adminServerName=myServerName,domainName=myDomain,
     username=user,password=password,systemProperties=props,
     domainDir=myDomainDirectory,block="true")
  connect(user,user,url)
edit()
startEdit()
# Look up or create the WLDF System resource
wldfResourceName = "mywldf"
myWldfVar = cmo.lookupSystemResource(wldfResourceName)
if myWldfVar==None:
  print "Unable to find named resource"
  print "creating WLDF System Resource: " + wldfResourceName
  myWldfVar=cmo.createWLDFSystemResource(wldfResourceName)
# Target the System Resource to the demo server
wldfServer=cmo.lookupServer(myServerName)
myWldfVar.addTarget(wldfServer)
cd("/WLDFSystemResources/mywldf/WLDFResource/mywldf/WatchNotification/mywldf")
watch=cmo.createWatch("mywatch")
watch.setEnabled(1)
jmxnot=cmo.createJMXNotification("myjmx")
watch.addNotification(jmxnot)
serverRuntime()
cd("/")
on=cmo.getObjectName().getCanonicalName()
watch.setRuleExpression("${"+on+"} > 1")
watch.getRuleExpression()
watch.setRuleExpression("${"+on+"//OpenSocketsCurrentCount} > 1")
watch.setAlarmResetPeriod(10000)
edit()
save()
activate()
disconnect()
exit()

Example: Writing a JMXWatchNotificationListener Class

You can use the JMX API to write a JMXWatchNotificationListener. Example F-4 shows an example.

Note:

This example is also included with the WebLogic Server code examples. For information about installing and configuring these examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

Example F-4 Example: JMXWatchNotificationListener Class (JMXWatchNotificationListener.java)

import javax.management.*;
import weblogic.diagnostics.watch.*;
import weblogic.diagnostics.watch.JMXWatchNotification;
import javax.management.Notification;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnector;
import javax.naming.Context;
import java.util.Hashtable;
import weblogic.management.mbeanservers.runtime.RuntimeServiceMBean;
public class JMXWatchNotificationListener implements NotificationListener, Runnable {
  private MBeanServerConnection rmbs = null;
  private String notifName = "myjmx";
  private int notifCount = 0;
  private String serverName = "myserver";  
  public JMXWatchNotificationListener(String serverName) {
  }
  public void register() throws Exception {
    rmbs = getRuntimeMBeanServerConnection();
    addNotificationHandler();
  }
  public void handleNotification(Notification notif, Object handback) {
    synchronized (this) {
      try {
        if (notif instanceof JMXWatchNotification) {
          WatchNotification wNotif =
                ((JMXWatchNotification)notif).getExtendedInfo();
          notifCount++;
  System.out.println("===============================================");
          System.out.println("Notification name:    " +
                 notifName + " called. Count= " + notifCount + ".");
          System.out.println("Watch severity:         " +
                 wNotif.getWatchSeverityLevel());
          System.out.println("Watch time:             " +
                 wNotif.getWatchTime());
          System.out.println("Watch ServerName:       " +
                 wNotif.getWatchServerName());
          System.out.println("Watch RuleType:         " +
                 wNotif.getWatchRuleType());
          System.out.println("Watch Rule:             " +
                 wNotif.getWatchRule());
          System.out.println("Watch Name:             " +
                 wNotif.getWatchName());
          System.out.println("Watch DomainName:       " +
                 wNotif.getWatchDomainName());
          System.out.println("Watch AlarmType:        " +
                 wNotif.getWatchAlarmType());
          System.out.println("Watch AlarmResetPeriod: " +
                 wNotif.getWatchAlarmResetPeriod());
  System.out.println("===============================================");
        }
      } catch (Throwable x) {
        System.out.println("Exception occurred processing JMX policy  
                 action: " + notifName +"\n" + x);
        x.printStackTrace();
      }
    }
  }
  private void addNotificationHandler() throws Exception {
    /*
     * The JMX policy action listener registers with a Runtime MBean
     * that matches the name of the corresponding policy bean.
     * Each policy has its own Runtime MBean instance.
     */    
    ObjectName oname = 
      new ObjectName(
          "com.bea:ServerRuntime=" + serverName + ",Name=" +  
          JMXWatchNotification.GLOBAL_JMX_NOTIFICATION_PRODUCER_NAME + 
          ",Type=WLDFWatchJMXNotificationRuntime," +
          "WLDFWatchNotificationRuntime=WatchNotification," +
          "WLDFRuntime=WLDFRuntime"
          );
     System.out.println("Adding notification handler for: " +
       oname.getCanonicalName());
    rmbs.addNotificationListener(oname, this, null, null);
  }
  private void removeNotificationHandler(String name,
               NotificationListener list) throws Exception {
    ObjectName oname = 
      new ObjectName(
          "com.bea:ServerRuntime=" + serverName + ",Name=" +  
          JMXWatchNotification.GLOBAL_JMX_NOTIFICATION_PRODUCER_NAME + 
          ",Type=WLDFWatchJMXNotificationRuntime," +
          "WLDFWatchNotificationRuntime=WatchNotification," +
          "WLDFRuntime=WLDFRuntime"
          );
    System.out.println("Removing notification handler for: " +
        oname.getCanonicalName());
    rmbs.removeNotificationListener(oname, list);
  }
  public void run() {
    try {
      System.out.println("VM shutdown, unregistering notification
          listener");
      removeNotificationHandler(notifName, this);
    } catch (Throwable t) {
      System.out.println("Caught exception in shutdown hook");
      t.printStackTrace();
    }
  }
  private String user = "weblogic";
  private String password = "password";
  public MBeanServerConnection getRuntimeMBeanServerConnection()
    throws Exception {    
    String JNDI = "/jndi/";
    JMXServiceURL serviceURL;
    serviceURL =
      new JMXServiceURL("t3", "localhost", 7001,
                        JNDI + RuntimeServiceMBean.MBEANSERVER_JNDI_NAME);
    System.out.println("URL=" + serviceURL);
    Hashtable h = new Hashtable();
    h.put(Context.SECURITY_PRINCIPAL,user);
    h.put(Context.SECURITY_CREDENTIALS,password);
    h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
          "weblogic.management.remote");
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL,h);
    return connector.getMBeanServerConnection();
  }
  public static void  main(String[] args) {
    try {
      String serverName = "myserver";
      if (args.length > 0)
        serverName = args[0];
      JMXWatchNotificationListener listener =
              new JMXWatchNotificationListener(serverName);
      System.out.println("Adding shutdown hook");
      Runtime.getRuntime().addShutdownHook(new Thread(listener));
      listener.register();
      // Sleep waiting for notifications
      Thread.sleep(Long.MAX_VALUE);
    } catch (Throwable e) {
      e.printStackTrace();
    } // end of try-catch 
  } // end of main()
}

Example: Registering MBeans and Attributes For Harvesting

You can use WLST to register MBeans and attributes for collection by the WLDF Harvester. The script shown in Example F-5 does the following:
  • Connects to a server and boots the server first if necessary.

  • Looks up or creates a WLDF system resource.

  • Sets the sampling frequency.

  • Adds a type for collection.

  • Adds an attribute of a specific instance for collection.

  • Saves and activates the configuration.

  • Displays a few cycles of the harvested data.

Note:

This example is also included with the WebLogic Server code examples. For information about installing and configuring these examples, see Sample Applications and Code Examples in Understanding Oracle WebLogic Server.

Example F-5 Example: MBean Registration and Data Collection (demoHarvester.py)

# Script name: demoHarvester.py
##################################################################
# Demo script showing how register MBeans and attributes for collection
# by the WLDF Harvester Service.  This script will:
# - Connect to a server, booting it first if necessary
# - Look up or create a WLDF System Resource
# - Set the sampling frequency
# - Add a type for collection
# - Add an attribute of a specific instance for collection
# - Save and activate
#####################################################################
from java.util import Date
from java.text import SimpleDateFormat
from java.lang import Long
import jarray
#####################################################################
# Helper functions for adding types/attributes to the harvester
# configuration
#######################################################################
def findHarvestedType(harvester, typeName):
  htypes=harvester.getHarvestedTypes()
  for ht in (htypes):
    if ht.getName() == typeName:
      return ht
  return None
def addType(harvester, mbeanInstance):
  typeName = "weblogic.management.runtime."\
                 + mbeanInstance.getType() + "MBean"
  ht=findHarvestedType(harvester, typeName)
  if ht == None:
    print "Adding " + typeName + " to harvestables collection for "\
             + harvester.getName()
    ht=harvester.createHarvestedType(typeName)
  return ht;
def addAttributeToHarvestedType(harvestedType, targetAttribute):
  currentAttributes = PyList()
  currentAttributes.extend(harvestedType.getHarvestedAttributes());
  print "Current attributes: " + str(currentAttributes)
  try:
    currentAttributes.index(targetAttribute)
    print "Attribute is already in set"
    return
  except ValueError:
    print targetAttribute + " not in list, adding"
  currentAttributes.append(targetAttribute)
  newSet = jarray.array(currentAttributes, java.lang.String)
  print "New attributes for type "\
           + harvestedType.getName() + ": " + str(newSet)
  harvestedType.setHarvestedAttributes(newSet)
  return
def addTypeForInstance(harvester, mbeanInstance):
  typeName = "weblogic.management.runtime."\
                + mbeanInstance.getType() + "MBean"
  return addTypeByName(harvester, typeName, 1)
def addInstanceToHarvestedType(harvester, mbeanInstance):
  harvestedType = addTypeForInstance(harvester, mbeanInstance)
  currentInstances = PyList()
  currentInstances.extend(harvestedType.getHarvestedAttributes());
  on = mbeanInstance.getObjectName().getCanonicalName()
  print "Adding " + str(on) + " to set of harvested instances for type "\
        + harvestedType.getName()
  print "Current instances : " + str(currentInstances)
  for inst in currentInstances:
    if inst == on:
      print "Found " + on + " in existing set"
      return harvestedType
  # only get here if the target attribute is not in the set
  currentInstances.append(on)
  # convert the new list back to a Java String array
  newSet = jarray.array(currentInstances, java.lang.String)
  print "New instance set for type " + harvestedType.getName()\
          + ": " + str(newSet)
  harvestedType.setHarvestedInstances(newSet)
  return harvestedType
def addTypeByName(harvester, _typeName, knownType=0):
  ht=findHarvestedType(harvester, _typeName)
  if ht == None:
    print "Adding " + _typeName + " to harvestables collection for "\
             + harvester.getName()
    ht=harvester.createHarvestedType(_typeName)
    if knownType == 1:
        print "Setting known type attribute to true for " + _typeName
        ht.setKnownType(knownType)
  return ht;
def addAttributeForInstance(harvester, mbeanInstance, attributeName):
  typeName = mbeanInstance.getType() + "MBean"
  ht = addInstanceToHarvestedType(harvester, mbeanInstance)
  return addAttributeToHarvestedType(ht,attributeName)
#####################################################################
# Display the currently registered types for the specified harvester
#######################################################################
def displayHarvestedTypes(harvester):
  harvestedTypes = harvester.getHarvestedTypes()
  print ""
  print "Harvested types:"
  print ""
  for ht in (harvestedTypes):
    print "Type: " + ht.getName()
    attributes = ht.getHarvestedAttributes()
    if attributes != None:
      print "  Attributes: " + str(attributes)
    instances = ht.getHarvestedInstances()
    print "  Instances:  " + str(instances)
    print ""
  return
########################################################################
# Main script flow -- create a WLDF System resource and add harvestables
########################################################################
myDomainDirectory="domain"
url="t3://localhost:7001"
user="weblogic"
myServerName="myserver"
myDomain="mydomain"
props="weblogic.GenerateDefaultConfig=true,weblogic.RootDirectory="\
         +myDomainDirectory
try:
  connect(user,user,url)
except:
  startServer(adminServerName=myServerName,domainName=myDomain,
     username=user,password=password,systemProperties=props,
     domainDir=myDomainDirectory,block="true")
  connect(user,user,url)
# start an edit session
edit()
startEdit()
cd("/")
# Look up or create the WLDF System resource
wldfResourceName = "mywldf"
systemResource = cmo.lookupSystemResource(wldfResourceName)
if systemResource==None:
  print "Unable to find named resource,\
        creating WLDF System Resource: " + wldfResourceName
  systemResource=cmo.createWLDFSystemResource(wldfResourceName)
# Obtain the harvester bean instance for configuration
print "Getting WLDF Resource Bean from " + str(wldfResourceName)
wldfResource = systemResource.getWLDFResource()
print "Getting Harvester Configuration Bean from " + wldfResourceName
harvester = wldfResource.getHarvester()
print "Harvester: " + harvester.getName()
# Target the WLDF System Resource to the demo server
wldfServer=cmo.lookupServer(myServerName)
systemResource.addTarget(wldfServer)
# The harvester Jython wrapper maintains refs to
# the SystemResource objects
harvester.setSamplePeriod(5000)
harvester.setEnabled(1)
# add an instance-based RT MBean attribute for collection
serverRuntime()
cd("/")
addAttributeForInstance(harvester, cmo, "OpenSocketsCurrentCount")
# have to return to the edit tree to activate
edit()
# add a RT MBean type, all instances and attributes,
# with KnownType = "true"
addTypeByName(harvester,
        "weblogic.management.runtime.WLDFInstrumentationRuntimeMBean", 1)
addTypeByName(harvester,
        "weblogic.management.runtime.WLDFWatchNotificationRuntimeMBean", 1)
addTypeByName(harvester,
        "weblogic.management.runtime.WLDFHarvesterRuntimeMBean", 1)
try:
    save()
    activate(block="true")
except:
    print "Error while trying to save and/or activate."
    dumpStack()
# display the data
displayHarvestedTypes(harvester)
disconnect()
exit()

Example: Setting the WLDF Diagnostic Volume

You can use WLST to configure the volume of Java Flight Recorder data that is captured in a diagnostic image. By default, WLDF gathers data and record most events in a WebLogic Server instance, unless specifically configured otherwise. Note that even when WLDF diagnostic volume is set to Off, WLDF, and potentially the JVM if flight recording is enabled, generate global events that have information about the recording settings; for example, JVM metadata events that list active recordings, and WLDF GlobalInformationEvents that list the volume level for the domain, server, and machine.

Example F-6 shows changing the WLDF diagnostic volume to Medium:

Example F-6 Setting WLDF Diagnostic Volume

connect()
edit()
startEdit()
cd("Servers/myserver")
cd("ServerDiagnosticConfig")
cd("myserver")
cmo.setWLDFDiagnosticVolume("Medium")
save()
activate()

Example: Capturing a Diagnostic Image

You can use WLST to create a diagnostic image capture for a WebLogic Server instance. (Note that you can also create a diagnostic image capture using the WebLogic Server Administration Console or by executing an image action by means of the Policies and Actions component.)

Note:

If WebLogic Server is running in production mode, the server's SSL port must be used when executing the commands included in this script.

Example F-7 show a sample WLST script that captures a diagnostic image. This example does the following:

  • Captures an diagnostic image after connecting, and then waits for the image task to complete.

  • Uses the getAvailableCapturedImages() command to obtain a list of available diagnostic image files in the server's image directory.

  • Loops through the list of available images in the diagnostic image capture and saves each image file locally using the saveDiagnosticImageCaptureFile() command.

Example F-7 Creating a Diagnostic Image Capture

#
# WLST script to capture a WLDF Diagnostic Image and
# retrieve the image files to a local dir.
#
# Usage:
#
# java weblogic.WLST captureImage.py [username] [passwd] [url] [output-dir] 
#
# where 
# 
#   username       Username to use to connect
#   passwd         Password for connecting to server
#   url            URL to connect to the server
#   output-dir     Path to place saved entries
#
from java.io import File
 
# Retrieve a positional argument if it exists; if not,
# the provided default is returned.
#
# Params:
# pos   The integer location in sys.argv of the parameter
# default  The default value to return if the parameter does not exist
#
# returns the value at sys.argv[pos], or the provided default if necesssary
def getPositionalArgument(pos, default):
  value=None
  try:
    value=sys.argv[pos]
  except:
    value=default
  return value
 
# Credential arguments
uname=getPositionalArgument(1, "weblogic")
passwd=getPositionalArgument(2, "password")
url=getPositionalArgument(3, "t3://localhost:7001")
outputDir=getPositionalArgument(4, ".")
 
connect(uname, passwd, url)
serverRuntime()
currentDrive=currentTree()
 
# Capture a new diagnostic image
try:
  cd("serverRuntime:/WLDFRuntime/WLDFRuntime/WLDFImageRuntime/Image")
  task=cmo.captureImage()
  Thread.sleep(1000)
  while task.isRunning():
    Thread.sleep(5000)
  cmo.resetImageLockout();
finally:
  currentDrive()
 
# List the available diagnostic image files in the server's image capture dir
images=getAvailableCapturedImages()
if len(images) > 0:
  # For each diagnostic image found, retrieve image file, renaming it as
  # the user sees fit
  for image in images:
    saveName=outputDir+File.separator+serverName+'-'+image
    saveDiagnosticImageCaptureFile(image,saveName)

Example: Retrieving a JFR File from a Diagnostic Image Capture

You can use WLST to retrieve the Java Flight Recorder (JFR) file from each diagnostic image capture that is located in the image destination directory on the server and copy it to a local directory. The script shown in Example F-8 does the following:
  • Connects to WebLogic Server, passing the required credentials.

  • Creates a diagnostic image capture.

  • Obtains a list of the available diagnostic image files in the server's configured image directory.

  • For each diagnostic image file, attempts to retrieve the JFR file and save it to a local directory, ensuring that each file is renamed as necessary to avoid any from being overwritten.

Note:

If WebLogic Server is running in production mode, the server's SSL port must be used when executing the commands included in this script.

Example F-8 Retrieving a Diagnostic Image Capture File

#
# WLST script to capture a WLDF Diagnostic Image and
# save the FlightRecording.jfr entry locally
#
# Usage:
#
# java weblogic.WLST captureImageEntry.py [username] [passwd] [url] [output-dir] [image-suffix]
#
# where 
# 
#   username       Username to use to connect
#   passwd         Password for connecting to server
#   url            URL to connect to the server
#   output-dir     Path to place saved entries
#   image-suffix   Suffix to use to rename JFR image entries locally
#
import os.path
from java.io import File
 
# Retrieve a positional argument if it exists; if not,
# the provided default is returned.
#
# Params:
# pos   The integer location in sys.argv of the parameter
# default  The default value to return if the parameter does not exist
#
# returns the value at sys.argv[pos], or the provided default if necesssary
def getPositionalArgument(pos, default):
  value=None
  try:
    value=sys.argv[pos]
  except:
    value=default
  return value
 
# Credential arguments
uname=getPositionalArgument(1, "weblogic")
passwd=getPositionalArgument(2, "password")
url=getPositionalArgument(3, "t3://localhost:7001")
outputDir=getPositionalArgument(4, ".")
imageSuffix=getPositionalArgument(5, "_WLS")
 
connect(uname, passwd, url)
serverRuntime()
currentDrive=currentTree()
 
# Capture a new diagnostic image capture file
try:
  cd("serverRuntime:/WLDFRuntime/WLDFRuntime/WLDFImageRuntime/Image")
  task=cmo.captureImage()
  Thread.sleep(1000)
  while task.isRunning():
    Thread.sleep(5000)
  cmo.resetImageLockout();
finally:
  currentDrive()
 
# List the available diagnostic image captures in the server's image capture dir
images=getAvailableCapturedImages()
if len(images) > 0:
  # For each image capture found, retrieve the JFR entry and save it to a local
  # file, renaming it to avoid collisions in the event there are multiple
  # diagnostic image capture files with JFR entries.
  i=0
  for image in images:
    saveName=outputDir+File.separator+"FlightRecording_"+imageSuffix+"-"+str(i)+".jfr"
    while os.path.exists(saveName):
      i+=1
      saveName=outputDir+File.separator+"FlightRecording_"+imageSuffix+"-"+str(i)+".jfr"
    saveDiagnosticImageCaptureEntryFile(image,'FlightRecording.jfr',saveName)
    i+=1