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