Promethues

Prometheus简介

什么是Prometheus?

使用Go语言开发的开源监控报警系统和时序列数据库(TSDB)

通过基于HTTP的pull方式采集时序数据

所有采集的监控数据均以指标(metric)的形式保存在内置的时间序列数据库当中(TSDB)。

当单实例 Prometheus Server 的任务量过大时,可以通过功能分区(sharding)+联邦集群(federation)进行扩展。

架构

img

  • 存储计算层
➢ Prometheus Server,里面包含了存储引擎和计算引擎。
➢ Retrieval 组件为取数组件,它会主动从 Pushgateway 或者 Exporter 拉取指标数据。
➢ Service discovery,可以动态发现要监控的目标。
➢ TSDB,数据核心存储与查询。
➢ HTTP server,对外提供 HTTP 服务。
  • 采集层
采集层分为两类,一类是生命周期较短的作业,还有一类是生命周期较长的作业。
➢ 短作业:直接通过 API,在退出时间指标推送给 Pushgateway。
➢ 长作业:Retrieval 组件直接从 Job 或者 Exporter 拉取数据。
  • 应用层
应用层主要分为两种,一种是 AlertManager,另一种是数据可视化。
➢ AlertManager:对接 Pagerduty,是一套付费的监控报警系统。
➢ 数据可视化:Prometheus build-in WebUI、Grafana、其他基于 API 开发的客户端

Promethus安装部署

prometheus安装

下载安装

sudo yum install wget -y
wget  https://github.com/prometheus/prometheus/releases/download/v2.16.0-rc.0/prometheus-2.16.0-rc.0.linux-amd64.tar.gz

tar zxvf prometheus-2.16.0-rc.0.linux-amd64.tar.gz  -C /usr/local/prometheus/ --strip-components 1  # 解压到/usr/local/prometheus/目录下,--strip-components 1代表解压后去掉一层目录结构。

/usr/local/prometheus/prometheus --config.file="/usr/local/prometheus/prometheus.yml" &  
# 以守护进程形式(&)启动 Prometheus 服务。指定配置文件路径为 /usr/local/prometheus/prometheus.yml

ln /usr/local/prometheus/prometheus /bin/

vim /usr/local/prometheus/prometheus.yml
    - targets: ['192.168.248.10:9090']  # 修改为本机IP

安装验证

  • 访问界面

通过浏览器访问http://服务器IP:9090就可以访问到prometheus的主界面
默认只监控了本机一台,点Status –->点Targets –->可以看到只监控了本机
img

  • 主机数据展示

通过http://服务器IP:9090/metrics可以查看到监控的数据
img

  • 在web主界面可以通过关键字查询监控项

img

Promethues命令行

/usr/local/prometheus/prometheus --help

命令行选项 说明
--config.file="prometheus.yml" 指定配置文件,默认是当前目录下的prometheus.yml,所以要带上绝对路径
--web.listen-address="0.0.0.0:9090" 端口和监听地址
--web.max-connections=512 并发连接数
--storage.tsdb.path="data/" TSDB数据存放目录
--log.level=info 日志级别 [debug, info, warn, error]
--log.format=logfmt 日志消息的输出格式。选项包括:[logfmt, json]
/usr/local/prometheus/prometheus --config.file="/usr/local/prometheus/prometheus.yml" --web.listen-address="0.0.0.0:9090" --web.max-connections=512 > /var/log/prometheus.log 2>&1 &
2>&1:将错误输出(stderr)也重定向到同一个日志文件。

制作system启动文件

vi /etc/systemd/system/prometheus.service

[Unit]
Description=Prometheus Server
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/usr/local/prometheus/
ExecStart=/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml --web.listen-address=0.0.0.0:9090 --web.max-connections=512
Restart=on-failure
# 使用 systemd 日志功能替代手动重定向
StandardOutput=append:/var/log/prometheus.log
StandardError=append:/var/log/prometheus.log

