Telegraf+Influxdb+Grafana構建監控平臺

本文章爲本人在ops內容建設團隊第二期分享
歡迎關注微信公衆號:OPS無界工程師
本文章最後更新時間:2018-05-13
我的博客地址:blog.sqdyy.cn
html

你們晚上好,今晚由我來分享基於telegraf+influxdb+grafana構建監控平臺的方案,首先咱們先來了解InfluxDB。influxdb是一款專爲時序數據編寫的高性能數據庫,採用GO語言開發,而且開源!它是TICK技術棧的一部分。它採用TSM引擎進行高速攝取和數據壓縮。並提供高性能的寫入/查詢 HTTP API,其表達式語句相似SQL查詢語句(但數據結構概念不太同樣,詳見InfluxDB design insights and tradeoffsjava

先對上面的一些名稱進行解釋,TICK技術棧指的是InfluxData公司研發的四款監控開源產品,包括Telegraf、InfluxDB、Chronograf、Kapacitor。其中InfluxDB使用最普遍,是開源的時序數據庫,一個比較常見的應用場景爲日誌存儲。Kapacitor提供了基於influxdb的監控報警方案,支持多種數據聚合,選擇,變換,預測方法。Chronograf用於對數據進行展現,可使用功能更強大的Grafana替代。node

TSM引擎這塊我也不太熟悉,屬於進階知識,網上資料也很少,感興趣的大佬能夠本身去研究:linux

TSM

influxdb

時序數據庫主要用於存儲系統的監控數據,通常具備以下特徵:算法

  • 以時間爲維度的高效查詢
  • 方便的down sampling
  • 高效的處理過時數據

對於influxdb的學習方式,我建議先參考Linux大學的InfluxDB系列教程對Influxdb有一個基本的瞭解(但不須要死摳,由於其中有些描述是過期的),而後再去influxdb官檔深刻學習爲佳。數據庫

下載並安裝influxdb

# 添加yum 源
cat <<EOF | sudo tee /etc/yum.repos.d/influxdb.repo
[influxdb]
name = InfluxDB Repository - RHEL \$releasever
baseurl = https://repos.influxdata.com/rhel/\$releasever/\$basearch/stable
enabled = 1
gpgcheck = 1
gpgkey = https://repos.influxdata.com/influxdb.key
EOF
sudo yum install influxdb
influx -version
複製代碼

啓動服務、添加開機啓動:json

sudo service influxdb start
sudo systemctl start influxdb
複製代碼

主要概念

InfluxDB與傳統數據庫在概念上有一些不一樣,我介紹一些基本的概念,若是你想了解更多請參考官檔influxdb conceptscentos

與傳統數據庫中的名詞作比較

influxDB中的名詞 傳統數據庫中的概念
database 數據表
measurement 數據庫中的表
points 表裏面的一行數據

InfluxDB的獨有概念

剛纔說的是InfluxDB與傳統數據庫相同的概念,下面介紹它的特有概念。api

Point

Point至關於傳統數據庫中表裏面的一行數據,由timestamp(時間戳),field(數據),tags(標籤)組成。bash

Point屬性 傳統數據庫中的概念
timestamp 每一個數據都須要一個時間戳(主索引&自動生成),在TSM存儲引擎中會特殊對待,覺得了優化後續的查詢操做
field (field key,field set,field value) 各類記錄值(沒有索引的屬性),例如溫度
tag (tag key,tag sets,tag value) 各類有索引的屬性,例如地區
series

series至關因而InfluxDB中一些數據的集合。全部在數據庫中的數據,都要經過圖表展現出來,而series則表示表裏面的數據,能夠在圖表上畫成幾條線(經過tags排列組合算出來):

> show series from cpu
key
---
cpu,cpu=cpu-total,host=VM_42_233_centos
cpu,cpu=cpu0,host=VM_42_233_centos
cpu,cpu=cpu1,host=VM_42_233_centos
cpu,cpu=cpu2,host=VM_42_233_centos
cpu,cpu=cpu3,host=VM_42_233_centos
複製代碼

其代碼結構以下:

type Series struct {
    mu          sync.RWMutex
    Key         string              // series key
    Tags        map[string]string   // tags
    id          uint64              // id
    measurement *Measurement        // measurement
}
複製代碼
shard

每一個存儲策略下會存在許多shard,每一個shard存儲一個指定時間段的數據,例如7點-8點的數據落入shard0中,8點-9點的數據落到shard1中,每一個shard都對應一個底層的tsm存儲引擎,有獨立的cache,wal,tsm file。

數據保留策略

保留策略(RP)是用來定義數據在InfluxDB存放的時間,或者定義保存某個期間的數據。當你建立數據庫時,InfluxDB會自動建立一個autogen(具備無限保留的保留策略):

> SHOW RETENTION POLICIES ON telegraf
name    duration shardGroupDuration replicaN default
----    -------- ------------------ -------- -------
autogen 0s       168h0m0s           1        true
複製代碼

上面是查詢數據庫現有策略的語句,查詢結果各字段含義以下:

字段 含義
name 策略名稱
duration 持續時間,0表明無限保留
shardGroupDuration shardGroup是InfluxDB的一個基本儲存結構,168h0m0s表上單個shard所存儲的時間間隔爲168小時,超過168小時後會被存放到下一個shard中
replicaN 全稱replication,副本個數(不太懂)
default 是不是默認策略
func shardGroupDuration(d time.Duration) time.Duration {
    if d >= 180*24*time.Hour || d == 0 { // 6 months or 0
        return 7 * 24 * time.Hour
    } else if d >= 2*24*time.Hour { // 2 days
        return 1 * 24 * time.Hour
    }
    return 1 * time.Hour
}
複製代碼

咱們能夠建立一個新的保留策略,下面語句在telegraf庫中建立了一個2小時保留策略,名爲2h0m0s並設置爲默認策略:

> CREATE RETENTION POLICY "2h0m0s" ON "telegraf" DURATION 2h REPLICATION 1 DEFAULT
> SHOW RETENTION POLICIES ON telegraf
name    duration shardGroupDuration replicaN default
----    -------- ------------------ -------- -------
autogen 0s       168h0m0s           1        false
2h0m0s  2h0m0s   1h0m0s             1        true
複製代碼

目前咱們的autogen已經再也不是默認策略,若是你須要查詢這個策略的數據,你須要在查詢時顯式的加上策略名:

> SELECT time,host,usage_system FROM "autogen".cpu limit 2
name: cpu
time                host             usage_system
----                ----             ------------
1526008670000000000 VM_42_233_centos 1.7262947210419817
1526008670000000000 VM_42_233_centos 1.30130130130254
複製代碼

更多保留策略相關的內容,請參考官檔database_management

連續查詢

連續查詢(CQ)是在數據庫中自動定時啓動的一組語句,InfulxDB會將查詢結果存儲在指定的數據表中。

  • 使用連續查詢是最優下降採樣率的方式,連續查詢和存儲策略搭配使用將會大大下降InfulxDB的系統佔用量。
  • 使用連續查詢後,數據會存放到指定的數據表中,這樣就爲之後統計不一樣精度的數據提供了方便。
  • 連續查詢一旦建立就沒法更改。要更改連續查詢,您必須先DROP再從新使用CREATE建立新查詢。

下面是連續查詢的語法:

// 基本語法
CREATE CONTINUOUS QUERY <cq_name> ON <database_name>
RESAMPLE EVERY <interval> FOR <interval>
BEGIN
  SELECT <function[s]> INTO <destination_measurement> 
  FROM <measurement> [WHERE <stuff>] 
  GROUP BY time(<interval>)[,<tag_key[s]>]
END
複製代碼

例如,下面語句在telegraf庫中新建了一個名爲cq_30m的連續查詢,每30分鐘會取used字段的平均值加入到mem_used_30m表中。使用的數據保留策略都是default:

CREATE CONTINUOUS QUERY cq_30m ON telegraf BEGIN SELECT mean(used) INTO mem_used_30m FROM mem GROUP BY time(30m) END
複製代碼

下面是一些經常使用操做:

SQL 描述
SHOW CONTINUOUS QUERIES 查詢全部CQ
DROP CONTINUOUS QUERY <cq_name> ON <database_name> 刪除連續查詢

更多連續查詢相關的內容,請參考官檔continuous_queries

經常使用函數

InfluxDB提供了不少的有用的函數,其中分爲三類:

  • 聚合類函數
函數 描述
count(field_key) 返回計數
DISTINCT(field_key) 返回惟一值
INTEGRAL(field_key) 計算字段值覆蓋的曲面的面積值並獲得面積之和
MEAN(field_key) 返回平均值
MEDIAN(field_key) 返回中間值
MODE(field_key) 返回字段裏最頻繁的值
SPREAD(field_key) 返回最大差值
SUM(field_key) 返回總和
  • 選擇類函數
函數 描述
BOTTOM(field_key,N) 返回最小的N個值
FIRST(field_key) 返回一個字段中最老的取值
LAST(field_key) 返回一個字段中最新的取值
MAX(field_key) 返回一個字段中的最大值
MIN(field_key) 返回一個字段中的最小值
PERCENTILE(field_key,N) Returns the Nth percentile field value.
SAMPLE(field_key,N) 返回N個字段的隨機樣本
TOP(field_key,N) 返回最大的N個值
  • 轉換類函數
函數 描述
CEILING() ~
CUMULATIVE_SUM() ~
DERIVATIVE() ~
DIFFERENCE() ~
ELAPSED() ~
FLOOR() ~
HISTOGRAM() ~
MOVING_AVERAGE() ~
NON_NEGATIVE_DERIVATIVE() ~
NON_NEGATIVE_DIFFERENCE() ~
  • 預測類
函數 描述
HOLT_WINTERS() 季節性預測算法-對數據流量趨勢進行預測和預警

Telegraf

創建起了對時序庫的概念後,接下來咱們就該往時序庫寫數據了,你能夠經過你應用服務的metrics程序採集指標,而後經過influxdb提供的http api向influxdb寫入數據,可是本期咱們並不介紹這樣的用法(如java的metrics還需介紹java的語法),下面爲你們介紹一款與influxdb完美結合的採集數據的代理程序:Telegraf

Telegraf是用Go寫的代理程序,能夠用於收集系統和服務的統計數據,是TICK技術棧的一部分。它具有輸入插件,能夠直接從系統獲取指標數據,從第三方API獲取指標數據,甚至能夠經過statsd和Kafka獲取指標數據。它還具有輸出插件,能夠將採集的指標發送到各類數據存儲,服務和消息隊列。好比InfluxDB,Graphite,OpenTSDB,Datadog,Librato,Kafka,MQTT,NSQ等等。

下載並安裝Telegraf:

wget https://dl.influxdata.com/telegraf/releases/telegraf-1.6.2-1.x86_64.rpm
sudo yum install telegraf-1.6.2-1.x86_64.rpm
telegraf -version
複製代碼

若是你的telegraf是安裝的,其配置文件位置爲:

/etc/telegraf/telegraf.conf
複製代碼

編輯配置文件,將咱們配置好的influxdb數據庫指定爲指望的輸出源:

[[outputs.influxdb]]
  urls=["http://localhost:8086"]
複製代碼

啓動服務、添加開機啓動:

sudo systemctl start telegraf.service
sudo service telegraf status
sudo systemctl enable telegraf.service
複製代碼

在InfluxDB上檢查默認配置下telegraf採集了哪些數據:

> show databases
> use telegraf
> show measurements
> SHOW FIELD KEYS
複製代碼

如何進行配置

默認配置下,會啓用system分類下的INPUT插件,即telegraf.conf有以下配置:

# Read metrics about cpu usage
# 讀取有關CPU使用狀況的指標
[[inputs.cpu]]
  ## Whether to report per-cpu stats or not
  percpu = true
  ## Whether to report total system cpu stats or not
  totalcpu = true
  ## If true, collect raw CPU time metrics.
  collect_cpu_time = false
  ## If true, compute and report the sum of all non-idle CPU states.
  report_active = false

# Read metrics about disk usage by mount point
# 經過mount point讀取有關磁盤使用狀況的指標
[[inputs.disk]]
  ## Ignore mount points by filesystem type.
  ignore_fs = ["tmpfs", "devtmpfs", "devfs"]

# Read metrics about disk IO by device
# 經過device讀取有關磁盤IO的指標
[[inputs.diskio]]

# Get kernel statistics from /proc/stat
# 經過/proc/stat獲取內核統計信息
[[inputs.kernel]]
  # no configuration

# Read metrics about memory usage
# 讀取有關內存使用量的指標
[[inputs.mem]]
  # no configuration

# Get the number of processes and group them by status
# 獲取進程的數量並按狀態分組
[[inputs.processes]]
  # no configuration

# Read metrics about swap memory usage
# 讀取有關交換內存使用量的指標
[[inputs.swap]]
  # no configuration

# Read metrics about system load & uptime
# 讀取有關係統負載和運行時間的指標
[[inputs.system]]
  # no configuration
複製代碼

其具體採集數據以下(其中第一級別爲measurements,第二級別爲字段(省略了時間戳字段)):

- cpu[units: percent (out of 100)]
    - usage_guest      float
    - usage_guest_nice float
    - usage_idle       float
    - usage_iowait     float
    - usage_irq        float
    - usage_nice       float
    - usage_softirq    float
    - usage_steal      float
    - usage_system     float
    - usage_user       float
- disk
    - free         integer
    - inodes_free  integer
    - inodes_total integer
    - inodes_used  integer
    - total        integer
    - used         integer
    - used_percent float
- diskio
    - io_time          integer
    - iops_in_progress integer
    - read_bytes       integer
    - read_time        integer
    - reads            integer
    - weighted_io_time integer
    - write_bytes      integer
    - write_time       integer
    - writes           integer
- kernel
    - boot_time        integer
    - context_switches integer
    - entropy_avail    integer
    - interrupts       integer
    - processes_forked integer
- mem
    - active            integer
    - available         integer
    - available_percent float
    - buffered          integer
    - cached            integer
    - free              integer
    - inactive          integer
    - slab              integer
    - total             integer
    - used              integer
    - used_percent      float
    - wired             integer
- processes
    - blocked       integer
    - dead          integer
    - idle          integer
    - paging        integer
    - running       integer
    - sleeping      integer
    - stopped       integer
    - total         integer
    - total_threads integer
    - unknown       integer
    - zombies       integer
- swap
    - free         integer
    - in           integer
    - out          integer
    - total        integer
    - used         integer
    - used_percent float
- system
    - load1         float
    - load15        float
    - load5         float
    - n_cpus        integer
    - n_users       integer
    - uptime        integer
    - uptime_format string
複製代碼

如何查找指標及其採集數據

telegraf主要分爲輸入插件和輸入插件,其源碼目錄分別對應plugins/inputsplugins/outputs,你只要參考telegraf官檔找到你所須要的插件而後去到源碼對應的目錄找到相應的.md文件,按照提示獲取相關信息進行配置便可。

啓用telegraf服務後,你會發如今influxdb中多了一個telegraf的庫,其中有多個measurement,這說明咱們的數據採集已經成功了。有了數據之後,咱們須要關心的是如何把數據聚合而後進行展現。下面將介紹一款可視化套件grafana。


Grafana

Grafana是一個開源指標分析和可視化套件,經常使用於可視化基礎設施的性能數據和應用程序分析的時間序列數據。也能夠應用於其餘領域,包括工業傳感器,家庭自動化,天氣和過程控制。但請注意,咱們使用Grafana最關心的是如何把數據進行聚合後進行展現。

Grafana支持多種不一樣的時序數據庫數據源,Grafana對每種數據源提供不一樣的查詢方法,並且能很好的支持每種數據源的特性。它支持下面幾種數據源:Graphite、Elasticsearch、CloudWatch、InfluxDB、OpenTSDB、Prometheus、MySQL、Postgres、Microsoft SQL Server (MSSQL)。每種數據源都有相應的文檔,您能夠將多個數據源的數據合併到一個單獨的儀表板上,本文只舉例influxdb數據源的應用。

下載並安裝Telegraf:

# 安裝grafana
wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-5.1.2-1.x86_64.rpm 
# 啓動服務、添加開機啓動:
systemctl enable grafana-server
systemctl start grafana-server
# 配置
配置文件 /etc/grafana/grafana.ini
systemd服務名 grafana-server.service
默認日誌文件 /var/log/grafana/grafana.log
默認數據庫文件 /var/lib/grafana/grafana.db
複製代碼

簡單使用

啓動服務後訪問http://localhost:3000,默認端口爲3000,可在配置文件修改。默認用戶名和密碼爲admin/admin。登陸後按照提示配置數據源:

配置數據源1
配置數據源2

接着建立一個dashboard:

建立面板1.png

咱們先選擇導入模板的方式來預覽效果,再來了解grafana/dashboard的相關配置,這裏選擇官方提供的一套Telegraf: system dashboard,地址https://grafana.com/dashboards/928。請你根據它的提示配置你的telegraf。而後在dashboards中選擇import->Upload.jsonFile,將下載的模板導入:

導入模板

查看結果:

telegraf-system-dashboard

你還能夠安裝一些插件,例如安裝一款時間面板插件

安裝方式是到你的/var/lib/grafana/plugins目錄下執行grafana-cli工具安裝插件,下面安裝時間面板插件:

> sudo grafana-cli plugins install grafana-clock-panel
 installing grafana-clock-panel @ 0.0.9
 from url: https://grafana.com/api/plugins/grafana-clock-panel/versions/0.0.9/download
 into: /var/lib/grafana/plugins
 
 ✔ Installed grafana-clock-panel successfully 
  
 Restart grafana after installing plugins . <service grafana-server restart>

# 重啓服務
> sudo systemctl restart grafana-server
複製代碼

本身動手配置幾個

咱們建立一個新的dashboard,Dashboard由多個Row組成,一行Row分爲12列,咱們能夠自定義面板的Span寬度和高度。如今咱們選擇添加一個Singlestat(若是是繪製線性表選Graph),而後點擊Panel Title->Edit編輯咱們的面板信息,默認打開Metrics視圖,咱們修改後獲得以下信息:

upTime1

咱們修改options中的單位和顏色:

upTime2

一樣的,你能夠嘗試添加其餘的面板實現下面效果:

最終效果

Grafana的功能很是豐富,在這裏不能詳細敘述,請您參考官檔瞭解更多: http://docs.grafana.org/features/datasources/

相關文章
相關標籤/搜索