Skip to content

Commit cd287ca

Browse files
barnabasdomozibruntib
authored andcommitted
Disable PostgreSQL timeouts during schema migration and garbage collection
During garbage collection and schema migration, we want all transactions to run to completion. These include long-running queries that can currently be aborted if the server has a short statement_timeout or idle_in_transaction_session_timeout configured.
1 parent f63a513 commit cd287ca

4 files changed

Lines changed: 102 additions & 35 deletions

File tree

‎web/server/codechecker_server/database/database.py‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@
1818

1919
from alembic.util import CommandError
2020
import sqlalchemy
21-
from sqlalchemy import event
21+
from sqlalchemy import event, text, Connection as SA_Connection
2222
from sqlalchemy.engine.url import URL, make_url
23-
from sqlalchemy.orm import sessionmaker
23+
from sqlalchemy.orm import sessionmaker, Session as SA_Session
2424
from sqlalchemy.pool import NullPool
25-
from sqlalchemy.engine import Engine
25+
from sqlalchemy.engine import Engine as SA_Engine
2626

2727
from codechecker_api_shared.ttypes import DBStatus
2828

@@ -66,6 +66,12 @@ class DBContext:
6666
setup was successful.
6767
"""
6868

69+
sql_server: "SQLServer"
70+
db_engine: SA_Engine | None
71+
db_session: SA_Session | None
72+
db_connection: SA_Connection | None
73+
db_error: int | None
74+
6975
def __init__(self, sql_server: "SQLServer"):
7076
self.sql_server = sql_server
7177
self.db_engine = None
@@ -91,23 +97,23 @@ def __enter__(self):
9197
return self
9298

9399
@property
94-
def error(self):
100+
def error(self) -> int | None:
95101
# Indicate that there is some problem with the
96102
# database setup.
97103
return self.db_error
98104

99105
@property
100-
def engine(self):
106+
def engine(self) -> SA_Engine | None:
101107
# Get the configured engine.
102108
return self.db_engine
103109

104110
@property
105-
def connection(self):
111+
def connection(self) -> SA_Connection | None:
106112
# Get the configured connection.
107113
return self.db_connection
108114

109115
@property
110-
def session(self):
116+
def session(self) -> SA_Session | None:
111117
# Get the configured session.
112118
return self.db_session
113119

@@ -305,6 +311,8 @@ def upgrade(self):
305311
if db.error:
306312
return db.error
307313

314+
assert db.session
315+
308316
LOG.debug("Create/update database schema for %s",
309317
self.__model_meta['identifier'])
310318

@@ -313,6 +321,8 @@ def upgrade(self):
313321
cfg.attributes["connection"] = db.connection
314322
cfg.attributes["database_name"] = self.name_in_log
315323

324+
disable_transaction_timeouts(db.session)
325+
316326
command.upgrade(cfg, "head")
317327
db.session.commit()
318328

@@ -371,7 +381,7 @@ def _register_engine_hooks(self, engine):
371381
by create_engine.
372382
"""
373383

374-
def create_engine(self) -> Engine:
384+
def create_engine(self) -> SA_Engine:
375385
"""
376386
Creates a new SQLAlchemy engine.
377387
"""
@@ -608,3 +618,17 @@ def escape_like(string, escape_char='*'):
608618
return string.replace(escape_char, escape_char * 2) \
609619
.replace('%', escape_char + '%') \
610620
.replace('_', escape_char + '_')
621+
622+
623+
def disable_transaction_timeouts(db_session: SA_Session):
624+
"""
625+
Disable PostgreSQL timeouts only for the current transaction.
626+
This is typically used during long-running queries that need to complete,
627+
e.g. garbage collection and schema migration.
628+
SQLite has no statement_timeout or idle_in_transaction_session_timeout.
629+
"""
630+
if db_session.get_bind().dialect.name == "postgresql":
631+
db_session.execute(
632+
text("SET LOCAL statement_timeout = 0"))
633+
db_session.execute(
634+
text("SET LOCAL idle_in_transaction_session_timeout = 0"))

‎web/server/codechecker_server/database/db_cleanup.py‎

Lines changed: 65 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from codechecker_common import util
2222
from codechecker_common.logger import get_logger
2323

24-
from .database import DBSession
24+
from .database import DBSession, disable_transaction_timeouts
2525
from .run_db_model import \
2626
AnalysisInfo, AnalysisInfoFile, \
2727
CheckerSet, \
@@ -36,32 +36,38 @@
3636
SQLITE_LIMIT_COMPOUND_SELECT = 500
3737

3838

39-
def remove_expired_data(product):
39+
def remove_expired_data(product, disable_database_timeouts: bool = False):
4040
"""Remove information that has timed out from the database."""
41-
remove_expired_run_locks(product)
41+
remove_expired_run_locks(product, disable_database_timeouts)
4242

