source: trunk/packages/invirt-remote/host/usr/sbin/invirt-availability @ 2464

Last change on this file since 2464 was 2161, checked in by andersk, 16 years ago

Don't confuse {KB, MB, GB} with {KiB, MiB, GiB}.

File size: 1.9 KB
Line 
1#!/usr/bin/env python
2"""
3Gathers availability data for the VM host it's running on.
4"""
5
6from subprocess import PIPE, Popen, call
7import sys
8import yaml
9import os
10
11# return the amount of memory in kibibytes represented by s
12def parseUnits(s):
13    num, unit = s.split(' ')
14    assert unit == 'kB', "unexpected unit"
15    return int(num)
16
17def 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
61if __name__ == '__main__':
62    sys.exit(main(sys.argv))
Note: See TracBrowser for help on using the repository browser.