Authored by jack

zabbix 读数据库重写

Showing 29 changed files with 547 additions and 787 deletions
... ... @@ -7,7 +7,7 @@
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- dataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<bean id="cmdbDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>com.mysql.jdbc.Driver</value>
</property>
... ... @@ -28,8 +28,8 @@
<!-- dataSource -->
<!--mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<bean id="cmdbSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="cmdbDataSource"/>
<property name="configLocation" value="classpath:META-INF/mybatis/mybatis-config.xml"/>
<property name="typeAliasesPackage" value="com.model"/>
<property name="transactionFactory">
... ... @@ -38,21 +38,23 @@
</bean>
<!--配置Mybatis模版 -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
<bean id="cmdbSqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="cmdbSqlSessionFactory"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<bean id="cmdbMapperScan" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="cmdbSqlSessionFactory"></property>
<property name="sqlSessionTemplateBeanName" value="cmdbSqlSessionTemplate"></property>
<property name="basePackage" value="com.monitor.mysql.mapper"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
<bean id="cmdbTxManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="cmdbDataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
<bean id="cmdbTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="cmdbDataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<tx:annotation-driven transaction-manager="cmdbTxManager"/>
</beans>
... ...
... ... @@ -6,6 +6,7 @@
<result column="module_name" property="moduleName" jdbcType="VARCHAR" />
<result column="module_level" property="moduleLevel" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, module_name, module_level
</sql>
... ...
zabbix_server=http://10.66.0.191:8080/api_jsonrpc.php
zabbix.jdbc.url=jdbc:mysql://10.66.0.191:3306/zabbix
zabbix_user=chao.xu
zabbix.jdbc.user=zabbix_ops
zabbix_pwd=Yoho123456
zabbix.jdbc.password=yoho@zabbix
zabbix_type=gateway
zabbix_key=system.cpu,vm.memory,net.if
\ No newline at end of file
zabbix_type=gateway
\ No newline at end of file
... ...
zabbix_server=http://192.168.102.76/zabbix/api_jsonrpc.php
zabbix_user=admin
zabbix.jdbc.url=jdbc:mysql://192.168.102.76:3306/zabbix
zabbix_pwd=zabbix
zabbix.jdbc.user=root
zabbix_type=jack
zabbix.jdbc.password=123456
zabbix_key=system.cpu,vm.memory,net.if
zabbix_type=jack
... ...
package com.monitor.zabbix.comp;
import com.monitor.zabbix.model.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* Created by yoho on 2016/10/9.
*/
@Component
public class ZabbixHttpComp {
public static final Logger DEBUG = LoggerFactory.getLogger(ZabbixHttpComp.class);
@Resource(name = "restTemplate")
RestTemplate restTemplate;
@Value("${zabbix_server}")
private String zabbixServer;
@Value("${zabbix_user}")
private String zabbixUser;
@Value("${zabbix_pwd}")
private String zabbixPwd;
private String auth = StringUtils.EMPTY;
private void login() {
LoginRequest request = LoginRequest.buildRequest(this.zabbixUser, this.zabbixPwd);
LoginResponse response = restTemplate.postForObject(zabbixServer, request, LoginResponse.class);
if (null != response || StringUtils.isNotBlank(response.getResult())) {
this.auth = response.getResult();
} else {
DEBUG.error("Failed to login zabbix server...error {}", response);
}
}
public String sendRequest(ZabbixRequest request) {
if (StringUtils.isBlank(this.auth)) {
login();
}
request.setAuth(this.auth);
String obj = restTemplate.postForObject(zabbixServer, request, String.class);
return obj;
}
/* public static void main(String[] args) throws IOException {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
RestTemplate template = new RestTemplate(factory);
LoginRequest request = LoginRequest.buildRequest("admin", "zabbix");
*//* HttpHeaders headers = new HttpHeaders();
headers.setContentType(new MediaType("application", "json-rpc", DEFAULT_CHARSET));*//*
LoginResponse response = template.postForObject("http://192.168.102.76/zabbix/api_jsonrpc.php", request, LoginResponse.class);
System.out.println(response);
List<String> hostIps = new ArrayList<>();
hostIps.add("192.168.102.76");
HostInterfaceRequest request1 = HostInterfaceRequest.buildRequest(hostIps);
request1.setAuth(response.getResult());
HostInterfaceResponse response1 = template.postForObject("http://192.168.102.76/zabbix/api_jsonrpc.php", request1, HostInterfaceResponse.class);
System.out.println(response1);
List<String> items = new ArrayList<>();
items.add("23716");
items.add("23717");
items.add("23718");
long start=System.currentTimeMillis()-120*60*1000;
int start1=(int)(start/1000);
System.out.println(start1);
long end=System.currentTimeMillis()-110*60*1000;
int end1=(int)(end/1000);
System.out.println(end1);
HistoryRequest request2 = HistoryRequest.buildRequest("10105", items, String.valueOf(start1), String.valueOf(end1));
request2.setAuth(response.getResult());
HistoryResponse response2 = template.postForObject("http://192.168.102.76/zabbix/api_jsonrpc.php", request2, HistoryResponse.class);
System.out.println(response2);
ItemRequest request3 = ItemRequest.buildRequest(10105, "system.cpu");
request3.setAuth(response.getResult());
request3.setId(response.getId());
ItemResponse itemId = template.postForObject("http://192.168.102.76/zabbix/api_jsonrpc.php", request3, ItemResponse.class);
System.out.println(itemId);
*//* *//**//** 获取itemId **//**//*
JSONObject json = new JSONObject();
for(SystemCpuEnum cpu : SystemCpuEnum.values()){
System.out.println(cpu.key());
ItemRequest request3 = ItemRequest.buildRequest(10105, cpu.key(),);
request3.setAuth(response.getResult());
request3.setId(response.getId());
String itemId = template.postForObject("http://192.168.102.76/zabbix/api_jsonrpc.php", request3, String.class);
//取出返回的json串中的itemid
JSONObject jsonObject=JSONObject.parseObject(itemId);
String result=jsonObject.getString("result").replace("[", "").replace("]", "");
JSONObject jsonObject0=JSONArray.parseObject(result);
String itemid=jsonObject0.getString("itemid");
//重新组成json
json.put(itemid,cpu.key());
}
System.out.println(json);*//*
}*/
}
... ... @@ -2,7 +2,7 @@ package com.monitor.zabbix.constants;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.monitor.zabbix.model.ItemResponse;
import com.monitor.zabbix.model.ZabbixItemInfo;
import java.util.HashMap;
import java.util.List;
... ... @@ -27,9 +27,9 @@ public interface Constants {
ObjectMapper OBJECT_MAPPER = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Map<String, String> HOSTIP_TO_IDS = new HashMap<>();
Map<String, Integer> HOSTIP_TO_IDS = new HashMap<>();
Map<String, String> HOSTID_TO_IPS = new HashMap<>();
Map<Integer, String> HOSTID_TO_IPS = new HashMap<>();
Map<String, List<ItemResponse.Item>> HOSTID_TO_ITEMS = new HashMap<>();
Map<Integer, List<ZabbixItemInfo>> HOSTID_TO_ITEMS = new HashMap<>();
}
... ...
... ... @@ -4,14 +4,14 @@ import com.monitor.zabbix.constants.Constants;
import com.monitor.zabbix.enums.NetIfEnum;
import com.monitor.zabbix.enums.SystemCpuEnum;
import com.monitor.zabbix.enums.VmMemoryEnum;
import com.monitor.zabbix.model.HistoryResponse;
import com.monitor.zabbix.model.ItemResponse;
import com.monitor.zabbix.model.ZabbixDHistoryInfo;
import com.monitor.zabbix.model.ZabbixItemInfo;
import com.monitor.zabbix.model.ZabbixUHistoryInfo;
import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
... ... @@ -28,7 +28,7 @@ public class PointBuilder {
static Map<String, String> totalMemMap = new HashMap<>();
public static Point buildPoint(String type, String ip, List<ItemResponse.Item> items, List<HistoryResponse.HistoryItem> historyItems) {
public static Point buildPoint(String ip, List<ZabbixItemInfo> items, List<Object> historyItems) {
Random random = new Random();
String net = "aws";
... ... @@ -38,12 +38,11 @@ public class PointBuilder {
}
Point point = Point.measurement(Constants.VM_MEASUREMENTS)
.tag("type", type)
.tag("ip", ip)
.tag("net", net)
.addField(SystemCpuEnum.CPU_LOAD_AVG1.name(), findValueByKey(SystemCpuEnum.CPU_LOAD_AVG1.key(), items, historyItems))
/*.addField(SystemCpuEnum.CPU_LOAD_AVG1.name(), findValueByKey(SystemCpuEnum.CPU_LOAD_AVG1.key(), items, historyItems))
.addField(SystemCpuEnum.CPU_LOAD_AVG5.name(), findValueByKey(SystemCpuEnum.CPU_LOAD_AVG5.key(), items, historyItems))
.addField(SystemCpuEnum.CPU_LOAD_AVG15.name(), findValueByKey(SystemCpuEnum.CPU_LOAD_AVG15.key(), items, historyItems))
.addField(SystemCpuEnum.CPU_LOAD_AVG15.name(), findValueByKey(SystemCpuEnum.CPU_LOAD_AVG15.key(), items, historyItems))*/
.addField(SystemCpuEnum.CPU_UTIL_IDLE.name(), findValueByKey(SystemCpuEnum.CPU_UTIL_IDLE.key(), items, historyItems))
.addField(SystemCpuEnum.CPU_UTIL_INTERRUPT.name(), findValueByKey(SystemCpuEnum.CPU_UTIL_INTERRUPT.key(), items, historyItems))
.addField(SystemCpuEnum.CPU_UTIL_IOWAIT.name(), findValueByKey(SystemCpuEnum.CPU_UTIL_IOWAIT.key(), items, historyItems))
... ... @@ -61,54 +60,54 @@ public class PointBuilder {
return point;
}
private static Double findValueByKey(String key, List<ItemResponse.Item> items, List<HistoryResponse.HistoryItem> historyItems) {
private static Double findValueByKey(String key, List<ZabbixItemInfo> items, List<Object> historyItems) {
String itemId = StringUtils.EMPTY;
int itemId = 0;
String itemValue = "0";
try {
for (ItemResponse.Item item : items) {
for (ZabbixItemInfo item : items) {
if (StringUtils.equals(key, item.getKey_())) {
if (StringUtils.equals(key, item.getKeyName())) {
itemId = item.getItemid();
itemId = item.getItemId();
break;
}
}
if (StringUtils.isNotBlank(itemId)) {
if (0 != itemId) {
for (HistoryResponse.HistoryItem historyItem : historyItems) {
for (Object historyItem : historyItems) {
if (StringUtils.equals(itemId, historyItem.getItemid())) {
if (historyItem instanceof ZabbixDHistoryInfo) {
itemValue = historyItem.getValue();
ZabbixDHistoryInfo historyInfo = (ZabbixDHistoryInfo) historyItem;
//如果取到总内存,存在内存中
if (StringUtils.equals(VmMemoryEnum.MEMORY_SIZE_TOTAL.key(), key)) {
totalMemMap.put(itemId, itemValue);
if (itemId == historyInfo.getItemId()) {
itemValue = String.valueOf(historyInfo.getValue());
break;
}
break;
} else if (historyItem instanceof ZabbixUHistoryInfo) {
ZabbixUHistoryInfo historyInfo = (ZabbixUHistoryInfo) historyItem;
if (itemId == historyInfo.getItemId()) {
itemValue = String.valueOf(historyInfo.getValue());
break;
}
} else {
continue;
}
}
}
//如果本次未取到总内存,从内存中取
if (StringUtils.isBlank(itemValue) && totalMemMap.containsKey(itemId)) {
itemValue = totalMemMap.get(itemId);
}
} catch (Exception e) {
DEBUG.error("Failed to find value by key {},error {}", key, e);
}
DEBUG.info("Find zabbix item key {} id {} value {}", key, itemId, itemValue);
Double value = Double.parseDouble(itemValue);
return format(key, value);
... ...
package com.monitor.zabbix.mapper;
import com.monitor.zabbix.model.ZabbixDHistoryInfo;
import com.monitor.zabbix.model.ZabbixUHistoryInfo;
/**
* Created by yoho on 2016/10/25.
*/
public interface ZabbixHistoryMapper {
ZabbixDHistoryInfo queryDHistoryInfo(int itemId);
ZabbixUHistoryInfo queryUHistoryInfo(int itemId);
}
... ...
package com.monitor.zabbix.mapper;
import com.monitor.zabbix.model.ZabbixHostInfo;
import java.util.List;
/**
* Created by yoho on 2016/10/25.
*/
public interface ZabbixHostMapper {
List<ZabbixHostInfo> queryHostInfo(List<String> ipList);
}
... ...
package com.monitor.zabbix.mapper;
import com.monitor.zabbix.model.ZabbixItemInfo;
import java.util.List;
/**
* Created by yoho on 2016/10/25.
*/
public interface ZabbixItemMapper {
List<ZabbixItemInfo> queryItemInfo(List<Integer> idList);
}
... ...
package com.monitor.zabbix.model;
import lombok.Data;
import java.util.List;
/**
* Created by yoho on 2016/10/9.
*/
public class HistoryRequest extends ZabbixRequest {
public static HistoryRequest buildRequest(String hostId, List<String> itemIds, int flag) {
HistoryRequest request = new HistoryRequest();
request.setMethod("history.get");
request.setParams(new Params(hostId, itemIds, flag));
request.setId((int) System.currentTimeMillis());
return request;
}
@Data
public static class Params {
String hostids;
String output = "extend";
Integer history = 3;
List<String> itemids;
String sortfield = "clock";
String sortorder = "DESC";
Integer limit = 1;
public Params(String hostids, List<String> itemids, int flag) {
this.hostids = hostids;
this.itemids = itemids;
this.limit = itemids.size();
this.history = flag;
}
}
}
package com.monitor.zabbix.model;
import lombok.Data;
import java.util.List;
/**
* Created by yoho on 2016/10/10.
*/
@Data
public class HistoryResponse extends ZabbixResponse {
List<HistoryItem> result;
@Data
public static class HistoryItem {
String itemid;
String clock;
String value;
String ns;
}
}
package com.monitor.zabbix.model;
import lombok.Data;
import java.util.List;
/**
* Created by yoho on 2016/10/9.
*/
public class HostInterfaceRequest extends ZabbixRequest {
public static HostInterfaceRequest buildRequest(List<String> hostIps) {
HostInterfaceRequest request = new HostInterfaceRequest();
request.setMethod("hostinterface.get");
request.setId((int) System.currentTimeMillis());
request.setParams(new Params(new Filter(hostIps)));
return request;
}
@Data
public static class Params {
Filter filter;
String output[] = {"hostid", "ip"};
public Params(Filter filter) {
this.filter = filter;
}
}
@Data
public static class Filter {
List<String> ip;
public Filter(List<String> ips) {
this.ip = ips;
}
}
}
package com.monitor.zabbix.model;
import lombok.Data;
import java.util.List;
/**
* Created by yoho on 2016/10/10.
*/
@Data
public class HostInterfaceResponse extends ZabbixResponse {
List<HostInterface> result;
@Data
public static class HostInterface {
String hostid;
String ip;
}
}
package com.monitor.zabbix.model;
import lombok.Data;
public class ItemRequest extends ZabbixRequest {
public static ItemRequest buildRequest(String hostId) {
ItemRequest request = new ItemRequest();
request.setAuth(null);
request.setId(00);
request.setMethod("item.get");
request.setParams(new Params(hostId));
return request;
}
@Data
public static class Params {
private String hostids;
private String[] output = {"hostid","itemid","key_"};
private String sortfield = "name";
public Params(String hostId) {
this.hostids = hostId;
}
}
}
package com.monitor.zabbix.model;
import lombok.Data;
import java.util.List;
/**
* Created by yoho on 2016/10/11.
*/
@Data
public class ItemResponse extends ZabbixResponse {
List<Item> result;
@Data
public static class Item {
String itemid;
String key_;
}
}
package com.monitor.zabbix.model;
import lombok.Data;
/**
* Created by yoho on 2016/10/9.
*/
@Data
public class LoginRequest extends ZabbixRequest {
public static LoginRequest buildRequest(String user, String pwd) {
LoginRequest request = new LoginRequest();
request.setParams(new Params(user, pwd));
request.setId((int)System.currentTimeMillis());
request.setAuth(null);
request.setMethod("user.login");
return request;
}
@Data
public static class Params {
String user;
String password;
public Params(String user, String pwd) {
this.user = user;
this.password = pwd;
}
}
}
... ... @@ -3,9 +3,11 @@ package com.monitor.zabbix.model;
import lombok.Data;
/**
* Created by yoho on 2016/10/9.
* Created by yoho on 2016/10/25.
*/
@Data
public class LoginResponse extends ZabbixResponse{
private String result;
public class ZabbixDHistoryInfo {
private int itemId;
private double value;
}
... ...
... ... @@ -3,19 +3,14 @@ package com.monitor.zabbix.model;
import lombok.Data;
/**
* Created by yoho on 2016/10/9.
* Created by yoho on 2016/10/25.
*/
@Data
public class ZabbixRequest {
public class ZabbixHostInfo {
private int interfaceId;
private String jsonrpc = "2.0";
private int hostId;
private String method;
private Integer id;
private String auth;
private Object params;
private String ip;
}
... ...
package com.monitor.zabbix.model;
import lombok.Data;
/**
* Created by yoho on 2016/10/25.
*/
@Data
public class ZabbixItemInfo {
private int itemId;
private int hostId;
private String keyName;
private int valueType;
}
... ...
... ... @@ -3,12 +3,11 @@ package com.monitor.zabbix.model;
import lombok.Data;
/**
* Created by yoho on 2016/10/11.
* Created by yoho on 2016/10/25.
*/
@Data
public class ZabbixResponse {
public class ZabbixUHistoryInfo {
private int itemId;
private Integer id;
private String jsonrpc;
private long value;
}
... ...
package com.monitor.zabbix.service;
import com.monitor.common.util.SpringContextUtils;
import com.monitor.zabbix.comp.InfluxdbComp;
import com.monitor.zabbix.constants.Constants;
import com.monitor.zabbix.impl.PointBuilder;
import com.monitor.zabbix.mapper.ZabbixHistoryMapper;
import com.monitor.zabbix.mapper.ZabbixHostMapper;
import com.monitor.zabbix.mapper.ZabbixItemMapper;
import com.monitor.zabbix.model.ZabbixDHistoryInfo;
import com.monitor.zabbix.model.ZabbixHostInfo;
import com.monitor.zabbix.model.ZabbixItemInfo;
import com.monitor.zabbix.model.ZabbixUHistoryInfo;
import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Created by yoho on 2016/10/25.
*/
public class ZabbixIpTask implements Callable {
public static final Logger DEBUG = LoggerFactory.getLogger(ZabbixIpTask.class);
private List<String> taskIpList;
private BatchPoints batchPoints;
public ZabbixIpTask(List<String> ipList) {
taskIpList = new ArrayList<String>(Arrays.asList(new String[ipList.size()]));
Collections.copy(taskIpList, ipList);
batchPoints = BatchPoints.database(Constants.INFLUX_DB).retentionPolicy(Constants.INFLUX_POLICY).build();
}
@Override
public Object call() {
DEBUG.info("Start to execute zabbix task {}", taskIpList);
try {
queryIpToId();
queryIdToItem();
queryHistory();
writeInflux();
} catch (Exception e) {
DEBUG.error("Failed to execute zabbix task {}, error {}", taskIpList, e);
}
DEBUG.info("End to execute zabbix task {}", taskIpList);
return null;
}
/**
* 根据ip查询id,转存内存map中,供后续使用
*/
private void queryIpToId() {
ZabbixHostMapper hostMapper = SpringContextUtils.getBeanByClass(com.monitor.zabbix.mapper.ZabbixHostMapper.class);
List<String> ipList = new ArrayList<>();
//如果前期查过,则过滤
for (String ip : taskIpList) {
if (Constants.HOSTIP_TO_IDS.containsKey(ip)) {
continue;
}
ipList.add(ip);
}
if (ipList.isEmpty()) {
DEBUG.info("Not found new host in {}, no need to query id....", taskIpList);
return;
}
List<ZabbixHostInfo> hostInfoList = hostMapper.queryHostInfo(ipList);
DEBUG.info("Found host ip to id info {}", hostInfoList);
//after query,save into map
for (ZabbixHostInfo hostInfo : hostInfoList) {
if (null == hostInfo) {
continue;
}
Constants.HOSTIP_TO_IDS.put(hostInfo.getIp(), hostInfo.getHostId());
Constants.HOSTID_TO_IPS.put(hostInfo.getHostId(), hostInfo.getIp());
}
}
/**
* 根据id查询item,转存内存map中,供后续使用
*/
private void queryIdToItem() {
ZabbixItemMapper itemMapper = SpringContextUtils.getBeanByClass(com.monitor.zabbix.mapper.ZabbixItemMapper.class);
List<Integer> idList = new ArrayList<>();
//如果前期查过,则过滤
for (String ip : taskIpList) {
Integer id = Constants.HOSTIP_TO_IDS.get(ip);
if (Constants.HOSTID_TO_ITEMS.containsKey(id)) {
continue;
}
idList.add(id);
}
if (idList.isEmpty()) {
DEBUG.info("Not found new host in {}, no need to query item....", taskIpList);
return;
}
List<ZabbixItemInfo> itemInfoList = itemMapper.queryItemInfo(idList);
DEBUG.info("Found id to items info {}", itemInfoList);
for (ZabbixItemInfo itemInfo : itemInfoList) {
List<ZabbixItemInfo> itemInfos = Constants.HOSTID_TO_ITEMS.get(itemInfo.getHostId());
if (null == itemInfos) {
itemInfos = new ArrayList<>();
}
itemInfos.add(itemInfo);
Constants.HOSTID_TO_ITEMS.put(itemInfo.getHostId(), itemInfos);
}
}
/**
* 根据ip查询 item的历史记录
*/
private void queryHistory() {
ZabbixHistoryMapper historyMapper = SpringContextUtils.getBeanByClass(com.monitor.zabbix.mapper.ZabbixHistoryMapper.class);
for (String taskIp : taskIpList) {
Integer taskId = Constants.HOSTIP_TO_IDS.get(taskIp);
if (null == taskId) {
continue;
}
List<ZabbixItemInfo> itemInfos = Constants.HOSTID_TO_ITEMS.get(taskId);
if (null == itemInfos) {
continue;
}
List<Object> historyList = new ArrayList<>();
for (ZabbixItemInfo itemInfo : itemInfos) {
if (null == itemInfo) {
continue;
}
//system.cpu在另外一个库中,调用另一个接口
if (StringUtils.startsWith(itemInfo.getKeyName(), "system.cpu")) {
ZabbixDHistoryInfo dHistoryInfo = historyMapper.queryDHistoryInfo(itemInfo.getItemId());
if (null != dHistoryInfo) {
historyList.add(dHistoryInfo);
}
} else {
ZabbixUHistoryInfo uHistoryInfo = historyMapper.queryUHistoryInfo(itemInfo.getItemId());
if (null != uHistoryInfo) {
historyList.add(uHistoryInfo);
}
}
}
//build point
Point point = PointBuilder.buildPoint(taskIp, itemInfos, historyList);
batchPoints.point(point);
}
}
private void writeInflux() {
DEBUG.debug("Start to write batch points {} into influxdb...", this.batchPoints);
InfluxdbComp influxDBClient = (InfluxdbComp) SpringContextUtils.getBeanByClass(InfluxdbComp.class);
if (null != this.batchPoints.getPoints()) {
influxDBClient.doWritePoints(this.batchPoints);
}
}
}
... ...
package com.monitor.zabbix.service;
import com.model.HostInfo;
import com.monitor.cmdb.service.impl.HostInfoServiceImpl;
import com.monitor.common.util.SpringContextUtils;
import com.monitor.zabbix.comp.InfluxdbComp;
import com.monitor.zabbix.comp.ZabbixHttpComp;
import com.monitor.zabbix.constants.Constants;
import com.monitor.zabbix.impl.PointBuilder;
import com.monitor.zabbix.model.*;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import static com.monitor.zabbix.constants.Constants.HOSTID_TO_IPS;
import static com.monitor.zabbix.constants.Constants.HOSTID_TO_ITEMS;
import static com.monitor.zabbix.constants.Constants.HOSTIP_TO_IDS;
/**
* Created by yoho on 2016/10/11.
*/
@Data
public class ZabbixTask implements Callable {
public static final Logger DEBUG = LoggerFactory.getLogger(ZabbixTask.class);
String type;
String[] keys;
ZabbixHttpComp zabbixHttpComp;
public ZabbixTask(String type, String[] keys) {
this.type = type;
this.keys = keys;
zabbixHttpComp = SpringContextUtils.getBeanByClass(ZabbixHttpComp.class);
}
@Override
public Object call() {
List<String> hostIps = new ArrayList<>();
if (queryHostByType(hostIps)) {
return null;
}
try {
//根据ip找到hostid
queryHostIdByIp(hostIps);
queryItemByHostId(hostIps);
//根据 hostid itemid 取值
queryHistory();
} catch (Exception e) {
DEBUG.error("Failed to execute zabbix task...error {}", e);
}
return null;
}
private boolean queryHostByType(List<String> hostIps) {
HostInfoServiceImpl iHostInfoService = SpringContextUtils.getBeanByClass(com.monitor.cmdb.service.impl.HostInfoServiceImpl.class);
List<HostInfo> hostInfoList = iHostInfoService.getHostInfosByTag(type);
DEBUG.info("Found host {} in type {}", hostInfoList, type);
if (hostInfoList.isEmpty()) {
return true;
}
for (HostInfo hostInfo : hostInfoList) {
hostIps.add(hostInfo.getHostIp());
if (!HOSTIP_TO_IDS.containsKey(hostInfo.getHostIp())) {
HOSTIP_TO_IDS.put(hostInfo.getHostIp(), null);
}
}
return false;
}
private void queryHistory() throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(10, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
for (Map.Entry<String, List<ItemResponse.Item>> entry : HOSTID_TO_ITEMS.entrySet()) {
executorService.submit(new Runnable() {
@Override
public void run() {
List<HistoryResponse.HistoryItem> itemsHistory = new ArrayList<HistoryResponse.HistoryItem>();
List<ItemResponse.Item> itemList = entry.getValue();
for (String key : keys) {
List<String> itemIdList = new ArrayList<>();
for (ItemResponse.Item item : itemList) {
if (StringUtils.startsWith(item.getKey_(), key)) {
itemIdList.add(item.getItemid());
}
}
String response;
if (StringUtils.equals("system.cpu", key)) {
response = zabbixHttpComp.sendRequest(HistoryRequest.buildRequest(entry.getKey(), itemIdList, 0));
} else {
response = zabbixHttpComp.sendRequest(HistoryRequest.buildRequest(entry.getKey(), itemIdList, 3));
}
DEBUG.info("Found zabbix history response {} in items {}", response, itemIdList);
HistoryResponse historyResponse = null;
try {
historyResponse = Constants.OBJECT_MAPPER.readValue(response, HistoryResponse.class);
} catch (IOException e) {
DEBUG.error("Failed to parse zabbix history response {} in items {}", response, itemIdList);
return;
}
itemsHistory.addAll(historyResponse.getResult());
}
buildBatchPoints(HOSTID_TO_IPS.get(entry.getKey()), entry.getKey(), itemsHistory);
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(40, TimeUnit.SECONDS);
} catch (InterruptedException e) {
DEBUG.error("Failed to execute found zabbix history task in 20 seconds....");
}
}
private void queryItemByHostId(List<String> hostIps) {
ExecutorService executorService = Executors.newFixedThreadPool(10, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
for (String ip : hostIps) {
String hostId = HOSTIP_TO_IDS.get(ip);
if (null != hostId && null != HOSTID_TO_ITEMS.get(hostId)) {
DEBUG.info("Found hostid {} items in cache...no need to query zabbix server...", hostId);
continue;
}
//如果没有查询过该hostid的items信息,则查询
if (null != hostId) {
executorService.submit(new Runnable() {
@Override
public void run() {
String response = zabbixHttpComp.sendRequest(ItemRequest.buildRequest(hostId));
DEBUG.info("Found zabbix item response {} in hostId {}", response, hostId);
try {
ItemResponse itemResponse = Constants.OBJECT_MAPPER.readValue(response, ItemResponse.class);
//缓存items记录到内存中,省去下次查询耗时
HOSTID_TO_ITEMS.put(hostId, itemResponse.getResult());
} catch (Exception e) {
DEBUG.error("Failed to parese zabbix item {} in hostid {}", response, hostId);
}
}
});
}
}
executorService.shutdown();
try {
executorService.awaitTermination(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
DEBUG.error("Failed to execute found zabbix item task in 20 seconds....");
}
}
private void queryHostIdByIp(List<String> hostIps) throws IOException {
//ip 找 hostid , 如果已存在,则跳过
List<String> queryHostIdsList = new ArrayList<>();
for (String ip : hostIps) {
if (null == HOSTIP_TO_IDS.get(ip)) {
queryHostIdsList.add(ip);
}
}
if (queryHostIdsList.isEmpty()) {
DEBUG.info("Not found new host update.... no need to query zabbix...");
return;
}
String response = zabbixHttpComp.sendRequest(HostInterfaceRequest.buildRequest(queryHostIdsList));
DEBUG.info("Found zabbix interface response {} in type {}", response, type);
HostInterfaceResponse hostInterfaceResponse = Constants.OBJECT_MAPPER.readValue(response, HostInterfaceResponse.class);
List<HostInterfaceResponse.HostInterface> hostInterfaces = hostInterfaceResponse.getResult();
for (HostInterfaceResponse.HostInterface hostInterface : hostInterfaces) {
HOSTIP_TO_IDS.put(hostInterface.getIp(), hostInterface.getHostid());
HOSTID_TO_IPS.put(hostInterface.getHostid(), hostInterface.getIp());
}
}
public void buildBatchPoints(String ip, String hostId, List<HistoryResponse.HistoryItem> historyItems) {
DEBUG.info("start to build zabbix batch points...");
DEBUG.info("Build point by history items {}", historyItems);
BatchPoints pointBp = BatchPoints.database(Constants.INFLUX_DB).retentionPolicy(Constants.INFLUX_POLICY).build();
Point point = buildPoints(ip, HOSTID_TO_ITEMS.get(hostId), historyItems);
pointBp.point(point);
DEBUG.info("Start to write batch points {} into zabbix - influxdb", pointBp);
InfluxdbComp influxDBClient = (InfluxdbComp) SpringContextUtils.getBeanByClass(InfluxdbComp.class);
influxDBClient.doWritePoints(pointBp);
}
private Point buildPoints(String ip, List<ItemResponse.Item> items, List<HistoryResponse.HistoryItem> historyItems) {
Point point = PointBuilder.buildPoint(type, ip, items, historyItems);
return point;
}
}
package com.monitor.zabbix.service;
import com.monitor.zabbix.comp.ZabbixHttpComp;
import com.model.HostInfo;
import com.monitor.cmdb.service.IHostInfoService;
import com.monitor.zabbix.mapper.ZabbixHistoryMapper;
import com.monitor.zabbix.mapper.ZabbixHostMapper;
import com.monitor.zabbix.mapper.ZabbixItemMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
... ... @@ -10,6 +14,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
... ... @@ -23,41 +29,76 @@ public class ZabbixTaskService {
public static final Logger DEBUG = LoggerFactory.getLogger(ZabbixTaskService.class);
@Autowired
ZabbixHttpComp zabbixHttpComp;
ZabbixHostMapper hostMapper;
@Autowired
ZabbixItemMapper itemMapper;
@Autowired
ZabbixHistoryMapper historyMapper;
@Value("${zabbix_type}")
String zabbixTypes;
@Value("${zabbix_key}")
String zabbixKeys;
@Autowired
IHostInfoService hostInfoService;
@Scheduled(fixedRate = 1 * 60 * 1000)
public void doTask() {
String[] zTypes = StringUtils.split(this.zabbixTypes, ",");
String[] zKeys = StringUtils.split(this.zabbixKeys, ",");
if (0 >= zTypes.length) {
if (null == zTypes || 0 >= zTypes.length) {
DEBUG.info("Not found types need to collect from zabbix...");
return;
}
//查询所有待监控ip
List<String> allIpList = queryAllIpList(zTypes);
if (0 >= zKeys.length) {
DEBUG.info("Not found keys need to collect from zabbix....");
//10个一组 执行监控任务
int jobSize = (allIpList.size() / 10) + 1;
return;
}
ExecutorService executorService = Executors.newFixedThreadPool(jobSize);
ExecutorService executorService = Executors.newFixedThreadPool(zTypes.length);
List<String> taskIpList = new ArrayList<>();
for (String type : zTypes) {
for (int i = 0; i < allIpList.size(); i++) {
taskIpList.add(allIpList.get(i));
executorService.submit(new ZabbixTask(type, zKeys));
if (0 == (i + 1) % 10) {
executorService.submit(new ZabbixIpTask(taskIpList));
taskIpList.clear();
}
}
if (!taskIpList.isEmpty()) {
executorService.submit(new ZabbixIpTask(taskIpList));
}
executorService.shutdown();
}
private List<String> queryAllIpList(String[] keys) {
List<String> allIpList = new ArrayList<>();
for (String key : keys) {
List<HostInfo> hostInfoList = hostInfoService.getHostInfosByTag(key);
if (null == hostInfoList) {
continue;
}
for (HostInfo hostInfo : hostInfoList) {
if (!allIpList.contains(hostInfo.getHostIp())) {
allIpList.add(hostInfo.getHostIp());
}
}
}
return allIpList;
}
}
... ...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 这个配置使全局的映射器启用或禁用缓存。默认true -->
<setting name="cacheEnabled" value="true"/>
<!-- 全局启用或禁用延迟加载。默认true,为true的会使用cglib作代理-->
<setting name="lazyLoadingEnabled" value="false"/>
<!-- 允许或不允许多种结果集从一个单独的语句中返回。默认true -->
<setting name="multipleResultSetsEnabled" value="true"/>
<!-- 使用列标签代替列名。默认true -->
<setting name="useColumnLabel" value="true"/>
<!-- 允许JDBC支持生成的键。需要适合的驱动。默认false -->
<setting name="useGeneratedKeys" value="false"/>
<!-- 。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 。默认SIMPLE-->
<setting name="defaultExecutorType" value="SIMPLE"/>
<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 -->
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
<typeHandlers>
</typeHandlers>
<mappers>
</mappers>
</configuration>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- dataSource -->
<bean id="zabbixDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="jdbcUrl">
<value>${zabbix.jdbc.url}</value>
</property>
<property name="user">
<value>${zabbix.jdbc.user}</value>
</property>
<property name="password">
<value>${zabbix.jdbc.password}</value>
</property>
<property name="checkoutTimeout" value="3000"/>
<property name="acquireIncrement" value="2"/>
<property name="maxPoolSize" value="40"/>
<property name="minPoolSize" value="5"/>
</bean>
<!-- dataSource -->
<!--mybatis -->
<bean id="zabbixSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="zabbixDataSource"/>
<property name="configLocation" value="classpath:META-INF/mybatis/mybatis-zabbix-config.xml"/>
<property name="typeAliasesPackage" value="com.monitor.zabbix.model"/>
<property name="transactionFactory">
<bean class="org.mybatis.spring.transaction.SpringManagedTransactionFactory"/>
</property>
</bean>
<!--配置Mybatis模版 -->
<bean id="zabbixSqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="zabbixSqlSessionFactory"/>
</bean>
<bean id="zabbixMapperScan" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.monitor.zabbix.mapper"/>
<property name="sqlSessionFactoryBeanName" value="zabbixSqlSessionFactory"></property>
<property name="sqlSessionTemplateBeanName" value="zabbixSqlSessionTemplate"></property>
</bean>
<bean id="zabbixTxManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="zabbixDataSource"/>
</bean>
<bean id="zabbixTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="zabbixDataSource"/>
</bean>
<tx:annotation-driven transaction-manager="zabbixTxManager"/>
</beans>
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.monitor.zabbix.mapper.ZabbixHistoryMapper">
<resultMap id="dHistoryInfoMapper" type="com.monitor.zabbix.model.ZabbixDHistoryInfo">
<result column="itemid" property="itemId" jdbcType="INTEGER"/>
<result column="value" property="value" jdbcType="DOUBLE"/>
</resultMap>
<resultMap id="uHistoryInfoMapper" type="com.monitor.zabbix.model.ZabbixUHistoryInfo">
<result column="itemid" property="itemId" jdbcType="INTEGER"/>
<result column="value" property="value" jdbcType="BIGINT"/>
</resultMap>
<select id="queryDHistoryInfo" resultMap="dHistoryInfoMapper">
select
itemid,`value`
from history
where itemid = #{itemId,jdbcType=INTEGER}
order by clock desc limit 1;
</select>
<select id="queryUHistoryInfo" resultMap="uHistoryInfoMapper">
select itemid,`value`
from history_uint
where itemid = #{itemId,jdbcType=INTEGER}
order by clock desc limit 1;
</select>
</mapper>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.monitor.zabbix.mapper.ZabbixHostMapper">
<resultMap id="hostInfoMapper" type="com.monitor.zabbix.model.ZabbixHostInfo" >
<id column="interfaceid" property="interfaceId" jdbcType="INTEGER" />
<result column="hostid" property="hostId" jdbcType="INTEGER" />
<result column="ip" property="ip" jdbcType="VARCHAR" />
</resultMap>
<select id="queryHostInfo" resultMap="hostInfoMapper">
select
interfaceid,hostid,ip
from interface
where ip IN
<foreach collection="list" index="index" item="item" close=")" open="(" separator=",">
#{item}
</foreach>
</select>
</mapper>
\ No newline at end of file
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.monitor.zabbix.mapper.ZabbixItemMapper">
<resultMap id="itemResultMapper" type="com.monitor.zabbix.model.ZabbixItemInfo">
<id column="itemid" property="itemId" jdbcType="INTEGER"/>
<result column="hostid" property="hostId" jdbcType="INTEGER"/>
<result column="value_type" property="valueType" jdbcType="VARCHAR"/>
<result column="key_" property="keyName" jdbcType="VARCHAR"/>
</resultMap>
<select id="queryItemInfo" resultMap="itemResultMapper">
select
itemid,hostid,key_,value_type
from items
where hostid IN
<foreach collection="list" index="index" item="item" close=")" open="(" separator=",">
#{item}
</foreach>
AND
(key_ LIKE 'system.cpu.util%' OR key_ LIKE 'vm.memory%' OR key_ like 'net.if%')
</select>
</mapper>
\ No newline at end of file
... ...