Alertmanager+企业微信警报安装配置

废话不多说,直接上步骤:
 
1.下载 alertmanager-0.14.0.linux-amd64.tar.gz 到 、opt/minitor/alertmanager,不下载最新版是因为最新版(0.15.0)微信发送有推迟。
    
 
2.运行 tar -zxvf alertmanager-0.14.0.linux-amd64.tar.gz ,解压到当前目录。
 
3.在企业微信中创建应用

 

 

 

 

 
 
4.执行 vim /opt/minitor/prometheus/prometheus.yml,添加一下配置文件(红色部分):
# my global config
global:
  scrape_interval:     5s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 5s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).
 
# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
      - targets: ['192.168.6.54:9093']
 
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  - "/opt/prometheus/prome/prometheus-2.0.0.linux-amd64/rules/rules.yml" 
 
5.执行 vim /opt/minitor/prometheus/rules/rules.yml,添加一下内容:
groups:
- name: prometheus_go_goroutines
  rules:
  - alert: go_goroutines_numbers
    expr: go_goroutines > 10
    for: 5s
    annotations:
      summary: "服务器挂了!"
- name: node
  rules:
  - alert: server_status
    expr: up{job="linux"} == 0
    for: 5s
    annotations:
      summary: "机器linux挂了"
      description: "报告.请立即查看!" 
 
6.执行 vim /opt/minitor/alertmanager/alertmanager.yml,添加一下内容(具体参数含义参照上面的网址):
global:
  resolve_timeout: 5s
  wechat_api_url: 'https://qyapi.weixin.qq.com/cgi-bin/'
  wechat_api_secret: "HpwKB8OFO7QE6gBZyfdbk7ocJ3yT7BOEfKWSmvLC4cQ"
  wechat_api_corp_id: 'ww0846e90807ede753'
templates:
  - '/opt/prometheus/alert/alertmanager-0.14.0.linux-amd64/wechat.tmpl'
route:
  group_by: ['alertname']
  group_wait: 1s
  group_interval: 1s
  repeat_interval: 5s
  receiver: 'wechat'
receivers:
  - name: 'wechat'
    wechat_configs:
    - send_resolved: true
     # to_party: '1'
      to_user: '@all'
      agent_id: 1000006
      corp_id: 'ww0846e90807ede753'
      api_url: 'https://qyapi.weixin.qq.com/cgi-bin/'
      api_secret: "HpwKB8OFO7QE6gBZyfdbk7ocJ3yT7BOEfKWSmvLC4cQ"
      message: '{{ template "wechat.tmpl" . }}'
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']
 
7.执行 vim /opt/minitor/alertmanager/wechat.tmpl
{{ define "wechat.tmpl" }}
  {{ range $i, $alert := .Alerts.Firing }}
    [报警项]:{{ index $alert.Labels "alertname" }}
    [实例]:{{ index $alert.Labels "instance" }}
    [job]:{{ index $alert.Labels "job" }}
    [报警内容]:{{ index $alert.Annotations "summary" }}
    [开始时间]:{{ $alert.StartsAt.Format "2006-01-02 15:04:05" }}
  {{ end }}
{{ end }}
 
8.运行prometheus。
 
9.运行一下命令运行alertmanager.
nohup ./alertmanager --config.file=alertmanager.yml --web.listen-address=:9093 &
 
10.可能遇见的问题:
  10.1服务器dns配置有问题。通过查看服务器网管等方案解决,简单查看linux是否能访问外网及拥有的公网IP
1,测访问外网能力:curl -l http://www.baidu.com
2,测访问外网能力:wget http://www.baidu.com
3,查看公网IP:curl members.3322.org/dyndns/getip
注:ping命令不一定能正确反映系统的网络能力
  10.2 企业微信问题,通过以下程序测试是否联通(篇幅问题,代码进行折叠,如有需要,请打开查看)
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;


/**
 * 微信发送消息
 * @author zhangmingliang
 */
public class WeChatMsgSend {
    private CloseableHttpClient httpClient;
    /**
     *  用于提交登陆数据
     */
    private HttpPost httpPost;
    /**
     *  用于获得登录后的页面
     */
    private HttpGet httpGet;


    public static final String CONTENT_TYPE = "Content-Type";


    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private static Gson gson = new Gson();


