2 Agtente SNMP

Visión General

Puede ser necesario monitorear a través de SNMP algunos dispositivos como ser impresoras, switches de red, routers o UPS. Por lo general estos dispositivos tienen habilitado SNMP, o pueden habilitarse en su configuración. Esto es muy útil cuando los dispositivos no cuentan con un SO que soporte la instalación de, por ejemplo, un agente zabbix.

Para poder cosechar datos mediante SNMP de este tipo de dispositivos, el Zabbix server debe ser configurado con soporte SNMP.

Los chequeos SNMP son hechos a través del protocolo UDP únicamente.

Desde Zabbix 2.2.3 los demonios Zabbix server y proxies solicitan múltimples datos SNMP en un solo requerimiento. Esto es así para todos los items SNMP (simples ítems SNMP, ítems SNMP con índices dinámicos y las SNMP LDD (los level dsicoveries) ) para lograr hacer el proceso de SNMP mucho mas eficiente. Por favor refiérase a la seccion con detalles técnicos mas abajo para entender cómo funciona internamente. Desde Zabbix 2.4 hay una opción de "Use bulk requests" que permite deshabilitar este tipo de pedidos (bulk request) a nivel de interface, para los dispositivos que no puedan manejar este tipo de pedido de manera correcta.

Desde Zabbix 2.2.7 y Zabbix 2.4.2, los demonios Zabbix server y proxy logean lineas similarea a la siguiente si reciben una respuesta SNMP incorrecta:

SNMP response from host "gateway" does not contain all of the requested variable bindings

Aunque no abarquen todos los casos problemáticos, son útiles para identificar dispositivos SNMP en los que se debería deshabilitar esta opción.

Desde Zabbix 2.2, los demonios Zabbix server y proxy utilizan correctamente el seteo del parámetro Timeout cuando cosechan datos SNMP. Adicionalmente, los demonions no insisten luego de obtener un error en un pedido (timeout o error de credenciales). Anteriormente la librería SNMP utilizaba los valores por defecto de timeout y reintentos ( 1 segundo, 5 reintentos)

Desde Zabbix 2.2.8 y Zabbix 2.4.2, los demonios Zabbix server y proxy siempre van a reintentar al menos una vez, tanto a través del mecanismo de la librerís SNMP o a través de mecanismo de procesamiento interno.

Si se están monitoreando dispositivos SNMPv3, asegúrese de que msgAuthoritativeEngineID (también conocido como snmpEngineID o "Engine ID") no se repite en dos dispositivos. De acuerdo con RFC 2571 (section 3.1.1.1) debe ser único por dispositivo.

Configurando el monitoreo SNMP

Para comenzar a monitorear un dispositivo a través de SNMP, se deben seguir los siguientes pasos.

Paso 1

Crear un host para el dispositivo con una interfaz SNMP.

Ingrese la dirección IP. Se pueden usar los templates suministrados por zabbix (Template SNMP Device y otros) que van a agregar automáticamente un conjunto de ítems. Sin embargo, el template puede no ser compatible con el host. Click en Add para guardar el host.

Los chequeos SNMP no usan el Agent port, es ignorado.

Paso 2

Buscar el nombre SNMP o el OID del item que se desea chequear.

Para obtener una lista de los nombres SNMP, use el comando snmpwalk (parte de net-snmp que debe ser instalado cuando se instala Zabbix y se desea monitorear mediante SNMP) o una herramienta equivalente:

shell> snmpwalk -v 2c -c public <host IP> .

'2c' es la versión SNMP, puede ser sustituida por '1', para indicar la vesión 1 en el dispositivo

Esto debe retornar una lista de los nombres SNMP y su último valor. Si no es así, posiblemente la comunity no es el standard 'public', y se deberá de conseguir este valor para obtener la lista.

Se busca en la lista el nombre del que se quiere obtener el valor para monitorear, por ejemplo, si lo que se quiere es monitorear los bytes entrantes el el switch en el puerto 3, se usará IF-MIB::ifInOctets.3 como nombre, en la lista aparecerá algo como:

IF-MIB::ifInOctets.3 = Counter32: 3409739121

Puede usarse el comando snmpget para saber el valor numérico del OID para 'IF-MIB::ifInOctets.3':

shell> snmpget -v 2c -c public -On 10.62.1.22 IF-MIB::ifInOctets.3