4343

44-
def remove_unused_data(product):
44+
def remove_unused_data(product, disable_database_timeouts: bool = False):
4545
"""Remove dangling data (files, comments, etc.) from the database."""
46-
remove_unused_files(product)
47-
remove_unused_comments(product)
48-
remove_unused_analysis_info(product)
49-
remove_unused_checker_sets(product)
46+
remove_unused_files(product, disable_database_timeouts)
47+
remove_unused_comments(product, disable_database_timeouts)
48+
remove_unused_analysis_info(product, disable_database_timeouts)
49+
remove_unused_checker_sets(product, disable_database_timeouts)
5050

5151

52-
def update_contextual_data(product, context):
52+
def update_contextual_data(product, context,
53+
disable_database_timeouts: bool = False):
5354
"""
5455
Updates information in the database that comes from potentially changing
5556
contextual configuration of the server package.
5657
"""
57-
upgrade_severity_levels(product, context.checker_labels)
58+
upgrade_severity_levels(product, context.checker_labels,
59+
disable_database_timeouts)
5860

5961

60-
def remove_expired_run_locks(product):
62+
def remove_expired_run_locks(product,
63+
disable_database_timeouts: bool = False):
6164
with DBSession(product.session_factory) as session:
6265
LOG.debug("[%s] Garbage collection of expired run locks started...",
6366
product.endpoint)
6467
try:
68+
if disable_database_timeouts:
69+
disable_transaction_timeouts(session)
70+
6571
locks_expired_at = datetime.now() - timedelta(
6672
seconds=RUN_LOCK_TIMEOUT_IN_DATABASE)
6773

@@ -81,7 +87,7 @@ def remove_expired_run_locks(product):
8187
product.endpoint, str(ex))
8288

8389

84-
def remove_unused_files(product):
90+
def remove_unused_files(product, disable_database_timeouts: bool = False):
8591
# File deletion is a relatively slow operation due to database cascades.
8692
# Removing files in big chunks prevents reaching a potential database
8793
# statement timeout. This hard-coded value is a safe choice according to
@@ -93,6 +99,9 @@ def remove_unused_files(product):
9399
LOG.debug("[%s] Garbage collection of dangling files started...",
94100
product.endpoint)
95101
try:
102+
if disable_database_timeouts:
103+
disable_transaction_timeouts(session)
104+
96105
files = session.query(ReportPathDataFile.c.file_id) \
97106
.group_by(ReportPathDataFile.c.file_id)
98107

@@ -128,11 +137,14 @@ def remove_unused_files(product):
128137
product.endpoint, str(ex))
129138

130139

131-
def remove_unused_comments(product):
140+
def remove_unused_comments(product, disable_database_timeouts: bool = False):
132141
with DBSession(product.session_factory) as session:
133142
LOG.debug("[%s] Garbage collection of dangling comments started...",
134143
product.endpoint)
135144
try:
145+
if disable_database_timeouts:
146+
disable_transaction_timeouts(session)
147+
136148
sub = session.query(Comment.id) \
137149
.join(Report,
138150
Comment.bug_hash == Report.bug_id,
@@ -154,7 +166,8 @@ def remove_unused_comments(product):
154166
product.endpoint, str(ex))
155167

156168

157-
def remove_unused_analysis_info(product):
169+
def remove_unused_analysis_info(product,
170+
disable_database_timeouts: bool = False):
158171
with DBSession(product.session_factory) as session:
159172
LOG.debug("[%s] Garbage collection of dangling analysis info "
160173
"started...", product.endpoint)
@@ -168,7 +181,8 @@ def remove_unused_analysis_info(product):
168181
)
169182
drop_foreign_keys(session,
170183
RunHistoryAnalysisInfo.name,
171-
rh_ai_foreign_keys)
184+
rh_ai_foreign_keys,
185+
disable_database_timeouts)
172186

173187
rep_ai_foreign_keys = get_foreign_keys(
174188
session,
@@ -177,7 +191,11 @@ def remove_unused_analysis_info(product):
177191
)
178192
drop_foreign_keys(session,
179193
ReportAnalysisInfo.name,
180-
rep_ai_foreign_keys)
194+
rep_ai_foreign_keys,
195+
disable_database_timeouts)
196+
197+
if disable_database_timeouts:
198+
disable_transaction_timeouts(session)
181199

182200
to_delete = session.query(AnalysisInfo.id) \
183201
.join(
@@ -215,17 +233,23 @@ def remove_unused_analysis_info(product):
215233
if session.bind.dialect.name == "postgresql":
216234
add_foreign_keys(session,
217235
RunHistoryAnalysisInfo.name,
218-
rh_ai_foreign_keys)
236+
rh_ai_foreign_keys,
237+
disable_database_timeouts)
219238
add_foreign_keys(session,
220239
ReportAnalysisInfo.name,
221-
rep_ai_foreign_keys)
240+
rep_ai_foreign_keys,
241+
disable_database_timeouts)
222242

