fileio.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 _gen_template():
  16. template = {}
  17. for stat_group, _, subfields in fields:
  18. field_data = {}
  19. if stat_group != 'disk':
  20. for field in subfields:
  21. field_data[field] = [-1] * 1440
  22. template[stat_group] = field_data
  23. return template
  24. TEMPLATE = _gen_template()
  25. def read_stats(f):
  26. stats = {}
  27. for stat_group, format_code, subfields in fields:
  28. field_data = {}
  29. fmt = '1440' + format_code
  30. if stat_group != 'disk':
  31. size = struct.calcsize(fmt)
  32. for field in subfields:
  33. field_data[field] = struct.unpack(fmt, f.read(size))
  34. else:
  35. buf = f.read() # disk is last, so we can read everything
  36. index = 0
  37. while index < len(buf):
  38. mountpoint_size = ord(buf[index])
  39. disk_fmt = '%dp %s %s' % (mountpoint_size + 1, fmt, fmt)
  40. size = struct.calcsize(disk_fmt)
  41. data = struct.unpack(disk_fmt, buf[index:index+size])
  42. mountpoint = data[0]
  43. total = data[1:1441]
  44. used = data[1441:]
  45. field_data[mountpoint] = {'used': used, 'total': total}
  46. index += size
  47. stats[stat_group] = field_data
  48. return stats
  49. def dict_insert(d, split, value):
  50. if len(split) > 1:
  51. d.setdefault(split[0], {})
  52. dict_insert(d[split[0]], split[1:], value)
  53. else:
  54. d[split[0]] = value
  55. def write_datum(f, data):
  56. for stat_group, format_code, subfields in fields:
  57. fmt = '1440' + format_code
  58. if stat_group != 'disk':
  59. for field in subfields:
  60. array = data[stat_group][field]
  61. f.write(struct.pack(fmt, *array))
  62. else:
  63. for mountpoint, disk_data in data['disk'].items():
  64. mountpoint = mountpoint.encode('utf-8')
  65. disk_fmt = '%dp %s %s' % (len(mountpoint) + 1, fmt, fmt)
  66. array = disk_data['total'] + disk_data['used']
  67. f.write(struct.pack(disk_fmt, mountpoint, *array))