1 | #!/usr/bin/env python |
---|
2 | """ |
---|
3 | Gathers availability data for the VM host it's running on. |
---|
4 | """ |
---|
5 | |
---|
6 | from subprocess import PIPE, Popen, call |
---|
7 | import sys |
---|
8 | import yaml |
---|
9 | |
---|
10 | # return the amount of memory in kilobytes represented by s |
---|
11 | def parseUnits(s): |
---|
12 | num, unit = s.split(' ') |
---|
13 | return int(num) * {'kb':1, 'mb':1024}[unit.lower()] |
---|
14 | |
---|
15 | def main(argv): |
---|
16 | """ |
---|
17 | Calculate the amount of memory available for new VMs |
---|
18 | The numbers returned by xm info and xm info -c are in MB |
---|
19 | The numbers in /proc/xen/balloon have nice units |
---|
20 | All math is done in kilobytes for consistency |
---|
21 | Output is in MB |
---|
22 | """ |
---|
23 | p = Popen(['/usr/sbin/xm', 'info'], stdout=PIPE) |
---|
24 | output = p.communicate()[0] |
---|
25 | if p.returncode != 0: |
---|
26 | raise RuntimeError("Command '%s' returned non-zero exit status %d" |
---|
27 | % ('/usr/sbin/xm info', p.returncode)) |
---|
28 | xminfo = yaml.load(output, yaml.CSafeLoader) |
---|
29 | |
---|
30 | free_memory = int(xminfo['free_memory']) * 1024 |
---|
31 | |
---|
32 | ballooninfo = yaml.load(open('/proc/xen/balloon', 'r').read()) |
---|
33 | currentallocation = parseUnits(ballooninfo['Current allocation']) |
---|
34 | minimumtarget = parseUnits(ballooninfo['Minimum target']) |
---|
35 | |
---|
36 | p = Popen(['/usr/sbin/xm', 'info', '-c'], stdout=PIPE) |
---|
37 | output = p.communicate()[0] |
---|
38 | if p.returncode != 0: |
---|
39 | raise RuntimeError("Command '%s' returned non-zero exit status %d" |
---|
40 | % ('/usr/sbin/xm info -c', p.returncode)) |
---|
41 | xminfoc = yaml.load(output, yaml.CSafeLoader) |
---|
42 | |
---|
43 | # In kilobytes |
---|
44 | dom0minmem = int(xminfoc['dom0-min-mem']) * 1024 |
---|
45 | |
---|
46 | dom0_spare_memory = currentallocation - max(minimumtarget, dom0minmem) |
---|
47 | print int((free_memory + dom0_spare_memory)/1024) |
---|
48 | return 0 |
---|
49 | |
---|
50 | if __name__ == '__main__': |
---|
51 | sys.exit(main(sys.argv)) |
---|