Grafana + Prometheus监控

本次介绍的主要有三大工具:

  • Grafana:获取Prometheus数据并展示
  • Exporter:Node Agent客户端,获取服务器资源发送数据至Prometheus
  • Prometheus:服务端,监控工具,收集Exporter数据

Prometheus

简介

Prometheus(中文名:普罗米修斯)是由SoundCloud开发的开源监控报警系统和时序列数据库(TSDB)。Prometheus使用Go语言开发, 是Google BorgMon监控系统的开源版本。

Prometheus可以理解为一个监控工具,工具从各处抓来统一的数据,放入prometheus这一个时间序列数据库中

Prometheus的基本原理是通过HTTP协议周期性抓取被监控组件的状态,任意组件只要提供对应的HTTP接口就可以接入监控,不需要任何SDK或者其他的集成过程。输出被监控组件信息的HTTP接口被叫做exporter,目前开发常用的组件大部分都有exporter可以直接使用,比如Nginx、MySQL、Linux系统信息、Mongo、ES等。
相关网址:

官方架构图

Docker部署

官方部署文档地址
Prometheus配置文件目录在:/etc/prometheus/prometheus.yml,这个很重要,需要配置客户端Node节点。

Docker部署

#新建Data存储目录
mkdir -p  /dockerdata/prometheus/data

#新建一个临时容器拷贝配置文件
docker run -d --name prometheus prom/prometheus
docker cp prometheus:/etc/prometheus/prometheus.yml  /dockerdata/prometheus
docker rm -f prometheus
#新增目录写入权限
chown -R 1000:1000   /dockerdata/prometheus
chmod -R 777  /dockerdata/prometheus
#修改配置文件配置,参考下面模板和简洁版
vi  /dockerdata/prometheus/prometheus.yml


# Run,设置参数
docker run -d -p 9090:9090  --name prometheus  \
-v /dockerdata/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml  \
-v /dockerdata/prometheus/data:/data/PromDB  \
 prom/prometheus \
--config.file="/etc/prometheus/prometheus.yml" \
--web.listen-address="0.0.0.0:9090"  \
--web.max-connections=512  \
--web.enable-lifecycle    \
--storage.tsdb.path="/data/PromDB"   \
--storage.tsdb.retention.time=30d   \
--storage.tsdb.retention.size=2TB   \
--query.timeout=2m   \
--query.max-concurrency=20  \
--storage.tsdb.no-lockfile   \
--storage.tsdb.wal-compression   
参数 含义
config.file 指定配置文件
web.listen-address 指定监听地址
web.max-connections Web最大并发连接数
web.enable-lifecycle 动态加载配置功能
storage.tsdb.path 指定数存储目录
storage.tsdb.retention.time 数据保存时长,过期清理, 默认 15 天
storage.tsdb.retention.size 存储目录大小。B, KB, MB, GB, TB, PB, EB #指定 chunk 大小, 默认 512MB
query.timeout 最大查询超时时间
query.max-concurrency 最大查询并发数
storage.tsdb.no-lockfile 不在数据目录中创建锁文件
storage.tsdb.wal-compression 压缩tsdb WAL

服务参数

Prometheus服务参数相关配置,进入容器后可以使用prometheus -h命令查看

Flags:
#帮助
  -h, --help                     Show context-sensitive help (also try --help-long and --help-man).
#版本
      --version                  Show application version.
#配置文件
      --config.file="prometheus.yml"  
                                 Prometheus configuration file path.
#监听端口
      --web.listen-address="0.0.0.0:9090"  
                                 Address to listen on for UI, API, and telemetry.
#空闲连接的超时时间
      --web.read-timeout=5m      Maximum duration before timing out read of the request, and closing idle connections.
#最大连接数
      --web.max-connections=512  Maximum number of simultaneous connections.

