Beispiel #1
0
def test_content_not_escaped():
    content = Content('<a>test</a>',
                      tag='p',
                      attrs={'id': 'id<br>'},
                      escape=False)
    assert content.html() == '<p id="id&lt;br&gt;"><a>test</a></p>'
    assert content.text() == '<a>test</a>\n\n'
Beispiel #2
0
    def objgraph(self, request):
        import objgraph
        limit = int(request.args.get('limit', 10))
        types = objgraph.most_common_types(limit=limit, shortnames=False)
        leaking = objgraph.most_common_types(
            limit=limit,
            objects=objgraph.get_leaking_objects(),
            shortnames=False,
        )

        # html only links
        limits = [
            'Number of items: ',
            Link('{}', request.path + '?limit={}', 10).html(),
            Link('{}', request.path + '?limit={}', 20).html(),
            Link('{}', request.path + '?limit={}', 50).html(),
        ]
        return info_response(
            request,
            'Python Objects',
            Content(
                'Python Objects for Worker pid {}'.format(os.getpid()),
                'h1',
            ),
            Content(' '.join(limits), 'p', text=False, escape=False),
            Content('Most Common Objects', 'h2'),
            Table(types),
            Content('Leaking Objects (no referrer)', 'h2'),
            Table(leaking),
        )
Beispiel #3
0
    def workers(self, request):
        """Information about workers resource usage."""
        import psutil
        arbiter = psutil.Process(os.getppid())
        workers = arbiter.children()
        workers.sort(key=lambda p: p.pid)

        rows = [format_psutil_row('Gunicorn Master', arbiter)]
        for i, worker in enumerate(workers):
            rows.append(format_psutil_row('Worker {}'.format(i), worker))

        master = arbiter.as_dict(MASTER_FIELDS)
        master['cmdline'] = ' '.join(master['cmdline'])

        environ = master.pop('environ')
        config = talisker.get_config()
        clean_environ = [(k, v) for k, v in sorted(environ.items())
                         if k in config.METADATA]
        sorted_master = [(k, master[k]) for k in MASTER_FIELDS if k in master]

        return info_response(
            request.environ,
            'Workers',
            Content('Workers', 'h2'),
            Table(rows, headers=HEADERS, id='workers'),
            Content('Process Information', 'h2'),
            Table(sorted_master, id='process_info'),
            Content('Process Environment (whitelist)', 'h2'),
            Table(clean_environ, id='process_env'),
        )
Beispiel #4
0
    def workers(self, request):
        """Information about workers resource usage."""
        import psutil
        arbiter = psutil.Process(os.getppid())
        workers = arbiter.children()
        workers.sort(key=lambda p: p.pid)

        rows = [format_psutil_row('Gunicorn Master', arbiter)]
        for i, worker in enumerate(workers):
            rows.append(format_psutil_row('Worker {}'.format(i), worker))

        master = arbiter.as_dict(MASTER_FIELDS)
        master['cmdline'] = ' '.join(master['cmdline'])

        environ = master.pop('environ')
        if 'SENTRY_DSN' in environ:
            environ['SENTRY_DSN'] = sanitize_url(environ['SENTRY_DSN'])
        clean_environ = [
            (k, v) for k, v in sorted(environ.items())
            if k in TALISKER_ENV_VARS
        ]
        sorted_master = [(k, master[k]) for k in MASTER_FIELDS if k in master]

        return info_response(
            request,
            'Workers',
            Content('Workers', 'h2'),
            Table(rows, headers=HEADERS),
            Content('Process Information', 'h2'),
            Table(sorted_master),
            Content('Process Environment (whitelist)', 'h2'),
            Table(clean_environ),
        )
Beispiel #5
0
def test_content_simple_string():
    content = Content('test', tag='p', id='id', attrs={'foo': 'foo'})
    assert content.html() == '<p foo="foo" id="id">test</p>'
    assert content.text() == 'test\n\n'
    assert content._json() == ('id', 'test')
    assert Content('test', tag='h1').text() == 'test\n====\n\n'
    assert Content('test')._json() is None
