基于Zabbix API文档二次开发与java接口封装

(继续贴一篇之前工作期间写的经验案例)

一、           案例背景

我负责开发过一个平台的监控报警模块,基于zabbix实现,需要对zabbix进行二次开发。

Zabbix官方提供了Rest API的文档,并推荐了第三方库,但这些库都是zabbix老版本(2.2,2.4/3.0)的库,多年未更新过,且变量/方法命名都不符合java的驼峰式规范。

所以开发中基于3.4的文档,自己封装了一套库。结合二次开发中对zabbix业务逻辑的理解与实践,梳理总结出该篇接口开发文档。

二、           基础知识

二次开发前,zabbix的业务术语和基本的业务逻辑需要了解清楚。

包括 模板、应用、监控项、触发器、事件、异常、动作等。

参考官方手册:

https://www.zabbix.com/documentation/3.4/zh/manual/definitions

重点说明下problem event:

触发器被触发时,会生成一个 problem event 记录, 当问题恢复正常时,会生成一个recovery event记录,两个event的时间差,即为事件持续时间。所有的event都存在于同一张表。对应接口25)报警时间查询

problem存在于一张单独的表,每一条记录对应了两个事件,即problem event 和 recovery event。对应接口24)报警数据查询。

这张表zabbix后台会定期清理,problem事件恢复30分钟后,会被从表中删除。

所以如果要查当前的报警事件,去problem里查;如果要查事件的历史记录,到event里查,并且要对problem event 与 recovery event 进行匹配计算,一个开始对应一个结束,才算一条历史报警记录。

三、           接口封装与使用详解(代码见第五节的链接)

1)        登陆

zabbix登陆token的保留时间非常长,一次登陆后,基本可数周内不用重新登陆

/**
 * @return
登陆zabbix后台true/false
 */
Boolean login();

2)        在线状态

/**
 * 判断
zabbix是否已 在线(可用,并已登陆),没有的话 尝试登陆
 
* @return 在线/重连成功,返回1;自系统启动首次登陆成功返回2; 不在线,且重连失败,返回0
 */
Integer OnLine();

3)        请求zabbix后台,并返回结果

作为最基础的访问zabbix后台的接口,其他接口都是基于它实现的。

/**
 * 封装了
RestTemplate 请求 与 zabbix 自动重连功能
 
* @param zabbixMethod  请求方法
 
* @param zabbixParams  请求参数
 
* @return result Object
 */
ZabbixResponse requestZabbixForObject(String zabbixMethod, Object zabbixParams);

      

4)        模板-xml导入

对于用户来说,让他们配置一个相当复杂的“模板-应用集-监控项-触发器”是很有难度的,这些应该是开发人员做的事,用户只管会用就可以。所以我们把这些配置梳理好后,以xml文件的形式发给用户,用户只需上传模板,即可完成整个复杂的创建过程。

/**
 * 导入
xml模板
 
* @param sourceXml
 
* @return
 
*/
Boolean  importConfiguration(Document sourceXml);

5)        模板-Id 查询

/**
 * 根据模板
host名称(全英文的那个名字 在zabbix后台唯一标识模板) 查询 模板在zabbix后台的id
 * @param
tempLateHostName
 
* @return
 
*/
String getTemplateIdByHostName(String tempLateHostName);

6)        主机群组(host group)-Id查询

- 主机的逻辑组;它包含主机和模板。创建主机/模板时,必须指定其所属的主机群组,所以需要事先创建(导入模板xml时即会创建)。一个主机组里的主机和模板之间并没有任何直接的关联。通常在给不同用户组的主机分配权限时候使用主机组。

/**
 * 根据
group名称,查询group在zabbix后台的id
 * @param
groupName
 
* @return
 
*/
String getGroupIdByName(String groupName);

7)        主机-创建

/**
 * 创建主机
 
* @param hostIps 主机ip列表
 
* @param groupId 所属分组id(zabbix)
 * @return
hostIps 的顺序 返回 对应的hostId
 */
List<String> createHost(List<String> hostIps,String groupId);

8)        主机-查询全部

返回的Map以ip地址为key,hostId为value, 方便对返回值快速的搜索查询

/**
 * 查询全部主机
 
* @return key 主机host(Ip), value 主机hostId
 */
Map<String,String> getHostAll();

9)        模板-关联主机(批量)

关联成功后,会生成实际的监控项和触发器

/**
 * 批量将机器
hostIds(zabbix后台的hostId)(列表) 与 模板关联
 
* @param templateId
 
* @param hostIds
 
* @return
 
*/
Boolean templateMassAdd(String templateId,List<String> hostIds);

10)    模板-取消关联主机(批量)

/**
 * 主机
(批量) 取消 模板链接 并清理-(会删掉主机监控项)
 
* @param hostIds  需要取消模板关联的主机id列表
 
* @param templateId 需要取消关联的 模板id
 * @return
 
*/
Boolean hostMassRemoveTemplate(List<String> hostIds,String templateId);

