[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 |
---|
[770] | 9 | import random |
---|
[205] | 10 | import sha |
---|
| 11 | import simplejson |
---|
| 12 | import sys |
---|
[118] | 13 | import time |
---|
[447] | 14 | import urllib |
---|
[2186] | 15 | import socket |
---|
[2663] | 16 | import cherrypy |
---|
[205] | 17 | from StringIO import StringIO |
---|
| 18 | def revertStandardError(): |
---|
| 19 | """Move stderr to stdout, and return the contents of the old stderr.""" |
---|
| 20 | errio = sys.stderr |
---|
| 21 | if not isinstance(errio, StringIO): |
---|
[599] | 22 | return '' |
---|
[205] | 23 | sys.stderr = sys.stdout |
---|
| 24 | errio.seek(0) |
---|
| 25 | return errio.read() |
---|
| 26 | |
---|
| 27 | def printError(): |
---|
| 28 | """Revert stderr to stdout, and print the contents of stderr""" |
---|
| 29 | if isinstance(sys.stderr, StringIO): |
---|
| 30 | print revertStandardError() |
---|
| 31 | |
---|
| 32 | if __name__ == '__main__': |
---|
| 33 | import atexit |
---|
| 34 | atexit.register(printError) |
---|
| 35 | |
---|
[235] | 36 | import templates |
---|
[113] | 37 | from Cheetah.Template import Template |
---|
[209] | 38 | import validation |
---|
[446] | 39 | import cache_acls |
---|
[1612] | 40 | from webcommon import State |
---|
[209] | 41 | import controls |
---|
[632] | 42 | from getafsgroups import getAfsGroupMembers |
---|
[865] | 43 | from invirt import database |
---|
[1001] | 44 | from invirt.database import Machine, CDROM, session, connect, MachineAccess, Type, Autoinstall |
---|
[863] | 45 | from invirt.config import structs as config |
---|
[1612] | 46 | from invirt.common import InvalidInput, CodeError |
---|
[113] | 47 | |
---|
[2664] | 48 | from view import View |
---|
| 49 | |
---|
| 50 | class InvirtWeb(View): |
---|
| 51 | def __init__(self): |
---|
| 52 | super(self.__class__,self).__init__() |
---|
| 53 | connect() |
---|
[2665] | 54 | self._cp_config['tools.require_login.on'] = True |
---|
[2674] | 55 | self._cp_config['tools.mako.imports'] = ['from invirt.config import structs as config', |
---|
| 56 | 'from invirt import database'] |
---|
[2664] | 57 | |
---|
[2674] | 58 | |
---|
[2664] | 59 | @cherrypy.expose |
---|
[2665] | 60 | @cherrypy.tools.mako(filename="/list.mako") |
---|
[2669] | 61 | def list(self): |
---|
[2665] | 62 | """Handler for list requests.""" |
---|
| 63 | checkpoint.checkpoint('Getting list dict') |
---|
[2669] | 64 | d = getListDict(cherrypy.request.login, cherrypy.request.state) |
---|
[2665] | 65 | checkpoint.checkpoint('Got list dict') |
---|
[2668] | 66 | return d |
---|
[2665] | 67 | index=list |
---|
| 68 | |
---|
| 69 | @cherrypy.expose |
---|
| 70 | @cherrypy.tools.mako(filename="/helloworld.mako") |
---|
[2675] | 71 | def helloworld(self, **kwargs): |
---|
| 72 | return {'request': cherrypy.request, 'kwargs': kwargs} |
---|
[2665] | 73 | helloworld._cp_config['tools.require_login.on'] = False |
---|
[2664] | 74 | |
---|
[632] | 75 | def pathSplit(path): |
---|
| 76 | if path.startswith('/'): |
---|
| 77 | path = path[1:] |
---|
| 78 | i = path.find('/') |
---|
| 79 | if i == -1: |
---|
| 80 | i = len(path) |
---|
| 81 | return path[:i], path[i:] |
---|
| 82 | |
---|
[235] | 83 | class Checkpoint: |
---|
| 84 | def __init__(self): |
---|
| 85 | self.start_time = time.time() |
---|
| 86 | self.checkpoints = [] |
---|
| 87 | |
---|
| 88 | def checkpoint(self, s): |
---|
| 89 | self.checkpoints.append((s, time.time())) |
---|
| 90 | |
---|
| 91 | def __str__(self): |
---|
| 92 | return ('Timing info:\n%s\n' % |
---|
| 93 | '\n'.join(['%s: %s' % (d, t - self.start_time) for |
---|
| 94 | (d, t) in self.checkpoints])) |
---|
| 95 | |
---|
| 96 | checkpoint = Checkpoint() |
---|
| 97 | |
---|
[205] | 98 | def makeErrorPre(old, addition): |
---|
| 99 | if addition is None: |
---|
| 100 | return |
---|
| 101 | if old: |
---|
| 102 | return old[:-6] + '\n----\n' + str(addition) + '</pre>' |
---|
| 103 | else: |
---|
| 104 | return '<p>STDERR:</p><pre>' + str(addition) + '</pre>' |
---|
[139] | 105 | |
---|
[864] | 106 | Template.database = database |
---|
[866] | 107 | Template.config = config |
---|
[205] | 108 | Template.err = None |
---|
[139] | 109 | |
---|
[205] | 110 | class JsonDict: |
---|
| 111 | """Class to store a dictionary that will be converted to JSON""" |
---|
| 112 | def __init__(self, **kws): |
---|
| 113 | self.data = kws |
---|
| 114 | if 'err' in kws: |
---|
| 115 | err = kws['err'] |
---|
| 116 | del kws['err'] |
---|
| 117 | self.addError(err) |
---|
[139] | 118 | |
---|
[205] | 119 | def __str__(self): |
---|
| 120 | return simplejson.dumps(self.data) |
---|
| 121 | |
---|
| 122 | def addError(self, text): |
---|
| 123 | """Add stderr text to be displayed on the website.""" |
---|
| 124 | self.data['err'] = \ |
---|
| 125 | makeErrorPre(self.data.get('err'), text) |
---|
| 126 | |
---|
| 127 | class Defaults: |
---|
| 128 | """Class to store default values for fields.""" |
---|
| 129 | memory = 256 |
---|
| 130 | disk = 4.0 |
---|
| 131 | cdrom = '' |
---|
[443] | 132 | autoinstall = '' |
---|
[205] | 133 | name = '' |
---|
[609] | 134 | description = '' |
---|
[515] | 135 | type = 'linux-hvm' |
---|
| 136 | |
---|
[205] | 137 | def __init__(self, max_memory=None, max_disk=None, **kws): |
---|
| 138 | if max_memory is not None: |
---|
| 139 | self.memory = min(self.memory, max_memory) |
---|
| 140 | if max_disk is not None: |
---|
[1964] | 141 | self.disk = min(self.disk, max_disk) |
---|
[205] | 142 | for key in kws: |
---|
| 143 | setattr(self, key, kws[key]) |
---|
| 144 | |
---|
| 145 | |
---|
| 146 | |
---|
[209] | 147 | DEFAULT_HEADERS = {'Content-Type': 'text/html'} |
---|
[205] | 148 | |
---|
[572] | 149 | def invalidInput(op, username, fields, err, emsg): |
---|
[153] | 150 | """Print an error page when an InvalidInput exception occurs""" |
---|
[572] | 151 | d = dict(op=op, user=username, err_field=err.err_field, |
---|
[153] | 152 | err_value=str(err.err_value), stderr=emsg, |
---|
| 153 | errorMessage=str(err)) |
---|
[235] | 154 | return templates.invalid(searchList=[d]) |
---|
[153] | 155 | |
---|
[119] | 156 | def hasVnc(status): |
---|
[133] | 157 | """Does the machine with a given status list support VNC?""" |
---|
[119] | 158 | if status is None: |
---|
| 159 | return False |
---|
| 160 | for l in status: |
---|
| 161 | if l[0] == 'device' and l[1][0] == 'vfb': |
---|
| 162 | d = dict(l[1][1:]) |
---|
| 163 | return 'location' in d |
---|
| 164 | return False |
---|
| 165 | |
---|
[572] | 166 | def parseCreate(username, state, fields): |
---|
[629] | 167 | kws = dict([(kw, fields.getfirst(kw)) for kw in 'name description owner memory disksize vmtype cdrom autoinstall'.split()]) |
---|
[577] | 168 | validate = validation.Validate(username, state, strict=True, **kws) |
---|
[609] | 169 | return dict(contact=username, name=validate.name, description=validate.description, memory=validate.memory, |
---|
[2189] | 170 | disksize=validate.disksize, owner=validate.owner, machine_type=getattr(validate, 'vmtype', Defaults.type), |
---|
[572] | 171 | cdrom=getattr(validate, 'cdrom', None), |
---|
[629] | 172 | autoinstall=getattr(validate, 'autoinstall', None)) |
---|
[134] | 173 | |
---|
[632] | 174 | def create(username, state, path, fields): |
---|
[205] | 175 | """Handler for create requests.""" |
---|
| 176 | try: |
---|
[572] | 177 | parsed_fields = parseCreate(username, state, fields) |
---|
[577] | 178 | machine = controls.createVm(username, state, **parsed_fields) |
---|
[205] | 179 | except InvalidInput, err: |
---|
[207] | 180 | pass |
---|
[205] | 181 | else: |
---|
| 182 | err = None |
---|
[572] | 183 | state.clear() #Changed global state |
---|
[576] | 184 | d = getListDict(username, state) |
---|
[205] | 185 | d['err'] = err |
---|
| 186 | if err: |
---|
| 187 | for field in fields.keys(): |
---|
| 188 | setattr(d['defaults'], field, fields.getfirst(field)) |
---|
| 189 | else: |
---|
| 190 | d['new_machine'] = parsed_fields['name'] |
---|
[235] | 191 | return templates.list(searchList=[d]) |
---|
[205] | 192 | |
---|
| 193 | |
---|
[572] | 194 | def getListDict(username, state): |
---|
[438] | 195 | """Gets the list of local variables used by list.tmpl.""" |
---|
[535] | 196 | checkpoint.checkpoint('Starting') |
---|
[572] | 197 | machines = state.machines |
---|
[235] | 198 | checkpoint.checkpoint('Got my machines') |
---|
[133] | 199 | on = {} |
---|
[119] | 200 | has_vnc = {} |
---|
[572] | 201 | xmlist = state.xmlist |
---|
[235] | 202 | checkpoint.checkpoint('Got uptimes') |
---|
[572] | 203 | can_clone = 'ice3' not in state.xmlist_raw |
---|
[136] | 204 | for m in machines: |
---|
[535] | 205 | if m not in xmlist: |
---|
[144] | 206 | has_vnc[m] = 'Off' |
---|
[535] | 207 | m.uptime = None |
---|
[136] | 208 | else: |
---|
[535] | 209 | m.uptime = xmlist[m]['uptime'] |
---|
| 210 | if xmlist[m]['console']: |
---|
| 211 | has_vnc[m] = True |
---|
| 212 | elif m.type.hvm: |
---|
| 213 | has_vnc[m] = "WTF?" |
---|
| 214 | else: |
---|
[536] | 215 | has_vnc[m] = "ParaVM"+helppopup("ParaVM Console") |
---|
[572] | 216 | max_memory = validation.maxMemory(username, state) |
---|
| 217 | max_disk = validation.maxDisk(username) |
---|
[235] | 218 | checkpoint.checkpoint('Got max mem/disk') |
---|
[205] | 219 | defaults = Defaults(max_memory=max_memory, |
---|
| 220 | max_disk=max_disk, |
---|
[1739] | 221 | owner=username) |
---|
[235] | 222 | checkpoint.checkpoint('Got defaults') |
---|
[424] | 223 | def sortkey(machine): |
---|
[572] | 224 | return (machine.owner != username, machine.owner, machine.name) |
---|
[424] | 225 | machines = sorted(machines, key=sortkey) |
---|
[572] | 226 | d = dict(user=username, |
---|
| 227 | cant_add_vm=validation.cantAddVm(username, state), |
---|
[205] | 228 | max_memory=max_memory, |
---|
[144] | 229 | max_disk=max_disk, |
---|
[205] | 230 | defaults=defaults, |
---|
[113] | 231 | machines=machines, |
---|
[540] | 232 | has_vnc=has_vnc, |
---|
| 233 | can_clone=can_clone) |
---|
[205] | 234 | return d |
---|
[113] | 235 | |
---|
[632] | 236 | def vnc(username, state, path, fields): |
---|
[119] | 237 | """VNC applet page. |
---|
| 238 | |
---|
| 239 | Note that due to same-domain restrictions, the applet connects to |
---|
| 240 | the webserver, which needs to forward those requests to the xen |
---|
| 241 | server. The Xen server runs another proxy that (1) authenticates |
---|
| 242 | and (2) finds the correct port for the VM. |
---|
| 243 | |
---|
| 244 | You might want iptables like: |
---|
| 245 | |
---|
[205] | 246 | -t nat -A PREROUTING -s ! 18.181.0.60 -i eth1 -p tcp -m tcp \ |
---|
[438] | 247 | --dport 10003 -j DNAT --to-destination 18.181.0.60:10003 |
---|
[205] | 248 | -t nat -A POSTROUTING -d 18.181.0.60 -o eth1 -p tcp -m tcp \ |
---|
[438] | 249 | --dport 10003 -j SNAT --to-source 18.187.7.142 |
---|
[205] | 250 | -A FORWARD -d 18.181.0.60 -i eth1 -o eth1 -p tcp -m tcp \ |
---|
| 251 | --dport 10003 -j ACCEPT |
---|
[145] | 252 | |
---|
| 253 | Remember to enable iptables! |
---|
| 254 | echo 1 > /proc/sys/net/ipv4/ip_forward |
---|
[119] | 255 | """ |
---|
[572] | 256 | machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine |
---|
[438] | 257 | |
---|
[1618] | 258 | token = controls.vnctoken(machine) |
---|
[797] | 259 | host = controls.listHost(machine) |
---|
| 260 | if host: |
---|
[863] | 261 | port = 10003 + [h.hostname for h in config.hosts].index(host) |
---|
[797] | 262 | else: |
---|
| 263 | port = 5900 # dummy |
---|
[438] | 264 | |
---|
[209] | 265 | status = controls.statusInfo(machine) |
---|
[152] | 266 | has_vnc = hasVnc(status) |
---|
[438] | 267 | |
---|
[572] | 268 | d = dict(user=username, |
---|
[152] | 269 | on=status, |
---|
| 270 | has_vnc=has_vnc, |
---|
[113] | 271 | machine=machine, |
---|
[581] | 272 | hostname=state.environ.get('SERVER_NAME', 'localhost'), |
---|
[667] | 273 | port=port, |
---|
[113] | 274 | authtoken=token) |
---|
[235] | 275 | return templates.vnc(searchList=[d]) |
---|
[113] | 276 | |
---|
[252] | 277 | def getHostname(nic): |
---|
[438] | 278 | """Find the hostname associated with a NIC. |
---|
| 279 | |
---|
| 280 | XXX this should be merged with the similar logic in DNS and DHCP. |
---|
| 281 | """ |
---|
[1976] | 282 | if nic.hostname: |
---|
| 283 | hostname = nic.hostname |
---|
[252] | 284 | elif nic.machine: |
---|
[1976] | 285 | hostname = nic.machine.name |
---|
[252] | 286 | else: |
---|
| 287 | return None |
---|
[1976] | 288 | if '.' in hostname: |
---|
| 289 | return hostname |
---|
| 290 | else: |
---|
| 291 | return hostname + '.' + config.dns.domains[0] |
---|
[252] | 292 | |
---|
[133] | 293 | def getNicInfo(data_dict, machine): |
---|
[145] | 294 | """Helper function for info, get data on nics for a machine. |
---|
| 295 | |
---|
| 296 | Modifies data_dict to include the relevant data, and returns a list |
---|
| 297 | of (key, name) pairs to display "name: data_dict[key]" to the user. |
---|
| 298 | """ |
---|
[133] | 299 | data_dict['num_nics'] = len(machine.nics) |
---|
[227] | 300 | nic_fields_template = [('nic%s_hostname', 'NIC %s Hostname'), |
---|
[133] | 301 | ('nic%s_mac', 'NIC %s MAC Addr'), |
---|
| 302 | ('nic%s_ip', 'NIC %s IP'), |
---|
| 303 | ] |
---|
| 304 | nic_fields = [] |
---|
| 305 | for i in range(len(machine.nics)): |
---|
| 306 | nic_fields.extend([(x % i, y % i) for x, y in nic_fields_template]) |
---|
[1976] | 307 | data_dict['nic%s_hostname' % i] = getHostname(machine.nics[i]) |
---|
[133] | 308 | data_dict['nic%s_mac' % i] = machine.nics[i].mac_addr |
---|
| 309 | data_dict['nic%s_ip' % i] = machine.nics[i].ip |
---|
| 310 | if len(machine.nics) == 1: |
---|
| 311 | nic_fields = [(x, y.replace('NIC 0 ', '')) for x, y in nic_fields] |
---|
| 312 | return nic_fields |
---|
| 313 | |
---|
| 314 | def getDiskInfo(data_dict, machine): |
---|
[145] | 315 | """Helper function for info, get data on disks for a machine. |
---|
| 316 | |
---|
| 317 | Modifies data_dict to include the relevant data, and returns a list |
---|
| 318 | of (key, name) pairs to display "name: data_dict[key]" to the user. |
---|
| 319 | """ |
---|
[133] | 320 | data_dict['num_disks'] = len(machine.disks) |
---|
| 321 | disk_fields_template = [('%s_size', '%s size')] |
---|
| 322 | disk_fields = [] |
---|
| 323 | for disk in machine.disks: |
---|
| 324 | name = disk.guest_device_name |
---|
[438] | 325 | disk_fields.extend([(x % name, y % name) for x, y in |
---|
[205] | 326 | disk_fields_template]) |
---|
[211] | 327 | data_dict['%s_size' % name] = "%0.1f GiB" % (disk.size / 1024.) |
---|
[133] | 328 | return disk_fields |
---|
| 329 | |
---|
[632] | 330 | def command(username, state, path, fields): |
---|
[205] | 331 | """Handler for running commands like boot and delete on a VM.""" |
---|
[207] | 332 | back = fields.getfirst('back') |
---|
[205] | 333 | try: |
---|
[572] | 334 | d = controls.commandResult(username, state, fields) |
---|
[207] | 335 | if d['command'] == 'Delete VM': |
---|
| 336 | back = 'list' |
---|
[205] | 337 | except InvalidInput, err: |
---|
[207] | 338 | if not back: |
---|
[205] | 339 | raise |
---|
[572] | 340 | print >> sys.stderr, err |
---|
[261] | 341 | result = err |
---|
[205] | 342 | else: |
---|
| 343 | result = 'Success!' |
---|
[207] | 344 | if not back: |
---|
[235] | 345 | return templates.command(searchList=[d]) |
---|
[207] | 346 | if back == 'list': |
---|
[572] | 347 | state.clear() #Changed global state |
---|
[576] | 348 | d = getListDict(username, state) |
---|
[207] | 349 | d['result'] = result |
---|
[235] | 350 | return templates.list(searchList=[d]) |
---|
[207] | 351 | elif back == 'info': |
---|
[572] | 352 | machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine |
---|
[588] | 353 | return ({'Status': '303 See Other', |
---|
[633] | 354 | 'Location': 'info?machine_id=%d' % machine.machine_id}, |
---|
[407] | 355 | "You shouldn't see this message.") |
---|
[205] | 356 | else: |
---|
[261] | 357 | raise InvalidInput('back', back, 'Not a known back page.') |
---|
[205] | 358 | |
---|
[572] | 359 | def modifyDict(username, state, fields): |
---|
[438] | 360 | """Modify a machine as specified by CGI arguments. |
---|
| 361 | |
---|
| 362 | Return a list of local variables for modify.tmpl. |
---|
| 363 | """ |
---|
[177] | 364 | olddisk = {} |
---|
[1013] | 365 | session.begin() |
---|
[161] | 366 | try: |
---|
[609] | 367 | kws = dict([(kw, fields.getfirst(kw)) for kw in 'machine_id owner admin contact name description memory vmtype disksize'.split()]) |
---|
[572] | 368 | validate = validation.Validate(username, state, **kws) |
---|
| 369 | machine = validate.machine |
---|
[161] | 370 | oldname = machine.name |
---|
[153] | 371 | |
---|
[572] | 372 | if hasattr(validate, 'memory'): |
---|
| 373 | machine.memory = validate.memory |
---|
[438] | 374 | |
---|
[572] | 375 | if hasattr(validate, 'vmtype'): |
---|
| 376 | machine.type = validate.vmtype |
---|
[440] | 377 | |
---|
[572] | 378 | if hasattr(validate, 'disksize'): |
---|
| 379 | disksize = validate.disksize |
---|
[177] | 380 | disk = machine.disks[0] |
---|
| 381 | if disk.size != disksize: |
---|
| 382 | olddisk[disk.guest_device_name] = disksize |
---|
| 383 | disk.size = disksize |
---|
[1013] | 384 | session.save_or_update(disk) |
---|
[438] | 385 | |
---|
[446] | 386 | update_acl = False |
---|
[572] | 387 | if hasattr(validate, 'owner') and validate.owner != machine.owner: |
---|
| 388 | machine.owner = validate.owner |
---|
[446] | 389 | update_acl = True |
---|
[572] | 390 | if hasattr(validate, 'name'): |
---|
[586] | 391 | machine.name = validate.name |
---|
[1977] | 392 | for n in machine.nics: |
---|
| 393 | if n.hostname == oldname: |
---|
| 394 | n.hostname = validate.name |
---|
[609] | 395 | if hasattr(validate, 'description'): |
---|
| 396 | machine.description = validate.description |
---|
[572] | 397 | if hasattr(validate, 'admin') and validate.admin != machine.administrator: |
---|
| 398 | machine.administrator = validate.admin |
---|
[446] | 399 | update_acl = True |
---|
[572] | 400 | if hasattr(validate, 'contact'): |
---|
| 401 | machine.contact = validate.contact |
---|
[438] | 402 | |
---|
[1013] | 403 | session.save_or_update(machine) |
---|
[446] | 404 | if update_acl: |
---|
| 405 | cache_acls.refreshMachine(machine) |
---|
[1013] | 406 | session.commit() |
---|
[161] | 407 | except: |
---|
[1013] | 408 | session.rollback() |
---|
[163] | 409 | raise |
---|
[177] | 410 | for diskname in olddisk: |
---|
[209] | 411 | controls.resizeDisk(oldname, diskname, str(olddisk[diskname])) |
---|
[572] | 412 | if hasattr(validate, 'name'): |
---|
| 413 | controls.renameMachine(machine, oldname, validate.name) |
---|
| 414 | return dict(user=username, |
---|
| 415 | command="modify", |
---|
[205] | 416 | machine=machine) |
---|
[438] | 417 | |
---|
[632] | 418 | def modify(username, state, path, fields): |
---|
[205] | 419 | """Handler for modifying attributes of a machine.""" |
---|
| 420 | try: |
---|
[572] | 421 | modify_dict = modifyDict(username, state, fields) |
---|
[205] | 422 | except InvalidInput, err: |
---|
[207] | 423 | result = None |
---|
[572] | 424 | machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine |
---|
[205] | 425 | else: |
---|
| 426 | machine = modify_dict['machine'] |
---|
[209] | 427 | result = 'Success!' |
---|
[205] | 428 | err = None |
---|
[585] | 429 | info_dict = infoDict(username, state, machine) |
---|
[205] | 430 | info_dict['err'] = err |
---|
| 431 | if err: |
---|
| 432 | for field in fields.keys(): |
---|
| 433 | setattr(info_dict['defaults'], field, fields.getfirst(field)) |
---|
[207] | 434 | info_dict['result'] = result |
---|
[235] | 435 | return templates.info(searchList=[info_dict]) |
---|
[161] | 436 | |
---|
[438] | 437 | |
---|
[632] | 438 | def helpHandler(username, state, path, fields): |
---|
[145] | 439 | """Handler for help messages.""" |
---|
[139] | 440 | simple = fields.getfirst('simple') |
---|
| 441 | subjects = fields.getlist('subject') |
---|
[438] | 442 | |
---|
[1704] | 443 | help_mapping = { |
---|
[1705] | 444 | 'Autoinstalls': """ |
---|
[1704] | 445 | The autoinstaller builds a minimal Debian or Ubuntu system to run as a |
---|
| 446 | ParaVM. You can access the resulting system by logging into the <a |
---|
| 447 | href="help?simple=true&subject=ParaVM+Console">serial console server</a> |
---|
[1707] | 448 | with your Kerberos tickets; there is no root password so sshd will |
---|
[1706] | 449 | refuse login.</p> |
---|
[1704] | 450 | |
---|
[1707] | 451 | <p>Under the covers, the autoinstaller uses our own patched version of |
---|
| 452 | xen-create-image, which is a tool based on debootstrap. If you log |
---|
| 453 | into the serial console while the install is running, you can watch |
---|
| 454 | it. |
---|
[1704] | 455 | """, |
---|
| 456 | 'ParaVM Console': """ |
---|
[432] | 457 | ParaVM machines do not support local console access over VNC. To |
---|
| 458 | access the serial console of these machines, you can SSH with Kerberos |
---|
[1634] | 459 | to %s, using the name of the machine as your |
---|
| 460 | username.""" % config.console.hostname, |
---|
[536] | 461 | 'HVM/ParaVM': """ |
---|
[139] | 462 | HVM machines use the virtualization features of the processor, while |
---|
[1736] | 463 | ParaVM machines rely on a modified kernel to communicate directly with |
---|
| 464 | the hypervisor. HVMs support boot CDs of any operating system, and |
---|
| 465 | the VNC console applet. The three-minute autoinstaller produces |
---|
| 466 | ParaVMs. ParaVMs typically are more efficient, and always support the |
---|
[1737] | 467 | <a href="help?subject=ParaVM+Console">console server</a>.</p> |
---|
[1736] | 468 | |
---|
[1737] | 469 | <p>More details are <a |
---|
| 470 | href="https://xvm.scripts.mit.edu/wiki/Paravirtualization">on the |
---|
| 471 | wiki</a>, including steps to prepare an HVM guest to boot as a ParaVM |
---|
| 472 | (which you can skip by using the autoinstaller to begin with.)</p> |
---|
| 473 | |
---|
[1736] | 474 | <p>We recommend using a ParaVM when possible and an HVM when necessary. |
---|
| 475 | """, |
---|
[536] | 476 | 'CPU Weight': """ |
---|
[205] | 477 | Don't ask us! We're as mystified as you are.""", |
---|
[536] | 478 | 'Owner': """ |
---|
[205] | 479 | The owner field is used to determine <a |
---|
[536] | 480 | href="help?subject=Quotas">quotas</a>. It must be the name of a |
---|
[205] | 481 | locker that you are an AFS administrator of. In particular, you or an |
---|
| 482 | AFS group you are a member of must have AFS rlidwka bits on the |
---|
[432] | 483 | locker. You can check who administers the LOCKER locker using the |
---|
| 484 | commands 'attach LOCKER; fs la /mit/LOCKER' on Athena.) See also <a |
---|
[536] | 485 | href="help?subject=Administrator">administrator</a>.""", |
---|
| 486 | 'Administrator': """ |
---|
[205] | 487 | The administrator field determines who can access the console and |
---|
| 488 | power on and off the machine. This can be either a user or a moira |
---|
| 489 | group.""", |
---|
[536] | 490 | 'Quotas': """ |
---|
[408] | 491 | Quotas are determined on a per-locker basis. Each locker may have a |
---|
[2161] | 492 | maximum of 512 mebibytes of active ram, 50 gibibytes of disk, and 4 |
---|
[309] | 493 | active machines.""", |
---|
[536] | 494 | 'Console': """ |
---|
[309] | 495 | <strong>Framebuffer:</strong> At a Linux boot prompt in your VM, try |
---|
| 496 | setting <tt>fb=false</tt> to disable the framebuffer. If you don't, |
---|
| 497 | your machine will run just fine, but the applet's display of the |
---|
| 498 | console will suffer artifacts. |
---|
[912] | 499 | """, |
---|
| 500 | 'Windows': """ |
---|
[2161] | 501 | <strong>Windows Vista:</strong> The Vista image is licensed for all MIT students and will automatically activate off the network; see <a href="/static/msca-email.txt">the licensing confirmation e-mail</a> for details. The installer requires 512 MiB RAM and at least 7.5 GiB disk space (15 GiB or more recommended).<br> |
---|
[912] | 502 | <strong>Windows XP:</strong> This is the volume license CD image. You will need your own volume license key to complete the install. We do not have these available for the general MIT community; ask your department if they have one. |
---|
[309] | 503 | """ |
---|
[536] | 504 | } |
---|
[438] | 505 | |
---|
[187] | 506 | if not subjects: |
---|
[205] | 507 | subjects = sorted(help_mapping.keys()) |
---|
[438] | 508 | |
---|
[572] | 509 | d = dict(user=username, |
---|
[139] | 510 | simple=simple, |
---|
| 511 | subjects=subjects, |
---|
[205] | 512 | mapping=help_mapping) |
---|
[438] | 513 | |
---|
[235] | 514 | return templates.help(searchList=[d]) |
---|
[133] | 515 | |
---|
[438] | 516 | |
---|
[632] | 517 | def badOperation(u, s, p, e): |
---|
[438] | 518 | """Function called when accessing an unknown URI.""" |
---|
[607] | 519 | return ({'Status': '404 Not Found'}, 'Invalid operation.') |
---|
[205] | 520 | |
---|
[579] | 521 | def infoDict(username, state, machine): |
---|
[438] | 522 | """Get the variables used by info.tmpl.""" |
---|
[209] | 523 | status = controls.statusInfo(machine) |
---|
[235] | 524 | checkpoint.checkpoint('Getting status info') |
---|
[133] | 525 | has_vnc = hasVnc(status) |
---|
| 526 | if status is None: |
---|
| 527 | main_status = dict(name=machine.name, |
---|
| 528 | memory=str(machine.memory)) |
---|
[205] | 529 | uptime = None |
---|
| 530 | cputime = None |
---|
[133] | 531 | else: |
---|
| 532 | main_status = dict(status[1:]) |
---|
[662] | 533 | main_status['host'] = controls.listHost(machine) |
---|
[167] | 534 | start_time = float(main_status.get('start_time', 0)) |
---|
| 535 | uptime = datetime.timedelta(seconds=int(time.time()-start_time)) |
---|
| 536 | cpu_time_float = float(main_status.get('cpu_time', 0)) |
---|
| 537 | cputime = datetime.timedelta(seconds=int(cpu_time_float)) |
---|
[235] | 538 | checkpoint.checkpoint('Status') |
---|
[133] | 539 | display_fields = [('name', 'Name'), |
---|
[609] | 540 | ('description', 'Description'), |
---|
[133] | 541 | ('owner', 'Owner'), |
---|
[187] | 542 | ('administrator', 'Administrator'), |
---|
[133] | 543 | ('contact', 'Contact'), |
---|
[136] | 544 | ('type', 'Type'), |
---|
[133] | 545 | 'NIC_INFO', |
---|
| 546 | ('uptime', 'uptime'), |
---|
| 547 | ('cputime', 'CPU usage'), |
---|
[662] | 548 | ('host', 'Hosted on'), |
---|
[133] | 549 | ('memory', 'RAM'), |
---|
| 550 | 'DISK_INFO', |
---|
| 551 | ('state', 'state (xen format)'), |
---|
[536] | 552 | ('cpu_weight', 'CPU weight'+helppopup('CPU Weight')), |
---|
[133] | 553 | ] |
---|
| 554 | fields = [] |
---|
| 555 | machine_info = {} |
---|
[147] | 556 | machine_info['name'] = machine.name |
---|
[609] | 557 | machine_info['description'] = machine.description |
---|
[136] | 558 | machine_info['type'] = machine.type.hvm and 'HVM' or 'ParaVM' |
---|
[133] | 559 | machine_info['owner'] = machine.owner |
---|
[187] | 560 | machine_info['administrator'] = machine.administrator |
---|
[133] | 561 | machine_info['contact'] = machine.contact |
---|
| 562 | |
---|
| 563 | nic_fields = getNicInfo(machine_info, machine) |
---|
| 564 | nic_point = display_fields.index('NIC_INFO') |
---|
[438] | 565 | display_fields = (display_fields[:nic_point] + nic_fields + |
---|
[205] | 566 | display_fields[nic_point+1:]) |
---|
[133] | 567 | |
---|
| 568 | disk_fields = getDiskInfo(machine_info, machine) |
---|
| 569 | disk_point = display_fields.index('DISK_INFO') |
---|
[438] | 570 | display_fields = (display_fields[:disk_point] + disk_fields + |
---|
[205] | 571 | display_fields[disk_point+1:]) |
---|
[438] | 572 | |
---|
[211] | 573 | main_status['memory'] += ' MiB' |
---|
[133] | 574 | for field, disp in display_fields: |
---|
[167] | 575 | if field in ('uptime', 'cputime') and locals()[field] is not None: |
---|
[133] | 576 | fields.append((disp, locals()[field])) |
---|
[147] | 577 | elif field in machine_info: |
---|
| 578 | fields.append((disp, machine_info[field])) |
---|
[133] | 579 | elif field in main_status: |
---|
| 580 | fields.append((disp, main_status[field])) |
---|
| 581 | else: |
---|
| 582 | pass |
---|
| 583 | #fields.append((disp, None)) |
---|
[235] | 584 | |
---|
| 585 | checkpoint.checkpoint('Got fields') |
---|
| 586 | |
---|
| 587 | |
---|
[572] | 588 | max_mem = validation.maxMemory(machine.owner, state, machine, False) |
---|
[235] | 589 | checkpoint.checkpoint('Got mem') |
---|
[566] | 590 | max_disk = validation.maxDisk(machine.owner, machine) |
---|
[209] | 591 | defaults = Defaults() |
---|
[609] | 592 | for name in 'machine_id name description administrator owner memory contact'.split(): |
---|
[205] | 593 | setattr(defaults, name, getattr(machine, name)) |
---|
[516] | 594 | defaults.type = machine.type.type_id |
---|
[205] | 595 | defaults.disk = "%0.2f" % (machine.disks[0].size/1024.) |
---|
[235] | 596 | checkpoint.checkpoint('Got defaults') |
---|
[572] | 597 | d = dict(user=username, |
---|
[133] | 598 | on=status is not None, |
---|
| 599 | machine=machine, |
---|
[205] | 600 | defaults=defaults, |
---|
[133] | 601 | has_vnc=has_vnc, |
---|
| 602 | uptime=str(uptime), |
---|
| 603 | ram=machine.memory, |
---|
[144] | 604 | max_mem=max_mem, |
---|
| 605 | max_disk=max_disk, |
---|
[536] | 606 | owner_help=helppopup("Owner"), |
---|
[133] | 607 | fields = fields) |
---|
[205] | 608 | return d |
---|
[113] | 609 | |
---|
[632] | 610 | def info(username, state, path, fields): |
---|
[205] | 611 | """Handler for info on a single VM.""" |
---|
[572] | 612 | machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine |
---|
[579] | 613 | d = infoDict(username, state, machine) |
---|
[235] | 614 | checkpoint.checkpoint('Got infodict') |
---|
| 615 | return templates.info(searchList=[d]) |
---|
[205] | 616 | |
---|
[632] | 617 | def unauthFront(_, _2, _3, fields): |
---|
[510] | 618 | """Information for unauth'd users.""" |
---|
[2182] | 619 | return templates.unauth(searchList=[{'simple' : True, |
---|
[2185] | 620 | 'hostname' : socket.getfqdn()}]) |
---|
[510] | 621 | |
---|
[867] | 622 | def admin(username, state, path, fields): |
---|
[633] | 623 | if path == '': |
---|
| 624 | return ({'Status': '303 See Other', |
---|
[867] | 625 | 'Location': 'admin/'}, |
---|
[633] | 626 | "You shouldn't see this message.") |
---|
[2217] | 627 | if not username in getAfsGroupMembers(config.adminacl, 'athena.mit.edu'): |
---|
[867] | 628 | raise InvalidInput('username', username, |
---|
[2217] | 629 | 'Not in admin group %s.' % config.adminacl) |
---|
[867] | 630 | newstate = State(username, isadmin=True) |
---|
[632] | 631 | newstate.environ = state.environ |
---|
| 632 | return handler(username, newstate, path, fields) |
---|
| 633 | |
---|
| 634 | def throwError(_, __, ___, ____): |
---|
[598] | 635 | """Throw an error, to test the error-tracing mechanisms.""" |
---|
[602] | 636 | raise RuntimeError("test of the emergency broadcast system") |
---|
[598] | 637 | |
---|
[2665] | 638 | mapping = dict(#list=listVms, |
---|
[113] | 639 | vnc=vnc, |
---|
[133] | 640 | command=command, |
---|
| 641 | modify=modify, |
---|
[113] | 642 | info=info, |
---|
[139] | 643 | create=create, |
---|
[510] | 644 | help=helpHandler, |
---|
[598] | 645 | unauth=unauthFront, |
---|
[867] | 646 | admin=admin, |
---|
[869] | 647 | overlord=admin, |
---|
[598] | 648 | errortest=throwError) |
---|
[113] | 649 | |
---|
[205] | 650 | def printHeaders(headers): |
---|
[438] | 651 | """Print a dictionary as HTTP headers.""" |
---|
[205] | 652 | for key, value in headers.iteritems(): |
---|
| 653 | print '%s: %s' % (key, value) |
---|
| 654 | print |
---|
| 655 | |
---|
[598] | 656 | def send_error_mail(subject, body): |
---|
| 657 | import subprocess |
---|
[205] | 658 | |
---|
[863] | 659 | to = config.web.errormail |
---|
[598] | 660 | mail = """To: %s |
---|
[863] | 661 | From: root@%s |
---|
[598] | 662 | Subject: %s |
---|
| 663 | |
---|
| 664 | %s |
---|
[863] | 665 | """ % (to, config.web.hostname, subject, body) |
---|
[1718] | 666 | p = subprocess.Popen(['/usr/sbin/sendmail', '-f', to, to], |
---|
| 667 | stdin=subprocess.PIPE) |
---|
[598] | 668 | p.stdin.write(mail) |
---|
| 669 | p.stdin.close() |
---|
| 670 | p.wait() |
---|
| 671 | |
---|
[603] | 672 | def show_error(op, username, fields, err, emsg, traceback): |
---|
| 673 | """Print an error page when an exception occurs""" |
---|
| 674 | d = dict(op=op, user=username, fields=fields, |
---|
| 675 | errorMessage=str(err), stderr=emsg, traceback=traceback) |
---|
| 676 | details = templates.error_raw(searchList=[d]) |
---|
[1103] | 677 | exclude = config.web.errormail_exclude |
---|
| 678 | if username not in exclude and '*' not in exclude: |
---|
[627] | 679 | send_error_mail('xvm error on %s for %s: %s' % (op, username, err), |
---|
| 680 | details) |
---|
[603] | 681 | d['details'] = details |
---|
| 682 | return templates.error(searchList=[d]) |
---|
| 683 | |
---|
[632] | 684 | def handler(username, state, path, fields): |
---|
| 685 | operation, path = pathSplit(path) |
---|
| 686 | if not operation: |
---|
| 687 | operation = 'list' |
---|
| 688 | print 'Starting', operation |
---|
| 689 | fun = mapping.get(operation, badOperation) |
---|
| 690 | return fun(username, state, path, fields) |
---|
| 691 | |
---|
[579] | 692 | class App: |
---|
| 693 | def __init__(self, environ, start_response): |
---|
| 694 | self.environ = environ |
---|
| 695 | self.start = start_response |
---|
[205] | 696 | |
---|
[579] | 697 | self.username = getUser(environ) |
---|
| 698 | self.state = State(self.username) |
---|
[581] | 699 | self.state.environ = environ |
---|
[205] | 700 | |
---|
[634] | 701 | random.seed() #sigh |
---|
| 702 | |
---|
[579] | 703 | def __iter__(self): |
---|
[632] | 704 | start_time = time.time() |
---|
[864] | 705 | database.clear_cache() |
---|
[600] | 706 | sys.stderr = StringIO() |
---|
[579] | 707 | fields = cgi.FieldStorage(fp=self.environ['wsgi.input'], environ=self.environ) |
---|
| 708 | operation = self.environ.get('PATH_INFO', '') |
---|
| 709 | if not operation: |
---|
[633] | 710 | self.start("301 Moved Permanently", [('Location', './')]) |
---|
[579] | 711 | return |
---|
| 712 | if self.username is None: |
---|
| 713 | operation = 'unauth' |
---|
| 714 | |
---|
| 715 | try: |
---|
| 716 | checkpoint.checkpoint('Before') |
---|
[632] | 717 | output = handler(self.username, self.state, operation, fields) |
---|
[579] | 718 | checkpoint.checkpoint('After') |
---|
| 719 | |
---|
| 720 | headers = dict(DEFAULT_HEADERS) |
---|
| 721 | if isinstance(output, tuple): |
---|
| 722 | new_headers, output = output |
---|
| 723 | headers.update(new_headers) |
---|
| 724 | e = revertStandardError() |
---|
| 725 | if e: |
---|
[693] | 726 | if hasattr(output, 'addError'): |
---|
| 727 | output.addError(e) |
---|
| 728 | else: |
---|
| 729 | # This only happens on redirects, so it'd be a pain to get |
---|
| 730 | # the message to the user. Maybe in the response is useful. |
---|
| 731 | output = output + '\n\nstderr:\n' + e |
---|
[579] | 732 | output_string = str(output) |
---|
| 733 | checkpoint.checkpoint('output as a string') |
---|
| 734 | except Exception, err: |
---|
| 735 | if not fields.has_key('js'): |
---|
| 736 | if isinstance(err, InvalidInput): |
---|
| 737 | self.start('200 OK', [('Content-Type', 'text/html')]) |
---|
| 738 | e = revertStandardError() |
---|
[603] | 739 | yield str(invalidInput(operation, self.username, fields, |
---|
| 740 | err, e)) |
---|
[579] | 741 | return |
---|
[602] | 742 | import traceback |
---|
| 743 | self.start('500 Internal Server Error', |
---|
| 744 | [('Content-Type', 'text/html')]) |
---|
| 745 | e = revertStandardError() |
---|
[603] | 746 | s = show_error(operation, self.username, fields, |
---|
[602] | 747 | err, e, traceback.format_exc()) |
---|
| 748 | yield str(s) |
---|
| 749 | return |
---|
[587] | 750 | status = headers.setdefault('Status', '200 OK') |
---|
| 751 | del headers['Status'] |
---|
| 752 | self.start(status, headers.items()) |
---|
[579] | 753 | yield output_string |
---|
[535] | 754 | if fields.has_key('timedebug'): |
---|
[579] | 755 | yield '<pre>%s</pre>' % cgi.escape(str(checkpoint)) |
---|
[209] | 756 | |
---|
[579] | 757 | def constructor(): |
---|
[863] | 758 | connect() |
---|
[579] | 759 | return App |
---|
[535] | 760 | |
---|
[579] | 761 | def main(): |
---|
| 762 | from flup.server.fcgi_fork import WSGIServer |
---|
| 763 | WSGIServer(constructor()).run() |
---|
[535] | 764 | |
---|
[579] | 765 | if __name__ == '__main__': |
---|
| 766 | main() |
---|