研究了一下prometheus 使用consul的服务发现做监控,每次都是手动去注册服务,感觉很low,脚本整起来测试了一下基本可用,留着备用。
consul service相关的api参考:
https://www.consul.io/api/agent/service.html
https://my.oschina.net/guol/blog/353394
#!/bin/bash #usage: #param1:check_service or register_service or deregister_service #param2: an exist file,and the file content format is as follows,pay attention to remove the first # #group_name cluster_name redis_ip redis_port #注册服务 function register_service() { cat $1 | while read line do group_name=$(echo $line | awk '{print $1}') cluster_name=$(echo $line | awk '{print $2}') redis_ip=$(echo $line | awk '{print $3}') redis_port=$(echo $line | awk '{print $4}') let service_port=redis_port+10000 cat >redis-$redis_ip-$service_port.json<<EOF { "id":"redis-${redis_ip}-${service_port}", "name":"redis-${redis_ip}-${service_port}", "address":"${redis_ip}", "port":${service_port}, "tags":["redis-exporter"], "meta":{"group":"$group_name","cluster":"$cluster_name","redis_instance":"$redis_ip:$redis_port"}, "checks":[{ "http":"http://${redis_ip}:${service_port}/metrics", "interval":"5s" }], "Weights": { "Passing": 10, "Warning": 1 }, "EnableTagOverride": false } EOF curl --request PUT --data @redis-$redis_ip-$service_port.json http://${consul_host}:${consul_http_api_port}/v1/agent/service/register?replace-existing-checks=1 rm -rf redis-$redis_ip-$service_port.json done } #注销服务 function deregister_service() { cat $1 | while read line do redis_ip=$(echo $line | awk '{print $3}') redis_port=$(echo $line | awk '{print $4}') let service_port=redis_port+10000 consul_service_id="redis-$redis_ip-$service_port" curl --request PUT http://${consul_host}:${consul_http_api_port}/v1/agent/service/deregister/${consul_service_id} done } #检查服务 check_service() { cat $1 | while read line do redis_ip=$(echo $line | awk '{print $3}') redis_port=$(echo $line | awk '{print $4}') let service_port=redis_port+10000 consul_service_id="redis-$redis_ip-$service_port" ret1=$(curl -s http://${consul_host}:${consul_http_api_port}/v1/agent/service/$consul_service_id?pretty) if [[ $ret1 =~ "unknown proxy service ID" ]];then echo "不存在服务$consul_service_id" else ret2=$(curl -s http://${consul_host}:${consul_http_api_port}/v1/health/service/redis-$redis_ip-$service_port?pretty | grep "$redis_ip:$service_port/metrics: 200 OK") if [[ -z "$ret2" ]];then echo -e " 33[5;34m服务$consul_service_id已注册,但服务状态异常 <--- 33[0m" else echo "服务$consul_service_id已注册,且服务状态正常" fi fi done } function main() { if [[ $# -ne 2 ]];then echo -e "must two parameters: first exec_command(check_service or register_service or deregister_service) second filename" exit else case $1 in check_service) shift 1 check_service $1 ;; register_service) shift 1 register_service $1 ;; deregister_service) shift 1 deregister_service $1 ;; *) echo "无效的指令" esac fi } consul_host="192.168.68.60" consul_http_api_port=8500 main $1 $2