Telegraf 是什麼?
Telegraf 是一個用 Go 編寫的代理程序,是收集和報告指標和數據的代理。可收集系統和服務的統計數據,並寫入到 InfluxDB 數據庫。Telegraf 具備內存佔用小的特色,經過插件系統開發人員可輕鬆添加支持其餘服務的擴展。node
Telegraf是TICK Stack的一部分,是一個插件驅動的服務器代理,用於收集和報告指標。mysql
Telegraf 集成了直接從其運行的容器和系統中提取各類指標,事件和日誌,從第三方API提取指標,甚至經過StatsD和Kafka消費者服務監聽指標。nginx
它還具備輸出插件,可將指標發送到各類其餘數據存儲,服務和消息隊列,包括InfluxDB,Graphite,OpenTSDB,Datadog,Librato,Kafka,MQTT,NSQ等等。git
Telegraf做爲數據採集模塊,須要安裝至被監控的目標主機上。Telegraf設計目標是較小的內存使用,經過插件來構建各類服務和第三方組件的metrics收集
Telegraf由4個獨立的插件驅動:github
- Input Plugins
輸入插件,收集系統、服務、第三方組件的數據。 - Processor Plugins
處理插件,轉換、處理、過濾數據。 - Aggregator Plugins
聚合插件,數據特徵聚合。 - Output Plugins
輸出插件,寫metrics數據。
Influxdb 是一個開源的(集羣版收費)分佈式時序、時間和指標數據庫,使用 Go 語言編寫,無需外部依賴。Influxdb 有以下三大特性:redis
- 時序性(Time Series):與時間相關的函數的靈活使用(諸如最大、最小、求和等);
- 度量(Metrics):對實時大量數據進行計算;
- 事件(Event):支持任意的事件數據,換句話說,任意事件的數據咱們均可以作操做。
爲何要用?
在平臺監控系統中,可使用 Telegraf 採集多種組件的運行信息,而不須要本身手寫腳本定時採集,大大下降數據獲取的難度;且 Telegraf 配置極爲簡單,只要有基本的 Linux 基礎便可快速上手。Telegraf 按照時間序列採集數據,數據結構中包含時序信息,時序數據庫就是爲此類數據設計而來,使用 Influxdb 能夠針採集獲得的數據完成各類分析計算操做。sql
怎麼用?
這裏不介紹過多原理性的東西,儘量快速地在現有系統上安裝部署 Telegraf 和 Influxdb,並使用 Telegraf 採集部分數據寫入到 Influxdb 中。使用 wget 方式下載可能會較爲緩慢,建議使用迅雷等下載工具下載後再分發至服務器上。shell
1.安裝 Telegraf數據庫
[root@node1 ~]# wget http://get.influxdb.org/telegraf/telegraf-0.11.1-1.x86_64.rpm [root@node1 ~]# rpm -ivh telegraf-0.11.1-1.x86_64.rpm [root@node1 ~]# systemctl start telegraf
2.安裝 Influxdbvim
[root@node1 ~]# wget http://dl.influxdata.com/influxdb/releases/influxdb-1.0.2.x86_64.rpm [root@node1 ~]# rpm -ivh influxdb-1.0.2.x86_64.rpm [root@node1 ~]# systemctl start influxd
3.建立 Influxdb 用戶和數據庫
[root@node1 ~]# influx
Visit https://enterprise.influxdata.com to register for updates, InfluxDB server management, and monitoring.
Connected to http://localhost:8086 version 1.0.2
InfluxDB shell version: 1.0.2
> create user "telegraf" with password 'password' > show users; user admin telegraf false > create database telegraf > show databases name: databases --------------- name _internal telegraf
4.配置Telegraf
[root@node1 ~]# vim /etc/telegraf/telegraf.conf ## 修改內容以下: [[outputs.influxdb]] urls = ["http://localhost:8086"] # required database = "telegraf" # required retention_policy = "" precision = "s" timeout = "5s" username = "telegraf" password = "password" [root@node1 ~]# systemctl restart telegraf
5.查看數據
打開 Influxdb 查詢界面:http://node1:8083 , 輸入查詢語句seclect * from cpu
可查詢到 CPU 相關信息。
生成配置文件
可執行文件在 usr/bin/telegraf,配置文件在/etc/telegraf目錄下,也可直接配置生成
查看幫助
telegraf --help
生成配置文件
telegraf config > telegraf-mysql.conf # 好比在當前目錄下生成mysql相關的配置文件
建議生成的配置放置在 /etc/telegraf/telegraf.d目錄下
生成指定輸入和輸出插件的配置文件
telegraf --input-filter <pluginname>[:<pluginname>] --output-filter <outputname>[:<outputname>] config > telegraf.conf
例如,生成帶 cpu、memroy、disk、diskio、net 和 influxdb 插件的配置文件 telegraf.conf,指定輸出到 influxdb 和 opentsdb
telegraf --input-filter cpu:mem:disk:diskio:net --output-filter influxdb:opentsdb config > telegraf.conf
也可以使用默認的配置文件
telegraf --input-filter cpu:mem:http_listener --output-filter influxdb config
telegraf 支持讀取多個配置文件,可將多個配置文件放置在 /etc/telegraf/telegraf.d 目錄下
測試配置是否成功
示例
# 測試 /etc/telegraf/telegraf.conf 配置文件中輸入 cpu 配置是否正確
telegraf -config /etc/telegraf/telegraf.conf -input-filter cpu -test
# 測試 /etc/telegraf/telegraf.conf 輸出 influxdb 配置是否正確
telegraf -config /etc/telegraf/telegraf.conf -output-filter influxdb -test
# 測試 /etc/telegraf/telegraf.d/mysql.conf 輸入 cpu 和 輸出 influxdb 配置是否正確
telegraf -config /etc/telegraf/telegraf.d/mysql.conf -input-filter cpu -output-filter influxdb -test
配置正確的話,會輸出當前時間戳的配置指標和值;
配置錯誤的話,會顯示錯誤信息;
其餘測試配置文件方法能夠類比以上示例
查看 telegraf 的日誌
telegraf 日誌目錄 /var/log/telegraf/telegraf.log
配置文件保存修改後,記得要重啓 telegraf
# 重啓 telegraf 服務,使配置文件生效
service telegraf restart
# Linux 不一樣系統服務的啓動方式不一樣
systemctl start telegraf
Note: Telegraf will start automatically using the default configuration when installed from a deb package.
/etc/telegraf/telegraf.d is the default directory of configuration files.
配置多個配置文件示例
步驟:
生成配置文件
配置輸入輸出插件
修改配置文件中輸入輸出插件具體內容
在 /etc/telegraf/telegraf.d 生成其餘插件的配置文件(如須要配置多個配置文件)
測試配置文件是否配置正確
重啓 telegraf
# 例子:配置 os 和 redis 採集的配置文件
# 配置 os
cd /etc/telegraf
# 1.生成配置文件(將配置文件權限更改成777,以避免出現報錯)
telegraf config > telegraf.conf
chmod 777 telegraf.conf
# 2.在指定配置文件中添加輸入輸出插件相關的配置
telegraf --input-filter cpu:mem:disk:diskio:net --output-filter influxdb:opentsdb config > telegraf.conf
# 3.修改配置文件內容
vim telegraf.conf
# 4.<配置多個配置文件> 如,配置 redis
cd /etc/telegraf/telegraf.d
telegraf config > redis.conf
chmod 777 telegraf.conf
telegraf --input-filter redis --output-filter opentsdb:influxdb config > redis.conf
vim redis.conf
# 5.測試配置文件是否配置正確
telegraf -config redis.conf --input-filter redis --output-filter opentsdb:influxdb -test
# 6.重啓 telegraf
service telegraf restart
其中以 redis.conf 配置內容爲例,說明須要配置的內容
###############################################################################
# INPUT PLUGINS #
###############################################################################
# Read metrics from one or many redis servers
[[inputs.redis]]
## specify servers via a url matching:
## [protocol://][:password]@address[:port]
## e.g.
## tcp://localhost:6379
## tcp://:password@192.168.99.100
## unix:///var/run/redis.sock
##
## If no servers are specified, then localhost is used as the host.
## If no port is specified, 6379 is used
#servers = ["tcp://localhost:6379"]
# 配置 Redis 環境的地址
servers = ["tcp://10.132.49.128:6379"]
## specify server password
# password = "s#cr@t%"
## Optional TLS Config
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
## Use TLS but skip chain & host verification
# insecure_skip_verify = true
###############################################################################
# OUTPUT PLUGINS #
###############################################################################
# Configuration for OpenTSDB server to send metrics to
[[outputs.opentsdb]]
## prefix for metrics keys
# opentsdb 輸出的 metric 的前綴
prefix = "telegraf.redis."
## DNS name of the OpenTSDB server
## Using "opentsdb.example.com" or "tcp://opentsdb.example.com" will use the
## telnet API. "http://opentsdb.example.com" will use the Http API.
host = "10.128.2.97"
## Port of the OpenTSDB server
port = 44242
## Number of data points to send to OpenTSDB in Http requests.
## Not used with telnet API.
http_batch_size = 50
## URI Path for Http requests to OpenTSDB.
## Used in cases where OpenTSDB is located behind a reverse proxy.
http_path = "/api/put"
## Debug true - Prints OpenTSDB communication
debug = false
# Configuration for sending metrics to InfluxDB
[[outputs.influxdb]]
## The full HTTP or UDP URL for your InfluxDB instance.
##
## Multiple URLs can be specified for a single cluster, only ONE of the
## urls will be written to each interval.
# urls = ["unix:///var/run/influxdb.sock"]
# urls = ["udp://127.0.0.1:8089"]
urls = ["http://127.0.0.1:8086"]
## The target database for metrics; will be created as needed.
database = "telegraf"
## If true, no CREATE DATABASE queries will be sent. Set to true when using
## Telegraf with a user without permissions to create databases or when the
## database already exists.
# skip_database_creation = false
## Name of existing retention policy to write to. Empty string writes to
## the default retention policy. Only takes effect when using HTTP.
# retention_policy = ""
## Write consistency (clusters only), can be: "any", "one", "quorum", "all".
## Only takes effect when using HTTP.
# write_consistency = "any"
## HTTP Basic Auth
username = "admin"
password = "admin"
## HTTP User-Agent
# user_agent = "telegraf"
## UDP payload size is the maximum packet size to send.
# udp_payload = 512
## Optional TLS Config for use on HTTP connections.
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
## Use TLS but skip chain & host verification
# insecure_skip_verify = false
## HTTP Proxy override, if unset values the standard proxy environment
## variables are consulted to determine which proxy, if any, should be used.
# http_proxy = "http://corporate.proxy:3128"
## Additional HTTP headers
# http_headers = {"X-Special-Header" = "Special-Value"}
具體其餘配置含義見附錄說明
附錄說明
每個input插件配置文件內容不一樣,具體插件配置項可參看 Telegraf plugins
mysql 輸入插件配置內容
###############################################################################
# INPUT PLUGINS #
###############################################################################
# Read metrics from one or many mysql servers
[[inputs.mysql]]
## specify servers via a url matching:
## [username[:password]@][protocol[(address)]]/[?tls=[true|false|skip-verify|custom]]
## see https://github.com/go-sql-driver/mysql#dsn-data-source-name
## e.g.
## servers = ["user:passwd@tcp(127.0.0.1:3306)/?tls=false"]
## servers = ["user@tcp(127.0.0.1:3306)/?tls=false"]
#
## If no servers are specified, then localhost is used as the host.
servers = ["root@tcp(127.0.0.1:3306)/"]
## Selects the metric output format.
##
## This option exists to maintain backwards compatibility, if you have
## existing metrics do not set or change this value until you are ready to
## migrate to the new format.
##
## If you do not have existing metrics from this plugin set to the latest
## version.
##
## Telegraf >=1.6: metric_version = 2
## <1.6: metric_version = 1 (or unset)
metric_version = 2
## the limits for metrics form perf_events_statements
perf_events_statements_digest_text_limit = 120
perf_events_statements_limit = 250
perf_events_statements_time_limit = 86400
#
## if the list is empty, then metrics are gathered from all databasee tables
table_schema_databases = []
#
## gather metrics from INFORMATION_SCHEMA.TABLES for databases provided above list
gather_table_schema = false
#
## gather thread state counts from INFORMATION_SCHEMA.PROCESSLIST
gather_process_list = true
#
## gather user statistics from INFORMATION_SCHEMA.USER_STATISTICS
gather_user_statistics = true
#
## gather auto_increment columns and max values from information schema
gather_info_schema_auto_inc = true
#
## gather metrics from INFORMATION_SCHEMA.INNODB_METRICS
gather_innodb_metrics = true
#
## gather metrics from SHOW SLAVE STATUS command output
gather_slave_status = true
#
## gather metrics from SHOW BINARY LOGS command output
gather_binary_logs = false
#
## gather metrics from PERFORMANCE_SCHEMA.TABLE_IO_WAITS_SUMMARY_BY_TABLE
gather_table_io_waits = false
#
## gather metrics from PERFORMANCE_SCHEMA.TABLE_LOCK_WAITS
gather_table_lock_waits = false
#
## gather metrics from PERFORMANCE_SCHEMA.TABLE_IO_WAITS_SUMMARY_BY_INDEX_USAGE
gather_index_io_waits = false
#
## gather metrics from PERFORMANCE_SCHEMA.EVENT_WAITS
gather_event_waits = false
#
## gather metrics from PERFORMANCE_SCHEMA.FILE_SUMMARY_BY_EVENT_NAME
gather_file_events_stats = false
#
## gather metrics from PERFORMANCE_SCHEMA.EVENTS_STATEMENTS_SUMMARY_BY_DIGEST
gather_perf_events_statements = false
#
## Some queries we may want to run less often (such as SHOW GLOBAL VARIABLES)
interval_slow = "30m"
## Optional TLS Config (will be used if tls=custom parameter specified in server uri)
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
## Use TLS but skip chain & host verification
# insecure_skip_verify = false
按照本身實際須要對照說明進行修改
redis 輸入插件
###############################################################################
# INPUT PLUGINS #
###############################################################################
# Monitor process cpu and memory usage
[[inputs.procstat]]
## PID file to monitor process
#pid_file = "/var/run/nginx.pid"
# 配置須要監控的進程的 PID 文件目錄
pid_file = "/var/run/grafana-server.pid"
## executable name (ie, pgrep <exe>)
# exe = "nginx"
## pattern as argument for pgrep (ie, pgrep -f <pattern>)
# pattern = "nginx"
## user as argument for pgrep (ie, pgrep -u <user>)
# user = "nginx"
## Systemd unit name
# systemd_unit = "nginx.service"
## CGroup name or path
# cgroup = "systemd/system.slice/nginx.service"
## override for process_name
## This is optional; default is sourced from /proc/<pid>/status
# process_name = "bar"
## Field name prefix
# prefix = ""
## Add PID as a tag instead of a field; useful to differentiate between
## processes whose tags are otherwise the same. Can create a large number
## of series, use judiciously.
# pid_tag = false
## Method to use when finding process IDs. Can be one of 'pgrep', or
## 'native'. The pgrep finder calls the pgrep executable in the PATH while
## the native finder performs the search directly in a manor dependent on the
## platform. Default is 'pgrep'
# pid_finder = "pgrep"
Prometheus 輸入插件
###############################################################################
# INPUT PLUGINS #
###############################################################################
# Read metrics from one or many prometheus clients
[[inputs.prometheus]]
## An array of urls to scrape metrics from.
#urls = ["http://localhost:9100/metrics"]
# 配置 prometheus 的接口地址
urls = ["http://10.132.49.114:9104/metrics"]
## An array of Kubernetes services to scrape metrics from.
# kubernetes_services = ["http://my-service-dns.my-namespace:9100/metrics"]
## Use bearer token for authorization
# bearer_token = /path/to/bearer/token
## Specify timeout duration for slower prometheus clients (default is 3s)
# response_timeout = "3s"
## Optional TLS Config
# tls_ca = /path/to/cafile
# tls_cert = /path/to/certfile
# tls_key = /path/to/keyfile
## Use TLS but skip chain & host verification
# insecure_skip_verify = false
其餘配置文件說明
Agent 配置
Telegraf有一些能夠在配置[agent]部分下配置的選項。
interval:全部輸入的默認數據收集間隔
round_interval:將收集間隔舍入爲「interval」例如,若是interval =「10s」則始終收集於:00,:10,:20等。
metric_batch_size:Telegraf將指標發送到大多數metric_batch_size指標的批量輸出。
metric_buffer_limit:Telegraf將緩存metric_buffer_limit每一個輸出的指標,並在成功寫入時刷新此緩衝區。這應該是倍數,metric_batch_size不能少於2倍metric_batch_size。
collection_jitter:集合抖動用於隨機抖動集合。每一個插件在收集以前將在抖動內隨機休眠一段時間。這能夠用來避免許多插件同時查詢sysfs之類的東西,這會對系統產生可測量的影響。
flush_interval:全部輸出的默認數據刷新間隔。您不該將此設置爲如下間隔。最大值flush_interval爲flush_interval+flush_jitter
flush_jitter:將刷新間隔抖動一個隨機量。這主要是爲了不運行大量Telegraf實例的用戶出現大量寫入峯值。例如,flush_jitter5s和flush_interval10s之一意味着每10-15秒就會發生一次沖洗。
precision:默認狀況下,precision將設置爲與收集時間間隔相同的時間戳順序,最大值爲1s。精度不會用於服務輸入,例如logparser和statsd。有效值爲 ns,us(或µs)ms,和s。
logfile:指定日誌文件名。空字符串表示要登陸stderr。
debug:在調試模式下運行Telegraf。
quiet:以安靜模式運行Telegraf(僅限錯誤消息)。
hostname:覆蓋默認主機名,若是爲空使用os.Hostname()。
omit_hostname:若是爲true,則不host在Telegraf代理中設置標記。
Input 配置
如下配置參數可用於全部輸入:
interval:收集此指標的頻率。普通插件使用單個全局間隔,可是若是一個特定輸入應該運行得更少或更頻繁,則能夠在此處進行配置。
name_override:覆蓋度量的基本名稱。(默認爲輸入的名稱)。
name_prefix:指定附加到度量名稱的前綴。
name_suffix:指定附加到度量名稱的後綴。
tags:要應用於特定輸入測量的標籤映射。
Aggregator 配置
如下配置參數可用於全部聚合器:
period:刷新和清除每一個聚合器的時間段。聚合器將忽略在此時間段以外使用時間戳發送的全部度量標準。
delay:刷新每一個聚合器以前的延遲。這是爲了控制聚合器在從輸入插件接收度量標準以前等待多長時間,若是聚合器正在刷新而且輸入在相同的時間間隔內收集。
drop_original:若是爲true,聚合器將丟棄原始度量標準,而且不會將其發送到輸出插件。
name_override:覆蓋度量的基本名稱。(默認爲輸入的名稱)。
name_prefix:指定附加到度量名稱的前綴。
name_suffix:指定附加到度量名稱的後綴。
tags:要應用於特定輸入測量的標籤映射。
Processor 配置
如下配置參數可用於全部處理器:
order:這是執行處理器的順序。若是未指定,則處理器執行順序將是隨機的。
Measurement filtering (測量過濾)
能夠根據輸入,輸出,處理器或聚合器配置過濾器,請參閱下面的示例。
namepass:一個glob模式字符串數組。僅發出測量名稱與此列表中的模式匹配的點。
命名工做:逆轉namepass。若是找到匹配,則丟棄該點。這是在經過namepass測試後的點上測試的。
fieldpass:一個glob模式字符串數組。僅發出其字段鍵與此列表中的模式匹配的字段。不適用於輸出。
fielddrop:逆的fieldpass。具備匹配其中一個模式的字段鍵的字段將從該點中丟棄。不適用於輸出。
tagpass:將標記鍵映射到glob模式字符串數組的表。僅發出表中包含標記鍵的點和與其模式之一匹配的標記值。
tagdrop:逆的tagpass。若是找到匹配,則丟棄該點。這是在經過tagpass測試後的點上測試的。
taginclude:一個glob模式字符串數組。僅發出具備與其中一個模式匹配的標籤鍵的標籤。相反tagpass,它將根據其標記傳遞整個點,taginclude從該點移除全部不匹配的標記。此濾波器可用於輸入和輸出,但 建議在輸入上使用,由於在攝取點過濾掉標籤更有效。
tagexclude:倒數taginclude。具備與其中一個模式匹配的標記鍵的標記將從該點被丟棄。
注意: 因爲解析TOML的方式,tagpass而且tagdrop必須在插件定義的末尾定義參數,不然後續插件配置選項將被解釋爲tagpass / tagdrop表的一部分。