JAVA訪問Zabbix API

Zabbix

1、Zabbix 概述

zabbix是一個基於WEB界面的提供分佈式系統監視以及網絡監視功能的企業級的開源解決方案。zabbix能監視各類網絡參數,保證服務器系統的安全運營;並提供靈活的通知機制以讓系統管理員快速定位/解決存在的各類問題。php

zabbix由2部分構成,zabbix server與可選組件zabbix agent。

(1)zabbix agent須要安裝在被監視的目標服務器上,它主要完成對硬件信息或與操做系統有關的內存,CPU等信息的收集。
(2)zabbix server能夠單獨監視遠程服務器的服務狀態;同時也能夠與zabbix agent配合,能夠輪詢zabbix agent主動接收監視數據(agent方式),同時還可被動接收zabbix agent發送的數據(trapping方式)。java

2、Zabbix API

Zabbix的功能雖然很強大,能將數據以圖表形式展示在Web中,可是,一個監控系統的使用者若是不瞭解Zabbix,或者其非維護人員須要經過監控瞭解各個服務器大體運行情況時,Zabbix所提供的界面就不是很友好了。
Zabbix API偏偏解決了這一問題。咱們能夠從API接口中讀取想要了解的數據,用本身的方式展示在Web中。json

3、java程序以HTTP方式向API請求數據

zabbix監控中的幾個概念:api

  1. hostid:每一個被監控服務器惟一標識。能夠根據ip/hostname得到,具體方法爲代碼中的getHostIdByIp/getHostIdByHostName。
  2. key:監控項名字,能夠在zabbix平臺自行查到。例如"system.cpu.util[,idle]","system.cpu.load[all,avg1]","system.swap.size[,free]"等等。
  3. itemid:根據hostid和key惟一缺肯定,監控項的惟一標識。具體方法爲代碼中的getItemId(hostId, key)。
  4. value_type:數據類型,能夠經過官方API item.get獲取,history.get方法中就是傳value_type給history參數。獲取這個參數詳見我代碼中的方法getValueType(hostId, key),使用這個參數參考getHistoryDataByItemId(itemId, valueType, time_from, time_till)。具體參考:
    https://www.zabbix.com/documentation/2.4/manual/api/reference/item/object
    https://www.zabbix.com/documentation/2.4/manual/api/reference/history/get
package test.test;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author xueyuan@meizu.com
 * @since 建立時間:2016年8月10日 上午11:43:49
 */
public class ZabbixUtil {

    private static String       URL      = "http://IP:port/api_jsonrpc.php";

    private static String       AUTH     = null;

    private static final String USERNAME = "u";

    private static final String PASSWORD = "p";


    /**
     * 向Zabbix發送Post請求,並返回json格式字符串
     * 
     * @param param 請求參數
     * @return
     * @throws Exception
     */
    private static String sendPost(Map map) {
        String param = JSON.toJSONString(map);
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        StringBuffer sb = null;
        try {
            //建立鏈接
            URL url = new URL(URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "application/json"); // 設置接收數據的格式  
            connection.setRequestProperty("Content-Type", "application/json"); // 設置發送數據的格式  

            connection.connect();

            //POST請求
            out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(param);
            out.flush();

            //讀取響應
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return sb.toString();

    }


    /**
     * 經過用戶名和密碼設置AUTH,得到權限 @
     */
    private static void setAuth() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user", USERNAME);

        params.put("password", PASSWORD);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "user.login");
        map.put("params", params);
        map.put("auth", null);
        map.put("id", 0);

