source: package_branches/invirt-web/cherrypy/code/main.py @ 2452

Last change on this file since 2452 was 2452, checked in by ecprice, 15 years ago

disable GETting to post keyboards to ajaxterm

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