↓ 跳过正文
  1. 博客/
  2. Grafana/

用 Prometheus 存储指标数据

··976 字·5 分钟·
小钰大主宰
作者
小钰大主宰
建站工程师
目录
Grafana - 这篇文章属于一个选集。
§ 2: 本文

本文会用到 Proxmox 集群上两个运行 Debian GNU/Linux 的 LXC,把 Prometheus 服务器装好并配置成拉取、存储指标数据。

  1. prometheus1.localdomain.com 在 8080 端口运行 Prometheus 服务器。
  2. nginx1.localdomain.com 在 443 端口运行 NGINX 作反向代理,对外地址是 prometheus.publicdomain.com。

本系列假定已安装并正确配置了内部 DNS 服务器。localdomain.com 是集群内部使用的 DNS 区域,publicdomain.com 是用于从互联网访问服务的公网 DNS 区域。

它是怎么工作的
#

Prometheus 服务器会连接 exporter(也就是 agent)来采集指标数据——这些 exporter 运行在你想采集数据的宿主机或 guest 里,或者直接连接应用。每个 exporter 或应用监听不同的端口。

Prometheus 服务器会周期性地连接该地址和端口,请求 agent 提供数据,然后把数据存进本地磁盘上的时序数据库,位置在 /var/lib/prometheus/metrics2/。

它能用来做什么
#

Prometheus 可以用于:

  • 监控。采集并存储系统与应用的时序指标,了解它们的当前状态。
  • 历史分析。洞察系统与应用随时间变化的行为。
  • 容量规划。分析资源消耗趋势,预判未来需求。
  • 可观测性。把指标异常与事件、发布关联起来,排查并解决运维问题。
  • 告警。基于可配置的条件触发告警。
  • 服务等级目标(SLO)管理。定义并衡量对性能目标的达成情况。

安装
#

我们先从 Debian 仓库安装 Prometheus 服务器,再从 GitHub 上 Prometheus 的 releases 页面手工更新二进制文件。

apt-get update
apt-get install prometheus ssl-cert
adduser prometheus ssl-cert

我们会把 Prometheus 服务器配置成用 TLS 加密通信。因此把 prometheus 用户加入 ssl-cert 组(由 ssl-cert 包创建),这样它就能读取 Let’s Encrypt 签发的通配证书私钥 /etc/ssl/private/localdomain.com.key。

最后,用 Github 上更新的版本替换二进制文件:

export PROMETHEUS_VERSION="2.55.1"
wget https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz \
     --output-document=/tmp/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz
tar --directory=/tmp --extract --gzip --file=/tmp/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz
cp /tmp/prometheus-${PROMETHEUS_VERSION}.linux-amd64/prometheus /usr/bin/
cp /tmp/prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool /usr/bin/

Prometheus 配置
#

配置分两步:

  1. 配置 Prometheus 服务器。
  2. 配置 Prometheus 监控自身。

Prometheus 服务器使用三个主要配置文件:

  1. 主配置文件 /etc/prometheus/prometheus.yml。它决定 Prometheus 服务器会连接哪些 exporter 和应用。
  2. Web 配置文件 /etc/prometheus/web.yml。它配置 Prometheus 内部的 HTTP 服务器,供 NGINX 反向代理连接。
  3. 命令行参数文件 /etc/default/prometheus。它决定 Prometheus 守护进程的启动参数。

命令行参数
#

先从 systemd 服务文件1使用的环境文件 /etc/default/prometheus 开始,它负责把命令行参数传给服务器。

# Set the command-line arguments to pass to the server
# See: https://prometheus.io/docs/prometheus/latest/command-line/prometheus/
ARGS="--web.config.file='/etc/prometheus/web.yml' \
      --config.file='/etc/prometheus/prometheus.yml' \
      --web.listen-address=':8080' \
      --web.external-url='https://prometheus.publicdomain.com/' \
      --web.route-prefix='/' \
      --storage.tsdb.path='/var/lib/prometheus/metrics2/' \
      --storage.tsdb.retention.time='2y' \
      --web.console.libraries='/etc/prometheus/console_libraries' \
      --web.console.templates='/etc/prometheus/consoles'"

