iT邦幫忙

DAY 24
7

MySQL漫談,由使用Python撰寫之MySQL工具程式出發系列 第 24

MySQL漫談,由使用Python撰寫之MySQL工具程式出發(24)

今天將介紹File System 空間使用量的獲取,儲存與繪圖,
發送警告email.
還記得之前有開發一個Linux Quick Report,裡面就有列出
如下的資訊

Disk Info
        Filesystem -     /dev/sda1
              Size -     923G
              Used -     514G
         Available -     363G
       Use Percent -     59%
        Mounted on -     /

我們可以引用他.首先還是建立 RRD File.

#!/usr/bin/env python
# ------------------------
# Python RRDTool MySQL
# File System Space Usage
# create rrd file
# -----------------------

import rrdtool

rrdtool.create(
    'fsspace.rrd', '--step', '60',
    'DS:usedgiga:GAUGE:120:0:U',
    'DS:usedprcnt:GAUGE:120:0:U',
    'RRA:AVERAGE:0.5:1:2880',
    'RRA:AVERAGE:0.5:30:672',
    'RRA:AVERAGE:0.5:60:744',
    'RRA:AVERAGE:0.5:720:732',
    'RRA:MAX:0.5:1:2880',
    'RRA:MAX:0.5:30:672',
    'RRA:MAX:0.5:60:744',
    'RRA:MAX:0.5:720:732',
    'RRA:MIN:0.5:1:2880',
    'RRA:MIN:0.5:30:672',
    'RRA:MIN:0.5:60:744',
    'RRA:MIN:0.5:720:732',
    'RRA:LAST:0.5:1:2880',
    'RRA:LAST:0.5:30:672',
    'RRA:LAST:0.5:60:744',
    'RRA:LAST:0.5:720:732')

接著就是獲取File System Space,更新rrd的程式.

#!/usr/bin/env python
# -----------------------
# Python RRDTool MySQL
# File System Space Usage
# update rrd file
# -----------------------

import time
import rrdtool
import Linux_Quick_Report

def update_space_rrd():
    disk_info = Linux_Quick_Report.get_disk_info()
    sda1 = disk_info[0]
    used = sda1[2]
    percent = sda1[4]
    used = int(used[:-1])
    percent = int(percent[:-1])
    rrdtool.update('fsspace.rrd', 'N:' + `used` + ':' + `percent`)
#
if __name__ == '__main__':
    while 1:
        update_space_rrd()
        time.sleep(60)

放到背景執行,會每分鐘更新.接著是繪圖的程式.

#!/usr/bin/env python
# ---------------------------
# Python RRDTool MySQL
# File System Space Usage
# Create Image from rrd file
# ---------------------------
import rrdtool
import datetime
import Linux_Quick_Report

def space_graph_giga(rrdfile, period):
    timenow = datetime.datetime.now()
    disptime = datetime.datetime.strftime(timenow, '%Y-%m-%d %H-%M-%S')
    title = 'Space_Usage_Giga_' + period
    filename = title + '.png'
    
    # -------------------
    disk_info = Linux_Quick_Report.get_disk_info()
    sda1 = disk_info[0]
    size = sda1[1]
    size = int(size[:-1])
    upper = str(size)
    warn = size * 0.95
    warn = str(warn)
    # --------------------
    used = 'DEF:used=%s:usedgiga:AVERAGE' % rrdfile
    sizeline = 'HRULE:%s#FF0000:Size' % size
    warnline = 'HRULE:%s#DA5ADA:95 Percent Warning\\n' % warn
    # -------------------
    if period == 'yesterday':
        start = 'end-1d'
        end = '00:00'
        xgrid = 'HOUR:1:HOUR:2:HOUR:2:0:%H'
    if period == 'today':
        start = '00:00'
        end = '23:59'
        xgrid = 'HOUR:1:HOUR:2:HOUR:2:0:%H'
    if period == '4h':
        start = '-4h'
        end = 'now'
        xgrid = 'MINUTE:10:HOUR:1:HOUR:1:0:%H'
        
    rrdtool.graph(
        filename,
        '--start', start,
        '--end', end,
        '--title', title,
        '-a', 'PNG',
        '-W', 'Hitomitanaka for ITHelp',
        '--slope-mode',
        '--vertical-label=GB',
        '--rigid',
        '--upper-limit', upper,
        '--lower-limit', '0',
        '--width', '500',
        '--height', '150',
        '--x-grid', xgrid,
        '--alt-y-grid',
        '--color', 'BACK#000000',
        '--color', 'CANVAS#000000',
        '--color', 'FONT#FFF978',
        '--font=LEGEND:7',
        '--font', 'TITLE:8:',
        '--font', 'UNIT:7:',
        '--font', 'WATERMARK:9',
        # ---------------------------------
        used,
        'AREA:used#4444EE:Used',
        'GPRINT:used:LAST:  Current\\: %.01lf',
        'GPRINT:used:AVERAGE:   Average\\: %.01lf',
        'GPRINT:used:MIN:   Min\\: %.01lf',
        'GPRINT:used:MAX:   Max\\: %.01lf\\n',
        sizeline,
        warnline,
        'COMMENT:\t\t\t\tUpdate Time %s' % disptime)
