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