下表汇总了传给守护进程的参数:

参数说明
web.config.fileYAML 格式的 Web 配置
config.fileYAML 格式的主配置
web.listen-address服务器监听的地址与端口
web.external-urlPrometheus 对外可达的 URL
web.route-prefix内部端点路径前缀
storage.tsdb.path本地磁盘时序数据库路径
storage.tsdb.retention.time样本在存储中的保留时长
web.console.libraries控制台库目录路径
web.console.templates控制台模板目录路径

注意:web 命名空间下的选项都与 HTTP 服务器有关。

简而言之,我们让守护进程从 /etc/prometheus/web.yml 加载 HTTP 服务器配置、从 /etc/prometheus/prometheus.yml 加载主配置、监听 8080 端口(默认是 9090),并指定写回 Prometheus 自身时使用的相对与绝对链接方式。

HTTP 服务器
#

接着是配置文件 /etc/prometheus/web.yml,服务器用它配置认证并启用 TLS 加密。

# Prometheus web configuration
# See: https://prometheus.io/docs/prometheus/latest/configuration/https/

# Allow TLS connections
tls_server_config:
  cert_file: /etc/ssl/certs/localdomain.com.crt
  key_file: /etc/ssl/private/localdomain.com.key
  min_version: TLS12

# Enable HTTP/2 support
http_server_config:
  http2: true

除了启用 TLS 和 HTTP/2.0,http_server_config 键还可以用来设置响应头,视服务器所在环境可能有用。此外 basic_auth_users 键可以启用 HTTP 认证,但我们会在本文后面把这部分交给 NGINX。

主要选项
#

最后是主配置文件 /etc/prometheus/prometheus.yml,先从一个非常基础的配置开始,后面再扩展。

# Prometheus configuration
# See: https://prometheus.io/docs/prometheus/latest/configuration/configuration/

# Set the global defaults
global:
  # How frequently to scrape targets (default is 1m)
  scrape_interval: 30s
  # How long until a scrape request times out (default is 10s)
  scrape_timeout: 10s

# Scrapers configuration
scrape_configs:

  # Prometheus
  - job_name: 'prometheus'
    scheme: https
    proxy_from_environment: false
    tls_config:
      ca_file: /etc/ssl/certs/ISRG_Root_X1.pem
      insecure_skip_verify: false
    static_configs:
      - targets:
        - 'prometheus1.localdomain.com:8080'
        labels:
          group: 'prometheus'
    metrics_path: /metrics

两个主键:global 和 scrape_configs。前者定义全局变量,后者定义一组抓取配置,也就是服务器会去查询数据的那些指标 exporter。

本系列后面,每当我们安装一种抓取器(例如 PostgreSQL Exporter 或 NGINX Exporter)或要抓取某个应用(例如 MinIO),都会在 scrape_configs 里新增一条。

目前上面的例子只是查询 Prometheus 服务器本身,它自己就暴露了兼容 Prometheus 的指标。

此时服务文件应当已启用、守护进程也已启动,所以只需重启服务并检查状态:

systemctl restart prometheus
systemctl status prometheus

如果服务文件未启用,用 systemctl enable prometheus 启用,然后用 systemctl start prometheus 启动。

反向代理
#

我们会在另一个容器里用 NGINX 作反向代理。完整的 NGINX 安装与配置指南请参考

\[NGINX configuration\]

({{ < ref “/posts/nginx” > }}) 一文。眼下,一个基础的 server 块配置就够用了。

server {
  listen 443 ssl;
  server_name prometheus.publicdomain.com;
  ssl_certificate /etc/ssl/certs/publicdomain.com.crt;
  ssl_certificate_key /etc/ssl/private/publicdomain.com.key;
  location / {
    auth_basic "Prometheus | Calabruix";
    auth_basic_user_file /etc/nginx/.prometheus.htpasswd;
    proxy_http_version 1.1;
    proxy_pass https://prometheus1.localdomain.com:8080;
  }
}

下表汇总了这个 server 块的配置:

参数说明
listen 443 ssl在 443 端口监听并启用 SSL
server_name设置虚拟服务器的 FQDN
ssl_certificatePEM 格式 SSL 证书的路径
ssl_certificate_keyPEM 格式 SSL 证书私钥的路径
location按请求 URI 设置配置项
auth_basic启用用户名与密码校验
auth_basic_user_file存放用户名与密码的文件路径
proxy_http_version设置代理使用的 HTTP 协议版本
proxy_pass设置被代理服务器的协议、地址与端口

我们不需要把 nginx 用户加入 ssl-cert 组,因为 NGINX 的主进程以 root 运行,本来就能读取 Let’s Encrypt 签发的通配证书私钥 /etc/ssl/private/publicdomain.com.key。

如前所述,我们用 HTTP 基本认证限制访问。为此需要用 apache2-utils 包里的 htpasswd 命令填充 /etc/nginx/grafna.htpasswd 文件。

下面的命令会创建一个密码文件(如果已存在则去掉 -c 参数),用户名为 prometheus。在提示处输入两次密码。

htpasswd -cB -C 10 /etc/nginx/.prometheus.htpasswd prometheus

密码可以用下面的命令生成:

openssl rand -base64 25 | tr --delete /=+ | cut --characters -32

别忘了把 prometheus1.localdomain.com 和 prometheus.public.domain 的记录加进各自的 DNS 区域,或写进 /etc/hosts 文件。防火墙规则也要检查。

用 nginx -t 命令检查配置文件语法错误,最后让 NGINX 重新加载配置:

systemctl reload nginx

可选:用 systemctl status nginx 查看服务状态。现在可以在浏览器里打开 https://prometheus.publicdomain.com/ 了。

存储
#

Prometheus 默认以自定义的高效格式在本地存储时序数据。它面向可靠性和快速查询设计,但不是集群化的(也就是说没有内置复制)。

数据存放在一个目录里,本例中是 /var/lib/prometheus/metrics2/。摄入的样本被组织成块,放在各自独立的子目录中,每个块包含:

  • 一个 chunks/ 子目录,存放该时间段内的全部时序样本。
  • 一个元数据文件。
  • 一个索引文件,把指标名与标签映射到 chunks/ 子目录里的时序。

为防止崩溃丢数据,Prometheus 使用存放在 wal/ 子目录中、按段切分的 WAL,服务器重启时可以重放它来恢复数据。

# tree /var/lib/prometheus/metrics2/
/var/lib/prometheus/metrics2/
├── 01JNZ6T5EMKBXZ0BPMXSMCH2CK
│   ├── chunks
│   │   ├── 000001
│   │   ├── 000002
│   │   └── 000003
│   ├── index
│   ├── meta.json
│   └── tombstones
├── 01JP14KKHT2FQFX8Q4R5G81XXQ
│   ├── chunks
│   │   ├── 000001
│   │   ├── 000002
│   │   └── 000003
│   ├── index
│   ├── meta.json
│   └── tombstones
├── [..]
├── chunks_head
│   ├── 020194
│   ├── 020195
│   ├── 020196
│   └── 020197
├── lock
├── queries.active
└── wal
    ├── 00072044
    ├── 00072045
    ├── [..]
    ├── 00072054
    └── checkpoint.00072043
        └── 00000000

数据被切成块(最初通常是 2 小时的块),之后会被合并成更大的块,以减少存储占用,并通过减少查询时需要扫描的块数来提升查询性能。删除记录单独存放在 tombstone 文件里(而不是直接从块里删数据)。默认保留期是 15 天,之后旧数据会被删除。因此,磁盘速度、内存分配和保留期设置都会影响性能。

管理本地存储就是配置保留策略来控制磁盘占用。Prometheus 提供 --storage.tsdb.retention.time 之类的命令行参数来设定数据保留时长,超过指定时间的数据会被自动删除。

当磁盘容量成为限制时,可以用 storage.tsdb.retention.size 参数来限制存储大小。这种情况下,建议把该值设为分配给 Prometheus 磁盘空间的 80–85%。这个缓冲能保证旧数据在磁盘写满之前被清除,避免数据摄入出问题。