#
def space_graph_percent(rrdfile, period):
    timenow = datetime.datetime.now()
    disptime = datetime.datetime.strftime(timenow, '%Y-%m-%d %H-%M-%S')
    title = 'Space_Usage_Percent_' + period
    filename = title + '.png'
       
    # --------------------
    usepercent = 'DEF:used=%s:usedprcnt:AVERAGE' % rrdfile
    warnline = 'HRULE:95#FF8200:95 Percent Warning\\n' 
    # -------------------
    if period == 'yesterday':
        start = 'end-1d'
        end = '00:00'
        xgrid = 'HOUR:1:HOUR:2:HOUR:2:0:%H'
    if period == 'today':
        start = '00:00'
        end = '23:59'
        xgrid = 'HOUR:1:HOUR:2:HOUR:2:0:%H'
    if period == '4h':
        start = '-4h'
        end = 'now'
        xgrid = 'MINUTE:10:HOUR:1:HOUR:1:0:%H'
        
    rrdtool.graph(
        filename,
        '--start', start,
        '--end', end,
        '--title', title,
        '-a', 'PNG',
        '-W', 'Hitomitanaka for ITHelp',
        '--slope-mode',
        '--vertical-label=Percent',
        '--rigid',
        '--upper-limit', '100',
        '--lower-limit', '0',
        '--width', '500',
        '--height', '150',
        '--x-grid', xgrid,
        '--alt-y-grid',
        '--color', 'BACK#000000',
        '--color', 'CANVAS#000000',
        '--color', 'FONT#FFF978',
        '--font=LEGEND:7',
        '--font', 'TITLE:8:',
        '--font', 'UNIT:7:',
        '--font', 'WATERMARK:9',
        # ---------------------------------
        usepercent,
        'AREA:used#941494:Used',
        'GPRINT:used:LAST:  Current\\: %.01lf',
        'GPRINT:used:AVERAGE:   Average\\: %.01lf',
        'GPRINT:used:MIN:   Min\\: %.01lf',
        'GPRINT:used:MAX:   Max\\: %.01lf\\n',
        warnline,
        
        'COMMENT:\t\t\t\tUpdate Time %s' % disptime)
#
if __name__ == '__main__':
    space_graph_giga('fsspace.rrd', 'today')
    space_graph_giga('fsspace.rrd', '4h')
    space_graph_percent('fsspace.rrd', 'today')
    space_graph_percent('fsspace.rrd', '4h')

裡面有使用到Linux Quick Report 的函式,來取得File System的Size,
來決定圖形的上限,彈性調整圖形.
範例裡面是今天與4小時的情況,故變化不大,因為沒有採用以KB為單位,
而是採用GB與百分比,這適合長期觀察使用.RRD File在建立時,就有保留了
資料量可以存放兩年.
以下依序是 今天與4小時內的GB單位圖形,今天與4小時內的百分比圖形:



實務的運用上,也不會天天去檢查關於File System的圖形,是否達到警戒線?
所以接著將介紹檢查並透過email發出警告的程式.
程式透過GMail發送,不需要在內部再使用Mail Server.
可以設定在 cron, 每日定時執行,警戒值可視情況,自行調整.

#!/usr/bin/env python
# encoding: utf-8

import smtplib
from email import utils
from email.mime.text import MIMEText
import Linux_Quick_Report

# ----- 發送用的帳號 ------
MAIL_USER = 'apia0001@gmail.com'
MAIL_PASS = 'testpass'

# ----- 通知郵箱 可以輸入多個 ------
ALERT_MAILS = ['hitomitanaka666@gmail.com','test2@gmail.com']

# ---- 警報值 ----
WARN_SIZE = 500
WARN_PERCENT = 50


def send_gmail(fromaddr, passwd, toaddrs, subject, tranmsg):
    server = 'smtp.gmail.com'
    to = ', '.join(toaddrs)
    msg = MIMEText(tranmsg, _subtype='plain', _charset='utf-8')
    msg['To'] = to
    msg['From'] = fromaddr
    msg['Subject'] = subject
    msg['Date'] = utils.formatdate(localtime=1)
    msg['Message-ID'] = utils.make_msgid()
    #  ---- login smtp server ----
    smtpserver = smtplib.SMTP(server, 587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo()
    smtpserver.login(fromaddr, passwd)
    # ---- Try to Send Mail ----
    try:
        smtpserver.sendmail(fromaddr, toaddrs, msg.as_string())
        rtnval = True
    except smtplib.SMTPException:
        rtnval = False
#
    smtpserver.close()
    return rtnval
# -----------------------------
if __name__ == '__main__':
    disk_info = Linux_Quick_Report.get_disk_info()
    sda1 = disk_info[0]
    used = sda1[2]
    percent = sda1[4]
    used = int(used[:-1])
    percent = int(percent[:-1])
    if used >= WARN_SIZE or percent >= WARN_PERCENT:
        subj = u'系統空間使用量過高'
        msg = u'使用量: %d GB 百分比: %d %%' % (used, percent)
        send_gmail(MAIL_USER, MAIL_PASS, ALERT_MAILS, subj, msg)

收到測試的Alert信件.


上一篇
MySQL漫談,由使用Python撰寫之MySQL工具程式出發(23)
下一篇
MySQL漫談,由使用Python撰寫之MySQL工具程式出發(25)
系列文
MySQL漫談,由使用Python撰寫之MySQL工具程式出發30

2 則留言

0
ted99tw
iT邦高手 1 級 ‧ 2012-10-27 15:47:07

拍手拍手拍手

每篇都是這麼..........紮實!!!

讚讚讚

感謝泰大美言,也感謝fillano大.

0
patrickcheng
iT邦新手 4 級 ‧ 2012-10-28 10:28:08

將如此有用的輸出,推送到使用者的智慧手機,由使用者依個人需要設定接受訊息模式,善用雲端能力也發揮行動端智慧,造服使用者是也!

我要留言

立即登入留言