    /**
     * 微信授权请求,GET类型,获取授权响应,用于其他方法截取token
     * @param Get_Token_Url
     * @return String 授权响应内容
     * @throws IOException
     */
    protected String toAuth(String Get_Token_Url) throws IOException {


        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet(Get_Token_Url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
        return resp;
    }


    /**corpid应用组织编号   corpsecret应用秘钥
     * 获取toAuth(String Get_Token_Url)返回结果中键值对中access_token键的值
     * @param
     */
    public  String getToken(String corpid,String corpsecret) throws IOException {
        WeChatMsgSend sw = new WeChatMsgSend();
        WeChatUrlData uData = new WeChatUrlData();
        uData.setGet_Token_Url(corpid,corpsecret);
        String resp = sw.toAuth(uData.getGet_Token_Url());
        System.out.println("resp=====:"+resp);
        try{
        Map<String, Object> map = gson.fromJson(resp,new TypeToken<Map<String, Object>>() {}.getType());
            return map.get("access_token").toString();
        }catch (Exception e) {
        return resp;
}
    }
    /**
     * @Title:创建微信发送请求post数据
     * touser发送消息接收者    ,msgtype消息类型(文本/图片等),
     * application_id应用编号。
     * 本方法适用于text型微信消息,contentKey和contentValue只能组一对
     * @return String
     */
    public String createpostdata(String touser, String msgtype,
                                    int application_id, String contentKey ,String contentValue) {
        WeChatData wcd = new WeChatData();
        wcd.setTouser(touser);
        wcd.setAgentid(application_id);
        wcd.setMsgtype(msgtype);
        Map<Object, Object> content = new HashMap<Object, Object>();
        content.put(contentKey,contentValue);
        wcd.setText(content);
        return gson.toJson(wcd);
    }


    /**
     * @Title  创建微信发送请求post实体
     * charset消息编码    ,contentType消息体内容类型,
     * url微信消息发送请求地址,data为post数据,token鉴权token
     * @return String
     */
    public String post(String charset, String contentType, String url,
                       String data,String token) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httpPost = new HttpPost(url+token);
        httpPost.setHeader(CONTENT_TYPE, contentType);
        httpPost.setEntity(new StringEntity(data, charset));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
        return resp;
    }


}
WeChatMsgSend
import java.io.IOException;
public class Test {
    public static void main(String[] args) {
        WeChatMsgSend swx = new WeChatMsgSend();
        try {
            String token = swx.getToken("wwb984739233e461db","siyYqsKH6GEsa4umSPwzw3IQf3WMkJcCctn5_A51ZZc");
            String postdata = swx.createpostdata("HeiSeManDuoLa", "text", 1000002, "content","This alert Email come from IapppayBJQA");
            String resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE,(new WeChatUrlData()).getSendMessage_Url(), postdata, token);
            System.out.println("获取到的token======>" + token);
            System.out.println("请求数据======>" + postdata);
            System.out.println("发送微信的响应数据======>" + resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Test
public class WeChatData {
    //发送微信消息的URLString sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    /**
     * 成员账号
     */
    private String touser;
    /**
     * 消息类型
     */
    private String msgtype;
    /**
     * 企业应用的agentID
     */
    private int agentid;
    /**
     * 实际接收Map类型数据
     */
    private Object text;
    public Object getText() {
        return text;
    }
    public void setText(Object text) {
        this.text = text;
    }
    public String getMsgtype() {
        return msgtype;
    }
    public void setMsgtype(String msgtype) {
        this.msgtype = msgtype;
    }
    public int getAgentid() {
        return agentid;
    }
    public void setAgentid(int agentid) {
        this.agentid = agentid;
    }
    public String getTouser() {
        return touser;
    }
    public void setTouser(String touser) {
        this.touser = touser;
    }
}
WeChatData
/**
 * 微信授权请求
 * @author zhangmingliang
 */
public class WeChatUrlData {
    /**
     *  企业Id
     */
    private String corpid;
    /**
     * secret管理组的凭证密钥
     */
    private String corpsecret;
    /**
     * 获取ToKen的请求
     */
    private String Get_Token_Url;
    /**
     * 发送消息的请求
     */
    private String SendMessage_Url;
    public String getCorpid() {
        return corpid;
    }
    public void setCorpid(String corpid) {
        this.corpid = corpid;
    }
    public String getCorpsecret() {
        return corpsecret;
    }
    public void setCorpsecret(String corpsecret) {
        this.corpsecret = corpsecret;
    }
    public void setGet_Token_Url(String corpid,String corpsecret) {
        this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
    }
    public String getGet_Token_Url() {
        return Get_Token_Url;
    }
    public String getSendMessage_Url(){
        SendMessage_Url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
        return SendMessage_Url;
    }
}
WeChatUrlData

 

posted @ 2020-11-09 23:14  Fire♪一度  阅读(603)  评论(0编辑  收藏  举报