需求:监控某个页面的 SSL 和 TCP 握手耗时
使用 python + Flask + prometheus api 完成
注意脚本中的域名是写死的
# cat /data/prometheus_dir/nginx_ssl_check/nginx-ssl-check.py
import os
import re
import prometheus_client
from prometheus_client import Gauge, CollectorRegistry
from flask import Response, Flask
app = Flask(__name__)
REGISTRY = CollectorRegistry()
TCP = Gauge('TCP_handshake', 'TCP_handshake', registry=REGISTRY)
SSL = Gauge('SSL_handshake', 'SSL_handshake', registry=REGISTRY)
@app.route("/metrics")
def ssl_handshake():
num = os.popen('curl -w "TCP handshake: %{time_connect}, SSL handshake: %{time_appconnect}\n" -so /dev/null https://www.baidu.com/').read()
print(num)
SSL_handshake = re.findall(r"\d+.?\d*", num)
TCP_handshake = re.findall(r"\d+.?\d*", num)
print(TCP_handshake, SSL_handshake)
f_SSL = float(SSL_handshake[1])
f_TCP = float(TCP_handshake[0])
print(f_TCP, f_SSL)
SSL.set(f_SSL)
TCP.set(f_TCP)
return Response(prometheus_client.generate_latest(REGISTRY), mimetype="text/plain")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=10001)
docker方式托管
# cat Dockerfile
FROM python:3.9.13
RUN /usr/local/bin/python -m pip install --upgrade pip
RUN pip3 install prometheus_client
RUN pip3 install flask
CMD python3 /data/nginx-ssl-check.py
启动
注意挂载的py文件中域名要和指定的hosts域名一致
docker run -d \
-p 10001:10001 \
--name nginx-ssl-check-172.30.0.50 \
--restart=always \
--restart=on-failure:5 \
--add-host www.baidu.com:172.30.0.50 \
-v /data/prometheus_dir/nginx_ssl_check/nginx-ssl-check.py:/data/nginx-ssl-check.py \
promehtues_flask_py:v1
因为一般生产环境都是高可用配置,也就是一个域名解析到了多个nginx,所以要想监控单台服务器的ssl握手,就需要指定hosts,所以使用docker启动并绑定housts
访问
http://127.0.0.1:10001/metrics
结果
# HELP TCP_handshake TCP_handshake # TYPE TCP_handshake gauge TCP_handshake 0.041622 # HELP SSL_handshake SSL_handshake # TYPE SSL_handshake gauge SSL_handshake 0.135754