ヘッダをスキップ
Oracle® Fusion Middleware Oracle WebLogic Server 診断フレームワークのコンフィグレーションと使い方
11g リリース 1 (10.3.1)
B55523-01
 

目次へ
目次

戻る
戻る
 
次へ
次へ
 

D WebLogic Scripting Tool のサンプル

以下のサンプルでは、WLST および JMX を使用して WLDF コンポーネントと対話します。

WebLogic Scripting Tool (weblogic.WLST) スクリプトの実行については、『Oracle Fusion Middleware Oracle WebLogic Scripting Tool ガイド』の「Ant からの WLST の実行」を参照してください。JMX アプリケーションの開発については、『Oracle Fusion Middleware Oracle WebLogic Server JMX による管理の容易なアプリケーションの開発』を参照してください。

サンプル : DyeInjection モニタの動的な作成

このデモ スクリプトでは (コード リスト D-1 を参照)、weblogic.WLST ツールを使用して動的に DyeInjection モニタを作成する方法について示します。このスクリプトでは以下のことを行います。

コード リスト D-1 のデモ スクリプトは、診断コンテキストへ仕分け値を注入する仕分けモニタをコンフィグレーションするのみです。イベントをトリガするには、指定された仕分け条件を基に仕分けフィルタを使用してトリガを行う、下流工程の診断モニタを実装する必要があります。下流工程のモニタ アーティファクトの例については、コード リスト D-2 に示しています。これは weblogic-diagnostics.xml というファイルに設定して、アプリケーションのアーカイブの META-INF ディレクトリに配置する必要があります。JSR-88 のデプロイメント プランを使用してモニタを作成することも可能です。アプリケーションのデプロイの詳細については、『Oracle Fusion Middleware WebLogic Server アプリケーションのデプロイメント』を参照してください。

コード リスト D-1 サンプル : WLST を使用した DyeInjection モニタ(demoDyeMonitorCreate.py) の動的な作成

# スクリプト名 : demoDyeMonitorCreate.py
#########################################################################
# WLST によって DyeInjectionMonitor を動的に作成する方法を示す
# デモ スクリプト。このスクリプトでは以下のことを行う。
# - サーバに接続し、必要な場合には初めにサーバを起動する
# - WLDF システム リソースをルックアップまたは作成する
# - DyeInjection モニタ (DIM) を作成する
# - 仕分け条件を指定する
# - モニタを有効にする
# - 保存してアクティブ化する
# - ServerDiagnosticConfig MBean を介して 診断コンテキスト機能を有効にする
#   
# 注意 : ここでは、診断コンテキストに仕分けの値を挿入する仕分けモニタの
# コンフィグレーションのみを行う。イベントをトリガするには、
# 指定された仕分け条件を基にトリガを行うように設定された「下流工程」のモニタがある
# 必要がある。
##########################################################################
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 ("/")
# WLDF システム リソースをルックアップまたは作成する。
wldfResourceName = "mywldf"
myWldfVar = cmo.lookupSystemResource(wldfResourceName)
if myWldfVar==None:
  print "Unable to find named resource,\
           creating WLDF System Resource: " + wldfResourceName
  myWldfVar=cmo.createWLDFSystemResource(wldfResourceName)
# システム リソースをデモ サーバに割り当てる。
wldfServer=cmo.lookupServer(serverName)
myWldfVar.addTarget(wldfServer)
# DyeInjection モニタ (DIM) のプロパティを作成して設定する。
mywldfResource=myWldfVar.getWLDFResource()
mywldfInst=mywldfResource.getInstrumentation()
mywldfInst.setEnabled(1)
monitor=mywldfInst.createWLDFInstrumentationMonitor("DyeInjection")
monitor.setEnabled(1)
# DyeInjection モニタにプロパティを設定する際には、改行を 
# 含める必要がある。
monitor.setProperties("\nUSER1=larry@celtics.com\
                            \nUSER2=brady@patriots.com\n")
monitor.setDyeFilteringEnabled(1)
# ServerDiagnosticConfig を介して診断コンテキスト機能を
# 有効にする。
cd("/Servers/"+serverName+"/ServerDiagnosticConfig/"+serverName)
cmo.setDiagnosticContextEnabled(1)
# 保存して接続を切断する
save()
activate()
disconnect()
exit()

コード リスト D-2 サンプル : 下流工程のモニタ アーティファクト

<?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>

サンプル : 監視と JMX 通知のコンフィグレーション

このデモ スクリプトでは (コード リスト D-3 を参照)、weblogic.WLST ツールを用いて、WLDF の監視と通知コンポーネントを使用する、監視と JMX 通知をコンフィグレーションする方法を示します。このスクリプトでは以下のことを行います。

このスクリプトは以下のファイルおよびスクリプトと連携させることで使用できます。

これらのファイルを連携させるには、以下の手順を実行します。

  1. 次のように入力して、監視のコンフィグレーション スクリプト (demoWatch.py) を実行します。

      java weblogic.WLST demoWatch.py
    
  2. 次のように入力して、JMXWatchNotificationListener.java ソースをコンパイルします。

    javac JMXWatchNotificationListener.java
    
  3. 次のように入力して、JMXWatchNotificationListener.class ファイルを実行します。

    java JMXWatchNotificationListener
    

    注意 :

    前の手順で作成したクラスが見つかるよう、カレント ディレクトリがクラス パス内にあることを確認してください。

  4. 次のように入力して、demoHarvester.py スクリプトを実行します。

    java weblogic.WLST demoHarvester.py
    