为解决本地存储在可扩展性和持久性上的局限,Prometheus 提供了对接远程存储系统的接口,支持远程写(把摄入的样本发到远程端点)与远程读(从远程端点取回样本数据)。这些集成使用 snappy 压缩的 protocol buffer 编码,走 HTTP 传输。

Grafana Mimir 是 Grafana Labs 开发的开源、可横向扩展、高可用、多租户 TSDB,为 Prometheus 提供长期存储。如果你有非常大规模的部署和很长的保留期,活跃序列达到数十万级,值得研究一下。

尽管 Prometheus 默认就会在序列内部压缩样本,但由于我们的 Proxmox 集群部分节点上有一个名为 zfspool 的 ZFS 池,我们会让 LXC prometheus1.localdomain.com 使用它,以便享受 ZFS 的去重与压缩能力。

在我们的例子里,LXC prometheus1.localdomain.com 的 id 是 114。在 guest 所在节点的控制台上,可以列出池以及它所在的子卷:

# zfs list
NAME                        USED  AVAIL     REFER  MOUNTPOINT
zfspool/subvol-114-disk-0  15.7G  34.3G     15.7G  /zfspool/subvol-114-disk-0

还可以查看正在使用哪种压缩算法:

# zpool get feature@lz4_compress,feature@zstd_compress zfspool
NAME     PROPERTY               VALUE                  SOURCE
zfspool  feature@lz4_compress   active                 local
zfspool  feature@zstd_compress  enabled                local

用 man zfsprops 查看默认压缩算法。

最后可以查出实际达到的压缩比:

# zfs get compression,compressratio zfspool/subvol-114-disk-0
zfspool/subvol-114-disk-0  compressratio         2.07x                       -
zfspool/subvol-114-disk-0  compression           on                          inherited from zfspool

Prometheus 平均每个样本占用 2 字节。因此规划服务器容量时可以用下面的公式:

所需磁盘空间 = 保留时长(秒) × 每秒摄入样本数 × 每样本字节数

要降低样本摄入速率,可以减少抓取的时序数量(更少的目标,或每个目标更少的序列),或者增大抓取间隔。不过,由于序列内部会压缩样本,减少序列数量通常更有效。

指标类型
#

Prometheus 定义了四种主要指标类型来表示不同形式的数据:

  1. Counter(计数器):只增不减、或在重启时归零的累计型指标。它适合跟踪已服务的请求数、完成的任务数、遇到的错误数等。不应把会下降的值(例如内存使用量)做成 Counter。

    示例:Prometheus 服务器收到的 HTTP 请求总数。

    prometheus_http_requests_total{handler="/metrics"}

    示例:Prometheus 服务器在 1 小时窗口内、/metrics 端点上收到 HTTP 请求的每秒速率。

    rate(prometheus_http_requests_total{handler="/metrics"}[1h])
  2. Gauge(仪表):表示一个可升可降的数值。适用于当前内存使用量、活跃连接数、队列长度或活跃线程数之类的指标。

    示例:Prometheus 进程当前的常驻内存占用。

    process_resident_memory_bytes{job="prometheus"}

    用 Graph 标签页把内存使用量画成时序图。

  3. Histogram(直方图):对观测值(例如请求时长或响应大小)采样,并在可配置的桶中计数,同时提供所有观测值之和。直方图适合分析事件的分布与频次。

    示例:计算 1 小时窗口内的 95 分位请求时长,含义是95% 的请求在结果所示的毫秒数内完成。le 标签表示每个直方图桶的上界。

    histogram_quantile(0.95, sum(rate(prometheus_http_request_duration_seconds_bucket[1h])) by (le))
  4. Summary(摘要):与直方图类似,也对观测值采样,但提供的是滑动时间窗口上的可配置分位数,以及观测总数与总和。它在计算精确分位数上表现更好,但在跨多个实例聚合时有局限。

    示例:汇总 Prometheus 服务器垃圾回收(GC)暂停时长(秒)。分位数表示在不同百分位下暂停持续多久。同时还会提供 GC 操作次数(go_gc_duration_seconds_count)和 GC 花费的总时间(go_gc_duration_seconds_sum)。

    go_gc_duration_seconds{job="prometheus"}

    示例:取 50 分位(中位数)的 GC 暂停时长(秒):

    go_gc_duration_seconds{job="prometheus", quantile="0.5"}

    这表示 50% 的 GC 暂停时长小于或等于结果所示的微秒(µs)数。这能让你了解「正常」的暂停时长大概是多少。

    示例:取 90 分位的 GC 暂停时长(秒):

    go_gc_duration_seconds{job="prometheus", quantile="0.5"}

    这表示 90% 的 GC 暂停短于结果所示的微秒(µs)数。它能看出是否存在偶发的长暂停,而长暂停可能影响性能。

    示例:用总和除以次数,算出 1 小时窗口内的平均 GC 时长:

    rate(go_gc_duration_seconds_sum{job="prometheus"} [1h]) /
      rate(go_gc_duration_seconds_count{job="prometheus"} [1h])