#可从外部访问Prometheus的URL(例如,如果Prometheus是通过反向代理提供的)。 用于生成返回到Prometheus本身的相对和绝对链接。 如果URL包含路径部分,它将被用作Prometheus服务的所有HTTP端点的前缀。 如果省略,则会自动派生相关的URL组件。
      --web.external-url=<URL>   The URL under which Prometheus is externally reachable (for example, if Prometheus is served via a reverse proxy). Used for generating relative and absolute links back to
                                 Prometheus itself. If the URL has a path portion, it will be used to prefix all HTTP endpoints served by Prometheus. If omitted, relevant URL components will be derived
                                 automatically.
#内部路由的前缀。 默认为--web.external-url的路径。
      --web.route-prefix=<path>  Prefix for the internal routes of web endpoints. Defaults to path of --web.external-url.
#静态资源目录的路径,位于/ user
      --web.user-assets=<path>   Path to static asset directory, available at /user.
#启用是否通过HTTP请求重新加载
      --web.enable-lifecycle     Enable shutdown and reload via HTTP request.
#管理控制操作启用API端点
      --web.enable-admin-api     Enable API endpoints for admin control actions.
#模板目录的路径,位于/consoles
      --web.console.templates="consoles"  
                                 Path to the console template directory, available at /consoles.
#控制台库目录的路径
      --web.console.libraries="console_libraries"  
                                 Path to the console library directory.
#Prometheus实例页面的文档标题
      --web.page-title="Prometheus Time Series Collection and Processing Server"  
                                 Document title of Prometheus instance.
#用于CORS来源的正则表达式。 
      --web.cors.origin=".*"     Regex for CORS origin. It is fully anchored. Example: 'https?://(domain1|domain2)\.com'
#指标(数据)存储的基本路径
      --storage.tsdb.path="data/"  
                                 Base path for metrics storage.
#将数据保留多长时间。 此标志已被弃用,请改用“ storage.tsdb.retention.time”。
      --storage.tsdb.retention=STORAGE.TSDB.RETENTION  
                                 [DEPRECATED] How long to retain samples in storage. This flag has been deprecated, use "storage.tsdb.retention.time" instead.
#将数据保留多长时间。默认15天
      --storage.tsdb.retention.time=STORAGE.TSDB.RETENTION.TIME  
                                 How long to retain samples in storage. When this flag is set it overrides "storage.tsdb.retention". If neither this flag nor "storage.tsdb.retention" nor
                                 "storage.tsdb.retention.size" is set, the retention time defaults to 15d.
#可以为块存储的最大字节数。 支持的单位:KB,MB,GB,TB,PB。
      --storage.tsdb.retention.size=STORAGE.TSDB.RETENTION.SIZE  
                                 [EXPERIMENTAL] Maximum number of bytes that can be stored for blocks. Units supported: KB, MB, GB, TB, PB. This flag is experimental and can be changed in future releases.
#不在数据目录中创建锁文件
      --storage.tsdb.no-lockfile  
                                 Do not create lockfile in data directory.
#允许重叠的块,从而启用垂直压缩和垂直查询合并。
      --storage.tsdb.allow-overlapping-blocks  
                                 [EXPERIMENTAL] Allow overlapping blocks, which in turn enables vertical compaction and vertical query merge.
#压缩tsdb WAL
      --storage.tsdb.wal-compression  
                                 Compress the tsdb WAL.
#关闭或配置重新加载时等待刷写数据的时间
      --storage.remote.flush-deadline=<duration>  
                                 How long to wait flushing sample on shutdown or config reload.
#在单个查询中通过远程读取接口返回的最大样本总数。 0表示没有限制。 对于流式响应类型,将忽略此限制。
      --storage.remote.read-sample-limit=5e7  
                                 Maximum overall number of samples to return via the remote read interface, in a single query. 0 means no limit. This limit is ignored for streamed response types.
#并发远程读取调用的最大数目。 0表示没有限制。
      --storage.remote.read-concurrent-limit=10  
                                 Maximum number of concurrent remote read calls. 0 means no limit.
