Prometheus 監控技術與實踐
監控分類
- Logging 用于記錄離散的事件。例如,應用程序的調試信息或錯誤信息。它是我們診斷問題的依據。比如我們說的ELK就是基于Logging。
- Metrics 用于記錄可聚合的數據。例如,1、隊列的當前深度可被定義為一個度量值,在元素入隊或出隊時被更新;HTTP 請求個數可被定義為一個計數器,新請求到來時進行累。2、列如獲取當前CPU或者內存的值。 prometheus專注于Metrics領域。
- Tracing - 用于記錄請求范圍內的信息。例如,一次遠程方法調用的執行過程和耗時。它是我們排查系統性能問題的利器。最常用的有Skywalking,ping-point,zipkin。
Prometheus介紹
簡介
Prometheus(中文名:普羅米修斯)是由SoundCloud開發的開源監控報警系統和時序列數據庫(TSDB). Prometheus使用Go語言開發, 是Google BorgMon監控系統的開源版本。
Prometheus的基本原理是通過HTTP協議周期性抓取被監控組件的狀態, 任意組件只要提供對應的HTTP接口就可以接入監控. 不需要任何SDK或者其他的集成過程。輸出被監控組件信息的HTTP接口被叫做exporter,目前開發常用的組件大部分都有exporter可以直接使用, 比如Nginx、MySQL、Linux系統信息、Mongo、ES等
系統生態
Prometheus 可以從配置或者用服務發現,去調用各個應用的 metrics 接口,來采集數據,然后存儲在硬盤中,而如果是基礎應用比如數據庫,負載均衡器等,可以在相關的服務中安裝 Exporters 來提供 metrics 接口供 Prometheus 拉取。
采集到的數據有兩個去向,一個是報警,另一個是可視化。
Prometheus有著非常高效的時間序列數據存儲方法,每個采樣數據僅僅占用3.5byte左右空間,上百萬條時間序列,30秒間隔,保留60天,大概花了200多G(引用官方PPT)。
Prometheus內部主要分為三大塊,Retrieval是負責定時去暴露的目標頁面上去抓取采樣指標數據,Storage是負責將采樣數據寫磁盤,PromQL是Prometheus提供的查詢語言模塊。
Metrics
格式
<metric name>{<label name>=<label value>, ...}
- metric name: [a-zA-Z_:][a-zA-Z0-9_:]*
- label name: [a-zA-Z0-9_]*
- label value: .* (即不限制)
例如通過NodeExporter的metrics地址暴露指標內容:
node_cpu_seconds_total{cpu="0",mode="idle"} 927490.95
node_cpu_seconds_total{cpu="0",mode="iowait"} 27.74
樣本
在時間序列中的每一個點稱為一個樣本(sample),樣本由以下三部分組成:
- 指標(metric):指標名稱和描述當前樣本特征的 labelsets;
- 時間戳(timestamp):一個精確到毫秒的時間戳;
- 樣本值(value):一個 folat64 的浮點型數據表示當前樣本的值。
數據類型
Prometheus定義了4中不同的指標類型(metric type):Counter(計數器)、Gauge(儀表盤)、Histogram(直方圖)、Summary(摘要)。
在NodeExporter返回的樣本數據中,其注釋中也包含了該樣本的類型。例如:
# HELP node_cpu_seconds_total Seconds the cpus spent in each mode.
# TYPE node_cpu_seconds_total counter
node_cpu_seconds_total{cpu="0",mode="idle"} 927490.95
node_cpu_seconds_total{cpu="0",mode="iowait"} 27.74...
-
Counter
統計的數據是遞增的,不能使用計數器來統計可能減小的指標,計數器統計的指標是累計增加的,如http請求的總數,出現的錯誤總數,總的處理時間,api請求數等
例如:
第一次抓取 http_response_total{method="GET",endpoint="/api/tracks"} 100 第二次抓取 http_response_total{method="GET",endpoint="/api/tracks"} 150
-
Gauge
量規是一種度量標準,代表可以任意上下波動的單個數值,用于統計cpu使用率,內存使用率,磁盤使用率,溫度等指標,還可以統計上升和下降的計數。如并發請求數等。
例如:
第1次抓取 memory_usage_bytes{host="master-01"} 100 第2秒抓取 memory_usage_bytes{host="master-01"} 30 第3次抓取 memory_usage_bytes{host="master-01"} 50 第4次抓取 memory_usage_bytes{host="master-01"} 80
-
Histogram
統計在一定的時間范圍內數據的分布情況。如請求的持續/延長時間,請求的響應大小等,還提供度量指標的總和,數據以直方圖顯示。Histogram由_bucket{le=""},_bucket{le="+Inf"}, _sum,_count 組成
如:
apiserver_request_latencies_sum
apiserver_request_latencies_count
apiserver_request_latencies_bucketimage-20210621110126391 -
Summary
和Histogram直方圖類似,主要用于表示一段時間內數據采樣結果(通常是請求持續時間或響應大小之類的東西),還可以計算度量值的總和和度量值的分位數以及在一定時間范圍內的分位數,由{quantile="<φ>"},_sum,_count 組成
PromSQL
-
運算
乘:*
除:/
加:+
減:- -
函數
sum() 函數:求出找到所有value的值
irate() 函數:統計平均速率
by (標簽名) 相當于關系型數據庫中的group by函數
min:最小值
count: 元素個數
avg: 平均值
-
范圍匹配
5分鐘之內
[5m] -
案例
1、獲取cpu使用率 :100-(avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by(instance) *100)
image-202106191321463372、獲取內存使用率:100-(node_memory_MemFree_bytes+node_memory_Buffers_bytes+node_memory_Cached_bytes)/node_memory_MemTotal_bytes*100
下載安裝
- 官方下載安裝
# mac下載地址 https://prometheus.io/download/
# 解壓
tar -zxvf prometheus-2.26.0.darwin-amd64.tar.gz
#啟動
./prometheus --config.file=/usr/local/prometheus/prometheus.yml
-
docker 方式快速安裝
docker run -d --restart=always \ -p 9090:9090 \ -v ~/prometheus.yml:/etc/prometheus/prometheus.yml \ prom/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:
# - 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']
- job_name: 'erp-monitord'
metrics_path: '/prometheus'
# scheme defaults to 'http'.
static_configs:
- targets: ['localhost:50258']
Target
Graph
Springboot 集成
Springboot1.5集成
maven 依賴
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-spring-legacy</artifactId>
<version>1.3.15</version>
</dependency>
-
配置訪問地址
#endpoints.prometheus.path=${spring.application.name}/prometheus management.metrics.tags.application = ${spring.application.name}
-
啟動springboot 服務查看指標 http://xxxx:port/prometheus
image-20210619134755801
Springboot2.x 版本集成
-
maven 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-core</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency>
-
配置
#Prometheus springboot監控配置 management: endpoints: web: exposure: include: 'prometheus' # 暴露/actuator/prometheus metrics: tags: application: ${spring.application.name} # 暴露的數據中添加application label
自定義業務指標案例
- 代碼配置
import com.slightech.marvin.api.visitor.app.metrics.VisitorMetrics;
import com.slightech.marvin.api.visitor.app.service.VisitorStatisticsService;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author wanglu
*/
@Configuration
public class MeterConfig {
@Value("${spring.application.name}")
private String applicationName;
@Autowired
private VisitorStatisticsService visitorStatisticsService;
@Bean
public MeterRegistryCustomizer<MeterRegistry> configurer() {
return (registry) -> registry.config().commonTags("application", applicationName);
}
@Bean
public VisitorMetrics visitorMetrics() {
return new VisitorMetrics(visitorStatisticsService);
}
}
-
自定義指標處理類實現MeterBinder 接口
import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; /** * @author wanglu * @date 2019/11/08 */ public class VisitorMetrics implements MeterBinder { private static final String METRICS_NAME_SPACE = "visitor"; private VisitorStatisticsService visitorStatisticsService; public VisitorMetrics(VisitorStatisticsService visitorStatisticsService) { this.visitorStatisticsService = visitorStatisticsService; } @Override public void bindTo(MeterRegistry meterRegistry) { //公寓獲取二維碼次數-當天 //visitor_today_apartment_get_qr_code_count{"application"="xxx", "option"="apartment get qr code"} Gauge.builder(METRICS_NAME_SPACE + "_today_apartment_get_qr_code_count", visitorStatisticsService, VisitorStatisticsService::getTodayApartmentGetQrCodeCount) .description("today apartment get qr code count") .tag("option", "apartment get qr code") .register(meterRegistry); //visitor_today_apartment_get_qr_code_count{"application"="xxx", "option"="employee get qr code"} //員工獲取二維碼次數-當天 Gauge.builder(METRICS_NAME_SPACE + "_today_employee_get_qr_code_count", visitorStatisticsService, VisitorStatisticsService::getTodayEmployeeGetQrCodeCount) .description("today employee get qr code count") .tag("option", "employee get qr code") .register(meterRegistry); } }
-
埋點服務計數
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.Calendar; import java.util.Date; import java.util.concurrent.TimeUnit; /** * 數據統計 * * @author laijianzhen * @date 2019/11/08 */ @Service public class VisitorStatisticsService { /** * 公寓獲取二維碼次數-當天 */ private static final String COUNT_TODAY_APARTMENT_GET_QR_CODE_REDIS_KEY = "Visitor:Statistics:CountTodayApartmentGetQrCode"; /** * 員工獲取二維碼次數-當天 */ private static final String COUNT_TODAY_EMPLOYEE_GET_QR_CODE_REDIS_KEY = "Visitor:Statistics:CountTodayEmployeeGetQrCode"; @Autowired private RedisTemplate<String, Object> redisTemplate; public int getTodayApartmentGetQrCodeCount() { return getCountFromRedis(COUNT_TODAY_APARTMENT_GET_QR_CODE_REDIS_KEY); } public int getTodayEmployeeGetQrCodeCount() { return getCountFromRedis(COUNT_TODAY_EMPLOYEE_GET_QR_CODE_REDIS_KEY); } @Async public void countTodayApartmentGetQrCode() { increaseCount(COUNT_TODAY_APARTMENT_GET_QR_CODE_REDIS_KEY); } @Async public void countTodayEmployeeGetQrCode() { increaseCount(COUNT_TODAY_EMPLOYEE_GET_QR_CODE_REDIS_KEY); } private int getCountFromRedis(String key) { Object object = redisTemplate.opsForValue().get(key); if (object == null) { return 0; } return Integer.parseInt(String.valueOf(object)); } private void increaseCount(String redisKey) { Object object = redisTemplate.opsForValue().get(redisKey); if (object == null) { redisTemplate.opsForValue().set(redisKey, String.valueOf(1), getTodayLeftSeconds(), TimeUnit.SECONDS); return; } redisTemplate.opsForValue().increment(redisKey, 1); } private long getTodayLeftSeconds() { Date nowDate = new Date(); Calendar midnight = Calendar.getInstance(); midnight.setTime(nowDate); midnight.add(Calendar.DAY_OF_MONTH, 1); midnight.set(Calendar.HOUR_OF_DAY, 0); midnight.set(Calendar.MINUTE, 0); midnight.set(Calendar.SECOND, 0); midnight.set(Calendar.MILLISECOND, 0); return (midnight.getTime().getTime() - nowDate.getTime()) / 1000; } }
Grafana 集成
下載安裝
https://grafana.com/grafana/download?pg=get&plcmt=selfmanaged-box1-cta1&platform=mac
#下載解壓
curl -O https://dl.grafana.com/oss/release/grafana-7.5.4.darwin-amd64.tar.gz
tar -zxvf grafana-7.5.4.darwin-amd64.tar.gz
啟動
#啟動
./bin/grafana-server web
#訪問
http://localhost:3000
默認賬號密碼 admin admin
數據源配置
監控儀表盤
-
導入常用別人已配置的圖表信息,例如:springboot 用了micrometer 庫,從granfna官網可以找到該庫已提供的的JVM監控圖表
直接找到 id 導入即可。找找地址:https://grafana.com/grafana/dashboards
搜索
查看詳情
導入
JVM 監控儀表盤:
-
自定義制作
image-20210619141735924
報警
基于AlertManager報警
安裝
- 下載二進制安裝
# mac下載地址 https://prometheus.io/download/
# 解壓
tar -zxvf prometheus-2.26.0.darwin-amd64.tar.gz
#啟動 默認配置項為alertmanager.yml
./alertmanager --config.file=alertmanager.yml
-
docker 安裝
docker run --name alertmanager -d -p 127.0.0.1:9093:9093 quay.io/prometheus/alertmanager
配置
-
alertmanager.yml 配置
# 全局配置項 global: resolve_timeout: 5m #處理超時時間,默認為5min smtp_smarthost: 'smtp.sina.com:25' # 郵箱smtp服務器代理 smtp_from: '******@sina.com' # 發送郵箱名稱 smtp_auth_username: '******@sina.com' # 郵箱名稱 smtp_auth_password: '******' # 郵箱密碼或授權碼 wechat_api_url: 'https://qyapi.weixin.qq.com/cgi-bin/' # 企業微信地址 # 定義模板信心templates: - 'template/*.tmpl' # 定義路由樹信息 route: group_by: ['alertname'] # 報警分組依據 group_wait: 10s # 最初即第一次等待多久時間發送一組警報的通知 group_interval: 10s # 在發送新警報前的等待時間 repeat_interval: 1m # 發送重復警報的周期 對于email配置中,此項不可以設置過低,否則將會由于郵件發送太多頻繁,被smtp服務器拒絕 receiver: 'email' # 發送警報的接收者的名稱,以下receivers name的名稱 # 定義警報接收者信息 receivers: - name: 'email' # 警報 email_configs: # 郵箱配置 - to: '******@163.com' # 接收警報的email配置 html: '{{ template "test.html" . }}' # 設定郵箱的內容模板 headers: { Subject: "[WARN] 報警郵件"} # 接收郵件的標題 webhook_configs: # webhook配置 - url: 'http://127.0.0.1:5001' send_resolved: true wechat_configs: # 企業微信報警配置 - send_resolved: true to_party: '1' # 接收組的id agent_id: '1000002' # (企業微信-->自定應用-->AgentId) corp_id: '******' # 企業信息(我的企業-->CorpId[在底部]) api_secret: '******' # 企業微信(企業微信-->自定應用-->Secret) message: '{{ template "test_wechat.html" . }}' # 發送消息模板的設定# 一個inhibition規則是在與另一組匹配器匹配的警報存在的條件下,使匹配一組匹配器的警報失效的規則。兩個警報必須具有一組相同的標簽。 inhibit_rules: - source_match: severity: 'critical' target_match: severity: 'warning' equal: ['alertname', 'dev', 'instance']
啟用AlertManager 報警 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: ["localhost:9093"]
# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
- "first_rules.yml"
- "second_rules.yml"
-
Rule 定義
groups: - name: <string> rules: - alert: <string> expr: <string> for: [ <duration> | default 0 ] labels: [ <lable_name>: <label_value> ] annotations: [ <lable_name>: <tmpl_string> ]
參數 描述 - name: <string> 警報規則組的名稱 - alert: <string> 警報規則的名稱 expr: <string 使用PromQL表達式完成的警報觸發條件,用于計算是否有滿足觸發條件 <lable_name>: <label_value> 自定義標簽,允許自行定義標簽附加在警報上,比如 high
warning
annotations: <lable_name>: <tmpl_string> 用來設置有關警報的一組描述信息,其中包括自定義的標簽,以及expr計算后的值。
-
案例
groups: - name: operations rules: - alert: node-down expr: up{env="operations"} != 1 for: 5m labels: status: High team: operations annotations: description: "Environment: {{ $labels.env }} Instance: {{ $labels.instance }} is Down ! ! !" value: '{{ $value }}' summary: "The host node was down 20 minutes ago"
查看配置報警配置
-
告警展示
image-20210619144045025
基于Granfana 報警
-
創建Channel
image-20210619150015038
-
創建規則
image-20210619150511161
-
告警效果展示Email
image-20210619150810069