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)
76 elif 'I need' in err and 'but dom0_min_mem is' in err:
77 raise InvalidInput('action', 'create',
78 "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))
79 elif ('Booting VMs is temporarily disabled for maintenance, sorry' in err or
80 'LVM operations are temporarily disabled for maintenance, sorry' in err):
81 raise InvalidInput('action', 'create',
83 elif "Boot loader didn't return any data!" in err:
84 raise InvalidInput('action', 'create',
85 "The ParaVM bootloader was unable to find an operating system to boot. Do you have GRUB configured correctly?")
86 elif 'xc_dom_find_loader: no loader found' in err:
87 raise InvalidInput('action', 'create',
88 "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?")
90 raise CodeError('"%s" on "control %s create %s'
91 % (err, machine.name, cdtype))
93 def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall):
94 """Create a VM and put it in the database"""
95 # put stuff in the table
98 validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.)
101 machine.description = description
102 machine.memory = memory
103 machine.owner = owner
104 machine.administrator = None
105 machine.contact = contact
106 machine.uuid = uuidToString(randomUUID())
107 machine.boot_off_cd = True
108 machine.type = machine_type
109 session.save_or_update(machine)
110 disk = Disk(machine=machine,
111 guest_device_name='hda', size=disksize)
112 nic = NIC.query().filter_by(machine_id=None).filter_by(reusable=True).first()
113 if not nic: #No IPs left!
114 raise CodeError("No IP addresses left! "
115 "Contact %s." % config.web.errormail)
116 nic.machine = machine
118 session.save_or_update(nic)
119 session.save_or_update(disk)
120 cache_acls.refreshMachine(machine)
128 lvinstall(machine, autoinstall)
130 # tell it to boot with cdrom
131 bootMachine(machine, cdrom)
138 """Return a dictionary mapping machine names to dicts."""
139 value_string = remctl('web', 'listvms')
140 value_dict = yaml.load(value_string, yaml.CSafeLoader)
144 """Parse a status string into nested tuples of strings.
146 s = output of xm list --long <machine_name>
148 values = re.split('([()])', s)
150 for v in values[2:-2]: #remove initial and final '()'
157 if len(stack[-1]) == 1:
159 stack[-2].append(stack[-1])
164 stack[-1].extend(v.split())
167 def statusInfo(machine):
168 """Return the status list for a given machine.
170 Gets and parses xm list --long
172 value_string, err_string = remctl('control', machine.name, 'list-long',
174 if 'Unknown command' in err_string:
175 raise CodeError("ERROR in remctl list-long %s is not registered" %
177 elif 'is not on' in err_string:
180 raise CodeError("ERROR in remctl list-long %s: %s" %
181 (machine.name, err_string))
182 status = parseStatus(value_string)
185 def listHost(machine):
186 """Return the host a machine is running on"""
187 out, err = remctl('control', machine.name, 'listhost', err=True)
192 def vnctoken(machine):
193 """Return a time-stamped VNC token"""
194 out, err = remctl('control', machine.name, 'vnctoken', err=True)
199 def deleteVM(machine):
201 remctl('control', machine.name, 'destroy', err=True)
203 delete_disk_pairs = [(machine.name, d.guest_device_name)
204 for d in machine.disks]
206 for mname, dname in delete_disk_pairs:
207 remctl('web', 'lvremove', mname, dname)
208 for nic in machine.nics:
209 nic.machine_id = None
211 session.save_or_update(nic)
212 for disk in machine.disks:
214 session.delete(machine)
220 def commandResult(username, state, command_name, machine_id, fields):
222 machine = validation.Validate(username, state, machine_id=machine_id).machine
223 action = command_name
224 cdrom = fields.get('cdrom') or None
225 if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one():
226 raise CodeError("Invalid cdrom type '%s'" % cdrom)
227 if action not in "reboot create destroy shutdown delete".split(" "):
228 raise CodeError("Invalid action '%s'" % action)
229 if action == 'reboot':
230 if cdrom is not None:
231 out, err = remctl('control', machine.name, 'reboot', cdrom,
234 out, err = remctl('control', machine.name, 'reboot',
237 if re.match("machine '.*' is not on", err):
238 raise InvalidInput("action", "reboot",
241 print >> sys.stderr, 'Error on reboot:'
242 print >> sys.stderr, err
243 raise CodeError('ERROR on remctl')
245 elif action == 'create':
246 if validation.maxMemory(username, state, machine) < machine.memory:
247 raise InvalidInput('action', 'Power on',
248 "You don't have enough free RAM quota "
249 "to turn on this machine.")
250 bootMachine(machine, cdrom)
251 elif action == 'destroy':
252 out, err = remctl('control', machine.name, 'destroy', err=True)
254 if re.match("machine '.*' is not on", err):
255 raise InvalidInput("action", "Power off",
256 "Machine is not on.")
258 print >> sys.stderr, 'Error on power off:'
259 print >> sys.stderr, err
260 raise CodeError('ERROR on remctl')
261 elif action == 'shutdown':
262 out, err = remctl('control', machine.name, 'shutdown', err=True)
264 if re.match("machine '.*' is not on", err):
265 raise InvalidInput("action", "Shutdown",
266 "Machine is not on.")
268 print >> sys.stderr, 'Error on Shutdown:'
269 print >> sys.stderr, err
270 raise CodeError('ERROR on remctl')
271 elif action == 'delete':
274 d = dict(user=username,
279 def resizeDisk(machine_name, disk_name, new_size):
280 remctl("web", "lvresize", machine_name, disk_name, new_size)
282 def renameMachine(machine, old_name, new_name):
283 for disk in machine.disks:
284 remctl("web", "lvrename", old_name,
285 disk.guest_device_name, new_name)