[113] | 1 | #!/usr/bin/python |
---|
[205] | 2 | """Main CGI script for web interface""" |
---|
[113] | 3 | |
---|
[205] | 4 | import base64 |
---|
| 5 | import cPickle |
---|
[113] | 6 | import cgi |
---|
[205] | 7 | import datetime |
---|
| 8 | import hmac |
---|
[113] | 9 | import os |
---|
[205] | 10 | import sha |
---|
| 11 | import simplejson |
---|
| 12 | import sys |
---|
[118] | 13 | import time |
---|
[447] | 14 | import urllib |
---|
[205] | 15 | from StringIO import StringIO |
---|
[113] | 16 | |
---|
[205] | 17 | def revertStandardError(): |
---|
| 18 | """Move stderr to stdout, and return the contents of the old stderr.""" |
---|
| 19 | errio = sys.stderr |
---|
| 20 | if not isinstance(errio, StringIO): |
---|
| 21 | return None |
---|
| 22 | sys.stderr = sys.stdout |
---|
| 23 | errio.seek(0) |
---|
| 24 | return errio.read() |
---|
| 25 | |
---|
| 26 | def printError(): |
---|
| 27 | """Revert stderr to stdout, and print the contents of stderr""" |
---|
| 28 | if isinstance(sys.stderr, StringIO): |
---|
| 29 | print revertStandardError() |
---|
| 30 | |
---|
| 31 | if __name__ == '__main__': |
---|
| 32 | import atexit |
---|
| 33 | atexit.register(printError) |
---|
| 34 | sys.stderr = StringIO() |
---|
| 35 | |
---|
[113] | 36 | sys.path.append('/home/ecprice/.local/lib/python2.5/site-packages') |
---|
| 37 | |
---|
[235] | 38 | import templates |
---|
[113] | 39 | from Cheetah.Template import Template |
---|
[440] | 40 | import sipb_xen_database |
---|
[443] | 41 | from sipb_xen_database import Machine, CDROM, ctx, connect, MachineAccess, Type, Autoinstall |
---|
[209] | 42 | import validation |
---|
[446] | 43 | import cache_acls |
---|
[209] | 44 | from webcommon import InvalidInput, CodeError, g |
---|
| 45 | import controls |
---|
[113] | 46 | |
---|
[235] | 47 | class Checkpoint: |
---|
| 48 | def __init__(self): |
---|
| 49 | self.start_time = time.time() |
---|
| 50 | self.checkpoints = [] |
---|
| 51 | |
---|
| 52 | def checkpoint(self, s): |
---|
| 53 | self.checkpoints.append((s, time.time())) |
---|
| 54 | |
---|
| 55 | def __str__(self): |
---|
| 56 | return ('Timing info:\n%s\n' % |
---|
| 57 | '\n'.join(['%s: %s' % (d, t - self.start_time) for |
---|
| 58 | (d, t) in self.checkpoints])) |
---|
| 59 | |
---|
| 60 | checkpoint = Checkpoint() |
---|
| 61 | |
---|
[447] | 62 | def jquote(string): |
---|
| 63 | return "'" + string.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n') + "'" |
---|
[235] | 64 | |
---|
[205] | 65 | def helppopup(subj): |
---|
| 66 | """Return HTML code for a (?) link to a specified help topic""" |
---|
[447] | 67 | return ('<span class="helplink"><a href="help?' + |
---|
| 68 | cgi.escape(urllib.urlencode(dict(subject=subj, simple='true'))) |
---|
| 69 | +'" target="_blank" ' + |
---|
| 70 | 'onclick="return helppopup(' + cgi.escape(jquote(subj)) + ')">(?)</a></span>') |
---|
[205] | 71 | |
---|
| 72 | def makeErrorPre(old, addition): |
---|
| 73 | if addition is None: |
---|
| 74 | return |
---|
| 75 | if old: |
---|
| 76 | return old[:-6] + '\n----\n' + str(addition) + '</pre>' |
---|
| 77 | else: |
---|
| 78 | return '<p>STDERR:</p><pre>' + str(addition) + '</pre>' |
---|
[139] | 79 | |
---|
[440] | 80 | Template.sipb_xen_database = sipb_xen_database |
---|
[205] | 81 | Template.helppopup = staticmethod(helppopup) |
---|
| 82 | Template.err = None |
---|
[139] | 83 | |
---|
[205] | 84 | class JsonDict: |
---|
| 85 | """Class to store a dictionary that will be converted to JSON""" |
---|
| 86 | def __init__(self, **kws): |
---|
| 87 | self.data = kws |
---|
| 88 | if 'err' in kws: |
---|
| 89 | err = kws['err'] |
---|
| 90 | del kws['err'] |
---|
| 91 | self.addError(err) |
---|
[139] | 92 | |
---|
[205] | 93 | def __str__(self): |
---|
| 94 | return simplejson.dumps(self.data) |
---|
| 95 | |
---|
| 96 | def addError(self, text): |
---|
| 97 | """Add stderr text to be displayed on the website.""" |
---|
| 98 | self.data['err'] = \ |
---|
| 99 | makeErrorPre(self.data.get('err'), text) |
---|
| 100 | |
---|
| 101 | class Defaults: |
---|
| 102 | """Class to store default values for fields.""" |
---|
| 103 | memory = 256 |
---|
| 104 | disk = 4.0 |
---|
| 105 | cdrom = '' |
---|
[443] | 106 | autoinstall = '' |
---|
[205] | 107 | name = '' |
---|
| 108 | def __init__(self, max_memory=None, max_disk=None, **kws): |
---|
[440] | 109 | self.type = Type.get('linux-hvm') |
---|
[205] | 110 | if max_memory is not None: |
---|
| 111 | self.memory = min(self.memory, max_memory) |
---|
| 112 | if max_disk is not None: |
---|
| 113 | self.max_disk = min(self.disk, max_disk) |
---|
| 114 | for key in kws: |
---|
| 115 | setattr(self, key, kws[key]) |
---|
| 116 | |
---|
| 117 | |
---|
| 118 | |
---|
[209] | 119 | DEFAULT_HEADERS = {'Content-Type': 'text/html'} |
---|
[205] | 120 | |
---|
[153] | 121 | def error(op, user, fields, err, emsg): |
---|
[145] | 122 | """Print an error page when a CodeError occurs""" |
---|
[153] | 123 | d = dict(op=op, user=user, errorMessage=str(err), |
---|
| 124 | stderr=emsg) |
---|
[235] | 125 | return templates.error(searchList=[d]) |
---|
[113] | 126 | |
---|
[153] | 127 | def invalidInput(op, user, fields, err, emsg): |
---|
| 128 | """Print an error page when an InvalidInput exception occurs""" |
---|
| 129 | d = dict(op=op, user=user, err_field=err.err_field, |
---|
| 130 | err_value=str(err.err_value), stderr=emsg, |
---|
| 131 | errorMessage=str(err)) |
---|
[235] | 132 | return templates.invalid(searchList=[d]) |
---|
[153] | 133 | |
---|
[119] | 134 | def hasVnc(status): |
---|
[133] | 135 | """Does the machine with a given status list support VNC?""" |
---|
[119] | 136 | if status is None: |
---|
| 137 | return False |
---|
| 138 | for l in status: |
---|
| 139 | if l[0] == 'device' and l[1][0] == 'vfb': |
---|
| 140 | d = dict(l[1][1:]) |
---|
| 141 | return 'location' in d |
---|
| 142 | return False |
---|
| 143 | |
---|
[205] | 144 | def parseCreate(user, fields): |
---|
[134] | 145 | name = fields.getfirst('name') |
---|
[209] | 146 | if not validation.validMachineName(name): |
---|
[429] | 147 | raise InvalidInput('name', name, 'You must provide a machine name. Max 22 chars, alnum plus \'-\' and \'_\'.') |
---|
[162] | 148 | name = name.lower() |
---|
[134] | 149 | |
---|
| 150 | if Machine.get_by(name=name): |
---|
[153] | 151 | raise InvalidInput('name', name, |
---|
[205] | 152 | "Name already exists.") |
---|
[438] | 153 | |
---|
[228] | 154 | owner = validation.testOwner(user, fields.getfirst('owner')) |
---|
| 155 | |
---|
[134] | 156 | memory = fields.getfirst('memory') |
---|
[266] | 157 | memory = validation.validMemory(owner, memory, on=True) |
---|
[438] | 158 | |
---|
[243] | 159 | disk_size = fields.getfirst('disk') |
---|
[266] | 160 | disk_size = validation.validDisk(owner, disk_size) |
---|
[134] | 161 | |
---|
[113] | 162 | vm_type = fields.getfirst('vmtype') |
---|
[437] | 163 | vm_type = validation.validVmType(vm_type) |
---|
[113] | 164 | |
---|
| 165 | cdrom = fields.getfirst('cdrom') |
---|
| 166 | if cdrom is not None and not CDROM.get(cdrom): |
---|
[205] | 167 | raise CodeError("Invalid cdrom type '%s'" % cdrom) |
---|
[340] | 168 | |
---|
| 169 | clone_from = fields.getfirst('clone_from') |
---|
| 170 | if clone_from and clone_from != 'ice3': |
---|
| 171 | raise CodeError("Invalid clone image '%s'" % clone_from) |
---|
[438] | 172 | |
---|
[243] | 173 | return dict(contact=user, name=name, memory=memory, disk_size=disk_size, |
---|
[437] | 174 | owner=owner, machine_type=vm_type, cdrom=cdrom, clone_from=clone_from) |
---|
[113] | 175 | |
---|
[205] | 176 | def create(user, fields): |
---|
| 177 | """Handler for create requests.""" |
---|
| 178 | try: |
---|
| 179 | parsed_fields = parseCreate(user, fields) |
---|
[209] | 180 | machine = controls.createVm(**parsed_fields) |
---|
[205] | 181 | except InvalidInput, err: |
---|
[207] | 182 | pass |
---|
[205] | 183 | else: |
---|
| 184 | err = None |
---|
| 185 | g.clear() #Changed global state |
---|
| 186 | d = getListDict(user) |
---|
| 187 | d['err'] = err |
---|
| 188 | if err: |
---|
| 189 | for field in fields.keys(): |
---|
| 190 | setattr(d['defaults'], field, fields.getfirst(field)) |
---|
| 191 | else: |
---|
| 192 | d['new_machine'] = parsed_fields['name'] |
---|
[235] | 193 | return templates.list(searchList=[d]) |
---|
[205] | 194 | |
---|
| 195 | |
---|
| 196 | def getListDict(user): |
---|
[438] | 197 | """Gets the list of local variables used by list.tmpl.""" |
---|
[261] | 198 | machines = g.machines |
---|
[235] | 199 | checkpoint.checkpoint('Got my machines') |
---|
[133] | 200 | on = {} |
---|
[119] | 201 | has_vnc = {} |
---|
[152] | 202 | on = g.uptimes |
---|
[235] | 203 | checkpoint.checkpoint('Got uptimes') |
---|
[136] | 204 | for m in machines: |
---|
[205] | 205 | m.uptime = g.uptimes.get(m) |
---|
[144] | 206 | if not on[m]: |
---|
| 207 | has_vnc[m] = 'Off' |
---|
[138] | 208 | elif m.type.hvm: |
---|
[144] | 209 | has_vnc[m] = True |
---|
[136] | 210 | else: |
---|
[144] | 211 | has_vnc[m] = "ParaVM"+helppopup("paravm_console") |
---|
[209] | 212 | max_memory = validation.maxMemory(user) |
---|
| 213 | max_disk = validation.maxDisk(user) |
---|
[235] | 214 | checkpoint.checkpoint('Got max mem/disk') |
---|
[205] | 215 | defaults = Defaults(max_memory=max_memory, |
---|
| 216 | max_disk=max_disk, |
---|
[228] | 217 | owner=user, |
---|
[205] | 218 | cdrom='gutsy-i386') |
---|
[235] | 219 | checkpoint.checkpoint('Got defaults') |
---|
[424] | 220 | def sortkey(machine): |
---|
| 221 | return (machine.owner != user, machine.owner, machine.name) |
---|
| 222 | machines = sorted(machines, key=sortkey) |
---|
[113] | 223 | d = dict(user=user, |
---|
[209] | 224 | cant_add_vm=validation.cantAddVm(user), |
---|
[205] | 225 | max_memory=max_memory, |
---|
[144] | 226 | max_disk=max_disk, |
---|
[205] | 227 | defaults=defaults, |
---|
[113] | 228 | machines=machines, |
---|
[119] | 229 | has_vnc=has_vnc, |
---|
[443] | 230 | uptimes=g.uptimes) |
---|
[205] | 231 | return d |
---|
[113] | 232 | |
---|
[205] | 233 | def listVms(user, fields): |
---|
| 234 | """Handler for list requests.""" |
---|
[235] | 235 | checkpoint.checkpoint('Getting list dict') |
---|
[205] | 236 | d = getListDict(user) |
---|
[235] | 237 | checkpoint.checkpoint('Got list dict') |
---|
| 238 | return templates.list(searchList=[d]) |
---|
[438] | 239 | |
---|
[113] | 240 | def vnc(user, fields): |
---|
[119] | 241 | """VNC applet page. |
---|
| 242 | |
---|
| 243 | Note that due to same-domain restrictions, the applet connects to |
---|
| 244 | the webserver, which needs to forward those requests to the xen |
---|
| 245 | server. The Xen server runs another proxy that (1) authenticates |
---|
| 246 | and (2) finds the correct port for the VM. |
---|
| 247 | |
---|
| 248 | You might want iptables like: |
---|
| 249 | |
---|
[205] | 250 | -t nat -A PREROUTING -s ! 18.181.0.60 -i eth1 -p tcp -m tcp \ |
---|
[438] | 251 | --dport 10003 -j DNAT --to-destination 18.181.0.60:10003 |
---|
[205] | 252 | -t nat -A POSTROUTING -d 18.181.0.60 -o eth1 -p tcp -m tcp \ |
---|
[438] | 253 | --dport 10003 -j SNAT --to-source 18.187.7.142 |
---|
[205] | 254 | -A FORWARD -d 18.181.0.60 -i eth1 -o eth1 -p tcp -m tcp \ |
---|
| 255 | --dport 10003 -j ACCEPT |
---|
[145] | 256 | |
---|
| 257 | Remember to enable iptables! |
---|
| 258 | echo 1 > /proc/sys/net/ipv4/ip_forward |
---|
[119] | 259 | """ |
---|
[209] | 260 | machine = validation.testMachineId(user, fields.getfirst('machine_id')) |
---|
[438] | 261 | |
---|
[118] | 262 | TOKEN_KEY = "0M6W0U1IXexThi5idy8mnkqPKEq1LtEnlK/pZSn0cDrN" |
---|
| 263 | |
---|
| 264 | data = {} |
---|
[228] | 265 | data["user"] = user |
---|
[205] | 266 | data["machine"] = machine.name |
---|
| 267 | data["expires"] = time.time()+(5*60) |
---|
| 268 | pickled_data = cPickle.dumps(data) |
---|
[118] | 269 | m = hmac.new(TOKEN_KEY, digestmod=sha) |
---|
[205] | 270 | m.update(pickled_data) |
---|
| 271 | token = {'data': pickled_data, 'digest': m.digest()} |
---|
[118] | 272 | token = cPickle.dumps(token) |
---|
| 273 | token = base64.urlsafe_b64encode(token) |
---|
[438] | 274 | |
---|
[209] | 275 | status = controls.statusInfo(machine) |
---|
[152] | 276 | has_vnc = hasVnc(status) |
---|
[438] | 277 | |
---|
[113] | 278 | d = dict(user=user, |
---|
[152] | 279 | on=status, |
---|
| 280 | has_vnc=has_vnc, |
---|
[113] | 281 | machine=machine, |
---|
[119] | 282 | hostname=os.environ.get('SERVER_NAME', 'localhost'), |
---|
[113] | 283 | authtoken=token) |
---|
[235] | 284 | return templates.vnc(searchList=[d]) |
---|
[113] | 285 | |
---|
[252] | 286 | def getHostname(nic): |
---|
[438] | 287 | """Find the hostname associated with a NIC. |
---|
| 288 | |
---|
| 289 | XXX this should be merged with the similar logic in DNS and DHCP. |
---|
| 290 | """ |
---|
[252] | 291 | if nic.hostname and '.' in nic.hostname: |
---|
| 292 | return nic.hostname |
---|
| 293 | elif nic.machine: |
---|
| 294 | return nic.machine.name + '.servers.csail.mit.edu' |
---|
| 295 | else: |
---|
| 296 | return None |
---|
| 297 | |
---|
| 298 | |
---|
[133] | 299 | def getNicInfo(data_dict, machine): |
---|
[145] | 300 | """Helper function for info, get data on nics for a machine. |
---|
| 301 | |
---|
| 302 | Modifies data_dict to include the relevant data, and returns a list |
---|
| 303 | of (key, name) pairs to display "name: data_dict[key]" to the user. |
---|
| 304 | """ |
---|
[133] | 305 | data_dict['num_nics'] = len(machine.nics) |
---|
[227] | 306 | nic_fields_template = [('nic%s_hostname', 'NIC %s Hostname'), |
---|
[133] | 307 | ('nic%s_mac', 'NIC %s MAC Addr'), |
---|
| 308 | ('nic%s_ip', 'NIC %s IP'), |
---|
| 309 | ] |
---|
| 310 | nic_fields = [] |
---|
| 311 | for i in range(len(machine.nics)): |
---|
| 312 | nic_fields.extend([(x % i, y % i) for x, y in nic_fields_template]) |
---|
[227] | 313 | if not i: |
---|
[252] | 314 | data_dict['nic%s_hostname' % i] = getHostname(machine.nics[i]) |
---|
[133] | 315 | data_dict['nic%s_mac' % i] = machine.nics[i].mac_addr |
---|
| 316 | data_dict['nic%s_ip' % i] = machine.nics[i].ip |
---|
| 317 | if len(machine.nics) == 1: |
---|
| 318 | nic_fields = [(x, y.replace('NIC 0 ', '')) for x, y in nic_fields] |
---|
| 319 | return nic_fields |
---|
| 320 | |
---|
| 321 | def getDiskInfo(data_dict, machine): |
---|
[145] | 322 | """Helper function for info, get data on disks for a machine. |
---|
| 323 | |
---|
| 324 | Modifies data_dict to include the relevant data, and returns a list |
---|
| 325 | of (key, name) pairs to display "name: data_dict[key]" to the user. |
---|
| 326 | """ |
---|
[133] | 327 | data_dict['num_disks'] = len(machine.disks) |
---|
| 328 | disk_fields_template = [('%s_size', '%s size')] |
---|
| 329 | disk_fields = [] |
---|
| 330 | for disk in machine.disks: |
---|
| 331 | name = disk.guest_device_name |
---|
[438] | 332 | disk_fields.extend([(x % name, y % name) for x, y in |
---|
[205] | 333 | disk_fields_template]) |
---|
[211] | 334 | data_dict['%s_size' % name] = "%0.1f GiB" % (disk.size / 1024.) |
---|
[133] | 335 | return disk_fields |
---|
| 336 | |
---|
[205] | 337 | def command(user, fields): |
---|
| 338 | """Handler for running commands like boot and delete on a VM.""" |
---|
[207] | 339 | back = fields.getfirst('back') |
---|
[205] | 340 | try: |
---|
[209] | 341 | d = controls.commandResult(user, fields) |
---|
[207] | 342 | if d['command'] == 'Delete VM': |
---|
| 343 | back = 'list' |
---|
[205] | 344 | except InvalidInput, err: |
---|
[207] | 345 | if not back: |
---|
[205] | 346 | raise |
---|
[261] | 347 | #print >> sys.stderr, err |
---|
| 348 | result = err |
---|
[205] | 349 | else: |
---|
| 350 | result = 'Success!' |
---|
[207] | 351 | if not back: |
---|
[235] | 352 | return templates.command(searchList=[d]) |
---|
[207] | 353 | if back == 'list': |
---|
[205] | 354 | g.clear() #Changed global state |
---|
| 355 | d = getListDict(user) |
---|
[207] | 356 | d['result'] = result |
---|
[235] | 357 | return templates.list(searchList=[d]) |
---|
[207] | 358 | elif back == 'info': |
---|
[209] | 359 | machine = validation.testMachineId(user, fields.getfirst('machine_id')) |
---|
[407] | 360 | return ({'Status': '302', |
---|
| 361 | 'Location': '/info?machine_id=%d' % machine.machine_id}, |
---|
| 362 | "You shouldn't see this message.") |
---|
[205] | 363 | else: |
---|
[261] | 364 | raise InvalidInput('back', back, 'Not a known back page.') |
---|
[205] | 365 | |
---|
| 366 | def modifyDict(user, fields): |
---|
[438] | 367 | """Modify a machine as specified by CGI arguments. |
---|
| 368 | |
---|
| 369 | Return a list of local variables for modify.tmpl. |
---|
| 370 | """ |
---|
[177] | 371 | olddisk = {} |
---|
[161] | 372 | transaction = ctx.current.create_transaction() |
---|
| 373 | try: |
---|
[209] | 374 | machine = validation.testMachineId(user, fields.getfirst('machine_id')) |
---|
| 375 | owner = validation.testOwner(user, fields.getfirst('owner'), machine) |
---|
| 376 | admin = validation.testAdmin(user, fields.getfirst('administrator'), |
---|
| 377 | machine) |
---|
| 378 | contact = validation.testContact(user, fields.getfirst('contact'), |
---|
| 379 | machine) |
---|
| 380 | name = validation.testName(user, fields.getfirst('name'), machine) |
---|
[161] | 381 | oldname = machine.name |
---|
[205] | 382 | command = "modify" |
---|
[153] | 383 | |
---|
[161] | 384 | memory = fields.getfirst('memory') |
---|
| 385 | if memory is not None: |
---|
[209] | 386 | memory = validation.validMemory(user, memory, machine, on=False) |
---|
[161] | 387 | machine.memory = memory |
---|
[438] | 388 | |
---|
[440] | 389 | vm_type = validation.validVmType(fields.getfirst('vmtype')) |
---|
| 390 | if vm_type is not None: |
---|
| 391 | machine.type = vm_type |
---|
| 392 | |
---|
[209] | 393 | disksize = validation.testDisk(user, fields.getfirst('disk')) |
---|
[161] | 394 | if disksize is not None: |
---|
[209] | 395 | disksize = validation.validDisk(user, disksize, machine) |
---|
[177] | 396 | disk = machine.disks[0] |
---|
| 397 | if disk.size != disksize: |
---|
| 398 | olddisk[disk.guest_device_name] = disksize |
---|
| 399 | disk.size = disksize |
---|
| 400 | ctx.current.save(disk) |
---|
[438] | 401 | |
---|
[446] | 402 | update_acl = False |
---|
| 403 | if owner is not None and owner != machine.owner: |
---|
[161] | 404 | machine.owner = owner |
---|
[446] | 405 | update_acl = True |
---|
[187] | 406 | if name is not None: |
---|
[161] | 407 | machine.name = name |
---|
[446] | 408 | if admin is not None and admin != machine.administrator: |
---|
[187] | 409 | machine.administrator = admin |
---|
[446] | 410 | update_acl = True |
---|
[187] | 411 | if contact is not None: |
---|
| 412 | machine.contact = contact |
---|
[438] | 413 | |
---|
[161] | 414 | ctx.current.save(machine) |
---|
[446] | 415 | if update_acl: |
---|
| 416 | cache_acls.refreshMachine(machine) |
---|
[161] | 417 | transaction.commit() |
---|
| 418 | except: |
---|
| 419 | transaction.rollback() |
---|
[163] | 420 | raise |
---|
[177] | 421 | for diskname in olddisk: |
---|
[209] | 422 | controls.resizeDisk(oldname, diskname, str(olddisk[diskname])) |
---|
[187] | 423 | if name is not None: |
---|
[209] | 424 | controls.renameMachine(machine, oldname, name) |
---|
[205] | 425 | return dict(user=user, |
---|
| 426 | command=command, |
---|
| 427 | machine=machine) |
---|
[438] | 428 | |
---|
[205] | 429 | def modify(user, fields): |
---|
| 430 | """Handler for modifying attributes of a machine.""" |
---|
| 431 | try: |
---|
| 432 | modify_dict = modifyDict(user, fields) |
---|
| 433 | except InvalidInput, err: |
---|
[207] | 434 | result = None |
---|
[209] | 435 | machine = validation.testMachineId(user, fields.getfirst('machine_id')) |
---|
[205] | 436 | else: |
---|
| 437 | machine = modify_dict['machine'] |
---|
[209] | 438 | result = 'Success!' |
---|
[205] | 439 | err = None |
---|
| 440 | info_dict = infoDict(user, machine) |
---|
| 441 | info_dict['err'] = err |
---|
| 442 | if err: |
---|
| 443 | for field in fields.keys(): |
---|
| 444 | setattr(info_dict['defaults'], field, fields.getfirst(field)) |
---|
[207] | 445 | info_dict['result'] = result |
---|
[235] | 446 | return templates.info(searchList=[info_dict]) |
---|
[161] | 447 | |
---|
[438] | 448 | |
---|
[205] | 449 | def helpHandler(user, fields): |
---|
[145] | 450 | """Handler for help messages.""" |
---|
[139] | 451 | simple = fields.getfirst('simple') |
---|
| 452 | subjects = fields.getlist('subject') |
---|
[438] | 453 | |
---|
[205] | 454 | help_mapping = dict(paravm_console=""" |
---|
[432] | 455 | ParaVM machines do not support local console access over VNC. To |
---|
| 456 | access the serial console of these machines, you can SSH with Kerberos |
---|
| 457 | to sipb-xen-console.mit.edu, using the name of the machine as your |
---|
| 458 | username.""", |
---|
[205] | 459 | hvm_paravm=""" |
---|
[139] | 460 | HVM machines use the virtualization features of the processor, while |
---|
| 461 | ParaVM machines use Xen's emulation of virtualization features. You |
---|
| 462 | want an HVM virtualized machine.""", |
---|
[205] | 463 | cpu_weight=""" |
---|
| 464 | Don't ask us! We're as mystified as you are.""", |
---|
| 465 | owner=""" |
---|
| 466 | The owner field is used to determine <a |
---|
| 467 | href="help?subject=quotas">quotas</a>. It must be the name of a |
---|
| 468 | locker that you are an AFS administrator of. In particular, you or an |
---|
| 469 | AFS group you are a member of must have AFS rlidwka bits on the |
---|
[432] | 470 | locker. You can check who administers the LOCKER locker using the |
---|
| 471 | commands 'attach LOCKER; fs la /mit/LOCKER' on Athena.) See also <a |
---|
[205] | 472 | href="help?subject=administrator">administrator</a>.""", |
---|
| 473 | administrator=""" |
---|
| 474 | The administrator field determines who can access the console and |
---|
| 475 | power on and off the machine. This can be either a user or a moira |
---|
| 476 | group.""", |
---|
| 477 | quotas=""" |
---|
[408] | 478 | Quotas are determined on a per-locker basis. Each locker may have a |
---|
[205] | 479 | maximum of 512 megabytes of active ram, 50 gigabytes of disk, and 4 |
---|
[309] | 480 | active machines.""", |
---|
| 481 | console=""" |
---|
| 482 | <strong>Framebuffer:</strong> At a Linux boot prompt in your VM, try |
---|
| 483 | setting <tt>fb=false</tt> to disable the framebuffer. If you don't, |
---|
| 484 | your machine will run just fine, but the applet's display of the |
---|
| 485 | console will suffer artifacts. |
---|
| 486 | """ |
---|
[187] | 487 | ) |
---|
[438] | 488 | |
---|
[187] | 489 | if not subjects: |
---|
[205] | 490 | subjects = sorted(help_mapping.keys()) |
---|
[438] | 491 | |
---|
[139] | 492 | d = dict(user=user, |
---|
| 493 | simple=simple, |
---|
| 494 | subjects=subjects, |
---|
[205] | 495 | mapping=help_mapping) |
---|
[438] | 496 | |
---|
[235] | 497 | return templates.help(searchList=[d]) |
---|
[133] | 498 | |
---|
[438] | 499 | |
---|
[205] | 500 | def badOperation(u, e): |
---|
[438] | 501 | """Function called when accessing an unknown URI.""" |
---|
[205] | 502 | raise CodeError("Unknown operation") |
---|
| 503 | |
---|
| 504 | def infoDict(user, machine): |
---|
[438] | 505 | """Get the variables used by info.tmpl.""" |
---|
[209] | 506 | status = controls.statusInfo(machine) |
---|
[235] | 507 | checkpoint.checkpoint('Getting status info') |
---|
[133] | 508 | has_vnc = hasVnc(status) |
---|
| 509 | if status is None: |
---|
| 510 | main_status = dict(name=machine.name, |
---|
| 511 | memory=str(machine.memory)) |
---|
[205] | 512 | uptime = None |
---|
| 513 | cputime = None |
---|
[133] | 514 | else: |
---|
| 515 | main_status = dict(status[1:]) |
---|
[167] | 516 | start_time = float(main_status.get('start_time', 0)) |
---|
| 517 | uptime = datetime.timedelta(seconds=int(time.time()-start_time)) |
---|
| 518 | cpu_time_float = float(main_status.get('cpu_time', 0)) |
---|
| 519 | cputime = datetime.timedelta(seconds=int(cpu_time_float)) |
---|
[235] | 520 | checkpoint.checkpoint('Status') |
---|
[133] | 521 | display_fields = """name uptime memory state cpu_weight on_reboot |
---|
| 522 | on_poweroff on_crash on_xend_start on_xend_stop bootloader""".split() |
---|
| 523 | display_fields = [('name', 'Name'), |
---|
| 524 | ('owner', 'Owner'), |
---|
[187] | 525 | ('administrator', 'Administrator'), |
---|
[133] | 526 | ('contact', 'Contact'), |
---|
[136] | 527 | ('type', 'Type'), |
---|
[133] | 528 | 'NIC_INFO', |
---|
| 529 | ('uptime', 'uptime'), |
---|
| 530 | ('cputime', 'CPU usage'), |
---|
| 531 | ('memory', 'RAM'), |
---|
| 532 | 'DISK_INFO', |
---|
| 533 | ('state', 'state (xen format)'), |
---|
[139] | 534 | ('cpu_weight', 'CPU weight'+helppopup('cpu_weight')), |
---|
[133] | 535 | ('on_reboot', 'Action on VM reboot'), |
---|
| 536 | ('on_poweroff', 'Action on VM poweroff'), |
---|
| 537 | ('on_crash', 'Action on VM crash'), |
---|
| 538 | ('on_xend_start', 'Action on Xen start'), |
---|
| 539 | ('on_xend_stop', 'Action on Xen stop'), |
---|
| 540 | ('bootloader', 'Bootloader options'), |
---|
| 541 | ] |
---|
| 542 | fields = [] |
---|
| 543 | machine_info = {} |
---|
[147] | 544 | machine_info['name'] = machine.name |
---|
[136] | 545 | machine_info['type'] = machine.type.hvm and 'HVM' or 'ParaVM' |
---|
[133] | 546 | machine_info['owner'] = machine.owner |
---|
[187] | 547 | machine_info['administrator'] = machine.administrator |
---|
[133] | 548 | machine_info['contact'] = machine.contact |
---|
| 549 | |
---|
| 550 | nic_fields = getNicInfo(machine_info, machine) |
---|
| 551 | nic_point = display_fields.index('NIC_INFO') |
---|
[438] | 552 | display_fields = (display_fields[:nic_point] + nic_fields + |
---|
[205] | 553 | display_fields[nic_point+1:]) |
---|
[133] | 554 | |
---|
| 555 | disk_fields = getDiskInfo(machine_info, machine) |
---|
| 556 | disk_point = display_fields.index('DISK_INFO') |
---|
[438] | 557 | display_fields = (display_fields[:disk_point] + disk_fields + |
---|
[205] | 558 | display_fields[disk_point+1:]) |
---|
[438] | 559 | |
---|
[211] | 560 | main_status['memory'] += ' MiB' |
---|
[133] | 561 | for field, disp in display_fields: |
---|
[167] | 562 | if field in ('uptime', 'cputime') and locals()[field] is not None: |
---|
[133] | 563 | fields.append((disp, locals()[field])) |
---|
[147] | 564 | elif field in machine_info: |
---|
| 565 | fields.append((disp, machine_info[field])) |
---|
[133] | 566 | elif field in main_status: |
---|
| 567 | fields.append((disp, main_status[field])) |
---|
| 568 | else: |
---|
| 569 | pass |
---|
| 570 | #fields.append((disp, None)) |
---|
[235] | 571 | |
---|
| 572 | checkpoint.checkpoint('Got fields') |
---|
| 573 | |
---|
| 574 | |
---|
| 575 | max_mem = validation.maxMemory(user, machine, False) |
---|
| 576 | checkpoint.checkpoint('Got mem') |
---|
[209] | 577 | max_disk = validation.maxDisk(user, machine) |
---|
| 578 | defaults = Defaults() |
---|
[440] | 579 | for name in 'machine_id name administrator owner memory contact type'.split(): |
---|
[205] | 580 | setattr(defaults, name, getattr(machine, name)) |
---|
| 581 | defaults.disk = "%0.2f" % (machine.disks[0].size/1024.) |
---|
[235] | 582 | checkpoint.checkpoint('Got defaults') |
---|
[113] | 583 | d = dict(user=user, |
---|
[133] | 584 | on=status is not None, |
---|
| 585 | machine=machine, |
---|
[205] | 586 | defaults=defaults, |
---|
[133] | 587 | has_vnc=has_vnc, |
---|
| 588 | uptime=str(uptime), |
---|
| 589 | ram=machine.memory, |
---|
[144] | 590 | max_mem=max_mem, |
---|
| 591 | max_disk=max_disk, |
---|
[166] | 592 | owner_help=helppopup("owner"), |
---|
[133] | 593 | fields = fields) |
---|
[205] | 594 | return d |
---|
[113] | 595 | |
---|
[205] | 596 | def info(user, fields): |
---|
| 597 | """Handler for info on a single VM.""" |
---|
[209] | 598 | machine = validation.testMachineId(user, fields.getfirst('machine_id')) |
---|
[205] | 599 | d = infoDict(user, machine) |
---|
[235] | 600 | checkpoint.checkpoint('Got infodict') |
---|
| 601 | return templates.info(searchList=[d]) |
---|
[205] | 602 | |
---|
[113] | 603 | mapping = dict(list=listVms, |
---|
| 604 | vnc=vnc, |
---|
[133] | 605 | command=command, |
---|
| 606 | modify=modify, |
---|
[113] | 607 | info=info, |
---|
[139] | 608 | create=create, |
---|
[205] | 609 | help=helpHandler) |
---|
[113] | 610 | |
---|
[205] | 611 | def printHeaders(headers): |
---|
[438] | 612 | """Print a dictionary as HTTP headers.""" |
---|
[205] | 613 | for key, value in headers.iteritems(): |
---|
| 614 | print '%s: %s' % (key, value) |
---|
| 615 | print |
---|
| 616 | |
---|
| 617 | |
---|
| 618 | def getUser(): |
---|
| 619 | """Return the current user based on the SSL environment variables""" |
---|
[254] | 620 | username = os.environ['SSL_CLIENT_S_DN_Email'].split("@")[0] |
---|
| 621 | return username |
---|
[205] | 622 | |
---|
[438] | 623 | def main(operation, user, fields): |
---|
[235] | 624 | start_time = time.time() |
---|
[153] | 625 | fun = mapping.get(operation, badOperation) |
---|
[205] | 626 | |
---|
| 627 | if fun not in (helpHandler, ): |
---|
| 628 | connect('postgres://sipb-xen@sipb-xen-dev.mit.edu/sipb_xen') |
---|
[119] | 629 | try: |
---|
[235] | 630 | checkpoint.checkpoint('Before') |
---|
[153] | 631 | output = fun(u, fields) |
---|
[235] | 632 | checkpoint.checkpoint('After') |
---|
[205] | 633 | |
---|
[209] | 634 | headers = dict(DEFAULT_HEADERS) |
---|
[205] | 635 | if isinstance(output, tuple): |
---|
| 636 | new_headers, output = output |
---|
| 637 | headers.update(new_headers) |
---|
| 638 | e = revertStandardError() |
---|
[153] | 639 | if e: |
---|
[205] | 640 | output.addError(e) |
---|
| 641 | printHeaders(headers) |
---|
[235] | 642 | output_string = str(output) |
---|
| 643 | checkpoint.checkpoint('output as a string') |
---|
| 644 | print output_string |
---|
[421] | 645 | print '<!-- <pre>%s</pre> -->' % checkpoint |
---|
[205] | 646 | except Exception, err: |
---|
| 647 | if not fields.has_key('js'): |
---|
| 648 | if isinstance(err, CodeError): |
---|
| 649 | print 'Content-Type: text/html\n' |
---|
| 650 | e = revertStandardError() |
---|
| 651 | print error(operation, u, fields, err, e) |
---|
| 652 | sys.exit(1) |
---|
| 653 | if isinstance(err, InvalidInput): |
---|
| 654 | print 'Content-Type: text/html\n' |
---|
| 655 | e = revertStandardError() |
---|
| 656 | print invalidInput(operation, u, fields, err, e) |
---|
| 657 | sys.exit(1) |
---|
[153] | 658 | print 'Content-Type: text/plain\n' |
---|
[205] | 659 | print 'Uh-oh! We experienced an error.' |
---|
| 660 | print 'Please email sipb-xen@mit.edu with the contents of this page.' |
---|
| 661 | print '----' |
---|
| 662 | e = revertStandardError() |
---|
[153] | 663 | print e |
---|
| 664 | print '----' |
---|
| 665 | raise |
---|
[209] | 666 | |
---|
| 667 | if __name__ == '__main__': |
---|
| 668 | fields = cgi.FieldStorage() |
---|
| 669 | u = getUser() |
---|
| 670 | g.user = u |
---|
| 671 | operation = os.environ.get('PATH_INFO', '') |
---|
| 672 | if not operation: |
---|
| 673 | print "Status: 301 Moved Permanently" |
---|
| 674 | print 'Location: ' + os.environ['SCRIPT_NAME']+'/\n' |
---|
| 675 | sys.exit(0) |
---|
| 676 | |
---|
| 677 | if operation.startswith('/'): |
---|
| 678 | operation = operation[1:] |
---|
| 679 | if not operation: |
---|
| 680 | operation = 'list' |
---|
| 681 | |
---|
[248] | 682 | if os.getenv("SIPB_XEN_PROFILE"): |
---|
| 683 | import profile |
---|
| 684 | profile.run('main(operation, u, fields)', 'log-'+operation) |
---|
| 685 | else: |
---|
| 686 | main(operation, u, fields) |
---|