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導入

查看成品

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章