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

Last change on this file since 2139 was 2114, checked in by iannucci, 16 years ago

Fixed missing import

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