[comment]: # translation:outdated

[comment]: # ({cc8d2047-536e878a})
# - \#14 Agente JMX (Monitoração JMX)

[comment]: # ({/cc8d2047-536e878a})

[comment]: # ({f1161553-e3fddc4c})
#### - Visão geral

A monitoração JMX é feita através de contadores JMX de uma aplicação
escrita em JAVA. O Zabbix suporta este tipo de monitoração nativamente,
através do módulo "Zabbix Java gateway", que foi introduzido no Zabbix
2.0.

Para recuperar de um host o valor de um contador JMX, o Zabbix server os
requisita ao **Zabbix Java Gateway**, que utiliza-se da [API de
gerenciamento
JMX](http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/)
para obte-los da aplicação JAVA.

::: noteclassic
Veja o manual sobre o [Zabbix Java
gateway](/manual/concepts/java) para maiores detalhes sobre sua
implementação.
:::

[comment]: # ({/f1161553-e3fddc4c})

[comment]: # ({2c0d9a88-7feef73e})
#### - Habilitando monitoração JMX remota em aplicações Java

Uma aplicação Java não necessita de nenhum software adicional, mas
necessita ser iniciada com o parâmetro de linha de comando específico
para habilitar o suporte à monitoração remota via JMX.

No mínimo, se você quer começar a monitoração de uma aplicação feita em
java em um host local, sem definições específicas de segurança, você
deverá utilizar os parâmetros abaixo:

    java \
    -Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=12345 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    -jar /usr/share/doc/openjdk-6-jre-headless/demo/jfc/Notepad/Notepad.jar

Estes parâmetros informam ao Java para aceitar conexões JMX na porta
12345 e informa que não deverá ser requerida autenticação ou SSL.

Se, no seu caso, você precisa monitorar a aplicação a partir de outro
servidor, existem vários outros parâmetros que poderão ser utilizados.
Por exemplo, o próximo parâmetro inicia a aplicação aceitando conexões
de outros hosts, não somente do host local.

    java \
    -Djava.rmi.server.hostname=192.168.3.14 \
    -Dcom.sun.management.jmxremote \
    -Dcom.sun.management.jmxremote.port=12345 \
    -Dcom.sun.management.jmxremote.authenticate=true \
    -Dcom.sun.management.jmxremote.password.file=/etc/java-6-openjdk/management/jmxremote.password \
    -Dcom.sun.management.jmxremote.access.file=/etc/java-6-openjdk/management/jmxremote.access \
    -Dcom.sun.management.jmxremote.ssl=true \
    -Djavax.net.ssl.keyStore=$YOUR_KEY_STORE \
    -Djavax.net.ssl.keyStorePassword=$YOUR_KEY_STORE_PASSWORD \
    -Djavax.net.ssl.trustStore=$YOUR_TRUST_STORE \
    -Djavax.net.ssl.trustStorePassword=$YOUR_TRUST_STORE_PASSWORD \
    -Dcom.sun.management.jmxremote.ssl.need.client.auth=true \
    -jar /usr/share/doc/openjdk-6-jre-headless/demo/jfc/Notepad/Notepad.jar

A maioria destas configurações (se não todas) podem ser especificadas em
/etc/java-6-openjdk/management/management.properties (ou onde quer que
este arquivo tenha sido definido em seu ambiente).

Observe que se você precisar utilizar o SSL, você precisará alterar o
script de inicialização `startup.sh` e adicionar o parâmetro
`-Djavax.net.ssl.*` no Zabbix Java gateway, para que ele saiba onde
encontrar as chaves e redes de confiança.

