Esta es una traducción de la página de documentación original en español. Ayúdanos a mejorarla.

1 Objetos JavaScript adicionales

Descripción general

Esta sección describe las adiciones de Zabbix al lenguaje JavaScript implementado con Duktape y las funciones globales de JavaScript compatibles.

Objetos integrados

Zabbix

El objeto Zabbix proporciona interacción con la funcionalidad interna de Zabbix.

Método Descripción
log(loglevel, mensaje) Escribe el <mensaje> en el registro de Zabbix usando el nivel de registro <loglevel> (consulte el parámetro DebugLevel del archivo de configuración).

Ejemplo:

Zabbix.log(3, "esta es una entrada de registro escrita con el nivel de registro 'Advertencia'")

Puede utilizar los siguientes alias:

Alias Alias de
console.log(objeto) Zabbix.log(4, JSON.stringify(objeto))
console.warn(objeto) Zabbix.log(3, JSON.stringify(objeto))
console.error(objeto) Zabbix.log(2, JSON.stringify(objeto))

El tamaño total de todos los mensajes registrados está limitado a 8 MB por cada ejecución del script.

Método Descripción
sleep(delay) Retrasa la ejecución de JavaScript en delay milisegundos.

Ejemplo (retrasar la ejecución 15 segundos):

Zabbix.sleep(15000)

HttpRequest

This object encapsulates cURL handle allowing to make simple HTTP requests. Errors are thrown as exceptions.

HttpRequest is a new name for this object since Zabbix 5.4. Previously it used to be called CurlHttpRequest. Method names have also been changed in Zabbix 5.4. The old object/method names are now deprecated and their support will be discontinued after Zabbix 6.0.

Method Description
addHeader(name, value) Adds HTTP header field. This field is used for all following requests until cleared with the clearHeader() method.
clearHeader() Clears HTTP header. If no header fields are set, HttpRequest will set Content-Type to application/json if the data being posted is JSON-formatted; text/plain otherwise.
connect(url) Sends HTTP CONNECT request to the URL and returns the response.
customRequest(method, url, data) Allows to specify any HTTP method in the first parameter. Sends the method request to the URL with optional data payload and returns the response.
delete(url, data) Sends HTTP DELETE request to the URL with optional data payload and returns the response.
getHeaders() Returns object of received HTTP header fields.
get(url, data) Sends HTTP GET request to the URL with optional data payload and returns the response.
head(url) Sends HTTP HEAD request to the URL and returns the response.
options(url) Sends HTTP OPTIONS request to the URL and returns the response.
patch(url, data) Sends HTTP PATCH request to the URL with optional data payload and returns the response.
put(url, data) Sends HTTP PUT request to the URL with optional data payload and returns the response.
post(url, data) Sends HTTP POST request to the URL with optional data payload and returns the response.
getStatus() Returns the status code of the last HTTP request.
setProxy(proxy) Sets HTTP proxy to "proxy" value. If this parameter is empty then no proxy is used.
setHttpAuth(bitmask, username, password) Sets enabled HTTP authentication methods (HTTPAUTH_BASIC, HTTPAUTH_DIGEST, HTTPAUTH_NEGOTIATE, HTTPAUTH_NTLM, HTTPAUTH_NONE) in the 'bitmask' parameter.
The HTTPAUTH_NONE flag allows to disable HTTP authentication.
Examples:
request.setHttpAuth(HTTPAUTH_NTLM \| HTTPAUTH_BASIC, username, password)
request.setHttpAuth(HTTPAUTH_NONE)
trace(url, data) Sends HTTP TRACE request to the URL with optional data payload and returns the response.

Example:

