Debian Codegraph @

cylc/flow/main_loop/log_db.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Log all database transactions.
17
18 .. note::
19
20 This plugin is for Cylc developers debugging database issues.
21
22 Writes an SQL file into the workflow run directory on shutown.
23
24 """
25
26 import logging
27 from logging.handlers import RotatingFileHandler
28 from pathlib import Path
29
30 import sqlparse
31
32 from cylc.flow import CYLC_LOG
33 from cylc.flow.main_loop import (startup, shutdown)
34
35
36 DB_LOG = logging.getLogger(f'{CYLC_LOG}-db')
37
38
39 def _format(sql_string):
40 """Pretty print an SQL statement."""
41 return '\n'.join(
42 sqlparse.format(
43 statement,
44 reindent_aligned=True,
45 use_space_around_operators=True,
46 strip_comments=True,
47 keyword_case='upper',
48 identifier_case='lower',
49 )
50 for statement in sqlparse.split(sql_string)
51 ) + '\n'
52
53
54 def _log(sql_string):
55 """Log a SQL string."""
56 DB_LOG.info(_format(sql_string))
57
58
59 def _patch_db_connect(db_connect_method):
60 """Patch the workflow DAO to configure logging.
61
62 We patch the connect method so that any subsequent re-connections
63 are also patched.
64 """
65 def _inner(*args, **kwargs):
66 conn = db_connect_method(*args, **kwargs)
67 conn.set_trace_callback(_log)
68 return conn
69 return _inner
70
71
72 @startup
73 async def init(scheduler, state):
74 # configure log handler
75 DB_LOG.setLevel(logging.INFO)
76 handler = RotatingFileHandler(
77 str(Path(scheduler.workflow_run_dir, f'{__name__}.sql')),
78 maxBytes=1000000,
79 )
80 state['log_handler'] = handler
81 DB_LOG.addHandler(handler)
82
83 # configure the DB manager to log all DB operations
84 scheduler.workflow_db_mgr.pri_dao.connect = _patch_db_connect(
85 scheduler.workflow_db_mgr.pri_dao.connect
86 )
87
88
89 @shutdown
90 async def stop(scheduler, state):
91 handler = state.get('log_handler')
92 if handler:
93 handler.close()