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
51 installer_options = ['dist=%s' % autoinstall.distribution,
52 'mirror=%s' % autoinstall.mirror,
53 'arch=%s' % autoinstall.arch,
54 'imagesize=%s' % imagesize]
55 if autoinstall.preseed:
56 installer_options += ['preseed=http://'+config.web.hostname+'/static/preseed/'+autoinstall.distribution+'/'+autoinstall.arch+'.preseed']
58 remctl('control', machine.name, 'install',
61 def lvcopy(machine_orig_name, machine, rootpw):
62 """Copy a golden image onto a machine's disk"""
63 remctl('web', 'lvcopy', machine_orig_name, machine.name, rootpw)
65 def bootMachine(machine, cdtype):
66 """Boot a machine with a given boot CD.
68 If cdtype is None, give no boot cd. Otherwise, it is the string
69 id of the CD (e.g. 'gutsy_i386')
71 if cdtype is not None:
72 out, err = remctl('control', machine.name, 'create',
75 out, err = remctl('control', machine.name, 'create',
77 if 'already running' in err:
78 raise InvalidInput('action', 'create',
79 'VM %s is already on' % machine.name)
80 elif 'I need' in err and 'but dom0_min_mem is' in err:
81 raise InvalidInput('action', 'create',
82 "We're really sorry, but our servers don't have enough capacity to create your VM right now. Try creating a VM with less RAM, or shutting down another VM of yours. Feel free to ask %s if you would like to know when we plan to have more resources." % (config.contact))
83 elif ('Booting VMs is temporarily disabled for maintenance, sorry' in err or
84 'LVM operations are temporarily disabled for maintenance, sorry' in err):
85 raise InvalidInput('action', 'create',
87 elif "Boot loader didn't return any data!" in err:
88 raise InvalidInput('action', 'create',
89 "The ParaVM bootloader was unable to find an operating system to boot. Do you have GRUB configured correctly?")
90 elif 'xc_dom_find_loader: no loader found' in err:
91 raise InvalidInput('action', 'create',
92 "The ParaVM bootloader was unable to boot the kernel you have configured. Are you sure this kernel is capable of running as a Xen ParaVM guest?")
94 raise CodeError('"%s" on "control %s create %s'
95 % (err, machine.name, cdtype))
97 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
98 """Create a VM and put it in the database"""
99 # put stuff in the table
102 validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
105 machine.description = description
106 machine.memory = memory
107 machine.owner = owner
108 machine.administrator = None
109 machine.contact = contact
110 machine.uuid = uuidToString(randomUUID())
111 machine.boot_off_cd = True
112 machine.type = machine_type
113 session.save_or_update(machine)
114 disk = Disk(machine=machine,
115 guest_device_name='hda', size=disksize)
116 nic = NIC.query().filter_by(machine_id=None).filter_by(reusable=True).first()
117 if not nic: #No IPs left!
118 raise CodeError("No IP addresses left! "
119 "Contact %s." % config.web.errormail)
120 nic.machine = machine
122 session.save_or_update(nic)
123 session.save_or_update(disk)
124 cache_acls.refreshMachine(machine)
132 lvinstall(machine, autoinstall)
134 # tell it to boot with cdrom
135 bootMachine(machine, cdrom)
142 """Return a dictionary mapping machine names to dicts."""
143 value_string = remctl('web', 'listvms')
144 value_dict = yaml.load(value_string, yaml.CSafeLoader)
148 """Parse a status string into nested tuples of strings.
150 s = output of xm list --long <machine_name>
152 values = re.split('([()])', s)
154 for v in values[2:-2]: #remove initial and final '()'
161 if len(stack[-1]) == 1:
163 stack[-2].append(stack[-1])
168 stack[-1].extend(v.split())
171 def statusInfo(machine):
172 """Return the status list for a given machine.
174 Gets and parses xm list --long
176 value_string, err_string = remctl('control', machine.name, 'list-long',
178 if 'Unknown command' in err_string:
179 raise CodeError("ERROR in remctl list-long %s is not registered" %
181 elif 'is not on' in err_string:
184 raise CodeError("ERROR in remctl list-long %s: %s" %
185 (machine.name, err_string))
186 status = parseStatus(value_string)
189 def listHost(machine):
190 """Return the host a machine is running on"""
191 out, err = remctl('control', machine.name, 'listhost', err=True)
196 def vnctoken(machine):
197 """Return a time-stamped VNC token"""
198 out, err = remctl('control', machine.name, 'vnctoken', err=True)
203 def deleteVM(machine):
205 remctl('control', machine.name, 'destroy', err=True)
207 delete_disk_pairs = [(machine.name, d.guest_device_name)
208 for d in machine.disks]
210 for mname, dname in delete_disk_pairs:
211 remctl('web', 'lvremove', mname, dname)
212 for nic in machine.nics:
213 nic.machine_id = None
215 session.save_or_update(nic)
216 for disk in machine.disks:
218 session.delete(machine)
224 def commandResult(username, state, command_name, machine_id, fields):
226 machine = validation.Validate(username, state, machine_id=machine_id).machine
227 action = command_name
228 cdrom = fields.get('cdrom') or None
229 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
230 raise CodeError("Invalid cdrom type '%s'" % cdrom)
231 if action not in "reboot create destroy shutdown delete".split(" "):
232 raise CodeError("Invalid action '%s'" % action)
233 if action == 'reboot':
234 if cdrom is not None:
235 out, err = remctl('control', machine.name, 'reboot', cdrom,
238 out, err = remctl('control', machine.name, 'reboot',
241 if re.match("machine '.*' is not on", err):
242 raise InvalidInput("action", "reboot",
245 print >> sys.stderr, 'Error on reboot:'
246 print >> sys.stderr, err
247 raise CodeError('ERROR on remctl')
249 elif action == 'create':
250 if validation.maxMemory(username, state, machine) < machine.memory:
251 raise InvalidInput('action', 'Power on',
252 "You don't have enough free RAM quota "
253 "to turn on this machine.")
254 bootMachine(machine, cdrom)
255 elif action == 'destroy':
256 out, err = remctl('control', machine.name, 'destroy', err=True)
258 if re.match("machine '.*' is not on", err):
259 raise InvalidInput("action", "Power off",
260 "Machine is not on.")
262 print >> sys.stderr, 'Error on power off:'
263 print >> sys.stderr, err
264 raise CodeError('ERROR on remctl')
265 elif action == 'shutdown':
266 out, err = remctl('control', machine.name, 'shutdown', err=True)
268 if re.match("machine '.*' is not on", err):
269 raise InvalidInput("action", "Shutdown",
270 "Machine is not on.")
272 print >> sys.stderr, 'Error on Shutdown:'
273 print >> sys.stderr, err
274 raise CodeError('ERROR on remctl')
275 elif action == 'delete':
278 d = dict(user=username,
283 def resizeDisk(machine_name, disk_name, new_size):
284 remctl("web", "lvresize", machine_name, disk_name, new_size)
286 def renameMachine(machine, old_name, new_name):
287 for disk in machine.disks:
288 remctl("web", "lvrename", old_name,
289 disk.guest_device_name, new_name)