Telegraf和Grafana監控多平臺上的SQL Server-自定義監控資料收集
阿新 • • 發佈:2020-06-11
## 問題
在[上一篇文章](https://www.cnblogs.com/Joe-T/p/13026494.html)中,我們使用Telegraf自帶的Plugin配置好了的監控,但是自帶的Plugin並不能完全覆蓋我們想要的監控指標,就需要收集額外的自定義的監控資料,實現的方法有:
- 開發自己的Telegraf Plugin
- 使用可以執行自定義指令碼的inputs plugin
此處收集的監控項不多,收集間隔也不是很頻繁,所以我選擇Telegraf預置的Inputs.exec plugin實現。它非常靈活,可以執行任意命令和指令碼。在指令碼中實現獲取監控資料的邏輯,然後使用inputs.exec執行。獲取資料之後,需要按[InfluxDB Line Protocol](https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_reference/) 格式組織資料,才能寫入到Influxdb。這種格式的組織方式:
#### **[measurement],[tags] [fields] [timestamp]**
- measurement,類似於SQL中表的概念,資料存放的容器
- tags,K-V格式用於標記資料記錄,一般它們的值不經常變化,如主機名。同時tags上會建立索引,查詢效率會好一些.
- fields,K-V格式,表示真正收集的不同時間點的資料項,如CPU Load
- timestamp,UNIX 時間戳,Influxdb是時序資料庫,所有資料都要與時間關聯起來。
- measurement和tag之間用逗號分隔,fields 與它們用空格(whitespace)分隔
不管是執行在Linux還是Windows上的SQL,通常使用T-SQL查詢例項內部的資料和使用作業系統指令碼查詢例項外部的資料以實現監控。接下來,以執行T-SQL獲取自定義監控資料為例,看看在Windos和Linux上分別如何實現。
## 解決方案
首先在被監控的例項上把相應的邏輯寫成儲存過程,然後通過inputs.exec呼叫之。
例如我在目標例項的influx庫中建立了一個儲存過程influx.usp_getInstanceInfo獲取一些例項的配置資訊。然後需要在telegraf配置檔案中啟用inputs.exec呼叫這個儲存過程。儲存過程的輸出資料如下:
```
sqlserver_property,host=SQL19N1,sql_instance=SQL19N1 host_platform="Linux",host_distribution="CentOS Linux",host_release=7,edition="Developer Edition (64-bit)",product_version="15.0.4033.1",collation="SQL_Latin1_General_CP1_CI_AS",is_clustered=f,is_hadr=t,cpu_count=2,scheduler_count=2,physical_memory_kb=6523904,max_workers_count=512,max_dop=0,max_memmory=2147483647 1590915136000000000
```
資料寫入到sqlserver_property,tags包括host,sql_instance,後面的全是fields。
- #### SQL On Linux
使用SQLCMD呼叫儲存過程,把SQLCMD命令寫到一個bash檔案中/telegraf/get_sqlproperty.sh
```
#!/bin/bash
/opt/mssql-tools/bin/sqlcmd -S SQL19N1 -U telegraf -P -d influx -y 0 -Q "EXEC influx.usp_getInstanceInfo"
```
修改telegraf.conf中的inputs.exec, 然後重啟telegraf生效:
> 因為收集的是例項屬性資訊,收集間隔設定的比較長。
```
[[inputs.exec]]
# ## Commands array
commands = [
"/telegraf/get_sqlproperty.sh"
]
timeout = "5s"
interval="24h"
data_format = "influx"
```
- #### SQL On Windows
Windows上首選使用PowerShell實現,把執行SQL的命令寫到C:\Monitoring\scripts\get_sqlproperty.ps1。col_res是儲存過程輸出的列名。
```
(Invoke-Sqlcmd -ServerInstance SQL17N1 -Username telegraf -Password "" -Database influx -Query "exec influx.usp_getInstanceInfo" ).col_res
```
修改telegraf.conf中的inputs.exec, 然後重啟telegraf生效.
需要特別注意的問題:
- **指定檔案路徑時,要使用Linux路徑表達的forward slash(/), 而不是Windows中的 back slash(\\)**
- **ps1檔案路徑使用單引號(single quote)**
- **避免檔案路徑中有空格(whitespace)**
```
[[inputs.exec]]
# ## Commands array
commands = [
"powershell 'C:/Monitoring/scripts/get_sqlproperty.ps1' "
]
timeout = "5s"
interval="24h"
data_format = "influx"
```
配置完成後,看看measurement和資料:
## 總結
- 在inputs.exec中最好是呼叫指令碼,而不是命令。這樣當你需要變更資料收集邏輯,直接修改指令碼即可,而不需要修改Telegraf的配置檔案,避免重啟服務和配置干擾
- 被呼叫的指令碼的輸出,要是stdout,才能被正確寫入influxdb
- Windows 上檔案路徑和符號escape要特別注意
- 如果對收集效能特別敏感或者收集頻率特別高時,使用Go自定義Plugin
- **本文內容僅代表個人觀點,與任何公司和組織