view talosnames/web.py @ 72:c4ba60b663fa default tip

make executable
author Jeff Hammel <jhammel@mozilla.com>
date Thu, 07 Mar 2013 11:22:20 -0800
parents 6e495bad69bb
children
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

try:
    import json
except ImportError:
    import simplejson as json

here = os.path.dirname(os.path.abspath(__file__))

class Handler(object):

    paths = {'tbpl': 'tbpl.html'}

    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,
                     }

        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

        self.data['json'] = json.dumps(self.data, indent=2, sort_keys=True)

        self.data['list2cmdline'] = list2cmdline

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

    def render(self, template='index.html', 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]]

        path = self.template_path(template)
        contents = file(path).read()
        template = tempita.HTMLTemplate(contents)
        return template.substitute(data)

    def template_path(self, path):
        """returns template path"""
        path = path.strip('/')
        template = self.paths.get(path, 'index.html')
        return os.path.join(here, 'templates', template)

def paste_factory(global_conf, **app_conf):
    """factory interface for paste"""
    app = Handler(**app_conf)
    return app

def main(args=sys.argv[1:]):
    """CLI entry point"""

    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."
    print "http://localhost:%s/" % options.port

    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()