Manage, Administrate and Monitor GlassFish v3 from Java code usingAMX & 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的更多相关文章
- IBM Thread and Monitor Dump Analyzer for Java解决生产环境中的性能问题
这个工具的使用和 HeapAnalyzer 一样,非常容易,同样提供了详细的 readme 文档,这里也简单举例如下: #/usr/java50/bin/java -Xmx1000m -jar jca ...
- 微信支付 V3 的 Java 实现 Payment Spring Boot-1.0.7.RELEASE 发布
Payment Spring Boot 是微信支付V3的Java实现,仅仅依赖Spring内置的一些类库.配置简单方便,可以让开发者快速为Spring Boot应用接入微信支付. 功能特性 实现微信支 ...
- Java语言编码规范(Java Code Conventions)
Java语言编码规范(Java Code Conventions) 名称 Java语言编码规范(Java Code Conventions) 译者 晨光(Morning) 简介 本文档讲述了Java语 ...
- java code to byte code--partone--reference
Understanding how Java code is compiled into byte code and executed on a Java Virtual Machine (JVM) ...
- [转]Java Code Examples for android.util.JsonReader
[转]Java Code Examples for android.util.JsonReader The following are top voted examples for showing h ...
- SQL to Java code for Elasticsearch
Elasticsearch虽然定位为Search Engine,但是因其可以持久化数据,很多时候,我们把Elasticsearch当成Database用,但是Elasticsearch不支持SQL,就 ...
- JUnit单元测试教程(翻译自Java Code Geeks)
JUnit单元测试教程--终极指南 JUnit单元测试教程终极指南 说明 单元测试简介 1 什么是单元测试 2 测试覆盖 3 Java中的单元测试 JUnit简介 1 使用Eclipse实现简单JUn ...
- Java Code Style
近期困惑于团队成员代码风格迥异,代码质量不可控,作为一名老司机,忧患于后期服务的可维护性,多次一对一的代码Review,耗时耗力不说,效果也不明显.痛定思痛,多次反思之后得出结论:无规矩不成方圆,可靠 ...
- 玩转Eclipse — 自动代码生成的Java Code Template
文章转载地址:点击打开链接 当代码写到一定程度之后,就会发现很多代码都被重复地敲了N多遍,甚至毫不夸张地说:闭着眼睛都能敲出来.大量地敲这些重复地代码,除了锻炼敲键盘的速度,基本上没有其他益处,但是长 ...
随机推荐
- uva12433 Rent a Car
init 一开始搞成2*n+2了...囧 所以初始化很重要! 然后提交的时候忘了删调试的数据了..囧 技巧:设立虚拟节点 建图比较麻烦(非常). 要考虑到保养完了的车可以免费再用 设立S,T ,1 ...
- python django项目断点调试
- 二分+贪心 || CodeForces 551C GukiZ hates Boxes
N堆石头排成一列,每堆有Ai个石子.有M个学生来将所有石头搬走.一开始所有学生都在原点, 每秒钟每个学生都可以在原地搬走一块石头,或者向前移动一格距离,求搬走所有石头的最短时间. *解法:二分答案x( ...
- install mysql at linux
cd /usr/local wget http://repo.mysql.com//mysql57-community-release-el7-7.noarch.rpm rpm -ivh mysql5 ...
- 基于HLS(HTTP Live Streaming)的视频直播分析与实现
转自:http://www.cnblogs.com/haibindev/archive/2013/01/30/2880764.html HLS(HTTP Live Streaming)的分析: HTT ...
- 洛谷P2802 回家
贱呼呼的搜索题 这个最贱的还是在于路途的标记,大部分的题目路途的标记是直接标记即可也就是说我走过了这个点,那么这个点标记上以后不再走,这个题不是,我走过了,但是我可能回了血我又继续走 所以说我们标记的 ...
- 文艺平衡树(splay模板)
题干:splay模板,要求维护区间反转. splay是一种码量小于treap,但支持排名,前驱后继等treap可求的东西,也支持区间反转的平衡树. 但是有两个坏处: 1.splay常数远远大于trea ...
- 02-Mysql中的运算符
Mysql中运算符 1.算术运算符运算符 作用+ 加法- 减法* 乘法/,DIV 除法,返回商%,MOD 除法,返回余数 mysql root@localhost: ...
- redhat 7.x 、redhat 6.x查看硬盘UUID方法
1.查看磁盘分区UUID: [root@rac01 ~]# blkid /dev/sdb1: UUID="6bba92c4-0b25-4cc4-9442-ca87c563720a" ...
- 第十章:C++标准模板库
主要内容: 1.泛型程序设计 2.与STL有关的概念和术语 3.STL的容器 4.迭代器 5.STL的算法 6.函数对象 暂时略,内容有点多,而且也很重要!但我看完了,日后补上.