demoHarvester.py スクリプトを実行すると、手順 1 でコンフィグレーションされた監視の JMX 通知がトリガされます。

コード リスト D-3 サンプル : 監視と JMX 通知 (demoWatch.py)

# スクリプト名 : demoWatch.py
##########################################################################
# WLDF の監視と通知のフレームワークを使用する監視および JMX 通知の
# コンフィグレーション方法を示すデモ スクリプト。# このスクリプトでは以下のことを行う。
# - サーバに接続し、必要な場合には始めにサーバを起動する
# - WLDF システム リソースをルックアップまたは作成する
# - ServerRuntimeMBean に「OpenSocketsCurrentCount」属性用の
#     監視と監視ルールを作成する。
# - JMX 通知手段を使用するように監視をコンフィグレーションする
#
# このスクリプトは以下と連携させることで使用できる。
# - JMXWatchNotificationListener.java クラス
# - demoHarvester.py スクリプト
#   (このスクリプトでは、収集のためにハーベスタに「OpenSocketsCurrentCount」属性を登録する)。
# これらのファイルを連携させるには、以下の手順を実行する。
# 1. 監視のコンフィグレーション スクリプトを実行する
#       java weblogic.WLST demoWatch.py
# 2. JMXWatchNotificationListener.java ソース コードをコンパイルして起動する
#       javac JMXWatchNotificationListener.java
#         java JMXWatchNotificationListener
# 3. demoHarvester.py スクリプトを実行する
#       java weblogic.WLST demoHarvester.py
# demoHarvester.py スクリプトを実行すると、結果として手順 1 で
# コンフィグレーションされた監視の JMX 通知がトリガされる。
#########################################################################
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()
# WLDF システム リソースをルックアップまたは作成する
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)
# WLDF システム リソースをデモ サーバに割り当てる
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()

サンプル : JMXWatchNotificationListener クラスの記述

コード リスト D-4 に、JMXWatchNotificationListener の記述方法について示します。

コード リスト D-4 サンプル : JMXWatchNotificationListener クラス (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 {
    /*
     * JMX 監視通知リスナを対応する監視 Bean 名と一致する
     * 実行時 MBean に登録する。
     * 各監視に独自の実行時 MBean のインスタンスがある。     */    
    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();
      // 通知を待機してスリープする
      Thread.sleep(Long.MAX_VALUE);
    } catch (Throwable e) {
      e.printStackTrace();
    } // try-catch の終了 
  } // main() の終了
}

サンプル : 収集用の MBean と属性の登録

このデモ スクリプトでは、WLDF ハーベスタで収集するために、weblogic.WLST ツールを使用して MBean および属性を登録する方法を示します。このスクリプトでは以下のことを行います。

コード リスト D-5 サンプル : MBean の登録とデータ収集 (demoHarvester.py)

# スクリプト名 : demoHarvester.py
##################################################################
# WLDF ハーベスタ サービスで収集するために、MBean および属性を
# 登録する方法を示すデモ スクリプト。このスクリプトでは以下のことを行う。
# - サーバに接続し、必要な場合には始めにサーバを起動する
# - WLDF システム リソースをルックアップまたは作成する
# - サンプリングの頻度を設定する
# - 収集する型を追加する
# - 収集する特定のインスタンスの属性を追加する
# - 保存してアクティブ化する
#####################################################################
from java.util import Date
from java.text import SimpleDateFormat
from java.lang import Long
import jarray
#####################################################################
# ハーベスタのコンフィグレーションに型または属性を追加する
# ヘルパー関数
#######################################################################
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
  # セット内にターゲット属性がない場合はここに来るだけ
  currentInstances.append(on)
  # Java 配列に戻す
  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)
#####################################################################
# 指定したハーベスタに現時点で登録されている型を表示する
#######################################################################
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
########################################################################
# スクリプトのメイン フロー -- WLDF システム リソースを作成して収集可能なものを追加する
########################################################################
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()
cd("/")
# WLDF システム リソースをルックアップまたは作成する
wldfResourceName = "mywldf"
systemResource = cmo.lookupSystemResource(wldfResourceName)
if systemResource==None:
  print "Unable to find named resource,\
        creating WLDF System Resource: " + wldfResourceName
  systemResource=cmo.createWLDFSystemResource(wldfResourceName
# コンフィグレーション用のハーベスタ Bean インスタンスを取得する
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()
# WLDF システム リソースをデモ サーバに割り当てる
wldfServer=cmo.lookupServer(myServerName)
systemResource.addTarget(wldfServer)
# ハーベスタの Jython ラッパーで SystemResource オブジェクトへの
# 参照が維持される
harvester.setSamplePeriod(5000)
harvester.setEnabled(1)
# 収集するインスタンスベースの実行時 MBean の属性を追加する
serverRuntime()
cd("/")
addAttributeForInstance(harvester, cmo, "OpenSocketsCurrentCount")
# アクティブにするために編集ツリーに戻る必要がある
edit()
# KnownType = "true" の実行時 MBean の型、すべてのインスタンス、および属性
# を追加する
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()
# データを表示する
displayHarvestedTypes(harvester)
disconnect()
exit()