#用于流式传输远程读取响应类型的单个帧中的最大字节数。 请注意,客户端也可能会限制帧大小。 1MB为默认情况下由protobuf推荐
--storage.remote.read-max-bytes-in-frame=1048576  
                                 Maximum number of bytes in a single frame for streaming remote read response types before marshalling. Note that client might have limit on frame size as well. 1MB as
                                 recommended by protobuf by default.
#容忍中断以恢复警报“ for”状态的最长时间。
      --rules.alert.for-outage-tolerance=1h  
                                 Max time to tolerate prometheus outage for restoring "for" state of alert.
#警报和恢复的“ for”状态之间的最短持续时间。 仅对于配置的“ for”时间大于宽限期的警报,才保持此状态。
      --rules.alert.for-grace-period=10m  
                                 Minimum duration between alert and restored "for" state. This is maintained only for alerts with configured "for" time greater than grace period.
#将警报重新发送到Alertmanager之前等待的最短时间。
      --rules.alert.resend-delay=1m  
                                 Minimum amount of time to wait before resending an alert to Alertmanager.
#等待的Alertmanager通知的队列容量。
      --alertmanager.notification-queue-capacity=10000  
                                 The capacity of the queue for pending Alertmanager notifications.
#向Alertmanager发送警报的超时。
      --alertmanager.timeout=10s  
                                 Timeout for sending alerts to Alertmanager.
#在表达式求值期间检索指标的最大回溯持续时间。
      --query.lookback-delta=5m  The maximum lookback duration for retrieving metrics during expression evaluations.
#最大查询时间。
      --query.timeout=2m         Maximum time a query may take before being aborted.
#最大查询并发数
      --query.max-concurrency=20  
                                 Maximum number of queries executed concurrently.
#单个查询可以加载到内存中的最大样本数。 请注意,如果查询尝试将更多的样本加载到内存中,则查询将失败,因此这也限制了查询可以返回的样本数。
      --query.max-samples=50000000  
                                 Maximum number of samples a single query can load into memory. Note that queries will fail if they try to load more samples than this into memory, so this also limits the
                                 number of samples a query can return.
#日志级别
      --log.level=info           Only log messages with the given severity or above. One of: [debug, info, warn, error]
#日志格式
      --log.format=logfmt        Output format of log messages. One of: [logfmt, json]

Prometheus.yml配置

默认prometheus.yml配置

global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
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: ["localhost:9090"]

修改后的简化版prometheus.yml

global:
  scrape_interval:   60s
  evaluation_interval: 60s
 
scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ['localhost:9090']
        labels:
          instance: prometheus

浏览器访问http://172.25.255.30:9090,看看是否启动成功

浏览器访问http://172.25.255.30:9090/targets可以查看所有节点

Exporter

简介

Exporter是一类数据采集组件的总称。Exporter负责从目标处搜集数据,并将其转化为Prometheus支持的格式,它开放了一个http接口(以便Prometheus抓取数据)。与传统的数据采集组件不同的是Exporter并不向中央服务器发送数据,而是等待中央服务器(如Prometheus等)主动前来抓取数据。

Exporter有很多客户端部署方式,下载地址:https://prometheus.io/download/
相关网址:

客户端安装地址

部署

官方部署文档地址

Docker部署

docker pull prom/node-exporter
docker run -d -p 9100:9100 -v "/proc:/host/proc:ro" -v "/sys:/host/sys:ro" -v "/:/rootfs:ro" --name node-exporter prom/node-exporter   --path.rootfs=/host

访问http://172.25.255.30:9100,看看是否部署成功

Prometheus加入Exporter节点配置

编辑Prometheus配置文件添加node子节点,vi /dockerdata/prometheus/prometheus.yml

global:
  scrape_interval:   60s
  evaluation_interval: 60s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ['localhost:9090']
        labels:
          instance: prometheus

  - job_name: linuxnode1
    static_configs:
      - targets: ['172.25.255.30:9100']
        labels:
          instance: linuxnode1

