| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import copy
- import struct
- fields = [
- ('cpu', 'f', [
- 'num_cpus',
- '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', ['read_bytes', 'write_bytes', 'total', 'used']),
- ]
- def gen_template(val):
- template = {}
- for stat_group, _, subfields in fields:
- field_data = {}
- if stat_group == 'disk':
- field_data =
- else:
- for field in subfields:
- field_data[field] = copy.copy(val)
- template[stat_group] = field_data
- return template
- TEMPLATE = gen_template([-1] * 1440)
- 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_from(disk_fmt, buf, index)
- 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 field in subfields:
- array = data[stat_group][field]
- f.write(struct.pack(fmt, *array))
- else:
- for mountpoint, disk_data in data['disk'].iteritems():
- mountpoint = mountpoint.encode('utf-8')
- disk_fmt = '%dp %s %s' % (len(mountpoint) + 1, fmt, fmt)
- array = disk_data['total'] + disk_data['used']
- f.write(struct.pack(disk_fmt, mountpoint, *array))
|