11)    模板-查询关联的所有主机

这个接口其实更为通用,可以在params 中指定查询条件,查询返回所有符合条件的主机,此处要查询模板关联的机器,只需在params中指定templateids 即可,参数格式 参考官方文档:

https://www.zabbix.com/documentation/3.4/manual/api/reference/host/get

示例

(先声明List<String> templateIds)

zabbixService.getHosts(new HashMap(){{

    put("templateids",templateIds);

}});

/**
 * 查询 模板关联的所有机器
 
* @param params
 默认参数
:
{
"output": ["hostid","host"]
}
 * @return
 
*/
List<ZabbixHost> getHosts(Map params);
 

12)    模板-删除(批量)

/**
 * 批量删除模板,会清理掉模板当前所关联主机的所有监控项(已与模板解除关联的主机,其监控项不会被清理
)
 * @param
templateIds
 
* @return
 
*/
Boolean templateMassDelete(List<String> templateIds);

13)    主机-删除(批量)

/**
 * 批量删除主机
 
* @param hostIds 主机列表
 
* @return
 
*/
Boolean hostDelete(List<String> hostIds);

14)    监控项-查询1

关联查询应用,触发器,主机

/**
 * 查询主机关联的所有的监控项
 
* @param params {@link <a href = "https://www.zabbix.com/documentation/3.4/manual/api/reference/item/get">item.get</a>}
选填参数:
{
   "hostids":["10205"],
   "itemids":["27692","27707"],
   "triggerids":["12345"]
}
默认参数:
{
"output":["itemid","name","key_","delay","history","status","flags","units","lastvalue","value_type"],
"selectApplications": ["applicationid","name","hostid","templateids"],
"selectTriggers":["triggerid","templateid","description","expression","comments","status","priority","value"],
"selectHosts":["hostid","host"]
}
 * @return Item列表 或 空
Array
 */
List<ZabbixItem> getItems(Map params);

15)    监控项-查询2

关联查询应用,主机;

/**
 * 查询监控项数据,和监控项关联的
host,无用的字段不查
 
* @param params
 默认参数
{
"output":["itemid","name","lastclock","lastvalue","lastvalue","prevvalue","status","units"],
"selectApplications": ["applicationid","name","hostid","templateids"],
"selectHosts":["hostid","host"]
}
 * @return Item列表
key-zabbixItemId 或 空Map
 */
Map<String,ZabbixItem> getItemData(Map params);

16)    应用-查询-根据id

每个application都有个parentId和hostid, 根据parentId 向上回溯查询application,当其parentId为null时,对应的hostId才指向Template.

/**
 * 根据
application Id 查询 application 详情
 
* @param Id
 
* @return application 或 null
 */
ZabbixApplication getApplicationById(String Id);

17)    应用-查询-根据id(批量)

/**
 * 批量查询,根据
application Ids 查询 applications 详情
 
* @param ids
 
* @return key 为applicationId
 */
Map<String,ZabbixApplication> getApplicationsByIds(List<String> ids);

18)    应用-查询-根据模板id

/**
 * 批量查询,根据
application Ids 查询 applications 详情
 
* @param ids
 
* @return key 为applicationId
 */
Map<String,ZabbixApplication> getApplicationsByIds(List<String> ids);

19)    触发器-查询

/**
 * 获取所有的触发器
 
* doc:
 * @see
<a href = "https://www.zabbix.com/documentation/3.4/manual/api/reference/trigger/get">trigger.get</a>
 
* @param params
 
* 默认参数:
 {
    "output":["triggerid","description","priority","value","expression","status","comments"],
    "selectItems":["itemid","lastvalue","units"],
    "selectHosts":["host","hostid"]
 }
 * @return map  key = {@link ZabbixTrigger#triggerId} , value = {@link ZabbixTrigger}; 或空
Map
 */
Map<String,ZabbixTrigger> getTriggers(Map params);

20)    监控项-修改

/**
 * 根据
itemId 修改 item
 * @param
items 字段itemId 必填,只支持修改delay,history,status
 * @return
 
*/
Boolean itemsUpdate(List<ZabbixItem> items);

21)    触发器-修改

/**
 * 根据
triggerId 修改 trigger
 * @param
triggers 字段triggerId 必填,只支持修改 status,comments,expression,
 *                 注意
:通过模板关联生成的trigger 只能修改status,comments,其他是改不了的,会失败
 
* @return  true/false
 */
Boolean triggersUpdate(List<ZabbixTrigger> triggers);

22)    应用-监控项-组织结构查询-根据主机id

/**
 * 根据
hostIds 查询关联的application-Item 组织(组织结点 主要包含Id 和 name)
 
* @param hostIds
 
* @return
 
*/
List<ZabbixApplication> getApplicationAndItemOrgByHostId(List<String> hostIds);

23)    最新监控数据-查询

若要查询模板关联的监控项,先查模板关联的机器,然后调用该接口进行查询。

