本文主要介紹的是Prometheus採集數據,經過Grafana加上PromQL語句實現數據可視化以及經過Alertmanage實現告警推送功能。舒適提示,本篇文章特長,2w多的文字加上幾十張圖片,建議收藏觀看。html
Prometheus 是一套開源的系統監控報警框架。它啓發於 Google 的 borgmon 監控系統,由工做在 SoundCloud 的 google 前員工在 2012 年建立,做爲社區開源項目進行開發,並於 2015 年正式發佈。2016 年,Prometheus 正式加入 Cloud Native Computing Foundation,成爲受歡迎度僅次於 Kubernetes 的項目。node
做爲新一代的監控框架,Prometheus 具備如下特色:linux
示例圖:
git
在選擇Prometheus做爲監控工具前,要明確它的適用範圍,以及不適用的場景。
Prometheus在記錄純數值時間序列方面表現很是好。它既適用於以服務器爲中心的監控,也適用於高動態的面向服務架構的監控。
在微服務的監控上,Prometheus對多維度數據採集及查詢的支持也是特殊的優點。
Prometheus更強調可靠性,即便在故障的狀況下也能查看系統的統計信息。權衡利弊,以可能丟失少許數據爲代價確保整個系統的可用性。所以,它不適用於對數據準確率要求100%的系統,好比實時計費系統(涉及到錢)。github
Prometheus Server:正則表達式
Prometheus Server是Prometheus組件中的核心部分,負責實現對監控數據的獲取,存儲以及查詢。 Prometheus Server能夠經過靜態配置管理監控目標,也能夠配合使用Service Discovery的方式動態管理監控目標,並從這些監控目標中獲取數據。其次Prometheus Server須要對採集到的監控數據進行存儲,Prometheus Server自己就是一個時序數據庫,將採集到的監控數據按照時間序列的方式存儲在本地磁盤當中。最後Prometheus Server對外提供了自定義的PromQL語言,實現對數據的查詢以及分析。 Prometheus Server內置的Express Browser UI,經過這個UI能夠直接經過PromQL實現數據的查詢以及可視化。 Prometheus Server的聯邦集羣能力可使其從其餘的Prometheus Server實例中獲取數據,所以在大規模監控的狀況下,能夠經過聯邦集羣以及功能分區的方式對Prometheus Server進行擴展。spring
Exporters:sql
Exporter將監控數據採集的端點經過HTTP服務的形式暴露給Prometheus Server,Prometheus
Server經過訪問該Exporter提供的Endpoint端點,便可獲取到須要採集的監控數據。 通常來講能夠將Exporter分爲2類:
直接採集:這一類Exporter直接內置了對Prometheus監控的支持,好比cAdvisor,Kubernetes,Etcd,Gokit等,都直接內置了用於向Prometheus暴露監控數據的端點。
間接採集:間接採集,原有監控目標並不直接支持Prometheus,所以咱們須要經過Prometheus提供的Client Library編寫該監控目標的監控採集程序。例如: Mysql Exporter,JMX Exporter,Consul Exporter等。數據庫
PushGateway:json
在Prometheus Server中支持基於PromQL建立告警規則,若是知足PromQL定義的規則,則會產生一條告警,而告警的後續處理流程則由AlertManager進行管理。在AlertManager中咱們能夠與郵件,Slack等等內置的通知方式進行集成,也能夠經過Webhook自定義告警處理方式。
Service Discovery:
服務發如今Prometheus中是特別重要的一個部分,基於Pull模型的抓取方式,須要在Prometheus中配置大量的抓取節點信息才能夠進行數據收集。有了服務發現後,用戶經過服務發現和註冊的工具對成百上千的節點進行服務註冊,並最終將註冊中心的地址配置在Prometheus的配置文件中,大大簡化了配置文件的複雜程度,
也能夠更好的管理各類服務。 在衆多雲平臺中(AWS,OpenStack),Prometheus能夠
經過平臺自身的API直接自動發現運行於平臺上的各類服務,並抓取他們的信息Kubernetes掌握並管理着全部的容器以及服務信息,那此時Prometheus只須要與Kubernetes打交道就能夠找到全部須要監控的容器以及服務對象.
- Consul(官方推薦)等服務發現註冊軟件
- 經過DNS進行服務發現
- 經過靜態配置文件(在服務節點規模不大的狀況下)
Prometheus UI是Prometheus內置的一個可視化管理界面,經過Prometheus UI用戶可以輕鬆的瞭解Prometheus當前的配置,監控任務運行狀態等。 經過Graph面板,用戶還能直接使用PromQL實時查詢監控數據。訪問ServerIP:9090/graph打開WEB頁面,經過PromQL能夠查詢數據,能夠進行基礎的數據展現。
以下所示,查詢主機負載變化狀況,可使用關鍵字node_load1能夠查詢出Prometheus採集到的主機負載的樣本數據,這些樣本數據按照時間前後順序展現,造成了主機負載隨時間變化的趨勢圖表:
Grafana是一個跨平臺的開源的度量分析和可視化工具,能夠經過將採集的數據查詢而後可視化的展現。Grafana提供了對prometheus的友好支持,各類工具幫助你構建更加炫酷的數據可視化。
這裏咱們使用上面Prometheus使用關鍵字node_load1來使用Grafana進行可視化,點擊側邊欄的加號圖標,而後單擊Dashboard點擊建立,而後把剛剛Prometheus使用的查詢語句放到Metries,點擊右上角的apply便可。
示例圖:
上面的示例中咱們經過prometheus+grafana經過PromQL進行了簡單的服務器負載的監控可視化。咱們也能夠經過第三方提供可視化JSON文件來幫助咱們快速實現服務器、Elasticsearch、MYSQL等等監控。這裏咱們在grafana提供的第三方dashboards的地址https://grafana.com/grafana/dashboards來下載對應的json文件而後導入到grafana實現服務器的監控。
監控服務器的示例圖:
除了服務端的監控,能夠監控應用服務。Prometheus 監控應用的方式很是簡單,只須要進程暴露了一個用於獲取當前監控樣本數據的 HTTP 訪問地址。這樣的一個程序稱爲Exporter,Exporter 的實例稱爲一個 Target 。Prometheus 經過輪訓的方式定時從這些 Target 中獲取監控數據樣本,對於應用來說,只須要暴露一個包含監控數據的 HTTP 訪問地址便可,固然提供的數據須要知足必定的格式,這個格式就是 Metrics 格式: metric name>{
Prometheus以及相關組件使用的是2.x版本,Grafana使用的是7.x版本。
下載地址推薦使用清華大學或華爲的開源鏡像站。
下載地址:
https://prometheus.io/download/
https://mirrors.tuna.tsinghua.edu.cn/grafana/
Prometheus以及相關組件百度網盤地址:
連接:https://pan.baidu.com/s/1btErwq8EyAzG2-34lwGO4w
提取碼:4nlh
將下載好的Prometheus文件解壓
輸入
tar -zxvf prometheus-2.19.3.linux-amd64.tar.gz
而後移動到/opt/prometheus文件夾裏面,沒有該文件夾則建立
在prometheus-2.19.3.linux-amd64文件夾目錄下找到prometheus.yml配置文件並更改
prometheus.yml文件配置以下:
# my global config 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: ['192.168.8.181:9090']
在/opt/prometheus/prometheus-2.19.3.linux-amd64的目錄下輸入:
nohup ./prometheus >/dev/null 2>&1 &
啓動成功以後,在瀏覽器上輸入 ip+9090能夠查看相關信息。
將下載下來的grafana-7.1.1-1.x86_64.rpm的文件經過apm方式安裝
輸入:
rpm -ivh grafana-7.1.1-1.x86_64.rpm
進行安裝
若是出現以下錯誤:
error: Failed dependencies: urw-fonts is needed by grafana-6.1.4-1.x86_64
一個依賴包沒有安裝,須要先安裝這個依賴包,而後再安裝grafana
# yum install -y urw-fonts
root用戶下啓動
輸入:
sudo /bin/systemctl start grafana-server.service
啓動成功以後,在瀏覽器上輸入 ip+3000能夠查看相關信息
將下載好的Alertmanager文件解壓
輸入
tar -zxvf alertmanager-0.21.0.linux-386.tar.gz
而後移動到/opt/prometheus文件夾裏面,沒有該文件夾則建立
root用戶下啓動
輸入:
nohup ./alertmanager >/dev/null 2>&1 &
啓動成功以後,在瀏覽器上輸入 ip+9093能夠查看相關信息
示例圖:
將下載好的pushgateway文件解壓
輸入
tar -zxvf pushgateway-1.2.0.linux-amd64.tar.gz
而後移動到/opt/prometheus文件夾裏面,沒有該文件夾則建立
root用戶下啓動
輸入:
nohup ./pushgateway >/dev/null 2>&1 &
啓動成功以後,在瀏覽器上輸入 ip+9091能夠查看相關信息
將下載好的Node_export文件解壓
輸入
tar -zxvf node_exporter-0.17.0.linux-amd64.tar.gz
而後移動到/opt/prometheus文件夾裏面,沒有該文件夾則建立
root用戶下啓動
輸入:
nohup ./consul_exporter >/dev/null 2>&1 &
啓動成功以後,在瀏覽器上輸入 ip+9100能夠查看相關信息
Prometheus界面地址: ip+9090。
這裏我就使用圖片加上註釋來進行講解。
集成的組件須要下載對應export服務並啓動運行,而且在prometheus的配置中進行添加!
first_rules.yml的配置。
相關文檔:https://prometheus.io/docs/prometheus/latest/getting_started/
Grafanf 界面地址: ip+3000
初始帳號密碼: admin, admin
這裏我依舊用圖片加註釋來進行講解,想必這樣會更容易理解吧。。。
1.添加數據源
2.選擇prometheus
3.點擊建立儀表盤
4.點擊建立
5.輸入node_load1表示語句,填寫相關信息,點擊apply完成,並將名稱保存爲Test
6.點擊搜索Test,點擊就能夠查看
注:需提早添加好數據源。
1.點擊左上角的加號,點擊import
在線模式
地址:https://grafana.com/grafana/dashboards
離線模式
監控示例:
監控告警實現須要依賴 Alertmanager,已經相關的組件,好比上述實例中的監控服務器應用的node_server組件。
須要安裝Alertmanager,這裏由於郵件發送比較簡單,因此這裏我就直接貼配置了,其中帶有xxx字符的參數是須要根據狀況進行更改的。下面的企業微信告警同理。
Alertmanagers服務的alertmanager.yml的配置以下:
global: resolve_timeout: 5m smtp_from: 'xxx@qq.com' smtp_smarthost: 'smtp.qq.com:465' smtp_auth_username: 'xxx@qq.com' smtp_auth_password: 'xxx' smtp_require_tls: false smtp_hello: 'qq.com' route: group_by: ['alertname'] group_wait: 5s group_interval: 5s repeat_interval: 5m receiver: 'email' receivers: - name: 'email' email_configs: - to: 'xxx@qq.com' send_resolved: true inhibit_rules: - source_match: severity: 'critical' target_match: severity: 'warning' equal: ['alertname', 'dev', 'instance']
注: smtp_from、smtp_auth_username、to的郵箱能夠填寫同一個,smtp_auth_password填寫鑑權碼,須要開啓POS3。
若是不知道怎麼開啓POS3,能夠查看個人這篇文章: http://www.javashuo.com/article/p-rnabukqs-ep.html
Prometheus服務的Prometheus.yml配置以下:
# my global config 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: - '192.168.214.129:9093' # Load rules once and periodically evaluate them according to the global 'evaluation_interval'. rule_files: - "/opt/prometheus/prometheus-2.19.3.linux-amd64/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: ['192.168.214.129:9090'] - job_name: 'server' static_configs: - targets: ['192.168.214.129:9100']
注:targets若是有多個配置的話,在後面加上其餘服務的節點便可。alertmanagers最好寫服務器的ip,否則可能會出現告警數據沒法發送的狀況。
Error sending alert" err="Post \"http://alertmanager:9093/api/v1/alerts\": context deadline exceeded
配置了Prometheus.yml以後,咱們還須要配置告警的規則,也就是觸發條件,達到條件以後就進行觸發。咱們新建一個first_rules.yml,用於檢測服務器掛掉的時候進行發送消息
first_rules.yml告警配置:
注:job等於的服務名稱填寫Prometheus.yml配置對應的名稱,好比這裏設置的server對應Prometheus.yml配置的server。
groups: - name: node rules: - alert: server_status expr: up{job="server"} == 0 for: 15s annotations: summary: "機器{{ $labels.instance }} 掛了" description: "報告.請當即查看!"
依次啓動prometheus、altermanagers、node_server服務,查看告警,而後中止node_export服務,等待一段時間在查看。
和上面的示例操做基本一致,主要是配置的區別。
1.在企業微信中建立一個應用,並獲得secret、corp_id和agent_id配置。
2.而後修改alertmanager.yml配置,alertmanager.yml配置以下:
global: resolve_timeout: 5s wechat_api_url: 'https://qyapi.weixin.qq.com/cgi-bin/' wechat_api_secret: 'xxx' wechat_api_corp_id: 'xxx' templates: - '/opt/prometheus/alertmanager-0.21.0.linux-386/template/wechat.tmpl' route: group_by: ['alertname'] group_wait: 10s group_interval: 10s repeat_interval: 10s receiver: 'wechat' receivers: - name: 'wechat' wechat_configs: - send_resolved: true to_party: '2' agent_id: xxx corp_id: 'xxx' api_secret: 'xxx' api_url: 'https://qyapi.weixin.qq.com/cgi-bin/' inhibit_rules: - source_match: severity: 'critical' target_match: severity: 'warning' equal: ['alertname', 'dev', 'instance']
配置成功以後,操做和上述郵件發送的一致,便可在企業微信看到以下信息。
若是以爲上述的示例很差友好的話,咱們也能夠制定告警模板。
添加告警模板:
在alertmanagers的文件夾下建立一個template文件夾,而後在該文件夾建立一個微信告警的模板wechat.tmpl,添加以下配置:
{{ define "wechat.default.message" }} {{ range .Alerts }} ========start========= 告警程序: prometheus_alert 告警級別: {{ .Labels.severity}} 告警類型: {{ .Labels.alertname }} 故障主機: {{ .Labels.instance }} 告警主題: {{ .Annotations.summary }} 告警詳情: {{ .Annotations.description }} =========end=========== {{ end }} {{ end }}
而後再到alertmanager.yml 添加以下配置:
templates: - '/opt/prometheus/alertmanager-0.21.0.linux-386/template/wechat.tmpl'
效果圖:
Prometheus 監控應用的方式很是簡單,只須要進程暴露了一個用於獲取當前監控樣本數據的 HTTP
訪問地址。這樣的一個程序稱爲Exporter,Exporter 的實例稱爲一個 Target 。Prometheus經過輪訓的方式定時從這些 Target 中獲取監控數據樣本,對於應用來說,只須要暴露一個包含監控數據的 HTTP訪問地址便可,固然提供的數據須要知足必定的格式,這個格式就是 Metrics 格式: metric name>{= , ...} 。label name是標籤,label value是標籤的值。
Springboot應用實現步驟
1.在pom文件添加
<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
2.在代碼中添加以下配置:
private Counter requestErrorCount; private final MeterRegistry registry; @Autowired public PrometheusCustomMonitor(MeterRegistry registry) { this.registry = registry; } @PostConstruct private void init() { requestErrorCount = registry.counter("requests_error_total", "status", "error"); } public Counter getRequestErrorCount() { return requestErrorCount; }
3.在異常處理中添加以下記錄:
monitor.getRequestErrorCount().increment();
4.在prometheus的配置中添加springboot應用服務監控
- job_name: 'springboot' metrics_path: '/actuator/prometheus' scrape_interval: 5s static_configs: - targets: ['192.168.8.45:8080']
5.Prometheu.yml配置以下:
- job_name: 'springboot' metrics_path: '/actuator/prometheus' scrape_interval: 5s static_configs: - targets: ['192.168.8.45:8080']
規則文件配置以下:
6.在prometheus監控便可查看
企業微信告警效果圖:
監控的springboot項目地址:https://github.com/xuwujing/springBoot-study
Prometheus數據源的配置主要分爲靜態配置和動態發現, 經常使用的爲如下幾類:
file_sd_configs的方式提供簡單的接口,能夠實如今單獨的配置文件中配置拉取對象,並監視這些文件的變化並自動加載變化。基於這個機制,咱們能夠自行開發程序,監控監控對象的變化自動生成配置文件,實現監控對象的自動發現。
在prometheus文件夾目錄下建立targets.json文件
配置以下:
[ { "targets": [ "192.168.214.129:9100"], "labels": { "instance": "node", "job": "server-129" } }, { "targets": [ "192.168.214.134:9100"], "labels": { "instance": "node", "job": "server-134" } } ]
而後在prometheus目錄下新增以下配置:
- job_name: 'file_sd' file_sd_configs: - files: - targets.json
這是本人整理的一些服務應用告警的配置,也歡迎你們共同討論一些經常使用的相關配置。
內存告警設置
- name: test-rule rules: - alert: "內存報警" expr: 100 - ((node_memory_MemAvailable_bytes * 100) / node_memory_MemTotal_bytes) > 30 for: 15s labels: severity: warning annotations: summary: "服務名:{{$labels.instance}}內存使用率超過30%了" description: "業務500報警: {{ $value }}" value: "{{ $value }}"
示例圖:
磁盤設置:
總量百分比設置:
(node_filesystem_size_bytes {mountpoint ="/"} - node_filesystem_free_bytes {mountpoint ="/"}) / node_filesystem_size_bytes {mountpoint ="/"} * 100
查看某一目錄的磁盤使用百分比
(node_filesystem_size_bytes{mountpoint="/boot"}-node_filesystem_free_bytes{mountpoint="/boot"})/node_filesystem_size_bytes{mountpoint="/boot"} * 100
正則表達式來匹配多個掛載點
(node_filesystem_size_bytes{mountpoint=~"/|/run"}-node_filesystem_free_bytes{mountpoint=~"/|/run"})
/ node_filesystem_size_bytes{mountpoint=~"/|/run"} * 100
預計多長時間磁盤爆滿
predict_linear(node_filesystem_free_bytes {mountpoint ="/"}[1h],
43600) < 0 predict_linear(node_filesystem_free_bytes
{job="node"}[1h], 43600) < 0
100 - (avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by
(instance) * 100)
(node_memory_MemFree_bytes+node_memory_Cached_bytes+node_memory_Buffers_bytes)
/ node_memory_MemTotal_bytes * 100
100 -
(node_memory_MemFree_bytes+node_memory_Cached_bytes+node_memory_Buffers_bytes)
/ node_memory_MemTotal_bytes * 100
100 - (node_filesystem_free_bytes{mountpoint="/",fstype=~"ext4|xfs"} /
node_filesystem_size_bytes{mountpoint="/",fstype=~"ext4|xfs"} * 100)
這段時間比較忙,ELK相關得等待一段時間在進行更新,雖然發表的博客纔對應去年整理的博客。。。。
本篇文章準備了很久,邊整理編寫,沒想到寫了這麼多。不過感受這樣也不錯,一次寫出來或許比分開一次次的寫對讀者而言要好上不上,畢竟不用一篇篇的去找了。
原創不易,若是感受不錯,但願給個推薦!您的支持是我寫做的最大動力!
版權聲明:
做者:虛無境
博客園出處:http://www.cnblogs.com/xuwujing
CSDN出處:http://blog.csdn.net/qazwsxpcm
掘金出處:https://juejin.im/user/5ae45d5bf265da0b8a6761e4
我的博客出處:http://www.panchengming.com