fileio.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import struct
  2. formats = {
  3. 'cpu': 'f',
  4. 'mem': 'q',
  5. 'net': 'q',
  6. 'disk': 'q',
  7. }
  8. def read_stats(f):
  9. buf = f.read()
  10. stats = {}
  11. index = 0
  12. while index < len(buf):
  13. # read the key
  14. key_size = ord(buf[index])
  15. fmt = '%dp' % (key_size + 1)
  16. data = struct.unpack(fmt, buf[index:index+key_size+1])
  17. key = data[0]
  18. # get the format_code
  19. split = key.split('.')
  20. stat_group = split[0]
  21. format_code = formats[stat_group]
  22. # read the data
  23. fmt = '%dp 1440%s' % (key_size + 1, format_code)
  24. size = struct.calcsize(fmt)
  25. data = struct.unpack(fmt, buf[index:index+size])
  26. dict_insert(stats, split, data[1:])
  27. index += size
  28. return stats
  29. def dict_insert(d, split, value):
  30. if len(split) > 1:
  31. d.setdefault(split[0], {})
  32. dict_insert(d[split[0]], split[1:], value)
  33. else:
  34. d[split[0]] = value
  35. def write_datum(f, data):
  36. for stat_group, stats in data.items():
  37. if stat_group == 'client_id':
  38. continue
  39. format_code = formats[stat_group]
  40. for stat, datum in stats.items():
  41. key = '%s.%s' % (stat_group, stat)
  42. fmt = '%dp 1440%s' % (len(key) + 1, format_code)
  43. array = [-1] * 1440
  44. array[0] = datum
  45. f.write(struct.pack(fmt, key.encode('utf-8'), *array))