这些指标都能为 Prometheus 自身的性能提供有价值的洞察,也可参照着用于监控 Prometheus 体系里的其他服务。在 Prometheus WebGUI 的 PromQL 输入框里执行上面的示例,看看结果,也可以拿可用指标自己玩一玩。

Prometheus 指标类型

其他指标模型
#

Prometheus 是一个可观测性工具(涵盖采集、存储和查询),它使用的指标模型是为自身需求量身设计的。它定义了指标暴露格式和远程写协议,社区和众多厂商都已采纳,事实上成了标准。

不过,有两个 CNCF 项目在致力于提供厂商无关、标准化的替代模型:

  • OpenMetrics,用于指标采集,目标是被 IETF 采纳;
  • OpenTelemetry,统一指标、链路和日志的采集,让跨遥测信号的埋点与关联更容易。

如果你对这个话题感兴趣,可以看看 Timescale 的 Prometheus vs. OpenTelemetry Metrics: A Complete Guide。

Prometheus 服务器暴露的指标
#

目前我们唯一在监控的服务或系统就是 Prometheus 服务器自身。访问 Prometheus Web 服务器的 /metrics 路径(即 prometheus.publicdomain.com)即可获得可用指标的完整列表。在这个页面上:

  • # HELP 给出该指标的简要说明。
  • # TYPE 指明指标类型(例如 gauge、counter)。
  • 随后的行给出指标名及其当前值。

下面列出一些值得监控的关键 Prometheus 自身指标。它们能提供关于 Prometheus 性能、查询执行、垃圾回收、内存占用和整体健康度的洞察。

整体性能:

指标名类型说明
prometheus_http_requests_totalCounterPrometheus 收到的 HTTP 请求总数。
prometheus_http_request_duration_secondsHistogramPrometheus 处理的 HTTP 请求的延迟分布。
prometheus_http_response_size_bytesHistogramPrometheus 返回的 HTTP 响应大小分布。

查询引擎

指标名类型说明
prometheus_engine_queriesGaugePrometheus 中正在执行或等待的查询数。
prometheus_engine_queries_concurrent_maxGaugePrometheus 允许的最大并发查询数。
prometheus_engine_query_duration_secondsSummaryPrometheus 处理查询所耗时间的分布,按查询执行阶段分类。

垃圾回收(GC)

指标名类型说明
go_gc_duration_secondsSummary垃圾回收暂停时长(秒),带用于分析的分位数。
go_gc_cycles_total_gc_cycles_totalCounter已完成的垃圾回收周期总数。
go_gc_heap_allocs_bytes_totalCounter应用在堆上分配的内存累计总量。

内存与资源使用

指标名类型说明
process_resident_memory_bytesGaugePrometheus 进程当前的常驻内存占用。
go_memstats_heap_alloc_bytesGauge当前已分配并使用中的堆内存。
go_memstats_heap_sys_bytesGauge从系统获得的堆内存总量。

进程与系统信息

指标名类型说明
process_cpu_seconds_totalCounterPrometheus 消耗的用户态与系统态 CPU 时间总量(秒)。
process_open_fdsGaugePrometheus 当前使用的打开文件描述符数。
go_goroutinesGaugePrometheus 进程中当前运行的 goroutine 数。

  1. 位于 /lib/systemd/system/prometheus.service。↩︎
Grafana - 这篇文章属于一个选集。
§ 2: 本文

相关文章