try {
           Zabbix.log(4, 'jira webhook script value='+value);
         
           var result = {
               'tags': {
                   'endpoint': 'jira'
               }
           },
           params = JSON.parse(value),
           req = new HttpRequest(),
           fields = {},
           resp;
         
           req.addHeader('Content-Type: application/json');
           req.addHeader('Authorization: Basic '+params.authentication);
         
           fields.summary = params.summary;
           fields.description = params.description;
           fields.project = {"key": params.project_key};
           fields.issuetype = {"id": params.issue_id};
           resp = req.post('https://tsupport.zabbix.lan/rest/api/2/issue/',
               JSON.stringify({"fields": fields})
           );
         
           if (req.getStatus() != 201) {
               throw 'Response code: '+req.getStatus();
           }
         
           resp = JSON.parse(resp);
           result.tags.issue_id = resp.id;
           result.tags.issue_key = resp.key;
       } catch (error) {
           Zabbix.log(4, 'jira issue creation failed json : '+JSON.stringify({"fields": fields}));
           Zabbix.log(4, 'jira issue creation failed : '+error);
         
           result = {};
       }
         
       return JSON.stringify(result);

XML

El objeto XML permite el procesamiento de datos XML en la métrica y en el preprocesamiento de descubrimiento de bajo nivel y webhooks.

Para utilizar un objeto XML, el servidor/proxy debe estar compilado con soporte libxml2.

Método Descripción
XML.query(datos, expresión) Recupera el contenido del nodo usando XPath. Devuelve nulo si no se encuentra el nodo.
expresión: una expresión XPath;
datos: datos XML como una cadena.
XML.toJson(data) Convierte datos en formato XML a JSON.
XML.fromJson(object) Convierte datos en formato JSON a XML.

Ejemplo:

Entrada:

<menú>
           <comida tipo="desayuno">
               <nombre>Chocolate</nombre>
               <precio>$ 5,95</precio>
               <descripción></descripción>
               <calorías>650</calorías>
           </comida>
       </menú>

Salida:

{
           "menú": {
               "comida": {
                   "@tipo": "desayuno",
                   "nombre": "Chocolate",
                   "precio": "$5,95",
                   "descripción": nulo,
                   "calorías": "650"
               }
           }
       }
Serialization rules

XML to JSON conversion will be processed according to the following rules (for JSON to XML conversions reversed rules are applied):

1. XML attributes will be converted to keys that have their names prepended with '@'.

Example:

Input:

 <xml foo="FOO">
          <bar>
            <baz>BAZ</baz>
          </bar>
        </xml>

Output:

 {
          "xml": {
            "@foo": "FOO",
            "bar": {
              "baz": "BAZ"
            }
          }
        }

2. Self-closing elements (<foo/>) will be converted as having 'null' value.

Example:

Input:

<xml>
         <foo/>
       </xml>

Output:

{
         "xml": {
           "foo": null
         }
       }

3. Empty attributes (with "" value) will be converted as having empty string ('') value.

Example:

Input:

<xml>
         <foo bar="" />
       </xml>

Output:

{
         "xml": {
           "foo": {
             "@bar": ""
           }
         }
       }

4. Multiple child nodes with the same element name will be converted to a single key that has an array of values as its value.

Example:

Input:

<xml>
         <foo>BAR</foo>
         <foo>BAZ</foo>
         <foo>QUX</foo>
       </xml>

Output:

{
         "xml": {
           "foo": ["BAR", "BAZ", "QUX"]
         }
       }

5. If a text element has no attributes and no children, it will be converted as a string.

Example:

Input:

<xml>
           <foo>BAZ</foo>
       </xml>

Output:

{
         "xml": {
           "foo": "BAZ"
          }
       }

6. If a text element has no children, but has attributes: text content will be converted to an element with the key '#text' and content as a value; attributes will be converted as described in the serialization rule 1.

Example:

Input:

<xml>
         <foo bar="BAR">
           BAZ
         </foo>
       </xml>

Output:

{
         "xml": {
           "foo": {
             "@bar": "BAR",
             "#text": "BAZ"
           }
         }
       }

Global JavaScript functions

Additional global JavaScript functions have been implemented with Duktape:

  • btoa(string) - encodes string to base64 string
  • atob(base64_string) - decodes base64 string
try {
           b64 = btoa("utf8 string");
           utf8 = atob(b64);
       } 
       catch (error) {
           return {'error.name' : error.name, 'error.message' : error.message}
       }
  • md5(string) - calculates the MD5 hash of a string
  • sha256(string) - calculates the SHA256 hash of a string