/**
 * 查询 监控数据,以主机
ID 和 applicationName 作为过滤条件
 
* 会过滤掉 已被禁用的监控项数据
 
* @param hostIds
 
* @param appNames 为空 时,查询全部数据
 
* @return application-item
 
*/
List<ZabbixApplication> getLatestItemData(List<String> hostIds,List<String> appNames);

24)    报警数据-查询

/**
 * 查询报警数据
--来自触发器
 
* @param params 查询参数
 
* 默认参数:
 
{
    "output": "extend",
    "sortfield": ["eventid"],
    "sortorder": "DESC",
    "recent":"true",
    "selectAcknowledges": "extend"
 }
 * @see
<a href="https://www.zabbix.com/documentation/3.4/manual/api/reference/problem/get">problem.get</a>
 
* ctrl + 单击 查看url链接
 
* @return {@link ZabbixProblem}
 */
List<ZabbixProblem> getProblems(Map params);

25)    报警事件查询

/**
 * 查询报警事件
--来自触发器
 
* @param params
 
* 默认参数:
 
{  "output": "extend",
    "sortfield": ["clock", "eventid"],
    "sortorder": "DESC",
    "select_acknowledges":"extend",
    "selectRelatedObject":["triggerid","description","priority","value"],
    "selectHosts":["hostid","host"]
 }
 * @see
<a href="https://www.zabbix.com/documentation/3.4/manual/api/reference/event/get">event.get</a>
 
* @return {@link ZabbixProblem}
 */
List<ZabbixProblem> getEvents(Map params);

26)    关闭触发器

忽略并关闭报警事件

/**
 *
关闭触发器
 
* @param events  需关闭的event 列表
 
* 默认参数:
{
    "message": "
忽略",
    "action": 1
}
 * @return
 
*/
Boolean acknowledgeEvents(List<String> events);

27)    历史数据-查询

查询指定监控项的历史数据

参数history 表示返回值类型,摘录一段官方文档解释:

History object types to return. 

Possible values: 
0 - numeric float; 
1 - character; 
2 - log; 
3 - numeric unsigned; 
4 - text. 

Default: 3.

就是说实际的数据类型 和参数 history的类型 必须一致,否则会导致查不到数据。

所以查之前,需要先查询确定监控项的数据类型valueType.

/**
 *
查监控项的历史数据
 
* @param params  itemids  string/array 监控项id 必填  "history":3, 必填-不填或者类型不对将查不到数据
 
* @see <a href="https://www.zabbix.com/documentation/3.4/manual/api/reference/history/get">history.get</a>
必填参数:
{
"itemids": ["27702"]
}
默认参数:
{
"sortfield":"clock",
"sortorder":"DESC"
}

 * @return
 
*/
List<ZabbixHistory> getHistory(Map params);

28)    图表-查询配置

如果要查图表数据,需要先查图表配置,然后对图表配置中的监控项id, 通过getHistory接口查询监控项的历史数据。

/**
 * 查询图表配置信息
 
* @param params
 默认参数
:
params.put("output",new ArrayList(){{
add("graphid");
add("name");
add("graphtype");
}});

params.put("selectGraphItems",new ArrayList(){{
add("gitemid");
add("itemid");
add("color");
}});

params.put("selectItems",new ArrayList(){{
add("itemid");
add("name");
}});
 * @return
 
*/
List<GraphConfig> getGraphConfig(Map params);

29)    图表-创建

/**
 * 创建监控图表
 
* @param graphConfig
 
* @return
 
*/
GraphConfig createGraph(GraphConfig graphConfig) throws Exception;

30)    图表-修改

/**
 * 更新监控图表
 
* @param graphConfig
 
* @return
 
*/
GraphConfig updateGraph(GraphConfig graphConfig) throws Exception;

31)    图表-删除

/**
 * 删除图表
 
* @param params  图表id
 * @return
 
* @throws Exception
 */
Boolean deleteGraph(List params) throws Exception;

四、           监控数据单位转换

从zabbix 后台 查询到的监控数据,都是最小单位,如时间的单位是 秒s,存储的单位是B,流量的单位是B/s.

所以需要自适应进行转换,转成KB/s 或者 MB/s等。

1)转成最合适,无溢出的单位

/**
 * @param
value 原始数据
 
* @param units 原始单位
 
* @return 转成最合适 无溢出的单位
 
*/
public static UnitsFormatResult transformValueByUnits(String value,String units)

2) 转成指定单位的数据

绘制图表时,每个数据需要单位一致,才有可比性,才能进行正确的绘制,因此会用到此方法。

/**
 *
 * @param
value 原始数据
 
* @param units 原始单元
 
* @param targetUnits 目标单位
 
* @return
 
*/
public static UnitsFormatResult transformValueToTargetUnits(String value,String units,String targetUnits)

五、           请下载附件源码

https://files.cnblogs.com/files/wangzhen-fly/zabbix3.4api%E5%B0%81%E8%A3%85-src.zip

原文地址:https://www.cnblogs.com/wangzhen-fly/p/11081923.html