223243

224-
def remove_unused_checker_sets(product):
244+
def remove_unused_checker_sets(product,
245+
disable_database_timeouts: bool = False):
225246
with DBSession(product.session_factory) as session:
226247
LOG.debug("[%s] Garbage collection of checker sets started...",
227248
product.endpoint)
228249
try:
250+
if disable_database_timeouts:
251+
disable_transaction_timeouts(session)
252+
229253
used_checker_sets = session.query(AnalysisInfo.checker_set_id) \
230254
.filter(AnalysisInfo.checker_set_id.is_not(None)) \
231255
.group_by(AnalysisInfo.checker_set_id)
@@ -244,7 +268,8 @@ def remove_unused_checker_sets(product):
244268
product.endpoint, str(ex))
245269

246270

247-
def upgrade_severity_levels(product, checker_labels):
271+
def upgrade_severity_levels(product, checker_labels,
272+
disable_database_timeouts: bool = False):
248273
"""
249274
Updates the potentially changed severities to reflect the data in the
250275
current label configuration files.
@@ -253,6 +278,9 @@ def upgrade_severity_levels(product, checker_labels):
253278
LOG.debug("[%s] Upgrading severity levels started...",
254279
product.endpoint)
255280
try:
281+
if disable_database_timeouts:
282+
disable_transaction_timeouts(session)
283+
256284
count = 0
257285
for analyzer in sorted(checker_labels.get_analyzers()):
258286
checkers_for_analyzer_in_database = session \
@@ -382,7 +410,12 @@ def get_foreign_keys(
382410
return foreign_keys
383411

384412

385-
def drop_foreign_keys(session, table_name, foreign_keys):
413+
def drop_foreign_keys(session, table_name, foreign_keys,
414+
disable_database_timeouts: bool = False):
415+
416+
if disable_database_timeouts:
417+
disable_transaction_timeouts(session)
418+
386419
for fk in foreign_keys:
387420
session.execute(sqlalchemy.text(
388421
f"ALTER TABLE {table_name} "
@@ -391,7 +424,12 @@ def drop_foreign_keys(session, table_name, foreign_keys):
391424
session.commit()
392425

393426

394-
def add_foreign_keys(session, table_name, foreign_keys):
427+
def add_foreign_keys(session, table_name, foreign_keys,
428+
disable_database_timeouts: bool = False):
429+
430+
if disable_database_timeouts:
431+
disable_transaction_timeouts(session)
432+
395433
for fk in foreign_keys:
396434
constraint_name = fk["name"]
397435
constrained_columns = ", ".join(fk["constrained_columns"])
@@ -419,7 +457,8 @@ def add_foreign_keys(session, table_name, foreign_keys):
419457

420458
def delete_expired_auth_sessions(config_db_sessionmaker: sessionmaker,
421459
session_lifetime: int,
422-
user_name: Optional[str]):
460+
user_name: str | None,
461+
disable_database_timeouts: bool = False):
423462
"""
424463
Cleanup expired auth_sessions from the config database.
425464
If 'user_name' is specified, we only remove expired auth_sessions
@@ -435,6 +474,9 @@ def delete_expired_auth_sessions(config_db_sessionmaker: sessionmaker,
435474

436475
with DBSession(config_db_sessionmaker) as session:
437476
try:
477+
if disable_database_timeouts:
478+
disable_transaction_timeouts(session)
479+
438480
cutoff_date = (datetime.now() - timedelta(
439481
seconds=session_lifetime))
440482

‎web/server/codechecker_server/product.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,9 +198,9 @@ def cleanup_run_db(self):
198198
"""
199199
LOG.info("[%s] Garbage collection started...", self.endpoint)
200200

201-
db_cleanup.remove_expired_data(self)
202-
db_cleanup.remove_unused_data(self)
203-
db_cleanup.update_contextual_data(self, self.__context)
201+
db_cleanup.remove_expired_data(self, True)
202+
db_cleanup.remove_unused_data(self, True)
203+
db_cleanup.update_contextual_data(self, self.__context, True)
204204

205205
LOG.info("[%s] Garbage collection finished.", self.endpoint)
206206
return True

‎web/server/codechecker_server/server.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1001,7 +1001,8 @@ def cleanup_config_database(self):
10011001
db_cleanup.delete_expired_auth_sessions(
10021002
self.config_session,
10031003
self.manager.session_lifetime_duration,
1004-
None)
1004+
None,
1005+
True)
10051006
LOG.info("Finished garbage collection on the config database.")
10061007

10071008

0 commit comments

Comments
 (0)