#!/usr/bin/env python
# -*- coding: utf8 -*-
import socket,re
from prometheus_client import generate_latest, Gauge,Info
from prometheus_client.core import CollectorRegistry
from psutil import virtual_memory
from psutil import cpu_times def check_port(ip, port):
'''socket检测端口连通性'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
try:
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False REGISTRY = CollectorRegistry(auto_describe=False)
allportdata = [{'ip':'xxx.xxx.xxx.xxx','port':22},{'ip':'yyy.yyy.yyy.yyy','port':22},{'ip':'zzz.zzz.zzz.zzz','port':22}]
mem_percent = Gauge(
"system_memory_percent",
"Total system memory percent.",
registry=REGISTRY)
cpu_per = Gauge(
"system_cpu_percent",
"Total system cpu percent.",
registry=REGISTRY) mem_percent.set(virtual_memory().percent)
cpu_per.set(cpu_times().system) METRIC_NAME_RE = re.compile(r'^[a-zA-Z_:][a-zA-Z0-9_:]*$') name = 'ip_port_conn_status'
documentation = "IP PORT SOCKET CONNECT STATUS."
portcheck = Gauge(name=name, documentation=documentation, labelnames=('ip', 'port'), registry=REGISTRY) for i in allportdata:
status = check_port(i['ip'], i['port'])
portcheck.labels(i['ip'], i['port']).inc(status)
result = generate_latest(REGISTRY).decode()
print(result)

Python prometheus-client 安装

pip install prometheus-client

Python封装

# encoding: utf-8
from prometheus_client import Counter, Gauge, Summary
from prometheus_client.core import CollectorRegistry
from prometheus_client.exposition import choose_encoder class Monitor:
def __init__(self):
# 注册收集器&最大耗时map
self.collector_registry = CollectorRegistry(auto_describe=False)
self.request_time_max_map = {} # 接口调用summary统计
self.http_request_summary = Summary(name="http_server_requests_seconds",
documentation="Num of request time summary",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 接口最大耗时统计
self.http_request_max_cost = Gauge(name="http_server_requests_seconds_max",
documentation="Number of request max cost",
labelnames=("method", "code", "uri"),
registry=self.collector_registry) # 请求失败次数统计
self.http_request_fail_count = Counter(name="http_server_requests_error",
documentation="Times of request fail in total",
labelnames=("method", "code", "uri"),
registry=self.collector_registry) # 模型预测耗时统计
self.http_request_predict_cost = Counter(name="http_server_requests_seconds_predict",
documentation="Seconds of prediction cost in total",
labelnames=("method", "code", "uri"),
registry=self.collector_registry)
# 图片下载耗时统计
self.http_request_download_cost = Counter(name="http_server_requests_seconds_download",
documentation="Seconds of download cost in total",
labelnames=("method", "code", "uri"),
registry=self.collector_registry) # 获取/metrics结果
def get_prometheus_metrics_info(self, handler):
encoder, content_type = choose_encoder(handler.request.headers.get('accept'))
handler.set_header("Content-Type", content_type)
handler.write(encoder(self.collector_registry))
self.reset_request_time_max_map() # summary统计
def set_prometheus_request_summary(self, handler):
self.http_request_summary.labels(handler.request.method, handler.get_status(), handler.request.path).observe(handler.request.request_time())
self.set_prometheus_request_max_cost(handler) # 自定义summary统计
def set_prometheus_request_summary_customize(self, method, status, path, cost_time):
self.http_request_summary.labels(method, status, path).observe(cost_time)
self.set_prometheus_request_max_cost_customize(method, status, path, cost_time) # 失败统计
def set_prometheus_request_fail_count(self, handler, amount=1.0):
self.http_request_fail_count.labels(handler.request.method, handler.get_status(), handler.request.path).inc(amount) # 自定义失败统计
def set_prometheus_request_fail_count_customize(self, method, status, path, amount=1.0):
self.http_request_fail_count.labels(method, status, path).inc(amount) # 最大耗时统计
def set_prometheus_request_max_cost(self, handler):
requset_cost = handler.request.request_time()
if self.check_request_time_max_map(handler.request.path, requset_cost):
self.http_request_max_cost.labels(handler.request.method, handler.get_status(), handler.request.path).set(requset_cost)
self.request_time_max_map[handler.request.path] = requset_cost # 自定义最大耗时统计
def set_prometheus_request_max_cost_customize(self, method, status, path, cost_time):
if self.check_request_time_max_map(path, cost_time):
self.http_request_max_cost.labels(method, status, path).set(cost_time)
self.request_time_max_map[path] = cost_time # 预测耗时统计
def set_prometheus_request_predict_cost(self, handler, amount=1.0):
self.http_request_predict_cost.labels(handler.request.method, handler.get_status(), handler.request.path).inc(amount) # 自定义预测耗时统计
def set_prometheus_request_predict_cost_customize(self, method, status, path, cost_time):
self.http_request_predict_cost.labels(method, status, path).inc(cost_time) # 下载耗时统计
def set_prometheus_request_download_cost(self, handler, amount=1.0):
self.http_request_download_cost.labels(handler.request.method, handler.get_status(), handler.request.path).inc(amount) # 自定义下载耗时统计
def set_prometheus_request_download_cost_customize(self, method, status, path, cost_time):
self.http_request_download_cost.labels(method, status, path).inc(cost_time) # 校验是否赋值最大耗时map
def check_request_time_max_map(self, uri, cost):
if uri not in self.request_time_max_map:
return True
if self.request_time_max_map[uri] < cost:
return True
return False # 重置最大耗时map
def reset_request_time_max_map(self):
for key in self.request_time_max_map:
self.request_time_max_map[key] = 0.0

调用

import tornado
import tornado.ioloop
import tornado.web
import tornado.gen
from datetime import datetime
from tools.monitor import Monitor global g_monitor class ClassifierHandler(tornado.web.RequestHandler):
def post(self):
# TODO Something you need
# work....
# 统计Summary,包括请求次数和每次耗时
g_monitor.set_prometheus_request_summary(self)
self.write("OK") class PingHandler(tornado.web.RequestHandler):
def head(self):
print('INFO', datetime.now(), "/ping Head.")
g_monitor.set_prometheus_request_summary(self)
self.write("OK") def get(self):
print('INFO', datetime.now(), "/ping Get.")
g_monitor.set_prometheus_request_summary(self)
self.write("OK") class MetricsHandler(tornado.web.RequestHandler):
def get(self):
print('INFO', datetime.now(), "/metrics Get.")
g_monitor.set_prometheus_request_summary(self)
# 通过Metrics接口返回统计结果
g_monitor.get_prometheus_metrics_info(self) def make_app():
return tornado.web.Application([
(r"/ping?", PingHandler),
(r"/metrics?", MetricsHandler),
(r"/work?", ClassifierHandler)
]) if __name__ == "__main__":
g_monitor = Monitor() app = make_app()
app.listen(port)
tornado.ioloop.IOLoop.current().start()

Metrics返回结果实例

Python prometheus_client使用方式的更多相关文章

  1. [修]python普通继承方式和super继承方式

    [转]python普通继承方式和super继承方式 原文出自:http://www.360doc.com/content/13/0306/15/9934052_269664772.shtml 原文的错 ...

  2. 【转】python 退出程序的方式

    [转]python 退出程序的方式 python程序退出方式[sys.exit() os._exit() os.kill() os.popen(...)] 知乎说明 http://www.zhihu. ...

  3. 理解 Python 的执行方式,与字节码 bytecode 玩耍 (上)

    这里有个博客讲 Python 内部机制,已经有一些中文翻译. 可能因为我用的Python 3.5,例子跑起来有些不一样. 此外,我又查了其他一些参考资料,总结如下: Python 的执行方式 先看一个 ...

  4. 理解 Python 的执行方式,与字节码 bytecode 玩耍 (下)

    上次写到,Python 的执行方式是把代码编译成bytecode(字节码)指令,然后由虚拟机来执行这些 bytecode 而 bytecode 长成这个样子:  b'|\x00\x00d\x01\x0 ...

  5. [Spark][python]以DataFrame方式打开Json文件的例子

    [Spark][python]以DataFrame方式打开Json文件的例子: [training@localhost ~]$ cat people.json{"name":&qu ...

  6. python 退出程序的方式

    python程序退出方式[sys.exit() os._exit() os.kill() os.popen(...)] 知乎说明 http://www.zhihu.com/question/21187 ...

  7. Python模块调用方式详解

    Python模块调用方式详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其 ...

  8. python通过get方式,post方式发送http请求和接收http响应-urllib urllib2

    python通过get方式,post方式发送http请求和接收http响应-- import urllib模块,urllib2模块, httplib模块 http://blog.163.com/xyc ...

  9. 大华摄像头报警接口中图片加密,python调用c++方式实现解密

    项目中,大华摄像头的报警信息,里面有图片地址,需要1天内取下来,保持留痕 可惜,图片下载后,加密了,大华提供了android,ios,c++例子,没有提供java解密例子 没办法,只好先用c++例子简 ...

  10. [原]Python Web部署方式总结

    不要让服务器裸奔 学过PHP的都了解,php的正式环境部署非常简单,改几个文件就OK,用FastCgi方式也是分分钟的事情.相比起来,Python在web应用上的部署就繁杂的多,主要是工具繁多,主流服 ...

随机推荐

  1. Web刷题之polarctf靶场(1)

    PolarCTF 1.XFF 打开靶场发现需要ip为1.1.1.1的用户才行, 打开BurpSuite进行抓包并对数据包进行修改,根据题目XFF提示 flag{847ac5dd4057b1ece411 ...

  2. SpringBoot定时任务实现数据同步

    业务的需求是,通过中台调用api接口获得,设备数据,要求现实设备数据的同步. 方案一:通过轮询接口的方式执行 pullData() 方法实现数据同步 该方式的原理是先清空之前的所有数据,然后重新插入通 ...

  3. Logstash 配置Java日志格式的方法

    Logstash 是用于日志收集的开源工具,通常与 Elasticsearch 和 Kibana 一起使用,形成 ELK Stack(现在称为 Elastic Stack).Logstash 非常灵活 ...

  4. .NET 开源的功能强大的人脸识别 API

    前言 人工智能时代,人脸识别技术已成为安全验证.身份识别和用户交互的关键工具. 给大家推荐一款.NET 开源提供了强大的人脸识别 API,工具不仅易于集成,还具备高效处理能力. 本文将介绍一款如何利用 ...

  5. [TK] 理想的正方形

    题目描述 有一个整数组成的矩阵,现请你从中找出一个指定边长的正方形区域,使得该区域所有数中的最大值和最小值的差最小. 题目分析 其实这道题和滑动窗口很像,而滑动窗口使用优先队列解决. 我们都知道优先队 ...

  6. springboot 基本配置文件

    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/game?useUnicode=true&zeroDateTimeBehavior=conv ...

  7. 【赵渝强老师】Redis的RDB持久化

    Redis 提供了多种不同级别的持久化方式: RDB 持久化可以在指定的时间间隔内生成数据集的时间点快照(point-in-time snapshot). AOF (Append-only file) ...

  8. kali Linux 安装 AWVS 笔记

    安装 AWVS 笔记 配置安装 https://www.zwnblog.com/archives/kali-an-zhuang-awvs 根据这篇文章 配置并安装出来的 设定的账号和密码 账号:adm ...

  9. day14-Scanner

    Scanner对象 之前我们学的基本语法中我们并没有实现程序和人的交互,但是Java给我们提供了这样一个工具类,我们可以获取用户的输入.Java.util.Scanner是Java5的新特征,我们可以 ...

  10. 云原生周刊:Cilium v1.16.0 发布|20240729

    开源项目 Cyclops Cyclops 是一个开源的开发工具,通过易于使用的用户界面简化了 Kubernetes,使其更易上手.不再需要使用 YAML 创建和配置 Kubernetes 清单,可以使 ...