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