Veja [monitorando e gerenciando usando
JMX](http://download.oracle.com/javase/1.5.0/docs/guide/management/agent.html)
para mais detalhes.

[comment]: # ({/2c0d9a88-7feef73e})

[comment]: # ({a24f567e-4b8fd32c})
#### - Configurando interfaces e itens JMX na interface web do Zabbix

Com o Zabbix Java gateway em execução o Zabbix Server passa a saber onde
encontra-lo e como encontrar as aplicações com suporte a JMX, o próximo
passo é configurar os itens.

[comment]: # ({/a24f567e-4b8fd32c})

[comment]: # ({9173671a-01c1becc})
##### Configurando a interface JMX

Você começa criando uma interface JMX no host:

![](../../../../../assets/en/manual/config/items/itemtypes/jmx_interface.png){width="600"}

[comment]: # ({/9173671a-01c1becc})

[comment]: # ({7b82d929-d363daf9})
##### Adicionando um item Agente JMX

Para cada contador JMX que você estiver interessado você precisará
adicionar um item do tipo **Agente JMX** associado à interface criada no
passo anterior. Se você tiver configurado uma autenticação para a sua
aplicação Java você deverá especificar também um usuário e senha no
item.

A chave definida na imagem a seguir é
`jmx["java.lang:type=Memory","HeapMemoryUsage.used"]`, nesta definição
existem dois parâmetros:

-   object name - representa o objeto nome de um MBean
-   attribute name - um atributo MBean com composição opcional e campos
    de dados separados por pontos

Veja a seguir os detalhes do item JMX.

![](../../../../../assets/en/manual/config/items/itemtypes/jmx_item.png)

Se você quiser monitorar um contador booleano que seja "verdadeiro" ou
"falso", então você pode especificar o tipo de informação como "Numérico
(inteiro sem sinal)" e o tipo de dados como "Booleano". O Zabbix Server
irá armazenar os valores como 1 e 0, respectivamente.

[comment]: # ({/7b82d929-d363daf9})

[comment]: # ({eaf1dcd3-9430cb1d})
##### Detalhes sobre Chaves de itens JMX

**Atributos simples**

Um objeto MBean nada mais é um texto que você define em uma aplicação
Java. Um nome de atributo, por outro lado, pode ser mais complexo. Caso
um atributo retorne um tipo primitivo de dados (um inteiro, texto, etc)
não se preocupe, a chave será algo similar ao definido a seguir:

    jmx[com.example:Type=Hello,weight]

Neste exemplo o nome do objeto é "com.<example:Type=Hello>", o nome do
atributo é "weight" e provavelmente retornará um valor do tipo "Numerico
(fracionário)".

**Atributos retornando dados compostos**

Pode ser um pouco mais complicado quando o atributo retorna dados
compostos. Por exemplo: o nome do seu atributo é "apple" e retorna um
"hash" representando seus parâmetros, como "weight", "color" etc. Sua
chave pode ser algo similar ao exemplo a seguir:

    jmx[com.example:Type=Hello,apple.weight]

É assim que o nome do atributo e o "hash" da chave são separados, com um
ponto. Da mesma forma, se um atributo retorna dados compostos as partes
serão separadas por pontos:

    jmx[com.example:Type=Hello,fruits.apple.weight]

\
**Problemas com pontos**

Por enquanto tudo bem. Mas e se o nome do atributo ou a chave "hash"
contiver o símbolo "."? Um exemplo:

    jmx[com.example:Type=Hello,all.fruits.apple.weight]

Aí temos um problema. Como dizer ao Zabbix que o nome do atributo é
"all.fruits", não apenas "all"? Como distinguir o ponto que é parte do
nome do ponto que separa o nome de atributo e o hash de chaves?

Antes do Zabbix **2.0.4** o Zabbix Java gateway não conseguia gerir esta
situação e os usuários tinham itens com o estado 'não suportado'. Desde
o 2.0.4 isso passou a ser possível, tudo que você precisa é escapar os
pontos com uma "\\":

    jmx[com.example:Type=Hello,all\.fruits.apple.weight]

Da mesma forma, se seu hash de chave contêm um ponto, você pode
escapa-lo:

    jmx[com.example:Type=Hello,all\.fruits.apple.total\.weight]

\

**Outros problemas**

O caracter de escape pode ser escapado também:

    jmx[com.example:type=Hello,c:\\documents]

Se o nome do objeto ou o nome do atributo contiver espaços ou aspas
duplas:

    jmx["com.example:Type=Hello","fruits.apple.total weight"]

É isso que temos para o momento. Feliz monitoramento JMX!

[comment]: # ({/eaf1dcd3-9430cb1d})

[comment]: # ({105cc785-105cc785})
##### Simple attributes

An MBean object name is nothing but a string which you define in your
Java application. An attribute name, on the other hand, can be more
complex. In case an attribute returns primitive data type (an integer, a
string etc.) there is nothing to worry about, the key will look like
this:

    jmx[com.example:Type=Hello,weight]

In this example an object name is "com.<example:Type=Hello>", attribute
name is "weight" and probably the returned value type should be "Numeric
(float)".

[comment]: # ({/105cc785-105cc785})

[comment]: # ({00e3fc9b-00e3fc9b})
##### Attributes returning composite data

It becomes more complicated when your attribute returns composite data.
For example: your attribute name is "apple" and it returns a hash
representing its parameters, like "weight", "color" etc. Your key may
look like this:

    jmx[com.example:Type=Hello,apple.weight]

This is how an attribute name and a hash key are separated, by using a
dot symbol. Same way, if an attribute returns nested composite data the
parts are separated by a dot:

    jmx[com.example:Type=Hello,fruits.apple.weight]

[comment]: # ({/00e3fc9b-00e3fc9b})

[comment]: # ({ae61b0e7-ae61b0e7})
##### Attributes returning tabular data

Tabular data attributes consist of one or multiple composite attributes.
If such an attribute is specified in the attribute name parameter then
this item value will return the complete structure of the attribute in
JSON format. The individual element values inside the tabular data
attribute can be retrieved using preprocessing.

Tabular data attribute example:

     jmx[com.example:type=Hello,foodinfo]

Item value:

``` {.javascript}
[
  {
    "a": "apple",
    "b": "banana",
    "c": "cherry"
  },
  {
    "a": "potato",
    "b": "lettuce",
    "c": "onion"
  }
]
```

[comment]: # ({/ae61b0e7-ae61b0e7})

[comment]: # ({3a5802d2-3a5802d2})
##### Problem with dots

So far so good. But what if an attribute name or a hash key contains dot
symbol? Here is an example:

    jmx[com.example:Type=Hello,all.fruits.apple.weight]

That's a problem. How to tell Zabbix that attribute name is
"all.fruits", not just "all"? How to distinguish a dot that is part of
the name from the dot that separates an attribute name and hash keys?

Before **2.0.4** Zabbix Java gateway was unable to handle such
situations and users were left with UNSUPPORTED items. Since 2.0.4 this
is possible, all you need to do is to escape the dots that are part of
the name with a backslash:

    jmx[com.example:Type=Hello,all\.fruits.apple.weight]

Same way, if your hash key contains a dot you escape it:

    jmx[com.example:Type=Hello,all\.fruits.apple.total\.weight]

[comment]: # ({/3a5802d2-3a5802d2})

[comment]: # ({80aedcd9-80aedcd9})
##### Other issues

A backslash character in an attribute name should be escaped:

    jmx[com.example:type=Hello,c:\\documents]

For handling any other special characters in JMX item key, please see
the item key format
[section](/manual/config/items/item/key##parameter_-_quoted_string).

This is actually all there is to it. Happy JMX monitoring!

[comment]: # ({/80aedcd9-80aedcd9})

[comment]: # ({1813b2fc-1813b2fc})
##### Non-primitive data types

Since Zabbix 4.0.0 it is possible to work with custom MBeans returning
non-primitive data types, which override the **toString()** method.

[comment]: # ({/1813b2fc-1813b2fc})

[comment]: # ({d814626b-d814626b})
#### Using custom endpoint with JBoss EAP 6.4

Custom endpoints allow working with different transport protocols other
than the default RMI.

To illustrate this possibility, let's try to configure JBoss EAP 6.4
monitoring as an example. First, let's make some assumptions:

-   You have already installed Zabbix Java gateway. If not, then you can
    do it in accordance with the [documentation](/manual/concepts/java).
-   Zabbix server and Java gateway are installed with the prefix
    /usr/local/
-   JBoss is already installed in /opt/jboss-eap-6.4/ and is running in
    standalone mode
-   We shall assume that all these components work on the same host
-   Firewall and SELinux are disabled (or configured accordingly)

Let's make some simple settings in zabbix\_server.conf:

    JavaGateway=127.0.0.1
    StartJavaPollers=5

And in the zabbix\_java/settings.sh configuration file (or
zabbix\_java\_gateway.conf):

    START_POLLERS=5

Check that JBoss listens to its standard management port:

    $ netstat -natp | grep 9999
    tcp        0      0 127.0.0.1:9999          0.0.0.0:*               LISTEN      10148/java

Now let's create a host with JMX interface 127.0.0.1:9999 in Zabbix.

![](../../../../../assets/en/manual/config/items/itemtypes/jmx_jboss_example.png){width="600"}

As we know that this version of JBoss uses the the JBoss Remoting
protocol instead of RMI, we may mass update the JMX endpoint parameter
for items in our JMX template accordingly:

    service:jmx:remoting-jmx://{HOST.CONN}:{HOST.PORT}

![](../../../../../assets/en/manual/config/items/itemtypes/jmx_jboss_example_b.png)

Let's update the configuration cache:

    $ /usr/local/sbin/zabbix_server -R config_cache_reload

Note that you may encounter an error first.

![](../../../../../assets/en/manual/config/items/itemtypes/jmx_jboss_example4.png){width="600"}

"Unsupported protocol: remoting-jmx" means that Java gateway does not
know how to work with the specified protocol. That can be fixed by
creating a \~/needed\_modules.txt file with the following content:

    jboss-as-remoting
    jboss-logging
    jboss-logmanager
    jboss-marshalling
    jboss-remoting
    jboss-sasl
    jcl-over-slf4j
    jul-to-slf4j-stub
    log4j-jboss-logmanager
    remoting-jmx
    slf4j-api
    xnio-api
    xnio-nio</pre>

and then executing the command:

    $ for i in $(cat ~/needed_modules.txt); do find /opt/jboss-eap-6.4 -iname ${i}*.jar -exec cp {} /usr/local/sbin/zabbix_java/lib/ \; ; done

Thus, Java gateway will have all the necessary modules for working with
jmx-remoting. What's left is to restart the Java gateway, wait a bit and
if you did everything right, see that JMX monitoring data begin to
arrive in Zabbix:

![](../../../../../assets/en/manual/config/items/itemtypes/jmx_jboss_example5.png){width="600"}

[comment]: # ({/d814626b-d814626b})
