[209] | 1 | import validation |
---|
[1612] | 2 | from invirt.common import CodeError, InvalidInput |
---|
[209] | 3 | import random |
---|
| 4 | import sys |
---|
| 5 | import time |
---|
| 6 | import re |
---|
[265] | 7 | import cache_acls |
---|
[550] | 8 | import yaml |
---|
[209] | 9 | |
---|
[863] | 10 | from invirt.config import structs as config |
---|
[1001] | 11 | from invirt.database import Machine, Disk, Type, NIC, CDROM, session, meta |
---|
[1614] | 12 | from invirt.remctl import remctl as gen_remctl |
---|
[863] | 13 | |
---|
[209] | 14 | # ... and stolen from xend/uuid.py |
---|
| 15 | def randomUUID(): |
---|
| 16 | """Generate a random UUID.""" |
---|
| 17 | |
---|
| 18 | return [ random.randint(0, 255) for _ in range(0, 16) ] |
---|
| 19 | |
---|
| 20 | def uuidToString(u): |
---|
| 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) |
---|
| 24 | # end stolen code |
---|
| 25 | |
---|
[1614] | 26 | def remctl(*args, **kwargs): |
---|
[1618] | 27 | return gen_remctl(config.remote.hostname, |
---|
[1614] | 28 | principal='daemon/'+config.web.hostname, |
---|
[1618] | 29 | *args, **kwargs) |
---|
[1614] | 30 | |
---|
[209] | 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)) |
---|
| 35 | |
---|
| 36 | def makeDisks(machine): |
---|
| 37 | """Update the lvm partitions to add a disk.""" |
---|
| 38 | for disk in machine.disks: |
---|
| 39 | lvcreate(machine, disk) |
---|
| 40 | |
---|
[629] | 41 | def getswap(disksize, memsize): |
---|
| 42 | """Returns the recommended swap partition size.""" |
---|
| 43 | return int(min(disksize / 4, memsize * 1.5)) |
---|
| 44 | |
---|
| 45 | def lvinstall(machine, autoinstall): |
---|
| 46 | disksize = machine.disks[0].size |
---|
| 47 | memsize = machine.memory |
---|
[1096] | 48 | swapsize = getswap(disksize, memsize) |
---|
| 49 | imagesize = disksize - swapsize |
---|
[629] | 50 | ip = machine.nics[0].ip |
---|
[1096] | 51 | remctl('control', machine.name, 'install', |
---|
| 52 | 'dist=%s' % autoinstall.distribution, |
---|
| 53 | 'mirror=%s' % autoinstall.mirror, |
---|
[1695] | 54 | 'arch=%s' % autoinstall.arch, |
---|
[1096] | 55 | 'imagesize=%s' % imagesize) |
---|
[629] | 56 | |
---|
[340] | 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) |
---|
| 60 | |
---|
[209] | 61 | def bootMachine(machine, cdtype): |
---|
| 62 | """Boot a machine with a given boot CD. |
---|
| 63 | |
---|
| 64 | If cdtype is None, give no boot cd. Otherwise, it is the string |
---|
| 65 | id of the CD (e.g. 'gutsy_i386') |
---|
| 66 | """ |
---|
| 67 | if cdtype is not None: |
---|
[261] | 68 | out, err = remctl('control', machine.name, 'create', |
---|
| 69 | cdtype, err=True) |
---|
[209] | 70 | else: |
---|
[261] | 71 | out, err = remctl('control', machine.name, 'create', |
---|
| 72 | err=True) |
---|
[695] | 73 | if 'already running' in err: |
---|
[261] | 74 | raise InvalidInput('action', 'create', |
---|
| 75 | 'VM %s is already on' % machine.name) |
---|
| 76 | elif err: |
---|
| 77 | raise CodeError('"%s" on "control %s create %s' |
---|
| 78 | % (err, machine.name, cdtype)) |
---|
[209] | 79 | |
---|
[629] | 80 | def createVm(username, state, owner, contact, name, description, memory, disksize, machine_type, cdrom, autoinstall): |
---|
[209] | 81 | """Create a VM and put it in the database""" |
---|
| 82 | # put stuff in the table |
---|
[1013] | 83 | session.begin() |
---|
[209] | 84 | try: |
---|
[609] | 85 | validation.Validate(username, state, name=name, description=description, owner=owner, memory=memory, disksize=disksize/1024.) |
---|
[209] | 86 | machine = Machine() |
---|
| 87 | machine.name = name |
---|
[609] | 88 | machine.description = description |
---|
[209] | 89 | machine.memory = memory |
---|
[228] | 90 | machine.owner = owner |
---|
[1709] | 91 | machine.administrator = None |
---|
[228] | 92 | machine.contact = contact |
---|
[209] | 93 | machine.uuid = uuidToString(randomUUID()) |
---|
| 94 | machine.boot_off_cd = True |
---|
[1013] | 95 | machine.type = machine_type |
---|
| 96 | session.save_or_update(machine) |
---|
| 97 | disk = Disk(machine=machine, |
---|
[572] | 98 | guest_device_name='hda', size=disksize) |
---|
[1013] | 99 | nic = NIC.query().filter_by(machine_id=None).first() |
---|
| 100 | if not nic: #No IPs left! |
---|
[209] | 101 | raise CodeError("No IP addresses left! " |
---|
[879] | 102 | "Contact %s." % config.web.errormail) |
---|
[1013] | 103 | nic.machine = machine |
---|
[209] | 104 | nic.hostname = name |
---|
[1013] | 105 | session.save_or_update(nic) |
---|
| 106 | session.save_or_update(disk) |
---|
[265] | 107 | cache_acls.refreshMachine(machine) |
---|
[1013] | 108 | session.commit() |
---|
[209] | 109 | except: |
---|
[1013] | 110 | session.rollback() |
---|
[209] | 111 | raise |
---|
| 112 | makeDisks(machine) |
---|
[629] | 113 | if autoinstall: |
---|
| 114 | lvinstall(machine, autoinstall) |
---|
[1140] | 115 | else: |
---|
| 116 | # tell it to boot with cdrom |
---|
| 117 | bootMachine(machine, cdrom) |
---|
[209] | 118 | return machine |
---|
| 119 | |
---|
[554] | 120 | def getList(): |
---|
| 121 | """Return a dictionary mapping machine names to dicts.""" |
---|
[550] | 122 | value_string = remctl('web', 'listvms') |
---|
[574] | 123 | value_dict = yaml.load(value_string, yaml.CSafeLoader) |
---|
[554] | 124 | return value_dict |
---|
[209] | 125 | |
---|
| 126 | def parseStatus(s): |
---|
| 127 | """Parse a status string into nested tuples of strings. |
---|
| 128 | |
---|
| 129 | s = output of xm list --long <machine_name> |
---|
| 130 | """ |
---|
| 131 | values = re.split('([()])', s) |
---|
| 132 | stack = [[]] |
---|
| 133 | for v in values[2:-2]: #remove initial and final '()' |
---|
| 134 | if not v: |
---|
| 135 | continue |
---|
| 136 | v = v.strip() |
---|
| 137 | if v == '(': |
---|
| 138 | stack.append([]) |
---|
| 139 | elif v == ')': |
---|
| 140 | if len(stack[-1]) == 1: |
---|
| 141 | stack[-1].append('') |
---|
| 142 | stack[-2].append(stack[-1]) |
---|
| 143 | stack.pop() |
---|
| 144 | else: |
---|
| 145 | if not v: |
---|
| 146 | continue |
---|
| 147 | stack[-1].extend(v.split()) |
---|
| 148 | return stack[-1] |
---|
| 149 | |
---|
| 150 | def statusInfo(machine): |
---|
| 151 | """Return the status list for a given machine. |
---|
| 152 | |
---|
| 153 | Gets and parses xm list --long |
---|
| 154 | """ |
---|
| 155 | value_string, err_string = remctl('control', machine.name, 'list-long', |
---|
| 156 | err=True) |
---|
| 157 | if 'Unknown command' in err_string: |
---|
| 158 | raise CodeError("ERROR in remctl list-long %s is not registered" % |
---|
| 159 | (machine.name,)) |
---|
[626] | 160 | elif 'is not on' in err_string: |
---|
[209] | 161 | return None |
---|
| 162 | elif err_string: |
---|
| 163 | raise CodeError("ERROR in remctl list-long %s: %s" % |
---|
| 164 | (machine.name, err_string)) |
---|
| 165 | status = parseStatus(value_string) |
---|
| 166 | return status |
---|
| 167 | |
---|
[662] | 168 | def listHost(machine): |
---|
| 169 | """Return the host a machine is running on""" |
---|
| 170 | out, err = remctl('control', machine.name, 'listhost', err=True) |
---|
| 171 | if err: |
---|
| 172 | return None |
---|
[666] | 173 | return out.strip() |
---|
[662] | 174 | |
---|
[1615] | 175 | def vnctoken(machine): |
---|
| 176 | """Return a time-stamped VNC token""" |
---|
[1619] | 177 | out, err = remctl('control', machine.name, 'vnctoken', err=True) |
---|
[1615] | 178 | if err: |
---|
| 179 | return None |
---|
| 180 | return out.strip() |
---|
| 181 | |
---|
[209] | 182 | def deleteVM(machine): |
---|
| 183 | """Delete a VM.""" |
---|
| 184 | remctl('control', machine.name, 'destroy', err=True) |
---|
[1013] | 185 | session.begin() |
---|
[209] | 186 | delete_disk_pairs = [(machine.name, d.guest_device_name) |
---|
| 187 | for d in machine.disks] |
---|
| 188 | try: |
---|
[1013] | 189 | for mname, dname in delete_disk_pairs: |
---|
| 190 | remctl('web', 'lvremove', mname, dname) |
---|
[209] | 191 | for nic in machine.nics: |
---|
| 192 | nic.machine_id = None |
---|
| 193 | nic.hostname = None |
---|
[1013] | 194 | session.save_or_update(nic) |
---|
[209] | 195 | for disk in machine.disks: |
---|
[1013] | 196 | session.delete(disk) |
---|
| 197 | session.delete(machine) |
---|
| 198 | session.commit() |
---|
[209] | 199 | except: |
---|
[1013] | 200 | session.rollback() |
---|
[209] | 201 | raise |
---|
| 202 | |
---|
[572] | 203 | def commandResult(username, state, fields): |
---|
[209] | 204 | start_time = 0 |
---|
[572] | 205 | machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine |
---|
[209] | 206 | action = fields.getfirst('action') |
---|
| 207 | cdrom = fields.getfirst('cdrom') |
---|
[1074] | 208 | if cdrom is not None and not CDROM.query().filter_by(cdrom_id=cdrom).one(): |
---|
[209] | 209 | raise CodeError("Invalid cdrom type '%s'" % cdrom) |
---|
| 210 | if action not in ('Reboot', 'Power on', 'Power off', 'Shutdown', |
---|
| 211 | 'Delete VM'): |
---|
| 212 | raise CodeError("Invalid action '%s'" % action) |
---|
| 213 | if action == 'Reboot': |
---|
| 214 | if cdrom is not None: |
---|
| 215 | out, err = remctl('control', machine.name, 'reboot', cdrom, |
---|
| 216 | err=True) |
---|
| 217 | else: |
---|
| 218 | out, err = remctl('control', machine.name, 'reboot', |
---|
| 219 | err=True) |
---|
| 220 | if err: |
---|
[692] | 221 | if re.match("machine '.*' is not on", err): |
---|
[209] | 222 | raise InvalidInput("action", "reboot", |
---|
| 223 | "Machine is not on") |
---|
| 224 | else: |
---|
| 225 | print >> sys.stderr, 'Error on reboot:' |
---|
| 226 | print >> sys.stderr, err |
---|
| 227 | raise CodeError('ERROR on remctl') |
---|
| 228 | |
---|
| 229 | elif action == 'Power on': |
---|
[572] | 230 | if validation.maxMemory(username, state, machine) < machine.memory: |
---|
[209] | 231 | raise InvalidInput('action', 'Power on', |
---|
| 232 | "You don't have enough free RAM quota " |
---|
| 233 | "to turn on this machine.") |
---|
| 234 | bootMachine(machine, cdrom) |
---|
| 235 | elif action == 'Power off': |
---|
| 236 | out, err = remctl('control', machine.name, 'destroy', err=True) |
---|
| 237 | if err: |
---|
[694] | 238 | if re.match("machine '.*' is not on", err): |
---|
[209] | 239 | raise InvalidInput("action", "Power off", |
---|
| 240 | "Machine is not on.") |
---|
| 241 | else: |
---|
| 242 | print >> sys.stderr, 'Error on power off:' |
---|
| 243 | print >> sys.stderr, err |
---|
| 244 | raise CodeError('ERROR on remctl') |
---|
| 245 | elif action == 'Shutdown': |
---|
| 246 | out, err = remctl('control', machine.name, 'shutdown', err=True) |
---|
| 247 | if err: |
---|
[694] | 248 | if re.match("machine '.*' is not on", err): |
---|
[209] | 249 | raise InvalidInput("action", "Shutdown", |
---|
| 250 | "Machine is not on.") |
---|
| 251 | else: |
---|
| 252 | print >> sys.stderr, 'Error on Shutdown:' |
---|
| 253 | print >> sys.stderr, err |
---|
| 254 | raise CodeError('ERROR on remctl') |
---|
| 255 | elif action == 'Delete VM': |
---|
| 256 | deleteVM(machine) |
---|
| 257 | |
---|
[572] | 258 | d = dict(user=username, |
---|
[209] | 259 | command=action, |
---|
| 260 | machine=machine) |
---|
| 261 | return d |
---|
| 262 | |
---|
| 263 | def resizeDisk(machine_name, disk_name, new_size): |
---|
| 264 | remctl("web", "lvresize", machine_name, disk_name, new_size) |
---|
| 265 | |
---|
| 266 | def renameMachine(machine, old_name, new_name): |
---|
| 267 | for disk in machine.disks: |
---|
| 268 | remctl("web", "lvrename", old_name, |
---|
| 269 | disk.guest_device_name, new_name) |
---|
| 270 | |
---|