fileio.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import struct
  2. fields = [
  3. ('cpu', 'f', [
  4. 'user', 'iowait', 'system', 'nice',
  5. 'guest', 'guest_nice',
  6. 'irq', 'softirq', 'steal', 'idle',
  7. ]),
  8. ('mem', 'q', ['total', 'used', 'buffers', 'cached']),
  9. ('net', 'q', [
  10. 'bytes_recv', 'bytes_sent',
  11. 'dropin', 'dropout', 'errin', 'errout',
  12. ]),
  13. ('disk', 'q', ['total', 'used']),
  14. ]
  15. def read_stats(f):
  16. stats = {}
  17. for stat_group, format_code, subfields in fields:
  18. field_data = {}
  19. fmt = '1440' + format_code
  20. if stat_group != 'disk':
  21. size = struct.calcsize(fmt)
  22. for field in subfields:
  23. field_data[field] = struct.unpack(fmt, f.read(size))
  24. else:
  25. buf = f.read() # disk is last, so we can read everything
  26. index = 0
  27. while index < len(buf):
  28. mountpoint_size = ord(buf[index])
  29. disk_fmt = '%dp %s %s' % (mountpoint_size + 1, fmt, fmt)
  30. size = struct.calcsize(disk_fmt)
  31. data = struct.unpack(disk_fmt, buf[index:index+size])
  32. mountpoint = data[0]
  33. total = data[1:1441]
  34. used = data[1441:]
  35. field_data[mountpoint] = {'used': used, 'total': total}
  36. index += size
  37. stats[stat_group] = field_data
  38. return stats
  39. def dict_insert(d, split, value):
  40. if len(split) > 1:
  41. d.setdefault(split[0], {})
  42. dict_insert(d[split[0]], split[1:], value)
  43. else:
  44. d[split[0]] = value
  45. def write_datum(f, data):
  46. for stat_group, format_code, subfields in fields:
  47. fmt = '1440' + format_code
  48. if stat_group == 'disk':
  49. for mountpoint, disk_data in data['disk'].items():
  50. mountpoint = mountpoint.encode('utf-8')
  51. disk_fmt = '%dp %s %s' % (len(mountpoint) + 1, fmt, fmt)
  52. total = [-1] * 1440
  53. total[0] = disk_data['total']
  54. used = [-1] * 1440
  55. used[0] = disk_data['used']
  56. f.write(struct.pack(disk_fmt, mountpoint, *(total + used)))
  57. else:
  58. for field in subfields:
  59. array = [-1] * 1440
  60. array[0] = data[stat_group][field]
  61. f.write(struct.pack(fmt, *array))