第一部分、读取Prometheus监控数据
import pandas as pd
import requests
from urllib import parse
import json
# 获取CDN带宽数据
def getBillBand(vendor):
querystring = 'sum(CDNBandwidth{vendor="' + vendor + '"}) '
query = 'https://prometheus.ipcpu.com/api/v1/query_range?query=' + parse.quote_plus(querystring) + '&step=5m&start=1629129600&end=1629216000'
response = requests.get(query)
response.encoding = 'utf-8'
result = json.loads(response.text)
if len(result['data']['result']) == 0:
return []
else:
return result['data']['result'][0]['values']
# 读取监控数据
baishandata = pd.DataFrame(getBillBand('baishan'), columns=['Time', 'baishan'])
ksyundata = pd.DataFrame(getBillBand('kingsoft'), columns=['Time1', 'kingsoft'])
uclouddata = pd.DataFrame(getBillBand('ucloud'), columns=['Time3', 'ucloud'])
#合并数据
mydata = pd.concat([baishandata, ksyundata, uclouddata], axis=1)
print(mydata[['Time', 'baishan', 'kingsoft', 'ucloud']])
我们得到了如下的DataFrame数据
Time baishan kingsoft ucloud
0 1629129600 13109176942.450005 482991727 282104786
1 1629129900 12795432805.510002 304650879 198525687
2 1629130200 11825871531.54 364369260 223562448
第二部分、开始绘图
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
# Y轴显示单位自匹配
def y_fmt(tick_val, pos):
if tick_val > 1000000000:
val = int(tick_val/1000000000)
return '{:d} G'.format(val)
elif tick_val > 1000000:
val = int(tick_val/1000000)
return '{:d} M'.format(val)
elif tick_val > 1000:
val = int(tick_val/1000)
return '{:d} k'.format(val)
else:
return int(tick_val)
# 将时间戳转换为时间
mydata['Time'] = pd.to_datetime(mydata['Time'], unit='s')
# 将时间列设置为index
mydata.set_index('Time', inplace=True)
# 设定时区
#这个地方注意,tz_localize没有inplace=True,所以我这边新建一个dataFrame
newdata = mydata.tz_localize('UTC').tz_convert('Asia/Shanghai')
#设定数据列
newdata['baishan'].astype('float').plot(color='green')
newdata['kingsoft'].astype('float').plot(color='red')
newdata['ucloud'].astype('float').plot(color='blue')
plt.rcParams['font.sans-serif'] = 'SimHei' #设置中文字体,否则乱码
plt.rcParams['axes.unicode_minus'] = False ## 设置正常显示符号
# 使用自定义函数控制Y轴显示单位
plt.gca().yaxis.set_major_formatter(tick.FuncFormatter(y_fmt))
plt.autoscale(enable=True, axis='both')
plt.ylabel('带宽')
plt.xlabel('时间')
plt.legend(loc='best')
#绘图
plt.savefig('cdn.png')
plt.show()
#plt.show()放在plt.savefig()之前会导致plt.savefig()出现的是空白图。反过来就不会。