-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add /sql_profiler to enable SQL profiling
Disabled by default. You must enable it by setting the SQL_PROFILER_SECRET env var and using the view (/sql_profiler) to switch it ON and OFF. Warning, it will slow down everything.
- Loading branch information
Patrick Valsecchi
committed
Mar 29, 2017
1 parent
1de5fdd
commit d174b30
Showing
6 changed files
with
97 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
def _switch(app_connection, enable=None): | ||
params = {'secret': 'changeme'} | ||
if enable is not None: | ||
params['enable'] = "1" if enable else "0" | ||
answer = app_connection.get_json("sql_profiler", params=params) | ||
assert answer['status'] == 200 | ||
return answer['enabled'] | ||
|
||
|
||
def test_ok(app_connection, slave_db_connection): | ||
assert _switch(app_connection) is False | ||
assert _switch(app_connection, enable=True) is True | ||
try: | ||
assert _switch(app_connection) is True | ||
app_connection.get_json("hello") | ||
finally: | ||
_switch(app_connection, enable=False) | ||
|
||
|
||
def test_no_secret(app_connection): | ||
app_connection.get_json("sql_profiler", params={'enable': '1'}, expected_status=403) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
""" | ||
A view (URL=/sql_provider) allowing to enabled/disable a SQL spy that runs an "EXPLAIN ANALYZE" on | ||
every SELECT query going through SQLAlchemy. | ||
""" | ||
import logging | ||
import os | ||
from pyramid.httpexceptions import HTTPForbidden | ||
import re | ||
import sqlalchemy.event | ||
import sqlalchemy.engine | ||
|
||
ENV_KEY = 'SQL_PROFILER_SECRET' | ||
LOG = logging.getLogger(__name__) | ||
enabled = False | ||
|
||
|
||
def _sql_profiler_view(request): | ||
global enabled | ||
if request.params.get('secret') != os.environ[ENV_KEY]: | ||
raise HTTPForbidden('Missing or invalid secret parameter') | ||
if 'enable' in request.params: | ||
if request.params['enable'] == '1': | ||
if not enabled: | ||
LOG.warning("Enabling the SQL profiler") | ||
sqlalchemy.event.listen(sqlalchemy.engine.Engine, "before_cursor_execute", | ||
_before_cursor_execute) | ||
enabled = True | ||
return {'status': 200, 'enabled': True} | ||
else: | ||
if enabled: | ||
LOG.warning("Disabling the SQL profiler") | ||
sqlalchemy.event.remove(sqlalchemy.engine.Engine, "before_cursor_execute", | ||
_before_cursor_execute) | ||
enabled = False | ||
return {'status': 200, 'enabled': False} | ||
else: | ||
return {'status': 200, 'enabled': enabled} | ||
|
||
|
||
def _beautify_sql(statement): | ||
statement = re.sub(r'SELECT [^\n]*\n', 'SELECT ...\n', statement) | ||
statement = re.sub(r' ((?:LEFT )?(?:OUTER )?JOIN )', r'\n\1', statement) | ||
statement = re.sub(r' ON ', r'\n ON ', statement) | ||
statement = re.sub(r' GROUP BY ', r'\nGROUP BY ', statement) | ||
statement = re.sub(r' ORDER BY ', r'\nORDER BY ', statement) | ||
return statement | ||
|
||
|
||
def _indent(statement, indent=' '): | ||
return indent + ("\n" + indent).join(statement.split('\n')) | ||
|
||
|
||
def _before_cursor_execute(conn, _cursor, statement, parameters, _context, _executemany): | ||
if statement.startswith("SELECT ") and LOG.isEnabledFor(logging.INFO): | ||
output = "statement:\n%s\nparameters: %s\nplan:\n " % (_indent(_beautify_sql(statement)), | ||
repr(parameters)) | ||
output += '\n '.join([row[0] for row in conn.engine.execute("EXPLAIN ANALYZE " + statement, | ||
parameters)]) | ||
LOG.info(output) | ||
|
||
|
||
def init(config): | ||
""" | ||
Install a pyramid event handler that adds the request information | ||
""" | ||
if 'SQL_PROFILER_SECRET' in os.environ: | ||
config.add_route("sql_profiler", r"/sql_profiler", request_method="GET") | ||
config.add_view(_sql_profiler_view, route_name="sql_profiler", renderer="json", http_cache=0) | ||
LOG.info("Enabled the /sql_profiler API") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters