| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- import struct
- fields = [
- ('cpu', 'f', [
- 'user', 'iowait', 'system', 'nice',
- 'guest', 'guest_nice',
- 'irq', 'softirq', 'steal', 'idle',
- ]),
- ('mem', 'q', ['total', 'used', 'buffers', 'cached']),
- ('net', 'q', [
- 'bytes_recv', 'bytes_sent',
- 'dropin', 'dropout', 'errin', 'errout',
- ]),
- ('disk', 'q', ['total', 'used']),
- ]
- def read_stats(f):
- stats = {}
- for stat_group, format_code, subfields in fields:
- field_data = {}
- fmt = '1440' + format_code
- if stat_group != 'disk':
- size = struct.calcsize(fmt)
- for field in subfields:
- field_data[field] = struct.unpack(fmt, f.read(size))
- else:
- buf = f.read() # disk is last, so we can read everything
- index = 0
- while index < len(buf):
- mountpoint_size = ord(buf[index])
- disk_fmt = '%dp %s %s' % (mountpoint_size + 1, fmt, fmt)
- size = struct.calcsize(disk_fmt)
- data = struct.unpack(disk_fmt, buf[index:index+size])
- mountpoint = data[0]
- total = data[1:1441]
- used = data[1441:]
- field_data[mountpoint] = {'used': used, 'total': total}
- index += size
- stats[stat_group] = field_data
- return stats
- def dict_insert(d, split, value):
- if len(split) > 1:
- d.setdefault(split[0], {})
- dict_insert(d[split[0]], split[1:], value)
- else:
- d[split[0]] = value
- def write_datum(f, data):
- for stat_group, format_code, subfields in fields:
- fmt = '1440' + format_code
- if stat_group == 'disk':
- for mountpoint, disk_data in data['disk'].items():
- mountpoint = mountpoint.encode('utf-8')
- disk_fmt = '%dp %s %s' % (len(mountpoint) + 1, fmt, fmt)
- total = [-1] * 1440
- total[0] = disk_data['total']
- used = [-1] * 1440
- used[0] = disk_data['used']
- f.write(struct.pack(disk_fmt, mountpoint, *(total + used)))
- else:
- for field in subfields:
- array = [-1] * 1440
- array[0] = data[stat_group][field]
- f.write(struct.pack(fmt, *array))
|