Nótese que el último número en el nombre es el puerto al que se quiere hacer referencia. Vea también: Indices dinámicos.

Debería retornar algo como:

.1.3.6.1.2.1.2.2.1.10.3 = Counter32: 3472126941

Nuevamente, el último número en el OID es el puerto al que se quiere hacer referencia.

3COM parece usar los números de puerto en los cientos, por ejemplo, puerto 1 = 101, puerto 3 = 103, pero Cisco usar números comunes, por ejemplo puerto 3 = 3.

Algunos de los OIDs mas usados son traducidos automáticamente a su representación numérica por Zabbix.

En el último ejemplo el tipo de valor es "Counter32", que internamente corresponde a un tipo ASN_COUNTER. La lista completa de los tipos soportados es ASN_COUNTER, ASN_COUNTER64, ASN_UINTEGER, ASN_UNSIGNED64, ASN_INTEGER, ASN_INTEGER64, ASN_FLOAT, ASN_DOUBLE, ASN_TIMETICKS, ASN_GAUGE, ASN_IPADDRESS, ASN_OCTET_STR and ASN_OBJECT_ID (desde 2.2.8, 2.4.3). Estos tipos correspoden a "Counter32", "Counter64", "UInteger32", "INTEGER", "Float", "Double", "Timeticks", "Gauge32", "IpAddress", "OCTET STRING", "OBJECT IDENTIFIER" en la salidad del comando snmpget, pero pueden ser mostrados como "STRING", "Hex-STRING", "OID" y otros, dependiendo de la existencia de un display hint

Paso 3

Crear un item para monitorear.

En el host creado anteriormente, ir a Items. Dependiendo si se usó un template o no cuando se creó el host, se puede tener una lista de ítems asociados al host o una lista vacía de ítems. Vamos a trabajar asumiendo que vamos a crear el ítem, utilizando la información obtenida con los comandos snmpwalk y snmpget. Cliqueamos en Create Item. En el formulario desplegado, ingresamos el nombre del item. Asegúrese de que el campo de interface tiene la IP de dispositivo a monitorear y cambiamos el tipo de ítem a "SNMPv* agent", con la versión que corresponda. Ingresamos la community (usualmente public) y el valor textual o numérico del OID que obtuvimos antes, por ejemplo: .1.3.6.1.2.1.2.2.1.10.3

Ingrese el puerto SNMP, por defecto 161, y en el campo key algo con sentido como SNMP-InOctets-Bps. El tipo de información debe ser cambiado a Numeric (float) y en preprocessing un paso con Change per second o Simple Change dependiendo de lo que se quiera representar, dado que es un contador y siempre va creciendo. Otro paso con un custom multiplier si se desea para convertir a Bytes. En los campos 'Update interval' y 'History storage period' ingrese los valores en que se desea actualizar y durante cuanto tiempo se va a mantener esta información.

Todos los campos obligatorios están marcados con asterisco rojo

Guarde los cambios haciendo click en el botón Add y vaya a MonitoringLatest data para ver los datos cosechados.

Nótese las opciones esecíficas para SNMPv3:

Parámetro Descripción
Context name Ingrese el context name para identificar al item en la subnet SNMP.
Context name se soporta desde Zabbix 2.2.
Pueden usarse User macros en este campo.
Security name Ingrese el security name.
Se pueden usar User macros en este campo.
Security level Seleccione el nivel de seguridad:
noAuthNoPriv - no se utiliza autenticación ni protocolos de privacidad
AuthNoPriv - se utiliza el protocolo de autenticación no el protocolo de privacidad
AuthPriv - se utilizan ambos protocolos
Authentication protocol Seleccione el protocolo de autenticación - MD5 or SHA.
Authentication passphrase Ingrese la authentication passphrase.
Pueden usarse User macros en este campo.
Privacy protocol Seleccione el protocolo de privacidad - DES or AES.
Privacy passphrase Ingrese la privacy passphrase.
Pueden usarse User macros en este campo.

En caso de credenciales SNMPv3 incorrectas (security name, authentication protocol/passphrase, privacy protocol), Zabbix recibe un ERROR del net'snmp, excepto por Privacy passphrase incorrectasm en cuyo caso Zabbix recibe un error de TIMEOUT de net-snmp.

