http://kalali.me/manage-administrate-and-monitor-glassfish-v3-from-java-code-using-amx-jmx/


Manage, Administrate and Monitor GlassFish v3 from Java code usingAMX & JMX

Management is one of the most crucialparts of an application server set of functionalities. Developmentof the application which we deploy into the server happens oncewith minor development iteration during the software lifecycle, butthe
management is a lifetime task. One of the very powerfulfeatures of the GlassFish application server is the powerfuladministration and management channels that it provides fordifferent level of administrators and developers whom want toextend the application
server administration and managementinterfaces.

GlassFish as an application servercapable or serving mission critical and large scale applicationsbenefits from several administration channel including the CLI, webbased administration console and finally the possibility to managethe
application server by using standard Java management extensionor the JMX.

Not only GlassFish fully expose itsmanagement functionalities as JMX MBeans but also it provides avery easier way to manage the application server using localobjects which proxies JMX MBeans. These local objects are providedas AMX
APIs which lift the need for learning JMX by administers anddevelopers whom want to interact with the application server bycode.

GlassFish provides very powerfulmonitoring APIs in term of AMX MBeans which let developers andadministrators monitor any aspect of anything inside theapplication server using Java code without need to understand theJMX APIs or complexity
of monitoring factors and statisticsgathering. These monitoring APIs allows developers to monitor abulk of Java EE functionalities together or just monitor or singleattribute of a single configuration piece.

GlassFish self management capability isanother powerful feature based on the AMX and JMX APIs to letadministrators easily automate daily tasks which can consume ahandful amount of time without automation. Self management canmanage
the application server dynamically by monitoring theapplication server in runtime and changing the application serverconfiguration dynamically based on predefined rules.

1
Java Management eXtension (JMX)

JMX, native to Java platform,introduced to let Java developers have a standard and easy to learnand use way for managing and monitoring their Java applications andJava enabled devices. We as architects, designers and developers ofJava
applications which can be as small as an in house invoicemanagement or as big as a running stock exchange system need a wayto expose management of our developed software to other industryaccepted management software and JMX is the answer to theseneed.

1.1
What is JMX?

JMX is a part of Java Standard editionand was present from early days of Java platform existence and seenmany enhancements during Java platform evolution. The JMX relatedspecifications define the architecture, design patterns, APIs,
andservices in the Java programming language for managing andmonitoring applications and Java enabled devices.

Using the JMX technology, we candevelop Java classes which perform the management and monitoringtasks and expose a set of their functionalities or attributes bymeans of an interface to which later on are exposed to JMX clientsthrough
specific JMX services. The objects which we use to performand expose management functionalities are called Managed Beans orMBeans in brief.

In order for MBeans to be accessible toJMX clients, which will use them to perform management tasks orgathers monitoring data, they need to be registered in a registrywhich later on let our JMX client application to find andinitialize
them. This registry is one of the fundamental JMXservices and called MBean Server.

Now that we have our MBeans registeredwith a registry, we should have a way to let clients communicatewith the running application which registered the MBeans to executeour MBeans operations, this part of the system is called JMXconnectors
which let us communicate with the agent from a remote orlocal management station. The JMX connector and adapter APIprovides a two way converter which can transparently connect to JMXagent over different protocols and provides a standard way formanagement software
to communicate with the JMX agents regardlessof communication protocol.

1.2
JMX architecture

The JMX benefits from a layeredarchitecture heavily based on the interfaces to provideindependency between different layers in term of how each layerworks and how the data and services are provided for each layer byits previous one.

We can divide the JMX architecture tothree layers. Each layer only relay on its direct bottom layer andis not aware of its upper layer functionalities. These layers are:instrumentation, agent, and management layers. Each layer providessome
services either for other layers, in-JVM clients or remoteclients running in other JVMs. Figure 1 shows different layers ofJMX architecture.

id=ajhfp4djcnw6_453d85ffcdw_b" alt="" width="401" height="221" style="margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; border-top-style:none; border-right-style:none; border-bottom-style:none; border-left-style:none; border-width:initial; border-color:initial">

Figure 1 JMX layerd architecture andeach layer components

Instrumentation layer

This layer contains MBeans and theresources that MBeans are intended to manage. Any resource that hasa Java object representative can be instrumented by MBeans. MBeanscan change the value of object’s attributes or call itsoperations
which can affect the resource that this particular Javaobject represents. In addition to MBeans, notification model andMBean metadata objects are categorized in this layer. There are twodifferent types of MBeans for different use cases, these typesinclude:

Standard MBeans: Standard MBeansconsisting of an MBean interface which define the exposedoperations and properties (using getters and setters) and the MBeanimplementation class. The MBean implementation class and theinterface naming
should follow a standard naming pattern inStandard MBeans. There is another type of standard MBeans whichlift the urge for following the naming pattern called MXBeans. TheStandard MBeans naming pattern for MBeans interface isClassNameMBean and the implementation
class is ClassName. For theMXBeans naming pattern for the interface is AnythingMXBean and theimplementation class can have any name. We will discuss this namingmatter in more details later on.

Dynamic MBeans: A dynamic MBeanimplements javax.management.DynamicMBean, instead of implementingan static interface with a set of predefined methods. DynamicMBeans relies on javax.management.MBeanInfo that represents theattributes
and operations exposed by them. MBeans clientapplication call generic getters and setters whose implementationmust resolve the attribute or operation name to its intendedbehavior. Faster implementation of JMX management MBeans for analready completed application
and the amount of informationprovided by MBeans metadata classes are two benefits of DynamicMBeans.

Notification Model: JMX technologyintroduces a notification model based on the Java event model.Using this event model MBeans can emit notifications and anyinterested party can receive and process them, interested partiescan be management
applications or other MBeans.

MBean Metadata Classes: These classescontain the structures to describe all components of an MBean’smanagement interface including its attributes, operations,notification, and constructors. For each of these, the MBeanInfoclass include
a name, a description and its particularcharacteristics (for example, an attribute is readable, writeable,or both; for an operation, the signature of its parameter andreturn types).

Agent layer

This layer contains the JMX Agentswhich are intended to expose the MBeans to management applications.The JMX agent’s implementation specifications fall under thislayer. Agents are usually located in the same JVM that MBeans arelocated
but it is not an obligation. The JMX agent consisting of anMBean server and some helper services which facilitate MBeansoperations. Management software access the agent trough an adapteror connecter based on the management application communicationprotocol.

MBean Server: This is the MBeansregistry, where management applications will look to find whichMBeans are available to them to use. The registry expose the MBeansmanagement interface and not the implementation class. The MBeansregistry
provides two interfaces for accessing the MBeans from aremote and in the same JVM client. MBeans can be registered byanother MBeans, by the management application or by the Agentitself. MBeans are distinguished by a unique name which we willdiscuss more in
AMX section.

Agent Services: there some helperservices for MBeans and agent to facilitate some functionalities.These services include: Timer, dynamic class loader, observers toobserver numeric or string based properties of MBeans, and finallyrelation
service which define associations between MBeans andenforces the cardinality of the relation based on predefinedrelation types.

Management layer

The Management tier contains componentsrequired for developing management applications capable ofcommunicating with JMX agents. Such components provide an interfacefor a management application to interact with JMX agents through aconnector.
This layer may contain multiple adapters and connectorsto expose the JMX agent and its attached MBeans to differentmanagement platforms like SNMP or exposing them in a semantic richformat like HTML.

JMX related JSRs

There are six different JSRs definedfor the JMX related specifications during past 10 years. These JSRsinclude:

JMX 1.2 (JSR 3): First version of JMXwhich was included in J2SE 1.2

J2EE Management (JSR 77): A set ofstandard MBeans to expose application servers’ resources likeapplications, domains, and so on for management purposes.

JMX Remote API 1.0 (JSR 160):interaction with the JMX agents using RMI from a removelocaten.

Monitoring and Management Specificationfor the JVM (JSR 174): a set of API and standard MBeans forexposing JVMs management to any interested management software.

JMX 2.0 (JSR 255): The new version ofJMX for Java 0 which introduces using generics, annotation,extended monitors, and so on.

Web Services Connector for JMX Agents(JSR 262): define an specification which leads to use Web Servicesto access JMX instrumentation remotely.

1.3
JMX benefits

What are JMX benefits that JCP defineda lot of JSRs for it and on top of it, why we did not followanother management standard like IEEE Std 828-1990. The reason isbehind the following JMX benefits:

Java needs an open to extend and closeto change API for integration with emerging requirement andtechnologies, JMX does this by its layered architecture.

The JMX is based on already welldefined and proven Java technologies like Java event model forproviding some of required functionalities.

The JMX specification andimplementation let us use it in any Java enabled software in anyscale.

Almost no change is required for anapplication to become manageable by JMX.

Many vendors uses Java to enable theirdevices, JMX provide one standard to manage both software andhardware.

You can imagine many other benefits forJMX which are not listed above.

