fileio.py 2.0 KB

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