Se requiere un reinicio en el Server/proxy para que los cambios en Authentication protocol, Authentication passphrase, Privacy protocol o Privacy passphrase tengan efecto.

Ejemplo 1

Ejemplo generalÑ

Parámetro Descrición
Community public
OID 1.2.3.45.6.7.8.0 (or .1.2.3.45.6.7.8.0)
Key <String único para referenciar el ítem en los triggers>
Por ejemplo, "my_param".

Note that OID can be given in either numeric or string form. However, in some cases, string OID must be converted to numeric representation. Utility snmpget may be used for this purpose:

shell> snmpget -On localhost public enterprises.ucdavis.memory.memTotalSwap.0

Monitoring of SNMP parameters is possible if --with-net-snmp flag was specified while configuring Zabbix sources.

Example 2

Monitoring of uptime:

Parameter Description
Community public
Oid MIB::sysUpTime.0
Key router.uptime
Value type Float
Units uptime
Multiplier 0.01

Internal workings of bulk processing

Starting from 2.2.3 Zabbix server and proxy query SNMP devices for multiple values in a single request. This affects several types of SNMP items:

All SNMP items on a single interface with identical parameters are scheduled to be queried at the same time. The first two types of items are taken by pollers in batches of at most 128 items, whereas low-level discovery rules are processed individually, as before.

On the lower level, there are two kinds of operations performed for querying values: getting multiple specified objects and walking an OID tree.

For "getting", a GetRequest-PDU is used with at most 128 variable bindings. For "walking", a GetNextRequest-PDU is used for SNMPv1 and GetBulkRequest with "max-repetitions" field of at most 128 is used for SNMPv2 and SNMPv3.

Thus, the benefits of bulk processing for each SNMP item type are outlined below:

  • regular SNMP items benefit from "getting" improvements;
  • SNMP items with dynamic indexes benefit from both "getting" and "walking" improvements: "getting" is used for index verification and "walking" for building the cache;
  • SNMP low-level discovery rules benefit from "walking" improvements.

However, there is a technical issue that not all devices are capable of returning 128 values per request. Some always return a proper response, but others either respond with a "tooBig(1)" error or do not respond at all once the potential response is over a certain limit.

In order to find an optimal number of objects to query for a given device, Zabbix uses the following strategy. It starts cautiously with querying 1 value in a request. If that is successful, it queries 2 values in a request. If that is successful again, it queries 3 values in a request and continues similarly by multiplying the number of queried objects by 1.5, resulting in the following sequence of request sizes: 1, 2, 3, 4, 6, 9, 13, 19, 28, 42, 63, 94, 128.

However, once a device refuses to give a proper response (for example, for 42 variables), Zabbix does two things.

First, for the current item batch it halves the number of objects in a single request and queries 21 variables. If the device is alive, then the query should work in the vast majority of cases, because 28 variables were known to work and 21 is significantly less than that. However, if that still fails, then Zabbix falls back to querying values one by one. If it still fails at this point, then the device is definitely not responding and request size is not an issue.

The second thing Zabbix does for subsequent item batches is it starts with the last successful number of variables (28 in our example) and continues incrementing request sizes by 1 until the limit is hit. For example, assuming the largest response size is 32 variables, the subsequent requests will be of sizes 29, 30, 31, 32, and 33. The last request will fail and Zabbix will never issue a request of size 33 again. From that point on, Zabbix will query at most 32 variables for this device.

If large queries fail with this number of variables, it can mean one of two things. The exact criteria that a device uses for limiting response size cannot be known, but we try to approximate that using the number of variables. So the first possibility is that this number of variables is around the device's actual response size limit in the general case: sometimes response is less than the limit, sometimes it is greater than that. The second possibility is that a UDP packet in either direction simply got lost. For these reasons, if Zabbix gets a failed query, it reduces the maximum number of variables to try to get deeper into the device's comfortable range, but (starting from 2.2.8) only up to two times.

In the example above, if a query with 32 variables happens to fail, Zabbix will reduce the count to 31. If that happens to fail, too, Zabbix will reduce the count to 30. However, Zabbix will not reduce the count below 30, because it will assume that further failures are due to UDP packets getting lost, rather than the device's limit.

If, however, a device cannot handle bulk requests properly for other reasons and the heuristic described above does not work, since Zabbix 2.4 there is a "Use bulk requests" setting for each interface that allows to disable bulk requests for that device.