Changeset 579 for trunk


Ignore:
Timestamp:
Jun 3, 2008, 1:23:23 AM (17 years ago)
Author:
ecprice
Message:

Use fcgi

Location:
trunk/packages/sipb-xen-www/code
Files:
1 added
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/packages/sipb-xen-www/code/main.py

    r578 r579  
    473473
    474474
    475 def badOperation(u, e):
     475def badOperation(u, s, e):
    476476    """Function called when accessing an unknown URI."""
    477477    raise CodeError("Unknown operation")
    478478
    479 def infoDict(username, machine):
     479def infoDict(username, state, machine):
    480480    """Get the variables used by info.tmpl."""
    481481    status = controls.statusInfo(machine)
     
    573573    """Handler for info on a single VM."""
    574574    machine = validation.Validate(username, state, machine_id=fields.getfirst('machine_id')).machine
    575     d = infoDict(username, machine)
     575    d = infoDict(username, state, machine)
    576576    checkpoint.checkpoint('Got infodict')
    577577    return templates.info(searchList=[d])
     
    606606    return email[:-8]
    607607
    608 def main(operation, username, state, fields):
    609     start_time = time.time()
    610     fun = mapping.get(operation, badOperation)
    611 
    612     if fun not in (helpHandler, ):
    613         connect('postgres://sipb-xen@sipb-xen-dev.mit.edu/sipb_xen')
    614     try:
    615         checkpoint.checkpoint('Before')
    616         output = fun(username, state, fields)
    617         checkpoint.checkpoint('After')
    618 
    619         headers = dict(DEFAULT_HEADERS)
    620         if isinstance(output, tuple):
    621             new_headers, output = output
    622             headers.update(new_headers)
    623         e = revertStandardError()
    624         if e:
    625             if isinstance(output, basestring):
    626                 sys.stderr = StringIO()
    627                 x = str(output)
    628                 print >> sys.stderr, x
    629                 print >> sys.stderr, 'XXX'
    630                 print >> sys.stderr, e
    631                 raise Exception()
    632             output.addError(e)
    633         printHeaders(headers)
    634         output_string =  str(output)
    635         checkpoint.checkpoint('output as a string')
    636         print output_string
     608class App:
     609    def __init__(self, environ, start_response):
     610        self.environ = environ
     611        self.start = start_response
     612
     613        self.username = getUser(environ)
     614        self.state = State(self.username)
     615
     616    def __iter__(self):
     617        fields = cgi.FieldStorage(fp=self.environ['wsgi.input'], environ=self.environ)
     618        print >> sys.stderr, fields
     619        operation = self.environ.get('PATH_INFO', '')
     620        if not operation:
     621            self.start("301 Moved Permanently", [('Location',
     622                                                  os.environ['SCRIPT_NAME']+'/')])
     623            return
     624        if self.username is None:
     625            operation = 'unauth'
     626        if operation.startswith('/'):
     627            operation = operation[1:]
     628        if not operation:
     629            operation = 'list'
     630        print 'Starting', operation
     631
     632        start_time = time.time()
     633        fun = mapping.get(operation, badOperation)
     634        try:
     635            checkpoint.checkpoint('Before')
     636            output = fun(self.username, self.state, fields)
     637            checkpoint.checkpoint('After')
     638
     639            headers = dict(DEFAULT_HEADERS)
     640            if isinstance(output, tuple):
     641                new_headers, output = output
     642                headers.update(new_headers)
     643            print 'MOO2'
     644            e = revertStandardError()
     645            if e:
     646                if isinstance(output, basestring):
     647                    sys.stderr = StringIO()
     648                    x = str(output)
     649                    print >> sys.stderr, x
     650                    print >> sys.stderr, 'XXX'
     651                    print >> sys.stderr, e
     652                    raise Exception()
     653                output.addError(e)
     654            output_string =  str(output)
     655            checkpoint.checkpoint('output as a string')
     656        except Exception, err:
     657            if not fields.has_key('js'):
     658                if isinstance(err, CodeError):
     659                    self.start('500 Internal Server Error', [('Content-Type', 'text/html')])
     660                    e = revertStandardError()
     661                    s = error(operation, self.username, fields, err, e)
     662                    yield str(s)
     663                    return
     664                if isinstance(err, InvalidInput):
     665                    self.start('200 OK', [('Content-Type', 'text/html')])
     666                    e = revertStandardError()
     667                    yield str(invalidInput(operation, self.username, fields, err, e))
     668                    return
     669            self.start('500 Internal Server Error', [('Content-Type', 'text/plain')])
     670            import traceback
     671            yield '''Uh-oh!  We experienced an error.'
     672Please email xvm-dev@mit.edu with the contents of this page.'
     673----
     674%s
     675----
     676%s
     677----''' % (str(err), traceback.format_exc())
     678        self.start('200 OK', headers.items())
     679        yield output_string
    637680        if fields.has_key('timedebug'):
    638             print '<pre>%s</pre>' % cgi.escape(checkpoint)
    639     except Exception, err:
    640         if not fields.has_key('js'):
    641             if isinstance(err, CodeError):
    642                 print 'Content-Type: text/html\n'
    643                 e = revertStandardError()
    644                 print error(operation, state.username, fields, err, e)
    645                 sys.exit(1)
    646             if isinstance(err, InvalidInput):
    647                 print 'Content-Type: text/html\n'
    648                 e = revertStandardError()
    649                 print invalidInput(operation, state.username, fields, err, e)
    650                 sys.exit(1)
    651         print 'Content-Type: text/plain\n'
    652         print 'Uh-oh!  We experienced an error.'
    653         print 'Please email xvm-dev@mit.edu with the contents of this page.'
    654         print '----'
    655         e = revertStandardError()
    656         print e
    657         print '----'
    658         raise
     681            yield '<pre>%s</pre>' % cgi.escape(str(checkpoint))
     682
     683def constructor():
     684    connect('postgres://sipb-xen@sipb-xen-dev.mit.edu/sipb_xen')
     685    return App
     686
     687def main():
     688    from flup.server.fcgi_fork import WSGIServer
     689    WSGIServer(constructor()).run()
    659690
    660691if __name__ == '__main__':
    661     fields = cgi.FieldStorage()
    662 
    663     if fields.has_key('sqldebug'):
    664         import logging
    665         logging.basicConfig()
    666         logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
    667         logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.INFO)
    668 
    669     username = getUser(os.environ)
    670     state = State(username)
    671     operation = os.environ.get('PATH_INFO', '')
    672     if not operation:
    673         print "Status: 301 Moved Permanently"
    674         print 'Location: ' + os.environ['SCRIPT_NAME']+'/\n'
    675         sys.exit(0)
    676     if username is None:
    677         operation = 'unauth'
    678     if operation.startswith('/'):
    679         operation = operation[1:]
    680     if not operation:
    681         operation = 'list'
    682 
    683     if os.getenv("SIPB_XEN_PROFILE"):
    684         import profile
    685         profile.run('main(operation, username, state, fields)', 'log-'+operation)
    686     else:
    687         main(operation, username, state, fields)
     692    main()
Note: See TracChangeset for help on using the changeset viewer.