summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/main/java/com/nis/ConfagentMain.java21
-rw-r--r--src/main/java/com/nis/dao/AlertRuleDao.java11
-rw-r--r--src/main/java/com/nis/dao/ConfEventDao.java11
-rw-r--r--src/main/java/com/nis/dao/EndpointDao.java11
-rw-r--r--src/main/java/com/nis/dao/PromserverDao.java18
-rw-r--r--src/main/java/com/nis/dao/SysConfigDao.java11
-rw-r--r--src/main/java/com/nis/entity/AlertRule.java85
-rw-r--r--src/main/java/com/nis/entity/ConfEvent.java22
-rw-r--r--src/main/java/com/nis/entity/Endpoint.java63
-rw-r--r--src/main/java/com/nis/entity/Module.java57
-rw-r--r--src/main/java/com/nis/entity/Promserver.java45
-rw-r--r--src/main/java/com/nis/entity/SysConfig.java42
-rw-r--r--src/main/java/com/nis/job/ConfagentJob.java239
-rw-r--r--src/main/java/com/nis/job/ConfagentJobFactory.java22
-rw-r--r--src/main/java/com/nis/service/AlertRuleService.java12
-rw-r--r--src/main/java/com/nis/service/ConfEventService.java16
-rw-r--r--src/main/java/com/nis/service/EndpointService.java14
-rw-r--r--src/main/java/com/nis/service/PromserverService.java29
-rw-r--r--src/main/java/com/nis/service/SysConfigService.java9
-rw-r--r--src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java22
-rw-r--r--src/main/java/com/nis/service/impl/ConfEventServiceImpl.java49
-rw-r--r--src/main/java/com/nis/service/impl/EndpointServiceImpl.java21
-rw-r--r--src/main/java/com/nis/service/impl/PromserverServiceImpl.java35
-rw-r--r--src/main/java/com/nis/service/impl/SysConfigServiceImpl.java22
-rw-r--r--src/main/java/com/nis/util/PropertyPlaceholder.java31
-rw-r--r--src/main/java/com/nis/util/RuntimeUtil.java322
-rw-r--r--src/main/java/com/nis/util/YamlUtil.java156
-rw-r--r--src/main/resources/confagent.properties9
-rw-r--r--src/main/resources/log4j.properties8
-rw-r--r--src/main/resources/mapper/AlertRuleDao.xml19
-rw-r--r--src/main/resources/mapper/ConfEventDao.xml9
-rw-r--r--src/main/resources/mapper/EndpointDao.xml39
-rw-r--r--src/main/resources/mapper/PromserverDao.xml27
-rw-r--r--src/main/resources/mapper/SysConfigDao.xml16
-rw-r--r--src/main/resources/spring.xml142
35 files changed, 1665 insertions, 0 deletions
diff --git a/src/main/java/com/nis/ConfagentMain.java b/src/main/java/com/nis/ConfagentMain.java
new file mode 100644
index 0000000..c3f7cae
--- /dev/null
+++ b/src/main/java/com/nis/ConfagentMain.java
@@ -0,0 +1,21 @@
+package com.nis;
+
+
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+/*@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations="classpath:spring.xml")*/
+public class ConfagentMain {
+ private static Logger logger = LoggerFactory.getLogger(ConfagentMain.class);
+
+ public static void main(String[] args) {
+ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
+ System.out.println("initContext successfully");
+ logger.info("initContext successfully");
+ }
+}
diff --git a/src/main/java/com/nis/dao/AlertRuleDao.java b/src/main/java/com/nis/dao/AlertRuleDao.java
new file mode 100644
index 0000000..16ed893
--- /dev/null
+++ b/src/main/java/com/nis/dao/AlertRuleDao.java
@@ -0,0 +1,11 @@
+package com.nis.dao;
+
+import java.util.List;
+
+import com.nis.entity.AlertRule;
+
+public interface AlertRuleDao {
+
+ List<AlertRule> selectList();
+
+}
diff --git a/src/main/java/com/nis/dao/ConfEventDao.java b/src/main/java/com/nis/dao/ConfEventDao.java
new file mode 100644
index 0000000..a29d09c
--- /dev/null
+++ b/src/main/java/com/nis/dao/ConfEventDao.java
@@ -0,0 +1,11 @@
+package com.nis.dao;
+
+import java.util.List;
+
+import com.nis.entity.ConfEvent;
+
+public interface ConfEventDao {
+
+ List<ConfEvent> selectList();
+
+}
diff --git a/src/main/java/com/nis/dao/EndpointDao.java b/src/main/java/com/nis/dao/EndpointDao.java
new file mode 100644
index 0000000..f3025ef
--- /dev/null
+++ b/src/main/java/com/nis/dao/EndpointDao.java
@@ -0,0 +1,11 @@
+package com.nis.dao;
+
+import java.util.List;
+
+import com.nis.entity.Endpoint;
+
+public interface EndpointDao {
+
+ List<Endpoint> selectExporterInfos(Integer idcId);
+
+}
diff --git a/src/main/java/com/nis/dao/PromserverDao.java b/src/main/java/com/nis/dao/PromserverDao.java
new file mode 100644
index 0000000..e3820c7
--- /dev/null
+++ b/src/main/java/com/nis/dao/PromserverDao.java
@@ -0,0 +1,18 @@
+package com.nis.dao;
+
+import java.util.List;
+
+import org.apache.ibatis.annotations.Param;
+
+import com.nis.entity.Promserver;
+
+public interface PromserverDao {
+
+ List<Promserver> selectList();
+
+ Promserver selectRoleByIp(String ip);
+
+ List<Promserver> selectSubInfo(@Param("promserver")Promserver promserver);
+
+ List<Promserver> selectSubInfosByType(Integer type);
+}
diff --git a/src/main/java/com/nis/dao/SysConfigDao.java b/src/main/java/com/nis/dao/SysConfigDao.java
new file mode 100644
index 0000000..bb1d6ff
--- /dev/null
+++ b/src/main/java/com/nis/dao/SysConfigDao.java
@@ -0,0 +1,11 @@
+package com.nis.dao;
+
+import java.util.List;
+
+import com.nis.entity.SysConfig;
+
+public interface SysConfigDao {
+
+ List<SysConfig> selectList();
+
+}
diff --git a/src/main/java/com/nis/entity/AlertRule.java b/src/main/java/com/nis/entity/AlertRule.java
new file mode 100644
index 0000000..14319be
--- /dev/null
+++ b/src/main/java/com/nis/entity/AlertRule.java
@@ -0,0 +1,85 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+
+public class AlertRule implements Serializable{
+
+ private Integer id;
+ /**
+ * 告警名称
+ */
+ private String alertName;
+ /**
+ * 运算表达式
+ */
+ private String expr;
+ /**
+ * 持续时间,单位s
+ */
+ private Integer last;
+ /**
+ * 告警级别
+ */
+ private String severity;
+ /**
+ * 告警摘要
+ */
+ private String summary;
+ /**
+ * 告警详细描述
+ */
+ private String description;
+ /**
+ * 通知用户组
+ */
+ private Integer receiver;
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public String getAlertName() {
+ return alertName;
+ }
+ public void setAlertName(String alertName) {
+ this.alertName = alertName;
+ }
+ public String getExpr() {
+ return expr;
+ }
+ public void setExpr(String expr) {
+ this.expr = expr;
+ }
+ public Integer getLast() {
+ return last;
+ }
+ public void setLast(Integer last) {
+ this.last = last;
+ }
+ public String getSeverity() {
+ return severity;
+ }
+ public void setSeverity(String severity) {
+ this.severity = severity;
+ }
+ public String getSummary() {
+ return summary;
+ }
+ public void setSummary(String summary) {
+ this.summary = summary;
+ }
+ public String getDescription() {
+ return description;
+ }
+ public void setDescription(String description) {
+ this.description = description;
+ }
+ public Integer getReceiver() {
+ return receiver;
+ }
+ public void setReceiver(Integer receiver) {
+ this.receiver = receiver;
+ }
+
+}
diff --git a/src/main/java/com/nis/entity/ConfEvent.java b/src/main/java/com/nis/entity/ConfEvent.java
new file mode 100644
index 0000000..40bb409
--- /dev/null
+++ b/src/main/java/com/nis/entity/ConfEvent.java
@@ -0,0 +1,22 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+
+public class ConfEvent implements Serializable{
+
+ private String table;
+ private Integer value;
+ public String getTable() {
+ return table;
+ }
+ public void setTable(String table) {
+ this.table = table;
+ }
+ public Integer getValue() {
+ return value;
+ }
+ public void setValue(Integer value) {
+ this.value = value;
+ }
+
+}
diff --git a/src/main/java/com/nis/entity/Endpoint.java b/src/main/java/com/nis/entity/Endpoint.java
new file mode 100644
index 0000000..fbd6905
--- /dev/null
+++ b/src/main/java/com/nis/entity/Endpoint.java
@@ -0,0 +1,63 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+
+public class Endpoint implements Serializable{
+
+ private Integer id;
+ private Integer moduleId;
+ private Integer assetId;
+ private String host;
+ private Integer port;
+ private String param;
+ private String path;
+ private Module module;
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public Integer getModuleId() {
+ return moduleId;
+ }
+ public void setModuleId(Integer moduleId) {
+ this.moduleId = moduleId;
+ }
+ public Integer getAssetId() {
+ return assetId;
+ }
+ public void setAssetId(Integer assetId) {
+ this.assetId = assetId;
+ }
+ public String getHost() {
+ return host;
+ }
+ public void setHost(String host) {
+ this.host = host;
+ }
+ public Integer getPort() {
+ return port;
+ }
+ public void setPort(Integer port) {
+ this.port = port;
+ }
+ public String getParam() {
+ return param;
+ }
+ public void setParam(String param) {
+ this.param = param;
+ }
+ public String getPath() {
+ return path;
+ }
+ public void setPath(String path) {
+ this.path = path;
+ }
+ public Module getModule() {
+ return module;
+ }
+ public void setModule(Module module) {
+ this.module = module;
+ }
+}
diff --git a/src/main/java/com/nis/entity/Module.java b/src/main/java/com/nis/entity/Module.java
new file mode 100644
index 0000000..65851eb
--- /dev/null
+++ b/src/main/java/com/nis/entity/Module.java
@@ -0,0 +1,57 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+
+public class Module implements Serializable{
+
+ private Integer id;
+ private Integer projectId;
+ private String name;
+ private Integer port;
+ private String param;
+ private String path;
+ private String remark;
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public Integer getProjectId() {
+ return projectId;
+ }
+ public void setProjectId(Integer projectId) {
+ this.projectId = projectId;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ public Integer getPort() {
+ return port;
+ }
+ public void setPort(Integer port) {
+ this.port = port;
+ }
+ public String getParam() {
+ return param;
+ }
+ public void setParam(String param) {
+ this.param = param;
+ }
+ public String getPath() {
+ return path;
+ }
+ public void setPath(String path) {
+ this.path = path;
+ }
+ public String getRemark() {
+ return remark;
+ }
+ public void setRemark(String remark) {
+ this.remark = remark;
+ }
+
+}
diff --git a/src/main/java/com/nis/entity/Promserver.java b/src/main/java/com/nis/entity/Promserver.java
new file mode 100644
index 0000000..d8c5c5f
--- /dev/null
+++ b/src/main/java/com/nis/entity/Promserver.java
@@ -0,0 +1,45 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+
+public class Promserver implements Serializable{
+
+ private static final long serialVersionUID = 1L;
+ private Integer id;
+ private Integer idcId;
+ private String host;
+ private String relabel;
+ private Integer type;
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public Integer getIdcId() {
+ return idcId;
+ }
+ public void setIdcId(Integer idcId) {
+ this.idcId = idcId;
+ }
+ public String getHost() {
+ return host;
+ }
+ public void setHost(String host) {
+ this.host = host;
+ }
+ public String getRelabel() {
+ return relabel;
+ }
+ public void setRelabel(String relabel) {
+ this.relabel = relabel;
+ }
+ public Integer getType() {
+ return type;
+ }
+ public void setType(Integer type) {
+ this.type = type;
+ }
+
+
+}
diff --git a/src/main/java/com/nis/entity/SysConfig.java b/src/main/java/com/nis/entity/SysConfig.java
new file mode 100644
index 0000000..283774f
--- /dev/null
+++ b/src/main/java/com/nis/entity/SysConfig.java
@@ -0,0 +1,42 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+
+public class SysConfig implements Serializable{
+ private Integer id;
+ private String paramKey;
+ private String paramValue;
+ private Integer status;
+ private String remark;
+ public Integer getId() {
+ return id;
+ }
+ public void setId(Integer id) {
+ this.id = id;
+ }
+ public String getParamKey() {
+ return paramKey;
+ }
+ public void setParamKey(String paramKey) {
+ this.paramKey = paramKey;
+ }
+ public String getParamValue() {
+ return paramValue;
+ }
+ public void setParamValue(String paramValue) {
+ this.paramValue = paramValue;
+ }
+ public Integer getStatus() {
+ return status;
+ }
+ public void setStatus(Integer status) {
+ this.status = status;
+ }
+ public String getRemark() {
+ return remark;
+ }
+ public void setRemark(String remark) {
+ this.remark = remark;
+ }
+
+}
diff --git a/src/main/java/com/nis/job/ConfagentJob.java b/src/main/java/com/nis/job/ConfagentJob.java
new file mode 100644
index 0000000..6212331
--- /dev/null
+++ b/src/main/java/com/nis/job/ConfagentJob.java
@@ -0,0 +1,239 @@
+package com.nis.job;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import com.alibaba.fastjson.JSON;
+import com.nis.entity.AlertRule;
+import com.nis.entity.Endpoint;
+import com.nis.entity.Promserver;
+import com.nis.entity.SysConfig;
+import com.nis.service.AlertRuleService;
+import com.nis.service.ConfEventService;
+import com.nis.service.EndpointService;
+import com.nis.service.PromserverService;
+import com.nis.service.SysConfigService;
+import com.nis.util.PropertyPlaceholder;
+import com.nis.util.YamlUtil;
+
+/**
+ * confagent job任务相关 处理同步prometheus配置信息
+ * @author Th
+ *
+ */
+public class ConfagentJob{
+ private Logger logger = LoggerFactory.getLogger(ConfagentJob.class);
+ private Map<String,Integer> confEvents=null;
+ @Autowired
+ private PromserverService promserverService;
+ @Autowired
+ private ConfEventService confEventService;
+ @Autowired
+ private EndpointService endpointService;
+ @Autowired
+ private AlertRuleService alertRuleService;
+ @Autowired
+ private SysConfigService sysConfigService;
+
+ public void execute(){
+ logger.info("task start");
+ //获取本机ip地址 获取本机所属角色信息
+ String ipaddr = (String)PropertyPlaceholder.getProperty("ipaddr");
+ logger.info("The local IP address is {}",ipaddr);
+
+ Promserver promserver = promserverService.queryRoleByIp(ipaddr);
+ logger.info("The local role info {}",JSON.toJSON(promserver));
+
+ if(promserver!=null) {
+ // 判断本次表格数据与之前数据是否有变化判断是否执行操作
+ boolean changeFlag = confEventService.compareData(confEvents);
+ //先判断conf_event表中是否有数据变化 程序初始进入map数据为空 则全量配置更新同步
+ if(confEvents==null || changeFlag ) {
+ if(promserver.getType()==1) {
+ Map centerResult = centerHandle();
+ logger.debug("center result info {} ",JSON.toJSON(centerResult));
+ if(centerResult!=null) {
+ //获取yml文件信息替换对应内容
+ try {
+ boolean handleResult = YamlUtil.centerYmlHandle(centerResult);
+ logger.info("yamlHanlde center result {}",JSON.toJSON(handleResult));
+ } catch (Exception e) {
+ logger.error("yamlHanlde center error");
+ e.printStackTrace();
+ }
+ }
+ }else if(promserver.getType()==2) {
+ List result = subHandle(promserver);
+ logger.debug("subHandle list info {} ",JSON.toJSON(result));
+ if(result!=null) {
+ //获取yml文件信息替换对应内容
+ try {
+ boolean handleResult = YamlUtil.subYmlHandle(result);
+ logger.info("yamlHanlde sub result {}",JSON.toJSON(handleResult));
+ } catch (Exception e) {
+ logger.error("yamlHanlde sub error");
+ e.printStackTrace();
+ }
+ }
+ }
+ //处理完信息配置后 将confEvent数据保存 留待下个周期比较判断
+ confEvents=confEventService.queryConfEventMap();
+ }else {
+ // 如果表中数据无更新则本次无操作
+ logger.info("There is no change in the table data. This task is completed");
+ }
+ }
+ logger.info("Synchronization configurator end");
+ System.err.println("Synchronization configurator end");
+ }
+
+ /**
+ * 处理sub相关逻辑
+ */
+ public List subHandle(Promserver promserver) {
+ //查询同一个idc下相同角色sub的数量以及exporter的数量信息
+ List<Promserver> subInfos = promserverService.querySubInfos(promserver);
+ logger.info("subHandle : There are {} sub in total",subInfos.size());
+ logger.info("subHandle : There are all subInfos : {}",JSON.toJSON(subInfos));
+
+ List<Endpoint> endpointInfos = endpointService.queryExporterInfos(promserver.getIdcId());
+ logger.info("subHandle : There are {} exporter in total",endpointInfos.size());
+ logger.info("subHandle : There are all endpointInfos : {} ",JSON.toJSON(endpointInfos));
+ //获取当前sub排序信息
+ Integer index=null;
+ if(!subInfos.isEmpty()) {
+ for(int i=0;i<subInfos.size();i++) {
+ if(subInfos.get(i).getHost().equals(promserver.getHost())) {
+ index=i;
+ }
+ }
+ }
+ List result = null;
+ //两者模运算均匀分配
+ if(index!=null && !endpointInfos.isEmpty()) {
+ result=new ArrayList();
+ for(int m=0;m<endpointInfos.size();m++) {
+ if(m%subInfos.size()==index) {
+ Map job = new HashMap();
+ job.put("job_name", endpointInfos.get(m).getModule().getName()+endpointInfos.get(m).getHost());
+ List list=new ArrayList();
+ list.add(endpointInfos.get(m).getHost());
+ Map job2 = new HashMap();
+ job2.put("targets",list);
+ job.put("metrics_path", endpointInfos.get(m).getPath());
+ job.put("static_configs", job2);
+ result.add(job);
+ }
+ }
+ }
+ logger.info("subHandle : result : {} ",JSON.toJSON(result));
+ return result;
+ }
+
+ /**
+ * 处理center相关逻辑
+ */
+ public Map centerHandle() {
+ Map result=new HashMap();
+ //获取所有sub信息 配置联邦
+ List<Promserver> subInfos = promserverService.querySubInfosByType(2);
+ logger.info("centerHandle : There are all subInfos : {}",JSON.toJSON(subInfos));
+
+ // 配置组装联邦信息开始
+ List l = new ArrayList();
+ Map m1 = new LinkedHashMap();
+ m1.put("job_name", "federate");
+
+ m1.put("scrape_interval", "15s");
+ m1.put("honor_labels", true);
+ m1.put("metrics_path", "/federate");
+
+
+ List l2 =new ArrayList();
+ List l3 =new ArrayList();
+ //获取默认端口号
+ String prometheusPort = (String)PropertyPlaceholder.getProperty("prometheusPort");
+ for(Promserver subInfo:subInfos) {
+ l3.add(subInfo.getHost()+":"+prometheusPort);
+ }
+ Map m2 =new HashMap();
+ m2.put("targets", l3);
+ l2.add(m2);
+ m1.put("static_configs", l2);
+
+ Map m3 = new HashMap();
+ List l4=new ArrayList();
+ l4.add("{job=\"prometheus\"}");
+ l4.add("{__name__=~\"job:.*\"}");
+ m3.put("match[]", l4);
+ m1.put("params", m3);
+
+ l.add(m1);
+
+ result.put("scrape_configs", l);
+
+ logger.info("centerHandle : scrape_configs Info : {}",JSON.toJSON(l));
+ //配置联邦信息结束
+
+ //配置rule
+
+ //查询所有rule配置信息
+ List<AlertRule> alertRules = alertRuleService.queryList();
+
+ Map toCheck = new HashMap();
+
+ List groups = new ArrayList();
+
+ Map group = new HashMap();
+ groups.add(group);
+
+ List rules = new ArrayList();
+ group.put("name", "alertRule");
+ group.put("rules", rules);
+
+ for(AlertRule alertRule : alertRules) {
+ Map labels = new HashMap();
+ labels.put("severity", alertRule.getSeverity());
+ Map annotations = new HashMap();
+ annotations.put("summary", alertRule.getSummary());
+ annotations.put("description", alertRule.getDescription());
+ Map rule = new HashMap();
+ rule.put("alert", alertRule.getAlertName());
+ rule.put("expr", alertRule.getExpr());
+ rule.put("for", alertRule.getLast() + "s");
+ rule.put("labels", labels);
+ rule.put("annotations", annotations);
+ rules.add(rule);
+ }
+ result.put("groups", groups);
+
+ logger.info("centerHandle : alert rule Info : {}",JSON.toJSON(groups));
+ //配置alertManager
+
+ //查询sys_config表获取数据
+ List<SysConfig> sysConfigs = sysConfigService.queryList();
+ Map alertManager =new HashMap();
+ List staticConfigList=new ArrayList();
+ Map staticConfigs =new HashMap();
+ staticConfigList.add(staticConfigs);
+ List staticConfig =new ArrayList();
+ Map targets =new HashMap();
+ List target =new ArrayList();
+ List alertData =new ArrayList();
+ if(!sysConfigs.isEmpty()) {
+ alertData.add(sysConfigs.get(0).getParamValue());
+ }
+ alertManager.put("alertmanagers",staticConfigList);
+ staticConfigs.put("static_configs", staticConfig);
+ staticConfig.add(targets);
+ targets.put("targets", alertData);
+ result.put("alerting", alertManager);
+ logger.info("centerHandle : alert manager Info : {}",JSON.toJSON(alertManager));
+ return result;
+ }
+}
diff --git a/src/main/java/com/nis/job/ConfagentJobFactory.java b/src/main/java/com/nis/job/ConfagentJobFactory.java
new file mode 100644
index 0000000..b73c10d
--- /dev/null
+++ b/src/main/java/com/nis/job/ConfagentJobFactory.java
@@ -0,0 +1,22 @@
+package com.nis.job;
+
+import org.quartz.spi.TriggerFiredBundle;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
+import org.springframework.scheduling.quartz.AdaptableJobFactory;
+
+public class ConfagentJobFactory extends AdaptableJobFactory {
+
+ //这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
+ @Autowired
+ private AutowireCapableBeanFactory capableBeanFactory;
+
+ protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
+ //调用父类的方法
+ Object jobInstance = super.createJobInstance(bundle);
+ //进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
+ capableBeanFactory.autowireBean(jobInstance);
+ return jobInstance;
+ }
+
+}
diff --git a/src/main/java/com/nis/service/AlertRuleService.java b/src/main/java/com/nis/service/AlertRuleService.java
new file mode 100644
index 0000000..88e1919
--- /dev/null
+++ b/src/main/java/com/nis/service/AlertRuleService.java
@@ -0,0 +1,12 @@
+package com.nis.service;
+
+import java.util.List;
+import java.util.Map;
+
+import com.nis.entity.AlertRule;
+import com.nis.entity.ConfEvent;
+
+public interface AlertRuleService {
+
+ public List<AlertRule> queryList();
+}
diff --git a/src/main/java/com/nis/service/ConfEventService.java b/src/main/java/com/nis/service/ConfEventService.java
new file mode 100644
index 0000000..c28cfc2
--- /dev/null
+++ b/src/main/java/com/nis/service/ConfEventService.java
@@ -0,0 +1,16 @@
+package com.nis.service;
+
+import java.util.List;
+import java.util.Map;
+
+import com.nis.entity.ConfEvent;
+
+public interface ConfEventService {
+
+ public Map<String,Integer> queryConfEventMap();
+
+ /**
+ *
+ */
+ public boolean compareData(Map<String,Integer> map);
+}
diff --git a/src/main/java/com/nis/service/EndpointService.java b/src/main/java/com/nis/service/EndpointService.java
new file mode 100644
index 0000000..797b8bc
--- /dev/null
+++ b/src/main/java/com/nis/service/EndpointService.java
@@ -0,0 +1,14 @@
+package com.nis.service;
+
+import java.util.List;
+
+import com.nis.entity.Endpoint;
+
+public interface EndpointService {
+
+ /**
+ * 根据idc信息查询exporter数量信息
+ */
+ public List<Endpoint> queryExporterInfos(Integer idcId);
+
+}
diff --git a/src/main/java/com/nis/service/PromserverService.java b/src/main/java/com/nis/service/PromserverService.java
new file mode 100644
index 0000000..7ac8773
--- /dev/null
+++ b/src/main/java/com/nis/service/PromserverService.java
@@ -0,0 +1,29 @@
+package com.nis.service;
+
+import java.util.List;
+
+import com.nis.entity.Promserver;
+
+public interface PromserverService {
+
+ public List<Promserver> queryList();
+
+ /**
+ * 根据ip查询
+ * @param ip
+ * @return
+ */
+ public Promserver queryRoleByIp(String ip);
+
+ /**
+ * 查询sub信息 根据idcid及type
+ * @param promserver
+ * @return
+ */
+ public List<Promserver> querySubInfos(Promserver promserver);
+
+ /**
+ * 查询所有sub信息
+ */
+ public List<Promserver> querySubInfosByType(Integer type);
+}
diff --git a/src/main/java/com/nis/service/SysConfigService.java b/src/main/java/com/nis/service/SysConfigService.java
new file mode 100644
index 0000000..1a142fe
--- /dev/null
+++ b/src/main/java/com/nis/service/SysConfigService.java
@@ -0,0 +1,9 @@
+package com.nis.service;
+
+import java.util.List;
+import com.nis.entity.SysConfig;
+
+public interface SysConfigService {
+
+ public List<SysConfig> queryList();
+}
diff --git a/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java b/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java
new file mode 100644
index 0000000..d9d22db
--- /dev/null
+++ b/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java
@@ -0,0 +1,22 @@
+package com.nis.service.impl;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.nis.dao.AlertRuleDao;
+import com.nis.entity.AlertRule;
+import com.nis.service.AlertRuleService;
+
+@Service
+public class AlertRuleServiceImpl implements AlertRuleService {
+
+ @Autowired
+ private AlertRuleDao alertRuleDao;
+
+ @Override
+ public List<AlertRule> queryList() {
+ return alertRuleDao.selectList();
+ }
+}
diff --git a/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java b/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java
new file mode 100644
index 0000000..dc6c12d
--- /dev/null
+++ b/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java
@@ -0,0 +1,49 @@
+package com.nis.service.impl;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.nis.dao.ConfEventDao;
+import com.nis.entity.ConfEvent;
+import com.nis.service.ConfEventService;
+
+@Service
+public class ConfEventServiceImpl implements ConfEventService {
+
+ @Autowired
+ private ConfEventDao confEventDao;
+
+ @Override
+ public Map<String, Integer> queryConfEventMap() {
+ Map<String,Integer> result = new HashMap<String,Integer>();
+ List<ConfEvent> datas = confEventDao.selectList();
+ if(datas.size()>0) {
+ for(ConfEvent data:datas) {
+ result.put(data.getTable(), data.getValue());
+ }
+ return result;
+ }else {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean compareData(Map<String, Integer> map) {
+ boolean flag = false;
+ if(map==null) {
+ flag = true;
+ return flag;
+ }
+ List<ConfEvent> datas = confEventDao.selectList();
+ for(ConfEvent data:datas) {
+ if(!(data.getValue()==map.get(data.getTable()))) {
+ flag = true;
+ }
+ }
+ return flag;
+ }
+}
diff --git a/src/main/java/com/nis/service/impl/EndpointServiceImpl.java b/src/main/java/com/nis/service/impl/EndpointServiceImpl.java
new file mode 100644
index 0000000..d2af0da
--- /dev/null
+++ b/src/main/java/com/nis/service/impl/EndpointServiceImpl.java
@@ -0,0 +1,21 @@
+package com.nis.service.impl;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.nis.dao.EndpointDao;
+import com.nis.entity.Endpoint;
+import com.nis.service.EndpointService;
+@Service
+public class EndpointServiceImpl implements EndpointService{
+ @Autowired
+ private EndpointDao endpointDao;
+
+ @Override
+ public List<Endpoint> queryExporterInfos(Integer idcId) {
+ return endpointDao.selectExporterInfos(idcId);
+ }
+
+}
diff --git a/src/main/java/com/nis/service/impl/PromserverServiceImpl.java b/src/main/java/com/nis/service/impl/PromserverServiceImpl.java
new file mode 100644
index 0000000..5772d37
--- /dev/null
+++ b/src/main/java/com/nis/service/impl/PromserverServiceImpl.java
@@ -0,0 +1,35 @@
+package com.nis.service.impl;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import com.nis.dao.PromserverDao;
+import com.nis.entity.Promserver;
+import com.nis.service.PromserverService;
+
+@Service
+public class PromserverServiceImpl implements PromserverService {
+
+ @Autowired
+ private PromserverDao promserverDao;
+
+ public List<Promserver> queryList(){
+ return promserverDao.selectList();
+ }
+
+ @Override
+ public Promserver queryRoleByIp(String ip) {
+ return promserverDao.selectRoleByIp(ip);
+ }
+
+ @Override
+ public List<Promserver> querySubInfos(Promserver promserver) {
+ return promserverDao.selectSubInfo(promserver);
+ }
+
+ @Override
+ public List<Promserver> querySubInfosByType(Integer type) {
+ return promserverDao.selectSubInfosByType(type);
+ }
+}
diff --git a/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java b/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java
new file mode 100644
index 0000000..44ea0de
--- /dev/null
+++ b/src/main/java/com/nis/service/impl/SysConfigServiceImpl.java
@@ -0,0 +1,22 @@
+package com.nis.service.impl;
+
+import java.util.List;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.nis.dao.SysConfigDao;
+import com.nis.entity.SysConfig;
+import com.nis.service.SysConfigService;
+
+@Service
+public class SysConfigServiceImpl implements SysConfigService {
+
+ @Autowired
+ private SysConfigDao sysConfigDao;
+
+ @Override
+ public List<SysConfig> queryList() {
+ return sysConfigDao.selectList();
+ }
+}
diff --git a/src/main/java/com/nis/util/PropertyPlaceholder.java b/src/main/java/com/nis/util/PropertyPlaceholder.java
new file mode 100644
index 0000000..2404caa
--- /dev/null
+++ b/src/main/java/com/nis/util/PropertyPlaceholder.java
@@ -0,0 +1,31 @@
+package com.nis.util;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
+import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
+
+public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {
+
+ private static Map<String,String> propertyMap;
+
+ @Override
+ protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
+ super.processProperties(beanFactoryToProcess, props);
+ propertyMap = new HashMap<String, String>();
+ for (Object key : props.keySet()) {
+ String keyStr = key.toString();
+ String value = props.getProperty(keyStr);
+ propertyMap.put(keyStr, value);
+ }
+ }
+
+ //static method for accessing context properties
+ public static Object getProperty(String name) {
+ return propertyMap.get(name);
+ }
+ }
+
diff --git a/src/main/java/com/nis/util/RuntimeUtil.java b/src/main/java/com/nis/util/RuntimeUtil.java
new file mode 100644
index 0000000..53d6401
--- /dev/null
+++ b/src/main/java/com/nis/util/RuntimeUtil.java
@@ -0,0 +1,322 @@
+package com.nis.util;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.StringReader;
+import java.util.Arrays;
+import java.util.UUID;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Runtime工具类,用于本机执行某些命令
+ *
+ * @author fox
+ * @version 0.1.0
+ */
+public class RuntimeUtil {
+ // Log
+ private static Log log = LogFactory.getLog(RuntimeUtil.class);
+ // 当前Runtime
+ private static Runtime runtime = Runtime.getRuntime();
+
+ // 工具类不可实例化
+ private RuntimeUtil() {
+ }
+
+ /**
+ * 以非阻塞模式执行命令
+ *
+ * @param callback
+ * 回调类,当命令全部执行完成后会执行其onExit方法,null表示不进行回调
+ * @param envp
+ * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
+ * @param dir
+ * 命令执行的工作目录;null表示继承当前Java进程的工作目录
+ * @param startCommand
+ * 起始命令
+ * @param commands
+ * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
+ */
+ public static void runAsUnblocking(final RuntimeCallback callback, final String[] envp, final File dir,
+ final String[] startCommand, final String[]... commands) {
+ // 非阻塞的实现就是交给其他函数执行
+ new Thread(new Runnable() {
+ @Override
+ public void run() {
+ StringReader result = RuntimeUtil.run(envp, dir, startCommand, commands);
+
+ // 如果需要回调的话,调用回调函数
+ if (callback != null) {
+ callback.onExit(result, envp, dir, startCommand, commands);
+ }
+ }
+ }).start();
+ }
+
+ /**
+ * 以阻塞模式执行命令
+ *
+ * @param envp
+ * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
+ * @param dir
+ * 命令执行的工作目录;null表示继承当前Java进程的工作目录
+ * @param startCommand
+ * 起始命令
+ * @param commands
+ * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
+ * @return 命令执行后的最终结果
+ */
+ public static StringReader run(String[] envp, File dir, String[] startCommand, String[]... commands) {
+ // 生成一个命令id,只是为日志区别用
+ String commandId = UUID.randomUUID().toString();
+ log.info("Command(" + commandId + ") start");
+
+ StringBuilder result = new StringBuilder();
+ Process currentProcess = null;
+ Process nextProcess = null;
+
+ try {
+ // 见执行起始命令
+ currentProcess = run(commandId, startCommand, envp, dir);
+ // 用于管道的字节输出流
+ BufferedOutputStream out = null;
+ // 用于标准错误输出和最终结果的字符输入流
+ BufferedReader reader = null;
+ // 用于管道的字节输入流
+ BufferedInputStream in = null;
+ // 用于管道的IO缓冲
+ byte[] buffer = new byte[1024];
+ try {
+ // 遍历后续命令
+ for (String[] command : commands) {
+ try {
+ // 获取当前命令的标准错误流
+ reader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream()));
+
+ // 输出错误
+ for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
+ log.warn("Command(" + commandId + ") Error: " + temp);
+ }
+ // 获取当前命令的标准输出流
+ in = new BufferedInputStream(currentProcess.getInputStream());
+ // 启动下一条命令
+ nextProcess = run(commandId, command, envp, dir);
+ // 获取下一条命令的标准输入流
+ out = new BufferedOutputStream(nextProcess.getOutputStream());
+
+ // 管道的实现
+ for (int c = read(in, buffer); c >= 0; c = read(in, buffer)) {
+ write(out, buffer, c);
+ }
+
+ // 当前命令全部输出都已经输入到下一条命令中后,将下一条命令作为当前命令
+ currentProcess = nextProcess;
+ } finally { // 流关闭操作
+ if (out != null) {
+ out.flush();
+ out.close();
+ out = null;
+ }
+
+ if (in != null) {
+ in.close();
+ in = null;
+ }
+
+ if (reader != null) {
+ reader.close();
+ reader = null;
+ }
+ }
+ }
+
+ // 获取最终命令的标准错误流,
+ reader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream()));
+ // 输出错误
+ for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
+ log.warn("Command(" + commandId + ") Error: " + temp);
+ }
+ // 关闭
+ reader.close();
+ reader = null;
+
+ // 获取最终命令的标准输出流
+ reader = new BufferedReader(new InputStreamReader(currentProcess.getInputStream()));
+ // 将输出添加到结果缓冲中
+ for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
+ result.append(temp + "\n");
+ }
+ } finally { // 流关闭操作
+ if (out != null) {
+ out.flush();
+ out.close();
+ out = null;
+ }
+
+ if (in != null) {
+ in.close();
+ in = null;
+ }
+
+ if (reader != null) {
+ reader.close();
+ reader = null;
+ }
+ }
+ } catch (Exception e) { // 出现异常,尝试把启动的进程都销毁
+ log.warn("Command(" + commandId + ") Error", e);
+
+ if (currentProcess != null) {
+ currentProcess.destroy();
+ currentProcess = null;
+ }
+
+ if (nextProcess != null) {
+ nextProcess.destroy();
+ nextProcess = null;
+ }
+ }
+
+ log.info("Command(" + commandId + ") end");
+ // 用结果缓冲构建StringReader
+ return new StringReader(result.toString());
+ }
+
+ /**
+ * 读取StringReader为String
+ *
+ * @param stringReader
+ * StringReader
+ * @param skipWhiteLine
+ * 是否需要跳过空行
+ * @return
+ */
+ public static String readStringReader(StringReader stringReader, boolean skipWhiteLine) {
+ StringBuilder result = new StringBuilder();
+ BufferedReader reader = new BufferedReader(stringReader);
+
+ for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
+ if (skipWhiteLine == false || !temp.trim().equals("")) {
+ result.append(temp + "\n");
+ }
+ }
+
+ return result.toString();
+
+ }
+
+ /**
+ * 运行一个命令
+ *
+ * @param commandId
+ * 命令id, 日志区别用
+ * @param command
+ * 执行的命令
+ * @param envp
+ * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
+ * @param dir
+ * 命令执行的工作目录;null表示继承当前Java进程的工作目录
+ * @return 命令对应的Process对象Process
+ * @throws Exception
+ */
+ private static Process run(String commandId, String[] command, String[] envp, File dir) throws Exception {
+ log.info("Command(" + commandId + ") exec: " + Arrays.toString(command));
+
+ return runtime.exec(command, envp, dir);
+ }
+
+ /**
+ * 从输入流中读取数据进入buffer中,忽略异常
+ *
+ * @param in
+ * 输入流
+ * @param buffer
+ * 缓冲
+ * @return 基本等同于in.read(buffer)的返回值,不过在出现异常时,不会抛出异常而是返回-1
+ */
+ private static int read(InputStream in, byte[] buffer) {
+ int result = -1;
+
+ try {
+ result = in.read(buffer);
+ } catch (IOException e) {
+ result = -1;
+ }
+
+ return result;
+ }
+
+ /**
+ * 从输入流中读取一行字符串,忽略异常
+ *
+ * @param reader
+ * 输入流
+ * @return 基本等同于reader.readLine()的返回值,不过在出现异常时,不会抛出异常而是返回null
+ */
+ private static String readLine(BufferedReader reader) {
+ String result = null;
+
+ try {
+ result = reader.readLine();
+ } catch (IOException e) {
+ result = null;
+ }
+
+ return result;
+ }
+
+ /**
+ * 向输出流写入buffer从0~length位置的数据,忽略异常
+ *
+ * @param out
+ * 输出流
+ * @param buffer
+ * 缓冲
+ * @param length
+ * 最大位序号
+ */
+ private static void write(OutputStream out, byte[] buffer, int length) {
+ try {
+ out.write(buffer, 0, length);
+ } catch (IOException e) {
+ }
+ }
+
+ /**
+ * 非阻塞模式回调
+ *
+ * @author fox
+ */
+ public static interface RuntimeCallback {
+ /**
+ * 非阻塞模式回调函数
+ *
+ * @param result
+ * 命令执行结果
+ * @param startCommand
+ * 起始命令
+ * @param commands
+ * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
+ */
+ public void onExit(StringReader result, String[] envp, File dir, String[] startCommand, String[]... commands);
+ }
+
+ public static void main(String[] args) {
+
+ System.out.println(readStringReader(run(null, null, new String[] { "c:/promtool", "check", "rules", "d:/test.yml" }), false));
+ // 例子 ps -ef (注意用String[]方式来表示命令是不需要做转移的)
+ /*System.out.println(readStringReader(run(null, null, new String[] { "ps", "-ef" }), true));
+ System.out.println("-----------------------------------------------------------------");
+ // 例子 ps -ef | grep -i java
+ System.out.println(readStringReader(
+ run(null, null, new String[] { "ps", "-ef" }, new String[] { "grep", "-i", "java" }), true));*/
+ }
+}
diff --git a/src/main/java/com/nis/util/YamlUtil.java b/src/main/java/com/nis/util/YamlUtil.java
new file mode 100644
index 0000000..ad42363
--- /dev/null
+++ b/src/main/java/com/nis/util/YamlUtil.java
@@ -0,0 +1,156 @@
+package com.nis.util;
+
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.platform.commons.util.StringUtils;
+import org.yaml.snakeyaml.DumperOptions;
+import org.yaml.snakeyaml.Yaml;
+
+import com.alibaba.fastjson.JSON;
+
+
+
+public class YamlUtil {
+
+ private static Yaml y;
+
+ static {
+ DumperOptions options = new DumperOptions();
+ options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
+ y = new Yaml(options);
+ }
+
+ public static boolean subYmlHandle(List param) throws Exception {
+ boolean flag=false;
+ String ymlPath = (String)PropertyPlaceholder.getProperty("ymlPath");
+ if(!param.isEmpty() && StringUtils.isNotBlank(ymlPath)) {
+ File file = new File(ymlPath);
+ FileInputStream fileInputStream = new FileInputStream(file);
+ Map map = y.loadAs(fileInputStream, Map.class);
+ map.put("scrape_configs", param);
+ OutputStream out = new FileOutputStream(file);
+ OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
+ y.dump(map,osw);
+// RuntimeUtil.run(null, null, new String[]{"kill -hup `ps -ef |grep prometheus|grep -v grep|awk '{print $2}'`"});
+ flag = true;
+ }
+ return flag;
+ }
+
+ public static boolean centerYmlHandle(Map param) throws Exception {
+ boolean flag=false;
+ String ymlPath = (String)PropertyPlaceholder.getProperty("ymlPath");
+ if(!param.isEmpty() && StringUtils.isNotBlank(ymlPath)) {
+ File file = new File(ymlPath);
+ FileInputStream fileInputStream = new FileInputStream(file);
+ Map map = y.loadAs(fileInputStream, Map.class);
+ map.put("scrape_configs", param.get("scrape_configs"));
+ map.put("groups", param.get("groups"));
+ map.put("alerting", param.get("alerting"));
+ OutputStream out = new FileOutputStream(file);
+ OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
+ y.dump(map,osw);
+// RuntimeUtil.run(null, null, new String[]{"kill -hup `ps -ef |grep prometheus|grep -v grep|awk '{print $2}'`"});
+ flag = true;
+ }
+ return flag;
+ }
+
+
+ public static void main(String[] args) throws Exception {
+// File file = new File("F:/workspace/nz-web/nz-admin/tmp/promRuleCheck1574925561786.yml");
+ File file = new File("F:/prometheus.yml");
+ FileInputStream fileInputStream = new FileInputStream(file);
+ Map map = y.loadAs(fileInputStream, Map.class);
+
+ /**
+ List l = new ArrayList();
+ Map m1 = new LinkedHashMap();
+ m1.put("job_name", "federate");
+
+
+ m1.put("scrape_interval", "15s");
+ m1.put("honor_labels", true);
+ m1.put("metrics_path", "/federate");
+
+
+ List l2 =new ArrayList();
+ List l3 =new ArrayList();
+ l3.add("192.168.1.1:9090");
+ l3.add("192.168.2.2:9090");
+ Map m2 =new HashMap();
+ m2.put("targets", l3);
+ l2.add(m2);
+ m1.put("static_configs", l2);
+
+ Map m3 = new HashMap();
+ List l4=new ArrayList();
+ l4.add("{job=\"prometheus\"}");
+ l4.add("{__name__=~\"job:.*\"}");
+ m3.put("match[]", l4);
+ m1.put("params", m3);
+
+
+ l.add(m1);
+ map.put("scrape_configs", l);
+ **/
+
+ /*Map toCheck = new HashMap();
+
+ List groups = new ArrayList();
+
+ Map group = new HashMap();
+ groups.add(group);
+
+ List rules = new ArrayList();
+ group.put("name", "example");
+ group.put("rules", rules);
+
+ for(int i=0;i<3;i++) {
+ Map labels = new HashMap();
+ labels.put("severity", "warning");
+ Map annotations = new HashMap();
+ annotations.put("summary", "hhh");
+ annotations.put("description", "1111");
+ Map rule = new HashMap();
+ rule.put("alert", "tttt");
+ rule.put("expr", "up == 0");
+ rule.put("for", "70s");
+ rule.put("labels", labels);
+ rule.put("annotations", annotations);
+ rules.add(rule);
+ }
+ map.put("groups", groups);*/
+
+ Map alertManager =new HashMap();
+ List staticConfigList=new ArrayList();
+ Map staticConfigs =new HashMap();
+ staticConfigList.add(staticConfigs);
+ List staticConfig =new ArrayList();
+ Map targets =new HashMap();
+ List target =new ArrayList();
+ List alertData =new ArrayList();
+ alertData.add("192.168.41.134:8008");
+ alertManager.put("alertmanagers",staticConfigList);
+ staticConfigs.put("static_configs", staticConfig);
+ staticConfig.add(targets);
+ targets.put("targets", alertData);
+ map.put("alerting", alertManager);
+ OutputStream out = new FileOutputStream(file);
+ OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
+ y.dump(map,osw);
+ }
+}
diff --git a/src/main/resources/confagent.properties b/src/main/resources/confagent.properties
new file mode 100644
index 0000000..ea5af50
--- /dev/null
+++ b/src/main/resources/confagent.properties
@@ -0,0 +1,9 @@
+jdbc.driver=com.mysql.jdbc.Driver
+jdbc.url=jdbc:mysql://192.168.40.247:3306/nz?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
+jdbc.username=root
+jdbc.password=111111
+
+ipaddr=192.168.10.15
+ymlPath=F:/prometheus.yml
+prometheusPort=9090
+job.cron=0/30 * * * * ? \ No newline at end of file
diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties
new file mode 100644
index 0000000..f076a1b
--- /dev/null
+++ b/src/main/resources/log4j.properties
@@ -0,0 +1,8 @@
+### #\u914d\u7f6e\u6839Logger ###
+log4j.rootLogger=debug,stdout
+
+### \u8f93\u51fa\u5230\u63a7\u5236\u53f0 ###
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{yyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L - %m%n
diff --git a/src/main/resources/mapper/AlertRuleDao.xml b/src/main/resources/mapper/AlertRuleDao.xml
new file mode 100644
index 0000000..8f1e028
--- /dev/null
+++ b/src/main/resources/mapper/AlertRuleDao.xml
@@ -0,0 +1,19 @@
+<?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.nis.dao.AlertRuleDao">
+ <resultMap type="com.nis.entity.AlertRule" id="alertRule">
+ <result property="id" column="id"/>
+ <result property="alertName" column="alert_name"/>
+ <result property="expr" column="expr"/>
+ <result property="last" column="last"/>
+ <result property="severity" column="severity"/>
+ <result property="summary" column="summary"/>
+ <result property="description" column="description"/>
+ <result property="receiver" column="receiver"/>
+ </resultMap>
+
+ <select id="selectList" resultMap="alertRule">
+ select * from alert_rule
+ </select>
+
+</mapper> \ No newline at end of file
diff --git a/src/main/resources/mapper/ConfEventDao.xml b/src/main/resources/mapper/ConfEventDao.xml
new file mode 100644
index 0000000..c36a444
--- /dev/null
+++ b/src/main/resources/mapper/ConfEventDao.xml
@@ -0,0 +1,9 @@
+<?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.nis.dao.ConfEventDao">
+
+ <select id="selectList" resultType="com.nis.entity.ConfEvent">
+ select * from conf_event
+ </select>
+
+</mapper> \ No newline at end of file
diff --git a/src/main/resources/mapper/EndpointDao.xml b/src/main/resources/mapper/EndpointDao.xml
new file mode 100644
index 0000000..fcd868f
--- /dev/null
+++ b/src/main/resources/mapper/EndpointDao.xml
@@ -0,0 +1,39 @@
+<?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.nis.dao.EndpointDao">
+ <resultMap type="com.nis.entity.Endpoint" id="endpoint">
+ <result property="id" column="id"/>
+ <result property="moduleId" column="module_id"/>
+ <result property="assetId" column="asset_id"/>
+ <result property="host" column="host"/>
+ <result property="port" column="port"/>
+ <result property="param" column="param"/>
+ <result property="path" column="path"/>
+
+ <association columnPrefix="m_" property="module" javaType="com.nis.entity.Module">
+ <id column="module_id" property="id"/>
+ <result column="name" property="name"/>
+ <result column="remark" property="remark"/>
+ <result column="project_id" property="projectId"/>
+ <result column="port" property="port"/>
+ <result column="param" property="param"/>
+ <result column="path" property="path"/>
+ </association>
+ </resultMap>
+
+ <select id="selectExporterInfos" resultMap="endpoint">
+ select e.*,
+ m.id AS m_module_id,
+ m.project_id AS m_project_id,
+ m.name AS m_name,
+ m.port AS m_port,
+ m.param AS m_param,
+ m.path AS m_path,
+ m.remark AS m_remark
+ from
+ endpoint e left join asset a on e.asset_id=a.id
+ left join module m on e.module_id = m.id
+ where a.idc_id=#{idcId}
+ </select>
+
+</mapper> \ No newline at end of file
diff --git a/src/main/resources/mapper/PromserverDao.xml b/src/main/resources/mapper/PromserverDao.xml
new file mode 100644
index 0000000..3fcb02a
--- /dev/null
+++ b/src/main/resources/mapper/PromserverDao.xml
@@ -0,0 +1,27 @@
+<?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.nis.dao.PromserverDao">
+ <resultMap type="com.nis.entity.Promserver" id="promserver">
+ <result property="id" column="id"/>
+ <result property="idcId" column="idc_id"/>
+ <result property="host" column="host"/>
+ <result property="relabel" column="relabel"/>
+ <result property="type" column="type"/>
+ </resultMap>
+
+ <select id="selectList" resultMap="promserver">
+ select * from prom_server
+ </select>
+
+ <select id="selectRoleByIp" resultMap="promserver">
+ select * from prom_server where host=#{ip}
+ </select>
+
+ <select id="selectSubInfo" resultMap="promserver">
+ select * from prom_server where idc_id=#{promserver.idcId} and type=#{promserver.type} order by id asc
+ </select>
+
+ <select id="selectSubInfosByType" resultMap="promserver">
+ select * from prom_server where type=#{type}
+ </select>
+</mapper> \ No newline at end of file
diff --git a/src/main/resources/mapper/SysConfigDao.xml b/src/main/resources/mapper/SysConfigDao.xml
new file mode 100644
index 0000000..4b92e6b
--- /dev/null
+++ b/src/main/resources/mapper/SysConfigDao.xml
@@ -0,0 +1,16 @@
+<?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.nis.dao.SysConfigDao">
+ <resultMap type="com.nis.entity.SysConfig" id="sysConfig">
+ <result property="id" column="id"/>
+ <result property="paramKey" column="param_key"/>
+ <result property="paramValue" column="param_value"/>
+ <result property="status" column="status"/>
+ <result property="remark" column="remark"/>
+ </resultMap>
+
+ <select id="selectList" resultMap="sysConfig">
+ select * from sys_config where status=1
+ </select>
+
+</mapper> \ No newline at end of file
diff --git a/src/main/resources/spring.xml b/src/main/resources/spring.xml
new file mode 100644
index 0000000..6fe2c2d
--- /dev/null
+++ b/src/main/resources/spring.xml
@@ -0,0 +1,142 @@
+<?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:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
+ xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
+ http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
+ http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
+ http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
+ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
+ http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
+ http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd"
+ default-lazy-init="true">
+
+ <description>Spring Configuration</description>
+
+ <!-- 加载配置属性文件 -->
+ <context:property-placeholder location="classpath*:confagent.properties" />
+
+ <bean id="propertyConfigurer" class="com.nis.util.PropertyPlaceholder">
+ <property name="location">
+ <value>classpath:confagent.properties</value>
+ </property>
+ </bean>
+
+
+ <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 -->
+ <context:component-scan base-package="com.nis"><!-- base-package 如果多个,用“,”分隔 -->
+ <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
+ </context:component-scan>
+
+ <!-- MyBatis begin -->
+ <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
+ <property name="dataSource" ref="dataSource"/>
+ <property name="typeAliasesPackage" value="com.nis.entity"/>
+ <property name="mapperLocations" value="classpath:/mapper/*.xml"/>
+ <!-- <property name="configLocation" value="classpath:/mybatis-config.xml"></property> -->
+ </bean>
+
+ <!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->
+ <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
+ <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
+ <property name="basePackage" value="com.nis.dao"/>
+ <!-- <property name="annotationClass" value="com.nis.common.persistence.annotation.MyBatisDao"/> -->
+ </bean>
+
+ <!-- 定义事务 -->
+ <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
+ <property name="dataSource" ref="dataSource" />
+ </bean>
+
+ <!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 -->
+ <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
+ <!-- MyBatis end -->
+
+ <!-- 配置 JSR303 Bean Validator 定义 -->
+ <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
+
+ <!-- 计划任务配置,用 @Service @Lazy(false)标注类,用@Scheduled(cron = "0 0 2 * * ?")标注方法 -->
+ <task:executor id="executor" pool-size="10"/>
+ <task:scheduler id="scheduler" pool-size="10"/>
+ <task:annotation-driven scheduler="scheduler" executor="executor" proxy-target-class="true"/>
+
+ <!-- 数据源配置, 使用 BoneCP 数据库连接池 -->
+ <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
+ <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
+ <property name="driverClassName" value="${jdbc.driver}" />
+
+ <!-- 基本属性 url、user、password -->
+ <property name="url" value="${jdbc.url}" />
+ <property name="username" value="${jdbc.username}" />
+ <property name="password" value="${jdbc.password}" />
+
+ <!-- 配置初始化大小、最小、最大-->
+ <property name="initialSize" value="5" />
+ <property name="minIdle" value="5" />
+ <property name="maxActive" value="10" />
+
+ <!-- 配置获取连接等待超时的时间 -->
+ <property name="maxWait" value="15000" />
+
+ <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
+ <property name="timeBetweenEvictionRunsMillis" value="60000" />
+
+ <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
+ <property name="minEvictableIdleTimeMillis" value="300000" />
+
+ <!-- <property name="validationQuery" value="${jdbc.testSql}" /> -->
+ <property name="testWhileIdle" value="true" />
+ <property name="testOnBorrow" value="false" />
+ <property name="testOnReturn" value="false" />
+
+ <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用)
+ <property name="poolPreparedStatements" value="true" />
+ <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> -->
+
+ <!-- 配置监控统计拦截的filters -->
+ <property name="filters" value="stat" />
+ </bean>
+
+ <!-- <bean id="jobFactory" class="com.nis.job.ConfagentJobFactory"/>
+
+ <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
+ <property name="jobFactory" ref="jobFactory"/>
+ </bean> -->
+
+ <bean id="jobFactory" class="com.nis.job.ConfagentJobFactory"/>
+
+
+ <!-- 配置Job类 -->
+ <bean id="myJob" class="com.nis.job.ConfagentJob"></bean>
+
+ <!-- 配置JobDetail -->
+ <bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
+ <!-- 执行目标job -->
+ <property name="targetObject" ref="myJob"></property>
+ <property name="concurrent" value="false" />
+ <!-- 要执行的方法 -->
+ <property name="targetMethod" value="execute"></property>
+ </bean>
+
+ <!-- 配置tirgger触发器 -->
+ <bean id="cronTriggerFactoryBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
+ <!-- jobDetail -->
+ <property name="jobDetail" ref="jobDetail"></property>
+ <!-- cron表达式,执行时间 每5秒执行一次 -->
+ <property name="cronExpression" value="${job.cron}"></property>
+ </bean>
+
+ <!-- 配置调度工厂 -->
+ <bean id="springJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
+ <property name="jobFactory" ref="jobFactory"/>
+ <property name="triggers">
+ <list>
+ <ref bean="cronTriggerFactoryBean"></ref>
+ </list>
+ </property>
+
+ </bean>
+
+
+</beans> \ No newline at end of file