SHARE
TWEET

Untitled

a guest Jun 19th, 2017 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import sys
  6. import threading
  7. import time
  8.  
  9. descriptors = list()
  10. mount_points = list()
  11. Desc_Skel   = {}
  12. _Worker_Thread = None
  13. _Lock = threading.Lock() # synchronization lock
  14.  
  15. class UpdateMetricThread(threading.Thread):
  16.  
  17.     def __init__(self, params):
  18.         threading.Thread.__init__(self)
  19.         self.running      = False
  20.         self.shuttingdown = False
  21.         self.refresh_rate = 10
  22.         if "refresh_rate" in params:
  23.             self.refresh_rate = int(params["refresh_rate"])
  24.         self.metric       = {}
  25.  
  26.     def shutdown(self):
  27.         self.shuttingdown = True
  28.         if not self.running:
  29.             return
  30.         self.join()
  31.  
  32.     def run(self):
  33.         self.running = True
  34.  
  35.         while not self.shuttingdown:
  36.             _Lock.acquire()
  37.             self.update_metric()
  38.             _Lock.release()
  39.             time.sleep(self.refresh_rate)
  40.  
  41.         self.running = False
  42.  
  43.     def update_metric(self):
  44.         for mtp in mount_points:
  45.             #print >>sys.stderr, "mtp: ", mtp
  46.             try:
  47.                 st = os.statvfs(mtp)
  48.             except Exception as e:
  49.                 print 'error:{0}'.format(e)
  50.                 next
  51.  
  52.             if mtp == "/":
  53.                 part = "diskpart-root"
  54.             else:
  55.                 part = "diskpart-" + mtp.replace('/', '_').lstrip('_')
  56.             #print >>sys.stderr, "%u %u %u" % (st.f_blocks, st.f_bavail, st.f_bsize)
  57.             self.metric[ part+"-total" ] = float(st.f_blocks * st.f_bsize) / 1024/1024/1024
  58.             self.metric[ part+"-used"  ] = float((st.f_blocks - st.f_bavail) * st.f_bsize) / 1024/1024/1024
  59.  
  60.             self.metric[ part+"-inode-total" ] = st.f_files
  61.             self.metric[ part+"-inode-used"  ] = st.f_files - st.f_favail
  62.  
  63.  
  64.     def metric_of(self, name):
  65.         val = 0
  66.         if name in self.metric:
  67.             _Lock.acquire()
  68.             val = self.metric[name]
  69.             _Lock.release()
  70.         return val
  71.  
  72. def is_remotefs(dev, type):
  73.     if dev.find(":") >= 0:
  74.         return True
  75.     elif dev.startswith("//") and (type == "smbfs" or type == "cifs"):
  76.         return True
  77.     return False
  78.  
  79. def metric_init(params):
  80.     global descriptors, Desc_Skel, _Worker_Thread, mount_points
  81.  
  82.     print '[diskpart] diskpart'
  83.     print params
  84.  
  85.     # initialize skeleton of descriptors
  86.     Desc_Skel = {
  87.         'name'        : 'XXX',
  88.         'call_back'   : metric_of,
  89.         'time_max'    : 60,
  90.         'value_type'  : 'float',
  91.         'format'      : '%.3f',
  92.         'units'       : 'GB',
  93.         'slope'       : 'both',
  94.         'description' : 'XXX',
  95.         'groups'      : 'disk',
  96.         }
  97.  
  98.     if "refresh_rate" not in params:
  99.         params["refresh_rate"] = 10
  100.  
  101.     # IP:HOSTNAME
  102.     if "spoof_host" in params:
  103.         Desc_Skel["spoof_host"] = params["spoof_host"]
  104.  
  105.     f = open("/proc/mounts", "r")
  106.     # 0         1     2    3
  107.     # /dev/sda4 /home ext3 rw,relatime,errors=continue,data=writeback 0 0
  108.     for l in f:
  109.         (dev, mtp, fstype, opt) = l.split(None, 3)
  110.         if is_remotefs(dev, fstype):
  111.             continue
  112.         elif opt.startswith('ro'):
  113.             continue
  114.         elif not dev.startswith('/dev/') \
  115.           and not (mtp == "/" and fstype == "tmpfs"): # for netboot
  116.             continue;
  117.  
  118.         if mtp == "/":
  119.             part = "diskpart-root"
  120.         else:
  121.             part = "diskpart-" + mtp.replace('/', '_').lstrip('_')
  122.         #print >>sys.stderr, "dev=%s mount_point=%s part=%s" % (dev, mtp, part)
  123.  
  124.         descriptors.append(create_desc(Desc_Skel, {
  125.                     "name"       : part + "-total",
  126.                     "description": "total partition space",
  127.                     }))
  128.         descriptors.append(create_desc(Desc_Skel, {
  129.                     "name"       : part + "-used",
  130.                     "description": "partition space used",
  131.                     }))
  132.  
  133.         descriptors.append(create_desc(Desc_Skel, {
  134.                     "name"       : part + "-inode-total",
  135.                     "description": "total number of inode",
  136.                     "value_type" : "uint",
  137.                     "format"     : "%d",
  138.                     "units"      : "inode",
  139.                     }))
  140.         descriptors.append(create_desc(Desc_Skel, {
  141.                     "name"       : part + "-inode-used",
  142.                     "description": "total number of inode used",
  143.                     "value_type" : "uint",
  144.                     "format"     : "%d",
  145.                     "units"      : "inode",
  146.                     }))
  147.  
  148.         mount_points.append(mtp)
  149.  
  150.     _Worker_Thread = UpdateMetricThread(params)
  151.     _Worker_Thread.start()
  152.  
  153.     return descriptors
  154.  
  155. def create_desc(skel, prop):
  156.     d = skel.copy()
  157.     for k,v in prop.iteritems():
  158.         d[k] = v
  159.     return d
  160.  
  161. def metric_of(name):
  162.     return _Worker_Thread.metric_of(name)
  163.  
  164. def metric_cleanup():
  165.     _Worker_Thread.shutdown()
  166.  
  167. if __name__ == '__main__':
  168.     try:
  169.         params = {
  170.             }
  171.         metric_init(params)
  172.         while True:
  173.             for d in descriptors:
  174.                 v = d['call_back'](d['name'])
  175.                 print ('value for %s is '+d['format']) % (d['name'],  v)
  176.             time.sleep(5)
  177.     except KeyboardInterrupt:
  178.         time.sleep(0.2)
  179.         os._exit(1)
  180.     except:
  181.         print sys.exc_info()[0]
  182.         raise
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top