        String response = sendPost(map);
        JSONObject json = JSON.parseObject(response);
        AUTH = json.getString("result");
    }


    private static String getAuth() {
        if (AUTH == null) {
            setAuth();
        }
        return AUTH;
    }


    /**
     * 得到主機hostid
     * 
     * @param host Zabbix中配置的主機hosts
     * @return 返回hostid @
     */
    private static String getHostIdByHostName(String host) {
        Map<String, Object> filter = new HashMap<String, Object>();
        filter.put("host", host);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "hostid");
        params.put("filter", filter);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "host.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");
        if (result.size() > 0) {
            JSONObject json = result.getJSONObject(0);
            String hostid = json.getString("hostid");
            return hostid;
        } else {
            return null;
        }

    }


    /**
     * 得到主機hostid
     * 
     * @param host Zabbix中配置的主機hosts
     * @return 返回hostid @
     */
    private static String getHostIdByIp(String ip) {
        Map<String, Object> filter = new HashMap<String, Object>();
        filter.put("ip", ip);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("filter", filter);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "host.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");
        if (result.size() > 0) {
            JSONObject json = result.getJSONObject(0);
            String hostId = json.getString("hostid");
            return hostId;
        } else {
            return null;
        }

    }


    /**
     * 得到某主機的某個監控項id
     * 
     * @param host 主機
     * @param item 監控項
     * @return 監控項itemid
     * @throws Exception
     */
    private static String getItemId(String hostId, String key) throws Exception {
        JSONArray result = getItemByHostAndKey(hostId, key);
        if (result.size() > 0) {
            JSONObject json = result.getJSONObject(0);
            if (json != null) {
                return json.getString("itemid");
            }
        }
        return null;

    }


    /**
     * 獲取某主機某監控項的value_type
     * 
     * @param host
     * @param key
     * @return
     * @throws Exception
     * @author xueyuan@meizu.com
     * @since 建立時間:2016年8月12日 上午10:38:10
     */
    private static int getValueType(String hostId, String key) throws Exception {
        JSONArray result = getItemByHostAndKey(hostId, key);
        if (result.size() > 0) {
            JSONObject json = result.getJSONObject(0);
            if (json != null) {
                return json.getIntValue("value_type");
            }
        }
        return 3;

    }


    /**
     * 獲取某主機某監控項在一段時間內的數據
     * 
     * @param itemId
     * @param valueType
     * @param from
     * @param to
     * @return
     * @author xueyuan@meizu.com
     * @since 建立時間:2016年8月18日 上午11:42:48
     */
    public static JSONArray getHistoryDataByItemId(String itemId, int valueType, long from, long to) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("history", valueType);
        params.put("itemids", itemId);
        params.put("sortfield", "clock");
        params.put("sortorder", "DESC");//時間降序
        params.put("time_from", from / 1000);
        params.put("time_till", to / 1000);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "history.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");

        return result;

    }


    /**
     * 獲取某主機某監控項最近的數據
     * 
     * @param hostId
     * @param key
     * @return @
     * @author xueyuan@meizu.com
     * @since 建立時間:2016年8月12日 上午10:31:49
     */
    public static JSONArray getItemByHostAndKey(String hostId, String key) {
        if (hostId == null) {
            return null;
        }
        Date start = new Date();

        Map<String, Object> search = new HashMap<String, Object>();
        search.put("key_", key);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("hostids", hostId);
        params.put("search", search);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "item.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);

        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");

        return result;
    }


    /**
     * 多個監控項的當前數據
     * 
     * @param itemIds
     * @return
     * @author xueyuan@meizu.com
     * @since 建立時間:2016年8月18日 下午4:33:14
     */
    public static JSONArray getDataByItems(List<String> itemIds) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("itemids", itemIds);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "item.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);
        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");

        return result;

    }


    /**
     * 多個監控項的歷史數據
     * 
     * @param itemIds
     * @param valueType
     * @param from
     * @param to
     * @return
     * @author xueyuan@meizu.com
     * @since 建立時間:2016年8月18日 下午5:12:53
     */
    public static JSONArray getHistoryDataByItems(List<String> itemIds, int valueType, long from,
                                                  long to) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("output", "extend");
        params.put("history", valueType);
        params.put("itemids", itemIds);
        params.put("sortfield", "clock");
        params.put("sortorder", "DESC");//時間降序
        params.put("time_from", from / 1000);
        params.put("time_till", to / 1000);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("jsonrpc", "2.0");
        map.put("method", "history.get");
        map.put("params", params);
        map.put("auth", getAuth());
        map.put("id", 0);
        String response = sendPost(map);
        JSONArray result = JSON.parseObject(response).getJSONArray("result");

        return result;

    }


    public static void main(String[] args) throws Exception {
        setAuth();
        long time_till = new Date().getTime();
        long time_from = time_till - 5 * 60000;
        String ip = "10.1.1.13";
        String key = "system.cpu.util[,idle]";
        String hostId = getHostIdByIp(ip);
        String itemId = getItemId(hostId, key);
        int valueType = getValueType(hostId, key);
        getHistoryDataByItemId(itemId, valueType, time_from, time_till);
    }

}
相關文章
相關標籤/搜索