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