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