2 from invirt.common import CodeError, InvalidInput
10 from invirt.config import structs as config
11 from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta
12 from invirt.remctl import remctl as gen_remctl
14 # ... and stolen from xend/uuid.py
16 """Generate a random UUID."""
18 return [ random.randint(0, 255) for _ in range(0, 16) ]
21 """Turn a numeric UUID to a hyphen-seperated one."""
22 return "-".join(["%02x" * 4, "%02x" * 2, "%02x" * 2, "%02x" * 2,
23 "%02x" * 6]) % tuple(u)
26 def remctl(*args, **kwargs):
27 return gen_remctl(config.remote.hostname,
28 principal='daemon/'+config.web.hostname,
31 def lvcreate(machine, disk):
32 """Create a single disk for a machine"""
33 remctl('web', 'lvcreate', machine.name,
34 disk.guest_device_name, str(disk.size))
36 def makeDisks(machine):
37 """Update the lvm partitions to add a disk."""
38 for disk in machine.disks:
39 lvcreate(machine, disk)
41 def getswap(disksize, memsize):
42 """Returns the recommended swap partition size."""
43 return int(min(disksize / 4, memsize * 1.5))
45 def lvinstall(machine, autoinstall):
46 disksize = machine.disks[0].size
47 memsize = machine.memory
48 swapsize = getswap(disksize, memsize)
49 imagesize = disksize - swapsize
50 ip = machine.nics[0].ip
51 remctl('control', machine.name, 'install',
52 'dist=%s' % autoinstall.distribution,
53 'mirror=%s' % autoinstall.mirror,
54 'arch=%s' % autoinstall.arch,
55 'imagesize=%s' % imagesize)
57 def lvcopy(machine_orig_name, machine, rootpw):
58 """Copy a golden image onto a machine's disk"""
59 remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
61 def bootMachine(machine, cdtype):
62 """Boot a machine with a given boot CD.
64 If cdtype is None, give no boot cd. Otherwise, it is the string
65 id of the CD (e.g. 'gutsy_i386')
67 if cdtype is not None:
68 out, err = remctl('control', machine.name, 'create',
71 out, err = remctl('control', machine.name, 'create',
73 if 'already running' in err:
74 raise InvalidInput('action', 'create',
75 'VM %s is already on' % machine.name)
77 raise CodeError('"%s" on "control %s create %s'
78 % (err, machine.name, cdtype))
80 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
81 """Create a VM and put it in the database"""
82 # put stuff in the table
85 validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
88 machine.description = description
89 machine.memory = memory
91 machine.administrator = None
92 machine.contact = contact
93 machine.uuid = uuidToString(randomUUID())
94 machine.boot_off_cd = True
95 machine.type = machine_type
96 session.save_or_update(machine)
97 disk = Disk(machine=machine,
98 guest_device_name='hda', size=disksize)
99 nic = NIC.query().filter_by(machine_id=None).filter_by(reusable=True).first()
100 if not nic: #No IPs left!
101 raise CodeError("No IP addresses left! "
102 "Contact %s." % config.web.errormail)
103 nic.machine = machine
105 session.save_or_update(nic)
106 session.save_or_update(disk)
107 cache_acls.refreshMachine(machine)
115 lvinstall(machine, autoinstall)
117 # tell it to boot with cdrom
118 bootMachine(machine, cdrom)
125 """Return a dictionary mapping machine names to dicts."""
126 value_string = remctl('web', 'listvms')
127 value_dict = yaml.load(value_string, yaml.CSafeLoader)
131 """Parse a status string into nested tuples of strings.
133 s = output of xm list --long <machine_name>
135 values = re.split('([()])', s)
137 for v in values[2:-2]: #remove initial and final '()'
144 if len(stack[-1]) == 1:
146 stack[-2].append(stack[-1])
151 stack[-1].extend(v.split())
154 def statusInfo(machine):
155 """Return the status list for a given machine.
157 Gets and parses xm list --long
159 value_string, err_string = remctl('control', machine.name, 'list-long',
161 if 'Unknown command' in err_string:
162 raise CodeError("ERROR in remctl list-long %s is not registered" %
164 elif 'is not on' in err_string:
167 raise CodeError("ERROR in remctl list-long %s: %s" %
168 (machine.name, err_string))
169 status = parseStatus(value_string)
172 def listHost(machine):
173 """Return the host a machine is running on"""
174 out, err = remctl('control', machine.name, 'listhost', err=True)
179 def vnctoken(machine):
180 """Return a time-stamped VNC token"""
181 out, err = remctl('control', machine.name, 'vnctoken', err=True)
186 def deleteVM(machine):
188 remctl('control', machine.name, 'destroy', err=True)
190 delete_disk_pairs = [(machine.name, d.guest_device_name)
191 for d in machine.disks]
193 for mname, dname in delete_disk_pairs:
194 remctl('web', 'lvremove', mname, dname)
195 for nic in machine.nics:
196 nic.machine_id = None
198 session.save_or_update(nic)
199 for disk in machine.disks:
201 session.delete(machine)
207 def commandResult(username, state, command_name, machine_id, fields):
209 machine = validation.Validate(username, state, machine_id=machine_id).machine
210 action = command_name
211 cdrom = fields.get('cdrom') or None
212 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
213 raise CodeError("Invalid cdrom type '%s'" % cdrom)
214 if action not in "reboot create destroy shutdown delete".split(" "):
215 raise CodeError("Invalid action '%s'" % action)
216 if action == 'reboot':
217 if cdrom is not None:
218 out, err = remctl('control', machine.name, 'reboot', cdrom,
221 out, err = remctl('control', machine.name, 'reboot',
224 if re.match("machine '.*' is not on", err):
225 raise InvalidInput("action", "reboot",
228 print >> sys.stderr, 'Error on reboot:'
229 print >> sys.stderr, err
230 raise CodeError('ERROR on remctl')
232 elif action == 'create':
233 if validation.maxMemory(username, state, machine) < machine.memory:
234 raise InvalidInput('action', 'Power on',
235 "You don't have enough free RAM quota "
236 "to turn on this machine.")
237 bootMachine(machine, cdrom)
238 elif action == 'destroy':
239 out, err = remctl('control', machine.name, 'destroy', err=True)
241 if re.match("machine '.*' is not on", err):
242 raise InvalidInput("action", "Power off",
243 "Machine is not on.")
245 print >> sys.stderr, 'Error on power off:'
246 print >> sys.stderr, err
247 raise CodeError('ERROR on remctl')
248 elif action == 'shutdown':
249 out, err = remctl('control', machine.name, 'shutdown', err=True)
251 if re.match("machine '.*' is not on", err):
252 raise InvalidInput("action", "Shutdown",
253 "Machine is not on.")
255 print >> sys.stderr, 'Error on Shutdown:'
256 print >> sys.stderr, err
257 raise CodeError('ERROR on remctl')
258 elif action == 'delete':
261 d = dict(user=username,
266 def resizeDisk(machine_name, disk_name, new_size):
267 remctl("web", "lvresize", machine_name, disk_name, new_size)
269 def renameMachine(machine, old_name, new_name):
270 for disk in machine.disks:
271 remctl("web", "lvrename", old_name,
272 disk.guest_device_name, new_name)