1.4
Managed Beans (MBeans)

We discussed that generally there aretwo types of MBeans which we can choose to implement ourinstrumentation layer. Dynamic MBeans are a bit more complex and wewould rather skip them in this crash course, so in this section wewill
discuss how MXBeans can be developed, used locally andremotely to prepare ourselves for understanding and using AMX tomanage GlassFish.

We said that we should write aninterface which defines all exposed operation of the MBeans bothfor the MXBeans and standard MBeans. So first we will write theinterface. Listing 1 shows the WorkerMXBean interface, theinterface has two
methods which supposed to change a configurationin a worker thread and two properties which return the currentnumber of workers threads and maximum number of worker threads.Number of current workers thread is read only and maximum number ofthreads is both
readable and updateable.

Listing 1 The MXBean interfacefor WorkerMXBean

@MXBean

public interface WorkerIF

{

public int getWorkersCount();

public int getMaxWorkers();

public void setMaxWorkers(intnewMaxWorkers);

public int stopAllWorkers();

}

I did not told you that we can forgetabout the naming conversion for MXBean interfaces if we areintended to use Java annotation. As you can see we simply markedthe interface as an MBean interface and defined some setter andgetter methods
along with one operation which will stop someworkers and return the number of stopped workers.

The implementation of our MXBeaninterface will just implement some getter and setters along with adummy operation which just print a message in standard output.

Listing 2 the Worker MXBean implementation

public class Worker implements WorkerIF{

private int maxWorkers;

private int workersCount;

public Worker() {

}

public int getWorkersCount() {

return workersCount;

}

public int getMaxWorkers() {

return maxWorkers;

}

public void setMaxWorkers(intnewMaxWorkers) {

this.maxWorkers = newMaxWorkers;

}

public int stopAllWorkers() {

System.out.println(“Stopping allworkers”);

return 5;

}

}

We did not follow any naming conventionbecause we are using MXBean along with the annotation. If it was astandard MBean then we should have named the interface asWorkerMBean and the implementation class should have beenWorker.

Now we should register the MBean tosome MBean server to make it available to any management software.Listing 3 shows how we can develop a simple agent which will hostthe MBean server along with the registered MBeans.

Please replace the numbers with cueballs

Listing 3 How MBeans server works in a simple agent namedWorkerAgent

public class WorkerAgent {

public WorkerAgent() {

MBeanServer mbs =ManagementFactory.getPlatformMBeanServer(); #1

Worker workerBean = newWorker();                 #2

ObjectName workerName = null;

try {

workerName =new                               #3 ObjectName(“article:name=firstWorkerBean”);

mbs.registerMBean(workerBean,workerName);         #4

System.out.println(“Enter toexit…”);           #5

System.in.read();

} catch(Exception e) {

e.printStackTrace();

}

}

public static void main(String argv[]){

WorkerAgent agent = newWorkerAgent();

System.out.println(“Worker Agent isrunning…”);

}

}

At #1 we get the platform MBean Serverto register our MBean. Platform MBean server is the default JVMMBean server. At #2 we initialize an instance of our MBean.

At #3 we create a new ObjectName forour MBean. Each JVM may use many libraries which each of them canregister tens of MBeans, so MBeans should be uniquely identified inMBean server to prevent any naming collision. The ObjectName followa
format to represent an MBean name in order to ensure that it isshown in a correct place in the management tree and lift anypossibility for naming conflict. An ObjectName is made up of twoparts, a domain and a name value pair separated by a colon. In ourcase
the domain portion is article and the description isname=name=firstWorkerBean

At #4 as register the MBean to theMBean server. At #5 we just make sure that our application will notclose automatically and let us examine the MBean.

Sample code for this chapter isprovided along with the book, you can run the sample codes byfollowing the readme.txt file included in the chapter06 directoryof source code bundle. Using the sample code you will just useMaven to build
and run the application and JConsole to monitor it.But the behind the scene procedure described in the followingparagraph.

To run the application and see how ourMBean will appear in a management console which is standardJConsole bundled with JDK. To enable the JMX management agent forlocal access we need to pass the -Dco

