Pythond 是定时触发用户自定义 Python 采集脚本的一整套方案。本文以 “获取每个小时登录的用户数”作为指标上报给中心为例。

1.1. 业务演示介绍

业务流程大致如下: 从数据库中采集数据 (Python 脚本) -> pythond 采集器定时触发该脚本上报数据(datakit) -> 从中心可看到指标(web)。

数据库现在有一张表叫 customers, 表中有如下字段:

  • name: 姓名 (字符串)
  • last_logined_time : 登录时间 (时间戳)

建表语句如下:

  1. create table customers
  2. (
  3. `id` BIGINT(20) not null AUTO_INCREMENT COMMENT '自增 ID',
  4. `last_logined_time` BIGINT(20) not null DEFAULT 0 COMMENT '登录时间 (时间戳)',
  5. `name` VARCHAR(48) not null DEFAULT '' COMMENT '姓名',
  6. primary key(`id`),
  7. key idx_last_logined_time(last_logined_time)
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

往上面的表中插入测试数据:

  1. INSERT INTO customers (id, last_logined_time, name) VALUES (1, 1645600127, 'zhangsan');
  2. INSERT INTO customers (id, last_logined_time, name) VALUES (2, 1645600127, 'lisi');
  3. INSERT INTO customers (id, last_logined_time, name) VALUES (3, 1645600127, 'wangwu');

使用以下 SQL 语句来获取 “获取每个小时登录的用户数”:

  1. select count(1) from customers where last_logined_time>=(unix_timestamp()-3600);

把上面的数据以指标形式上报给中心。

下面详细讲述实现上述业务的具体步骤。

1.2. 前置条件

1.2.1. Python 环境

需要安装 Python,目前 Pythond 采集器处于 alpha 阶段,同时兼容 Python 2.7+ 和 Python 3+。但为了以后的兼容性,强烈建议使用 Python 3,毕竟 Python 2 官方已经不作支持了。下面的演示也是使用 Python 3。

1.2.2. Python 依赖库

需要安装以下依赖库:

  • requests(操作网络,用于上报指标)
  • pymysql(操作 MySQL 数据库,用于连接数据库获取业务数据)

安装方法如下:

  1. # python3
  2. python3 -m pip install requests
  3. python3 -m pip install pymysql

上述的安装需要安装 pip,如果你没有,可以参考以下方法(源自: 这里):

  1. # Linux/MacOS
  2. python3 -m ensurepip --upgrade
  3. # Windows
  4. py -m ensurepip --upgrade

1.3. 编写用户自定义脚本

需要用户继承 DataKitFramework 类,然后对 run 方法进行改写。DataKitFramework 类源代码文件是 datakit_framework.py,路径是 datakit/python.d/core/datakit_framework.py

具体的使用可以参见源代码文件 datakit/python.d/core/demo.py

我们这里根据上述需求,写成如下的 Python 脚本,命名为 hellopythond.py:

  1. from datakit_framework import DataKitFramework
  2. import pymysql
  3. import re
  4. import logging
  5. class MysqlConn():
  6. def __init__(self, logger, config):
  7. self.logger = logger
  8. self.config = config
  9. self.re_errno = re.compile(r'^\((\d+),')
  10. try:
  11. self.conn = pymysql.Connect(**self.config)
  12. self.logger.info("pymysql.Connect() ok, {0}".format(id(self.conn)))
  13. except Exception as e:
  14. raise e
  15. def __del__(self):
  16. self.close()
  17. def close(self):
  18. if self.conn:
  19. self.logger.info("conn.close() {0}".format(id(self.conn)))
  20. self.conn.close()
  21. def execute_query(self, sql_str, sql_params=(), first=True):
  22. res_list = None
  23. cur = None
  24. try:
  25. cur = self.conn.cursor()
  26. cur.execute(sql_str, sql_params)
  27. res_list = cur.fetchall()
  28. except Exception as e:
  29. err = str(e)
  30. self.logger.error('execute_query: {0}'.format(err))
  31. if first:
  32. retry = self._deal_with_network_exception(err)
  33. if retry:
  34. return self.execute_query(sql_str, sql_params, False)
  35. finally:
  36. if cur is not None:
  37. cur.close()
  38. return res_list
  39. def execute_write(self, sql_str, sql_params=(), first=True):
  40. cur = None
  41. n = None
  42. err = None
  43. try:
  44. cur = self.conn.cursor()
  45. n = cur.execute(sql_str, sql_params)
  46. except Exception as e:
  47. err = str(e)
  48. self.logger.error('execute_query: {0}'.format(err))
  49. if first:
  50. retry = self._deal_with_network_exception(err)
  51. if retry:
  52. return self.execute_write(sql_str, sql_params, False)
  53. finally:
  54. if cur is not None:
  55. cur.close()
  56. return n, err
  57. def _deal_with_network_exception(self, stre):
  58. errno_str = self._get_errorno_str(stre)
  59. if errno_str != '2006' and errno_str != '2013' and errno_str != '0':
  60. return False
  61. try:
  62. self.conn.ping()
  63. except Exception as e:
  64. return False
  65. return True
  66. def _get_errorno_str(self, stre):
  67. searchObj = self.re_errno.search(stre)
  68. if searchObj:
  69. errno_str = searchObj.group(1)
  70. else:
  71. errno_str = '-1'
  72. return errno_str
  73. def _is_duplicated(self, stre):
  74. errno_str = self._get_errorno_str(stre)
  75. # 1062:字段值重复,入库失败
  76. # 1169:字段值重复,更新记录失败
  77. if errno_str == "1062" or errno_str == "1169":
  78. return True
  79. return False
  80. class HelloPythond(DataKitFramework):
  81. __name = 'HelloPythond'
  82. interval = 10 # 每 10 秒钟采集上报一次。这个根据实际业务进行调节,这里仅作演示。
  83. # if your datakit ip is 127.0.0.1 and port is 9529, you won't need use this,
  84. # just comment it.
  85. # def __init__(self, **kwargs):
  86. # super().__init__(ip = '127.0.0.1', port = 9529)
  87. def run(self):
  88. config = {
  89. "host": "172.16.2.203",
  90. "port": 30080,
  91. "user": "root",
  92. "password": "Kx2ADer7",
  93. "db": "df_core",
  94. "autocommit": True,
  95. # "cursorclass": pymysql.cursors.DictCursor,
  96. "charset": "utf8mb4"
  97. }
  98. mysql_conn = MysqlConn(logging.getLogger(''), config)
  99. query_str = "select count(1) from customers where last_logined_time>=(unix_timestamp()-%s)"
  100. sql_params = ('3600')
  101. n = mysql_conn.execute_query(query_str, sql_params)
  102. data = [
  103. {
  104. "measurement": "hour_logined_customers_count", # 指标名称。
  105. "tags": {
  106. "tag_name": "tag_value", # 自定义 tag,根据自己想要标记的填写,我这里是随便写的
  107. },
  108. "fields": {
  109. "count": n[0][0], # 指标,这里是每个小时登录的用户数
  110. },
  111. },
  112. ]
  113. in_data = {
  114. 'M':data,
  115. 'input': "pyfromgit"
  116. }
  117. return self.report(in_data) # you must call self.report here

1.4. 将自定义脚本放入正确的位置

在 Datakit 安装目录的 python.d 目录下新建一个文件夹,并命名为 hellopythond,这个文件夹名称要与上面编写的类名相同,即为 hellopythond

然后将上面写好的脚本 hellopythond.py 放入此文件夹下,即最后的目录结构如下:

  1. ├── ...
  2. ├── datakit
  3. └── python.d
  4. ├── core
  5. ├── datakit_framework.py
  6. └── demo.py
  7. └── hellopythond
  8. └── hellopythond.py

上面的 core 文件夹是 Pythond 的核心文件夹,不要动。

上面是在没有开启 gitrepos 功能的情况下,如果是开启了 gitrepos 功能,那么路径结构就是这样的:

  1. ├── ...
  2. ├── datakit
  3. ├── python.d
  4. ├── gitrepos
  5. └── yourproject
  6. ├── conf.d
  7. ├── pipeline
  8. └── python.d
  9. └── hellopythond
  10. └── hellopythond.py

1.5. 开启 pythond 配置文件

将 Pythond 配置文件复制出来。在 conf.d/pythond 目录下复制 pythond.conf.samplepythond.conf,然后将配置成如下形式:

  1. [[inputs.pythond]]
  2. # Python 采集器名称
  3. name = 'some-python-inputs' # required
  4. # 运行 Python 采集器所需的环境变量
  5. #envs = ['LD_LIBRARY_PATH=/path/to/lib:$LD_LIBRARY_PATH',]
  6. # Python 采集器可执行程序路径(尽可能写绝对路径)
  7. cmd = "python3" # required. python3 is recommended.
  8. # 用户脚本的相对路径(填写文件夹,填好后该文件夹下一级目录的模块和 py 文件都将得到应用)
  9. dirs = ["hellopythond"] # 这里填的是文件夹名,即类名

1.6. 重启 Datakit

  1. sudo datakit --restart

1.7. 效果图

如果一切顺利的话,大概 1 分钟内我们就能在中心看到指标图。
14.pythond.png

1.8. 参考文档