前面的文章介紹瞭如何安裝influxdb以及grafana,如何使用python操作influxdb,本篇我們做一個小demo,使用python實時監控本機的資源佔用情況,並寫入influxdb數據庫,通過grafana進行監控。
二、InfluxDB1.1.0和1.8.0版本安裝並開啓web界面
-----------------------------------------------------------------------------------------------
Grafana官方網站:https://grafana.com/
InfluxDB官網:https://www.influxdata.com
安裝python包
pip install influxdb==5.3.0
pip install psutil==5.6.3
編寫腳本
import _thread
import time
import socket
import psutil
from influxdb import InfluxDBClient
client=InfluxDBClient('localhost',8086,'u_wyk13195','p_wyk13195','my_monitor')
#獲取本機IP
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 0))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
ip = get_ip()
print(ip)
#獲取cpu信息
def get_cpu(sec):
while True:
time.sleep(sec)
info=psutil.cpu_percent(0)
text=[
{
"measurement":"cpu_info",
"tags":{
"host":ip
},
"fields":{
"percent":info
}
}
]
client.write_points(text)
def get_memory(sec):
while True:
time.sleep(sec)
info=psutil.virtual_memory()
text=[
{
"measurement":"memory_info",
"tags":{
"host":ip
},
"fields":{
"mem_percent":info.percent,
"mem_used":info.used,
"mem_free":info.free,
}
}
]
client.write_points(text)
def get_disk(sec):
while True:
time.sleep(sec)
info=psutil.disk_usage('/')
text=[
{
"measurement":"disk_info",
"tags":{
"host":ip
},
"fields":{
"disk_used":info.used,
"disk_free":info.free,
"disk_percent":info.percent,
}
}
]
client.write_points(text)
def get_network(sec):
while True:
time.sleep(sec)
#print(psutil.net_io_counters(pernic=True))
info = psutil.net_io_counters(pernic=True)['WLAN 3']
text=[
{
"measurement":"network_info",
"tags":{
"host":ip
},
"fields":{
"bytes_sent":info.bytes_sent,
"bytes_recv":info.bytes_recv,
}
}
]
client.write_points(text)
try:
_thread.start_new_thread( get_cpu,(10,))
except:
print("ERROR:cpu unable to start thread")
try:
_thread.start_new_thread( get_memory, (10,))
except:
print("ERROR:memory unable to start thread")
try:
_thread.start_new_thread( get_disk, (10,))
except:
print("ERROR:disk unable to start thread")
try:
_thread.start_new_thread( get_network,(10,))
except:
print("ERROR:net unable to start thread")
while 1:
pass
啓動influxdb
nohup $INFLUXDB18_HOME/usr/bin/influxd -config $INFLUXDB18_HOME/etc/influxdb/influxdb.conf &>$INFLUXDB18_HOME/log &
啓動grafana
CentOS7:
systemctl restart grafana-server
systemctl enable grafana-server
CentOS6:
service grafana-server restart
chkconfig grafana-server on
啓動腳本
Grafana報表
其實grafana報表是以Json的方式存儲的,我們也可以將它導出,附件中會提供本篇的代碼和grafana報表的Json文件,按照上面的方式安裝之後就能做出一樣的效果。記得修改json文件中對應的grafana和influxdb的版本號,以及自定義的數據源名稱。
(請無視我的資源佔用太高。。)
導出報表:
點擊share dashbord-->Export--SavetoFile
需要修改的部分:datasource,grafana版本號
配置自動刷新規則:
在報表設置中time picker可以設置此報表自動刷新可以選擇的幾種選項:
右上角的時間點擊後可以選擇顯示的數據區間以及自動刷新時間間隔: