從Zabbix數據庫中提取內存採集的數據,做內存使用率計算

  背景需求很簡單,分析所有的設備的內存使用率,看那些設備的內存不夠用是否需要加內存。。。

  下面的腳本邏輯,就是通過提取zabbix數據庫中的hostid,在提取itemid。。

  然後通過item name過濾提取趨勢數據,獲取一天中最大的內存總數和最小可用內存

  然後在計算在一天中最小內存可用率的設備, 

 

  下面的是通過free來計算的,當然也可以通過used來計算了...

#!/usr/bin/ruby
$KCODE = 'utf8'
require 'mysql'

db = Mysql.real_connect('1.1.1.1','zabbix','abbix','zabbix',3389)
db.query('SET character_set_results = utf8 ;')

host = db.query("select hostid,host from hosts where host like '%sinanode.com%'")
time = Time.now - 3600*24

host.each_hash do |h|
    items = db.query("select itemid,name from items where hostid = #{h['hostid']} ")
    total = 0
    free = 0
    items.each_hash do |item|
      if item['name'] =~ /內存總數/
        total = db.query("select min(value_max) from trends_uint where itemid = '#{item['itemid']}' and clock > UNIX_TIMESTAMP('#{time.strftime('%F %X')}'); ").fetch_row
        puts "#{h['host']} #{item['itemid']}  #{item['name']}  #{total}"
      end

      if item['name'] =~ /可用內存/
        free = db.query("select min(value_max) from trends_uint where itemid = '#{item['itemid']}' and clock > UNIX_TIMESTAMP('#{time.strftime('%F %X')}'); ").fetch_row
        puts "#{h['host']} #{item['itemid']}  #{item['name']}  #{free}"
      end
    end
    

    if free != 0
      usage = free.to_s.to_f/total.to_s.to_f*100
      puts "#{h['host']} 最近一天最小空閒使用率: #{format("%.2f",usage)}   total: #{total}  free: #{free}"
    end

end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章