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