This is a translation of the original English documentation page. Help us make it better.

追加のJavaScriptオブジェクト

概要

本セクションでは、Duktapeで実装された JavaScript の Zabbix への追加と、サポートされるグローバル JavaScript 関数について説明します。

組込オブジェクト

Zabbix

ZabbixオブジェクトはZabbixの内部機能とのインタラクションを提供します。

メソッド 説明
log(loglevel, message) Writes <message> into Zabbix log using <loglevel> log level (see configuration file DebugLevel parameter).

例:

Zabbix.log(3, "this is a log entry written with 'Warning' log level")

以下のエイリアスを使用することができます:

エイリアス ~へのエイリアス
console.log(object) Zabbix.log(4, JSON.stringify(object))
console.warn(object) Zabbix.log(3, JSON.stringify(object))
console.error(object) Zabbix.log(2, JSON.stringify(object))
メソッド 説明
sleep(delay) Delay JavaScript execution by delay milliseconds.

例(実行を15秒遅らせる):

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

XMLオブジェクトは、item 内のXMLデータの処理と、ローレベルディスカバリープリプロセッシングおよびウェブフックを可能にします。

XMLオブジェクトを利用するためには,libxml2がサポートされた状態で server / proxy がコンパイルされている必要があります。

メソッド 説明
XML.query(data, expression) Retrieves node content using XPath. Returns null if node is not found.
expression - an XPath expression;
data - XML data as a string.
XML.toJson(data) Converts data in XML format to JSON.
XML.fromJson(object) Converts data in JSON format to XML.

例:

Input:

<menu>
           <food type = "breakfast">
               <name>Chocolate</name>
               <price>$5.95</price>
               <description></description>
               <calories>650</calories>
           </food>
       </menu>

Output:

{
           "menu": {
               "food": {
                   "@type": "breakfast",
                   "name": "Chocolate",
                   "price": "$5.95",
                   "description": null,
                   "calories": "650"
               }
           }
       }
シリアライズ規則

XMLからJSONへの変換は、以下の規則に従って処理されます(JSONからXMLへの変換は、逆の規則が適用されます)。

1. XML の属性は、名前の先頭に '@' を付加したキーに変換されます。

例:

Input:

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

Output:

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

2. セルフクロージングの要素(<foo/>)は、'null'値を持つものとして変換されます。

例:

Input:

<xml>
         <foo/>
       </xml>

Output:

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

3. 空の属性(""の値)は、空文字列('')の値として変換されます。

例:

Input:

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

Output:

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

4. 同じ要素名を持つ複数の子ノードは、値の配列を値とする1つのキーに変換されます。

例:

Input:

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

Output:

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

5. text 要素に属性がなく、子要素もない場合は、文字列として変換されます。

例:

Input:

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

Output:

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

6. text 要素に子がなく、属性がある場合、text の内容はキーが 'text'、値が content の要素に変換され、
属性はシリアライズ規則 1 のとおりに変換され ます。

例:

Input:

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

Output:

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

グローバル JavaScript 関数

DuktapeでグローバルJavaScriptの機能を追加実装しました:

  • btoa(string) - 文字列をbase64文字列にエンコードする
  • atob(base64_string) - base64文字列をデコードする
try {
           b64 = btoa("utf8 string");
           utf8 = atob(b64);
       } 
       catch (error) {
           return {'error.name' : error.name, 'error.message' : error.message}
       }
  • md5(string) - 文字列の MD5 ハッシュを計算する
  • sha256(string) - 文字列の SHA256 ハッシュを計算します。