stupid thinko
[invirt/packages/invirt-remote.git] / host / usr / sbin / invirt-availability
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 import os
10
11 def main(argv):
12     """
13     Calculate the amount of memory available for new VMs
14     The numbers returned by xm info and xm info -c are in MiB
15     The numbers in /proc/xen/balloon are in KiB
16     All math is done in kibibytes for consistency
17     Output is in MiB
18
19     Bail if /etc/invirt/nocreate exists
20     """
21     try:
22         os.stat('/etc/invirt/nocreate')
23         print 0
24         return 0
25     except OSError:
26         pass
27
28     p = Popen(['/usr/sbin/xm', 'info'], stdout=PIPE)
29     output = p.communicate()[0]
30     if p.returncode != 0:
31         raise RuntimeError("Command '%s' returned non-zero exit status %d"
32                            % ('/usr/sbin/xm info', p.returncode)) 
33     xminfo = yaml.load(output, yaml.CSafeLoader)
34
35     free_memory = int(xminfo['free_memory']) * 1024
36
37     currentallocation = int(open('/sys/devices/system/xen_memory/xen_memory0/info/current_kb', 'r').read())
38     minimumtarget = int(open('/sys/devices/system/xen_memory/xen_memory0/target_kb', 'r').read())
39     p = Popen(['/usr/sbin/xm', 'info', '-c'], stdout=PIPE)
40     output = p.communicate()[0]
41     if p.returncode != 0:
42         raise RuntimeError("Command '%s' returned non-zero exit status %d"
43                            % ('/usr/sbin/xm info -c', p.returncode)) 
44     xminfoc = yaml.load(output, yaml.CSafeLoader)
45
46     # In kibibytes
47     dom0minmem = int(xminfoc['dom0-min-mem']) * 1024
48
49     dom0_spare_memory = currentallocation - max(minimumtarget, dom0minmem)
50     print int((free_memory + dom0_spare_memory)/1024)
51     return 0
52
53 if __name__ == '__main__':
54     sys.exit(main(sys.argv))