Beispiel #6
0
def talisker_error_response(environ, headers, exc_info):
    """Returns WSGI iterable to be returned as an error response.

    This error response uses Talisker's built in rendering support to be able
    to render content in json (default), html, or text.

    Returns a tuple of (content_type, iterable)."""
    exc_type, exc, tb = exc_info
    config = talisker.get_config()
    tb = Content('[traceback hidden]', tag='p', id='traceback')

    rid = environ['REQUEST_ID']
    id_info = [('Request-Id', rid)]

    wsgi_environ = []
    request_headers = []

    for k, v in environ.items():
        if k.startswith('HTTP_'):
            request_headers.append((k[5:].replace('_', '-').title(), v))
        else:
            wsgi_environ.append((k, v))

    if config.devel:
        title = '{}: {}'.format(exc_type.__name__, exc)
        lines = traceback.format_exception(*exc_info)
        tb = PreformattedText(''.join(lines), id='traceback')
    else:
        title = 'Server Error: {}'.format(exc_type.__name__)

    content = [
        Content(title, tag='h1', id='title'),
        Table(id_info, id='id'),
        tb,
        Table(
            sorted(request_headers),
            id='request_headers',
            headers=['Request Headers', ''],
        ),
        Table(
            sorted(wsgi_environ),
            id='wsgi_env',
            headers=['WSGI Environ', ''],
        ),
        Table(
            headers,
            id='response_headers',
            headers=['Response Headers', ''],
        ),
    ]

    return render_best_content_type(environ, title, content)
Beispiel #7
0
def test_content_simple_string():
    content = Content('test', tag='p', id='id', attrs={'foo': 'foo'})
    assert content.html() == '<p foo="foo" id="id">test</p>'
    assert content.text() == 'test\n\n'
    assert content._json() == ('id', 'test')
    assert Content('test', tag='h1').text() == 'test\n====\n\n'
    assert Content('test')._json() is None
Beispiel #8
0
    def config(self, request):
        config = talisker.get_config()
        rows = []
        for name, meta in config.metadata().items():
            if meta.default is None:
                is_default = ''
            else:
                is_default = meta.default == meta.value

            rows.append((
                name,
                meta.value,
                '' if meta.raw is None else repr(meta.raw),
                is_default,
            ))

        return info_response(
            request.environ, 'Config', Content('Config', 'h2'),
            Table(
                rows,
                headers=['Name', 'Value', 'Raw Value', 'Is Default'],
                id='config',
            ))
Beispiel #9
0
def test_content_disabled():
    assert Content('test', html=False).html() == ''
    assert Content('test', text=False).text() == ''
Beispiel #10
0
def test_content_escaped():
    content = Content('te<br>st', tag='p', attrs={'id': 'id<br>'})
    assert content.html() == '<p id="id&lt;br&gt;">te&lt;br&gt;st</p>'
    assert content.text() == 'te<br>st\n\n'
Beispiel #11
0
def test_content_simple_string():
    content = Content('test', tag='p', attrs={'id': 'id'})
    assert content.html() == '<p id="id">test</p>'
    assert content.text() == 'test\n\n'
    assert Content('test', tag='h1').text() == 'test\n====\n\n'
Beispiel #12
0
def test_content_not_escaped():
    content = Content('<a>test</a>', tag='p', id='id<br>', escape=False)
    assert content.html() == '<p id="id&lt;br&gt;"><a>test</a></p>'
    assert content.text() == '<a>test</a>\n\n'
    assert content._json() == ('id<br>', '<a>test</a>')
Beispiel #13
0
def test_content_escaped():
    content = Content('te<br>st', tag='p', id='id<br>')
    assert content.html() == '<p id="id&lt;br&gt;">te&lt;br&gt;st</p>'
    assert content.text() == 'te<br>st\n\n'
    assert content._json() == ('id<br>', 'te<br>st')
Beispiel #14
0
def test_content_not_escaped():
    content = Content(
        '<a>test</a>', tag='p', id='id<br>', escape=False)
    assert content.html() == '<p id="id&lt;br&gt;"><a>test</a></p>'
    assert content.text() == '<a>test</a>\n\n'
    assert content._json() == ('id<br>', '<a>test</a>')
Beispiel #15
0
def test_content_escaped():
    content = Content('te<br>st', tag='p', id='id<br>')
    assert content.html() == '<p id="id&lt;br&gt;">te&lt;br&gt;st</p>'
    assert content.text() == 'te<br>st\n\n'
    assert content._json() == ('id<br>', 'te<br>st')