上文介绍了Alertmanager集成钉钉,我们还可以自己写一个webhook,用于接收Alertmanager的通知服务。
获取Alertmanager的请求内容
参考前文,我们知道Alertmanager会向配置的webhook地址发送一个POST请求,这里我们先编写一个简单的controller,用于接收Alertmanager的请求,如下:
@RequestMapping("/test")
public void watcher(HttpServletRequest request) throws IOException {
System.out.println(request.getMethod());
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String str = "";
String wholeStr = "";
while ((str = reader.readLine()) != null) {
wholeStr += str;
}
System.out.println("body:" + wholeStr);
}
写好上面的服务之后,修改Alertmanager中webhook地址,然后将上面打印的body分析分析。如下:
{
"receiver":"webhook_alert",
"status":"resolved",
"alerts":[
{
"status":"resolved",
"labels":{
"alertname":"curl test",
"severity":"warning"
},
"annotations":{
"description":"this is a test alert from curl",
"summary":"test alert from curl"
},
"startsAt":"2019-12-03T03:22:50.430372292Z",
"endsAt":"2019-12-03T03:26:50.430372292Z",
"generatorURL":"",
"fingerprint":"960077177807fca5"
}
],
"groupLabels":{
"alertname":"curl test"
},
"commonLabels":{
"alertname":"curl test",
"severity":"warning"
},
"commonAnnotations":{
"description":"this is a test alert from curl",
"summary":"test alert from curl"
},
"externalURL":"http://alertmanager-prometheus-operator-alertmanager-test-0:9093",
"version":"4",
"groupKey":"{}/{severity="warning"}:{alertname="curl test"}"
}
所有接收到的请求内容格式基本不变,标准的JSON格式
,我们编写一个实体类
用于接收。
编写实体类
编写内层实体类Alert.java
/**
* @ClassName: Alert
* @Description: TODO
* @Author: wuzhiyong
* @Time: 2019/12/3 11:39
* @Version: v1.0
**/
@Data
public class Alert {
/**
* 状态:firing / resolved
*/
private String status;
/**
* 标签
*/
private Map<String, String> labels;
/**
* 携带的其它信息
*/
private Map<String, String> annotations;
/**
* 开始时间
*/
private String startsAt;
private String endsAt;
/**
* 产生的alertmanager信息
*/
private String generatorURL;
private String fingerprint;
public Alert() {
}
}
编写外层实体类Alerts.java
/**
* @ClassName: Alerts
* @Description: Alertmanager发出的告警格式
* @Author: wuzhiyong
* @Time: 2019/12/3 11:49
* @Version: v1.0
**/
@Data
public class Alerts {
private String externalURL;
private String version;
private String groupKey;
private String receiver;
private String status;
private List<Alert> alerts;
private Map<String, String> groupLabels;
private Map<String, String> commonLabels;
private Map<String, String> commonAnnotations;
public Alerts() {
}
}
编写webhook
@RequestMapping(value = "/receive", method = RequestMethod.POST)
void receive(@RequestBody Alerts alerts) {
log.info("new alert: {}",alerts.getCommonLabels().get("alertname"));
}
上面接收到Alert manager
的请求,只是打印了alert name
的日志,我们可以根据接收到告警,做更多的事。
可以根据自身业务自行发挥。