Manage, Administrate and Monitor GlassFish v3 from Java code usingAMX & JMX的更多相关文章

  1. IBM Thread and Monitor Dump Analyzer for Java解决生产环境中的性能问题

    这个工具的使用和 HeapAnalyzer 一样,非常容易,同样提供了详细的 readme 文档,这里也简单举例如下: #/usr/java50/bin/java -Xmx1000m -jar jca ...

  2. 微信支付 V3 的 Java 实现 Payment Spring Boot-1.0.7.RELEASE 发布

    Payment Spring Boot 是微信支付V3的Java实现,仅仅依赖Spring内置的一些类库.配置简单方便,可以让开发者快速为Spring Boot应用接入微信支付. 功能特性 实现微信支 ...

  3. Java语言编码规范(Java Code Conventions)

    Java语言编码规范(Java Code Conventions) 名称 Java语言编码规范(Java Code Conventions) 译者 晨光(Morning) 简介 本文档讲述了Java语 ...

  4. java code to byte code--partone--reference

    Understanding how Java code is compiled into byte code and executed on a Java Virtual Machine (JVM) ...

  5. [转]Java Code Examples for android.util.JsonReader

    [转]Java Code Examples for android.util.JsonReader The following are top voted examples for showing h ...

  6. SQL to Java code for Elasticsearch

    Elasticsearch虽然定位为Search Engine,但是因其可以持久化数据,很多时候,我们把Elasticsearch当成Database用,但是Elasticsearch不支持SQL,就 ...

  7. JUnit单元测试教程(翻译自Java Code Geeks)

    JUnit单元测试教程--终极指南 JUnit单元测试教程终极指南 说明 单元测试简介 1 什么是单元测试 2 测试覆盖 3 Java中的单元测试 JUnit简介 1 使用Eclipse实现简单JUn ...

  8. Java Code Style

    近期困惑于团队成员代码风格迥异,代码质量不可控,作为一名老司机,忧患于后期服务的可维护性,多次一对一的代码Review,耗时耗力不说,效果也不明显.痛定思痛,多次反思之后得出结论:无规矩不成方圆,可靠 ...

  9. 玩转Eclipse — 自动代码生成的Java Code Template

    文章转载地址:点击打开链接 当代码写到一定程度之后,就会发现很多代码都被重复地敲了N多遍,甚至毫不夸张地说:闭着眼睛都能敲出来.大量地敲这些重复地代码,除了锻炼敲键盘的速度,基本上没有其他益处,但是长 ...

随机推荐

  1. Linux基础命令——查看进程命令

    linux是一个 多进程   多用户的操作系统 ps(显示当前进程的状态) ps -ef  查看当前linux 进程 ps -ef | grep 'mysqld'  过滤mysql的进程 (grep  ...

  2. centOS7安装 mysql-community-release-el7-5.noarch.rpm 包

    一.rpm包 1.wget http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm(下载rpm) 2.rpm -ivh mysql ...

  3. Visual Odometry

    http://www.cvlibs.net/datasets/kitti/eval_odometry.php

  4. 关于Java的三种普通排序

    首先要知道是哪几种排序 这里我们所说的是 冒泡排序,选择排序以及插入排序 然后要理解大概的排序速度 : 插入<选择<冒泡 下面是代码 大家可以拷贝自己在java环境里运行运行! publi ...

  5. HTML 5 <a> 标签

    href 属性 定义和用法 href 属性规定链接的目标地址. 如果未使用 href 属性,则 <a> 标签不是链接,而是链接的占位符. HTML 4.01 与 HTML 5 之间的差异 ...

  6. 关于python字符串拼接的几种方法

    当时看完python的基本语法后 给朋友写了个美元概率换算 写完后拼接结果时候 发现压根不知道python怎么拼接字符串 看了些资料自己做了个总结 首先就是和JavaScript一样的拼接方式 nam ...

  7. luogu P3393 逃离僵尸岛-搜索剪枝+spfa

    P3393 逃离僵尸岛 题目描述 小a住的国家被僵尸侵略了!小a打算逃离到该国唯一的国际空港逃出这个国家. 该国有N个城市,城市之间有道路相连.一共有M条双向道路.保证没有自环和重边. K个城市已经被 ...

  8. STL源码分析-iterator(迭代器)

    1. GOF 迭代器设计模式 前面一篇文章有写到stl_list的实现,也实现了一下相应的iterator,但是后面觉得,实现具体容器之前有必要介绍一下iterator(迭代器) .那么迭代器是什么呢 ...

  9. [LUOGU] P2920 [USACO08NOV]时间管理Time Management

    见7.3测试 #include<iostream> #include<algorithm> #include<cstdio> using namespace std ...

  10. 13. OPTIMIZER_TRACE

    13. OPTIMIZER_TRACE OPTIMIZER_TRACE表提供由跟踪语句的优化程序跟踪功能生成的信息. 要启用跟踪,请使用optimizer_trace系统变量. 有关详细信息,请参阅M ...