D WebLogic Scripting Tool Examples

The following examples use WLST and JMX to interact with WLDF components:

For information on running WebLogic Scripting Tool (weblogic.WLST) scripts, see "Running WLST from Ant" in Oracle Fusion Middleware Oracle WebLogic Scripting Tool. For information on developing JMX applications, see Oracle Fusion Middleware Developing Manageable Applications With JMX for Oracle WebLogic Server.

Example: Dynamically Creating DyeInjection Monitors

This demonstration script (see Example D-1) shows how to use the weblogic.WLST tool to create a DyeInjection monitor dynamically. This script:

  • 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 D-1 only configures the dye monitor, which injects dye values into the diagnostic context. To trigger events, you must implement downstream diagnostic monitors that use dye filtering to trigger on the specified dye criteria. An example downstream monitor artifact is shown in Example D-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. For more information on deploying applications, seeOracle Fusion Middleware Deploying Applications to Oracle WebLogic Server.

Example D-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 trigger events requires the
# existence of "downstream" monitors set to trigger on the specified
# dye criteria.
##########################################################################
myDomainDirectory="domain"
url="t3://localhost:7001"
user="weblogic"
password="weblogic"
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 D-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 Watch and a JMX Notification

This demonstration script (see Example D-3) shows how to use the weblogic.WLST tool to configure a watch and a JMX notification using the WLDF Watch and Notification component. This script:

  • Connects to a server and boots the server first if necessary.

  • Looks up/creates a WLDF system resource.

  • Creates a watch and watch rule on the ServerRuntimeMBean for the OpenSocketsCurrentCount attribute.

  • Configures the watch to use a JMXNotification medium.

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 watch 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 triggers the JMXNotification for the watch configured in step 1.

Example D-3 Example: Watch and JMXNotification (demoWatch.py)

# Script name: demoWatch.py
##########################################################################
# Demo script showing how to configure a Watch and a JMXNotification
# using the WLDF Watches and Notification framework.
# The script will:
# - Connect to a server, booting it first if necessary
# - Look up or create a WLDF System Resource
# - Create a watch and watch rule on the ServerRuntimeMBean for the
#     "OpenSocketsCurrentCount" attribute
# - Configure the watch 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 watch 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 triggers the
# JMXNotification for the watch 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=user,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

Example D-4 shows how to write a JMXWatchNotificationListener.

Example D-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 watch  
                 notification: " + notifName +"\n" + x);
        x.printStackTrace();
      }
    }
  }
  private void addNotificationHandler() throws Exception {
    /*
     * The JMX Watch notification listener registers with a Runtime MBean
     * that matches the name of the corresponding watch bean.
     * Each watch 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 = "weblogic";
  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

This demonstration script shows how to use the weblogic.WLST tool to register MBeans and attributes for collection by the WLDF Harvester. This script:

  • 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.

Example D-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=user,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()