[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start prometheus
systemctl enable prometheus

配置文件

# my global config
global:  # 控制 Prometheus 服务器的全局配置
  scrape_interval:     15s # prometheus采集间隔
  evaluation_interval: 15s # 规则验证(生成 alert)的时间间隔
  # scrape_timeout is set to the global default (10s).  # 采集数据超时时间

# Alertmanager configuration  # 告警插件
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

rule_files:  # 规则配置文件
  # - "first_rules.yml"
  # - "second_rules.yml"

scrape_configs:  # 数据采集配置
  - job_name: 'prometheus'  # 监控作业的名称
    static_configs:  # 表示静态目标配置,就是固定从某个 target 拉取数据
    - targets: ['192.168.248.10:9090']  # 指定监控的目标IP

  - job_name: 'prometheus-agent'
    static_configs:
    - targets: ['192.168.248.80:9100']  # 静态配置,指定采集对象,修改后要重启
	# file_sd_configs:  # 动态配置文件,动态读取文件内容,然后采集
  • 配置存储路径
storage:
  tsdb:
    path: "/data/prometheus"  # 自定义存储路径
    retention.time: 30d       # 数据保留时间(可选)
    retention.size: 512GB     # 数据保留大小(可选,需 Prometheus v2.37+)
vi /usr/lib/systemd/system/prometheus.service

ExecStart=/usr/local/prometheus/prometheus --config.file=/usr/local/prometheus/prometheus.yml --web.listen-address=0.0.0.0:9090 --web.max-connections=512 --storage.tsdb.path=/data/prometheus

img
img

符号 含义
= 等于
!= 不等于
=~ 匹配正则
!~ 不匹配正则

动态发现

基于文档的自动发现

file_sd_configs # 支持json和yaml格式
获取的exporter域名+端口,写入配置文件,prometheus可以定时读取并加入到prometheus的监控列表中
用于解决大量主机添加、删除的问题

  - job_name: 'prometheus-agent'
    file_sd_configs:  # 动态配置文件,动态读取文件内容,然后采集
    - files:
      - /usr/local/prometheus/discovery_node_exporter.yml  # 动态配置文件路径
      refresh_interval: 5s  # 动态配置文件刷新间隔
vi /usr/local/prometheus/discovery_node_exporter.yml
[
  {
    "targets": ["1.1.1.10:9100", "1.1.1.80:9100"],
    "labels": {"info": "wiseHYH"}
]

exporter

node_exporter安装

下载安装

wget https://github.com/prometheus/node_exporter/releases/download/v0.18.1/node_exporter-0.18.1.linux-amd64.tar.gz
tar zxvf node_exporter-0.18.1.linux-amd64.tar.gz  -C /usr/local/exporter/  # 解压到指定目录下
nohup /usr/local/node_exporter-0.18.1.linux-amd64/node_exporter &
# nohup:让命令在当前会话结束(如用户退出 SSH)后继续运行,忽略 SIGHUP 信号。
# &:将命令放入后台执行,释放当前终端,允许用户继续输入其他命令。
# Node Exporter 的输出会被重定向到当前目录的 nohup.out 文件中
ln /usr/local/exporter/node_exporter-0.18.1.linux-amd64/node_exporter /bin/

制作system启动文件

因为之前启动过了,所以需要先kill掉

vi /etc/systemd/system/node_exporter.service

[Unit]
Description=node_exporter
After=network.target
[Service]
User=root
Group=root
WorkingDirectory=/usr/local/exporter/node_exporter-0.18.1.linux-amd64
ExecStart=/usr/local/exporter/node_exporter-0.18.1.linux-amd64/node_exporter
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start node_exporter
systemctl enable node_exporter

安装验证

修改服务端配置

scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    static_configs:
    - targets: ['192.168.248.10:9090']

  - job_name: 'prometheus-agent'
    static_configs:
    - targets: ['192.168.248.80:9100']

img

pkill prometheus 
/usr/local/prometheus/prometheus –config.file=”/usr/local/prometheus/prometheus.yml” &

img

指标说明

CPU

node_cpu_seconds_total # CPU时间总量,单位为秒
modes: user, system, idle, iowait, irq, softirq, steal, guest, nice # 各种模式下的CPU时间
user: 用户态CPU时间 # 用户在程序中使用的时间,不包括nice值
system: 系统态CPU时间 # 内核执行程序所占用的时间
idle: 空闲CPU时间 # 未被使用的CPU时间,通常用于计算系统负载

100 * (sum(rate(node_cpu_seconds_total{mode="system"}[5m])) by (instance) / sum(rate(node_cpu_seconds_total[5m])) by (instance)) # 计算系统态CPU使用率
100 * (sum(rate(node_cpu_seconds_total{mode="user"}[5m])) by (instance) / sum(rate(node_cpu_seconds_total[5m])) by (instance)) # 计算用户态CPU使用率
100 * (sum(rate(node_cpu_seconds_total{mode!="idle"}[5m])) by (instance) / sum(rate(node_cpu_seconds_total[5m])) by (instance)) # 计算非空闲CPU使用率

内存

node_memory_MemFree_bytes # 空闲内存大小,单位为字节
node_memory_MemTotal_bytes # 总内存大小,单位为字节
node_memory_Buffers_bytes # 缓冲区内存大小,单位为字节
node_memory_Cached_bytes # 缓存内存大小,单位为字节
node_memory_MemAvailable_bytes # 可用内存大小,单位为字节
node_memory_SwapFree_bytes # 空闲交换空间大小,单位为字节
node_memory_SwapTotal_bytes # 总交换空间大小,单位为字节
node_memory_SwapCached_bytes # 缓存交换空间大小,单位为字节
100 * (node_memory_MemFree_bytes {instance="$instance"} / node_memory_MemTotal_bytes{instance="$instance"}) # 计算空闲内存使用率

total used free shared buff/cache available
Mem[内存] node_memory_MemTotal_bytes node_memory_MemFree_bytes node_memory_Shmem_bytes node_memory_Buffers_bytes + node_memory_Cached_bytes node_memory_MemAvailable_bytes
Swap[交换空间] node_memory_SwapTotal_bytes node_memory_SwapFree_bytes - -
磁盘

node_filesystem_avail_bytes # 可用磁盘空间大小,单位为字节
node_filesystem_size_bytes # 总磁盘空间大小,单位为字节

(1 - node_filesystem_avail_bytes{mountpoint="/", instance="$instance"} / node_filesystem_size_bytes{mountpoint="/", instance="$instance"}) * 100

linux-process-exporter

下载安装go环境并编译安装

wget https://golang.google.cn/dl/go1.21.0.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.21.0.linux-amd64.tar.gz  # 解压到 /usr/local

vi ~/.bashrc  # 末尾添加
export PATH=$PATH:/usr/local/go/bin  # 添加Go二进制路径
export GOPATH=$HOME/go  # 可选:设置Go工作区(默认路径为$HOME/go)

source ~/.bashrc  # 更新环境变量

go version  # 验证Go安装

下载安装linux-process-exporter

git clone https://github.com/hzbb2221/linux-process-exporter.git
cd linux-process-exporter
go env -w GOPROXY=https://goproxy.cn,direct  # 设置Go模块代理,加速依赖下载
go mod download  # 下载依赖 在go.mod所在的目录下执行
go build  # 编译项目 在项目根目录下执行
nohup ./linux-process-exporter &  # 后台运行编译后的程序
文件/目录 作用 典型使用场景
go.mod 记录依赖版本和模块信息 初始化项目、添加/更新依赖
go.sum 校验依赖的完整性 确保依赖未被篡改、实现可重复构建
main.go 定义程序入口点 编译可执行程序、启动服务

修改promethes配置文件

vi /usr/local/prometheus/discovery_node_exporter.yml

"1.1.1.10:9113"  # 加上即可

system

vi /etc/systemd/system/linux_process_exporter.service

[Unit]
Description=linux_process_exporter
After=network.target
[Service]
User=root
Group=root
WorkingDirectory=/usr/local/exporter/linux-process-exporter
ExecStart=/usr/local/exporter/linux-process-exporter/linux-process-exporter
[Install]
WantedBy=multi-user.target

指标说明

topk(10, process_memory_usage{name=~"$name", instance=~"$instance"})
topk(10, process_cpu_usage{name=~"$name", instance=~"$instance"})

pushgateway

下载安装

# 下载Push Gateway
wget https://github.com/prometheus/pushgateway/releases/download/v1.6.0/pushgateway-1.6.0.linux-amd64.tar.gz
tar -xzf pushgateway-1.6.0.linux-amd64.tar.gz -C /usr/local/pushgateway
cd /usr/local/pushgateway

# 启动Push Gateway(接收脚本推送的数据)
./pushgateway &

制作system启动文件

vi /etc/systemd/system/pushgateway.service

[Unit]
Description=pushgateway
After=network.target
[Service]
User=root
Group=root
WorkingDirectory=/usr/local/pushgateway
ExecStart=/usr/local/pushgateway/pushgateway
[Install]
WantedBy=multi-user.target

push和删除数据

http://:9091/metrics/job/{/<LABEL_NAME>/<LABEL_VALUE>}

echo "test_metric 123456" | curl --data-binary @- http://1.1.1.10:9091/metrics/job/test_job

cat <<EOF | curl --data-binary @- http://1.1.1.10:9091/metrics/job/disk_size_bytes/
directory_size{path="/"} 140744333959692
directory_size{path="/usr/local"} 1076691906
EOF

vi pgdata.txt
http_request_total{code="200",interface="/v1/save"} 276
http_request_total{code="404",interface="/v1/delete"} 0
http_request_total{code="500",interface="/v1/save"} 1
http_request_time{code="200",interface="/v1/core"} 0.122

curl -XPOST --data-binary @pgdata.txt http://172.30.12.167:9091/metrics/job/app/instance/app-172.30.0.0
import requests
import os
import time

while True:
    exit_code = os.system('du -B 1M / | sort -hr | head -n 15 > final.txt')
    if exit_code == 0:
        print('du Success')
    result = 'cat <<EOF | curl --data-binary @- http://1.1.1.10:9091/metrics/job/disk_size_bytes/\n'
    with open('final.txt', 'r', encoding='utf-8') as f:
        data = f.readlines()
        for info in data:
            info = info.strip()
            size = ' ' + info.split('\t')[0]
            dir = 'directory_size{path=' + '\"' + info.split('\t')[-1] + '\"' + '}'
            result += dir + str(size) + '\n'
        result += 'EOF'

    with open('curl.sh', 'w', encoding='utf-8') as f:
        f.write(result)
    exit_code = os.system('bash curl.sh')
    if exit_code == 0:
        print('Push Success')
    time.sleep(10)
    ```
posted @ 2025-07-31 14:54  WiseHYH  阅读(23)  评论(0)    收藏  举报