Prometheus 監控技術與實踐

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等

官網地址:https://prometheus.io/

系統生態

image-20210619121332849

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_bucket

    image-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-20210619132146337

    2、獲取內存使用率: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

image-20210619133715408

Graph

image-20210619134235335

Springboot 集成

Springboot1.5集成

 <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>
    
  • 默認地址: http://localhost:8990/actuator/prometheus

  • 配置

    #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
image-20210619140617363

數據源配置

image-20210619140724163
image-20210619140758511
image-20210619140826771

監控儀表盤

  • 導入常用別人已配置的圖表信息,例如:springboot 用了micrometer 庫,從granfna官網可以找到該庫已提供的的JVM監控圖表

    直接找到 id 導入即可。找找地址:https://grafana.com/grafana/dashboards

搜索

image-20210619141421183

查看詳情

image-20210619141451117

導入

image-20210619141534030

JVM 監控儀表盤:

image-20210619141631429
  • 自定義制作

    image-20210619141735924
image-20210619142427843

報警

基于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-20210619145400280
  • 告警展示

    image-20210619144045025

基于Granfana 報警

  • 創建Channel

    image-20210619150015038
image-20210619150415772
  • 創建規則

    image-20210619150511161
image-20210619150532175
  • 告警效果展示Email

    image-20210619150810069

Prometheus監控架構

image-20210619231930528
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,748評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,165評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,595評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,633評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,435評論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,943評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,035評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,175評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,713評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,599評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,788評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,303評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,034評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,412評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,664評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,408評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,747評論 2 370