重启容器

docker  restart   prometheus 
docker  restart   node-exporter

等2分钟后访问http://172.25.255.30:9090/targets,查看添加的节点是否Up

添加多个节点

global:
  scrape_interval:   60s
  evaluation_interval: 60s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ['localhost:9090']
        labels:
          instance: prometheus

  - job_name: linuxnode1
    static_configs:
      - targets:
        - 172.25.255.30:9100
        - 172.25.240.1:9182
        labels:
          instance: linuxnode1

  - job_name: linuxnode2
    static_configs:
      - targets:
        - 172.25.255.30:9100
        - 172.25.240.1:9182
        labels:
          instance: linuxnode2

访问http://172.25.255.30:9090/targets

Grafana

介绍

Grafana是开源的、炫酷的可视化监控、分析利器,无论您的数据在哪里,或者它所处的数据库是什么类型,您都可以将它与Grafana精美地结合在一起。它还有丰富的套件供您选择,目前,它已拥有54个数据源,50个面板,17个应用程序和1732个仪表盘。总而言之Grafana是一个跨平台的开源的度量分析和可视化工具,可以通过将采集的数据查询然后可视化的展示,并及时通知。
Grafana相关地址:

六大特点

  1. 展示方式:快速灵活的客户端图表,面板插件有许多不同方式的可视化指标和日志,官方库中具有丰富的仪表盘插件,比如热图、折线图、图表等多种展示方式;
  2. 数据源:Graphite,InfluxDB,OpenTSDB,Prometheus,MySql,Sql Server,PostgreSql,Elasticsearch,CloudWatch和KairosDB等;
  3. 通知提醒:以可视方式定义最重要指标的警报规则,Grafana将不断计算并发送通知,在数据达到阈值时通过Slack、PagerDuty等获得通知;
  4. 混合展示:在同一图表中混合使用不同的数据源,可以基于每个查询指定数据源,甚至自定义数据源;
  5. 注释:使用来自不同数据源的丰富事件注释图表,将鼠标悬停在事件上会显示完整的事件元数据和标记;
  6. 过滤器:Ad-hoc过滤器允许动态创建新的键/值过滤器,这些过滤器会自动应用于使用该数据源的所有查询。

部署

官方部署文档地址
grafana配置文件目录在:/etc/grafana/grafana.ini,一般默认配置即可。grafana默认使用 sqlite存储数据,数据存放在data/grafana.db

本次使用Docker容器部署

# 拉镜像
docker pull  grafana/grafana:latest
# 新建grafana持久化目录
mkdir /dockerdata
# Run一个临时容器拷贝相关目录
docker run -d --name grafana grafana/grafana:latest
docker cp grafana:/var/lib/grafana       /dockerdata
docker rm -f grafana
##添加权限
chown -R 1000:1000 /dockerdata/grafana
chmod -R 777  /dockerdata/grafana

# Run容器
docker run -d  -v /dockerdata/grafana:/var/lib/grafana -p 3000:3000 --name grafana  grafana/grafana:latest

添加数据源

浏览器访问http://172.25.255.30:3000,进入登陆界面。默认用户名密码:admin/admin,首次登录需要修改密码。

登录成功后进入首页,添加数据源

选择Prometheus

配置Prometheus名称和Url地址

请求HTTP Method选择Get然后保存

导入Dashboard

Dashboard模板地址
上一步导入了Prometheus数据源,但是还需要dashboard展示出来。
左边导航选择Dashboards-Import并填入JSONId。官方默认的模板ID:8919

添加项目名称和数据源并导入

查看面板成品并保存

模板库导入Dashboard

搜索对应模板Node Export

https://grafana.com/grafana/dashboards/?dataSource=prometheus&search=Node+Export


进入界面后可以看到模板Id和下载JSON

然后在Grafana中输入Id或者JSON导入

查看成品

posted @ 2022-11-14 17:32  雨水的命运  阅读(1699)  评论(0编辑  收藏  举报