view talosnames/web.py @ 46:fcd98303a90d

provide CLI handler for web
author Jeff Hammel <jhammel@mozilla.com>
date Mon, 13 Aug 2012 15:14:53 -0700
parents 10e59c3ae847
children 11249e75ced6
line wrap: on
line source

#!/usr/bin/env python

"""
web handler for talosnames
"""

import optparse
import os
import pprint
import sys
import talos.test
import tempita
from api import TalosNames
from subprocess import list2cmdline
from webob import Request, Response, exc

here = os.path.dirname(os.path.abspath(__file__))
template = os.path.join(here, 'templates', 'index.html')

class Handler(object):

    def __init__(self, **kw):
        self.api = TalosNames()

        # get data
        suites = sorted(self.api.suites.keys())
        tests = {}
        for suite in suites:
            try:
                test = self.api.test_config(suite)
                tests[suite] = test
            except:
                tests[suite] = None
        self.suites = suites

        self.data = {'suites': self.suites,
                     'enabled': self.api.buildbot_enabled, # whether the suite is enabled by default
                     'commands': self.api.buildbot_commands,
                     'tbpl': dict([(suite, self.api.tbpl_name(suite))
                                   for suite in suites]),
                     'tests': tests,
                     'list2cmdline': list2cmdline
                     }

        paint = {}
        chrome = {}
        graphserver = {}
        test_type = {}
        for suite in suites:
            for test in tests.get(suite) or []:
                config = self.api.talos_config(suite)
                _paint = '--mozAfterPaint' in self.data['commands'][suite]
                _chrome = '--noChrome' not in self.data['commands'][suite]
                extension = config.get('test_name_extension', '')
                _extension = ''
                if not _chrome:
                    _extension += '_nochrome'
                if _paint:
                    _extension += '_paint'
                if extension != _extension:
                    raise AssertionError
                paint[suite] = _paint
                chrome[suite] = _chrome

                # determine test extension
                # TODO: move this to api.py
                testname = test
                testobj = talos.test.test_dict[testname]
                if issubclass(testobj, talos.test.TsBase):
                    test_type.setdefault(suite, {})[test] = 'Startup Test'
                elif issubclass(testobj, talos.test.PageloaderTest):
                    test_type.setdefault(suite, {})[test] = 'Page Load Test'
                    testname += extension
                else:
                    raise Exception

                # get graphserver data
                names = self.api.graphserver_name(testname)
                if names:
                    graphserver.setdefault(suite, {})[test] = [names]
                else:
                    graphserver.setdefault(suite, {})[test] = None
        self.data['graphserver'] = graphserver
        self.data['paint'] = paint
        self.data['chrome'] = chrome
        self.data['test_type'] = test_type

    def __call__(self, environ, start_response):
        request = Request(environ)
        response = Response(content_type='text/html',
                            body=self.render(request))
        return response(environ, start_response)

    def render(self, request=None):

        # make a local copy of the data
        data = self.data.copy()

        if request :
            # filter by TBPL letter
            if 'tbpl' in request.GET:
                tbplnames = []
                for name in request.GET.getall('tbpl'):
                    if not name.startswith('Talos'):
                        name = 'Talos ' + name
                    tbplnames.append(name)
                suites = []
                for suite, value in self.data['tbpl'].items():
                    if value in tbplnames:
                        suites.append(suite)
                data['suites'] = sorted(suites)

            # filter by disabled
            if 'show' in request.GET:
                show = request.GET['show']
                if show == 'active':
                    data['suites'] = [i for i in data['suites']
                                      if data['enabled'][i]]
                elif show == 'disabled':
                    data['suites'] = [i for i in data['suites']
                                      if not data['enabled'][i]]


        contents = file(template).read()
        _template = tempita.HTMLTemplate(contents)
        return _template.substitute(data)

def main(args=sys.argv[1:]):
    parser = optparse.OptionParser()
    parser.add_option('-o', '--output', dest='output',
                      help="file to output to")
    parser.add_option('-p', '--port', dest='port',
                      default=8080, type='int',
                      help="port to serve on")
    options, args = parser.parse_args()

    app = Handler()
    print "Done creating handler."

    if options.output:
        f = file(options.output, 'w')
        f.write(app.render())
        f.close()
    else:
        from wsgiref import simple_server
        server = simple_server.make_server(host='0.0.0.0', port=options.port, app=app)
        server.serve_forever()


if __name__ == '__main__':
    main()