991b3c82f6da993db8b68a38f4a0993ec9d711f9
[invirt/packages/invirt-remote.git] / server / usr / sbin / invirt-remote-create
1 #!/usr/bin/python
2
3 """
4 Picks a host to "create" (boot) a VM on, and does so.
5
6 Current load-balancing algorithm: wherever there's more free RAM.
7
8 TODO: use a lock to avoid creating the same VM twice in a race
9 """
10
11 from invirt.remote import bcast
12 from subprocess import PIPE, Popen, call
13 import sys
14 import yaml
15
16 def choose_host():
17     # Query each of the hosts.
18     results = bcast('availability')
19     return max((int(o), s) for (s, o) in results)[1]
20
21 def main(argv):
22     if len(argv) < 3:
23         print >> sys.stderr, "usage: invirt-remote-create <operation> <machine> [<other args...>]"
24         return 2
25     operation = argv[1]
26     machine_name = argv[2]
27     args = argv[3:]
28     
29     if operation == 'install':
30         options = dict(arg.split('=', 1) for arg in args)
31         valid_keys = set(('mirror', 'dist', 'arch', 'imagesize', 'noinstall'))
32         if not set(options.keys()).issubset(valid_keys):
33             print >> sys.stderr, "Invalid argument. Use the help command to see valid arguments to install"
34             return 1
35         if any(' ' in val for val in options.values()):
36             print >> sys.stderr, "Arguments to the autoinstaller cannot contain spaces"
37             return 1
38
39     p = Popen(['/usr/sbin/invirt-remote-proxy-web', 'listvms'], stdout=PIPE)
40     output = p.communicate()[0]
41     if p.returncode != 0:
42         raise RuntimeError("Command '%s' returned non-zero exit status %d"
43                            % ('invirt-remote-proxy-web', p.returncode)) 
44     vms = yaml.load(output, yaml.CSafeLoader)
45
46     if machine_name in vms:
47         host = vms[machine_name]['host']
48         print >> sys.stderr, ("machine '%s' is already running on host %s"
49                               % (machine_name, host))
50         return 1
51
52     host = choose_host()
53     print 'Creating on host %s...' % host
54     sys.stdout.flush()
55     return call(['remctl', host, 'remote', 'control',
56                  machine_name, operation] + args)
57
58 if __name__ == '__main__':
59     sys.exit(main(sys.argv))
60
61 # vim:et:sw=4:ts=4