-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathdb_cleanup.py
More file actions
392 lines (333 loc) · 16 KB
/
db_cleanup.py
File metadata and controls
392 lines (333 loc) · 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# -------------------------------------------------------------------------
#
# Part of the CodeChecker project, under the Apache License v2.0 with
# LLVM Exceptions. See LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# -------------------------------------------------------------------------
"""
Contains housekeeping routines that are used to remove expired, obsolete,
or dangling records from the database.
"""
from datetime import datetime, timedelta
from typing import Dict
import sqlalchemy
from sqlalchemy import union
from codechecker_api.codeCheckerDBAccess_v6.ttypes import Severity
from codechecker_common import util
from codechecker_common.logger import get_logger
from .database import DBSession
from .run_db_model import \
AnalysisInfo, AnalysisInfoFile, \
BugPathEvent, BugReportPoint, \
Comment, Checker, \
File, FileContent, \
Report, ReportAnalysisInfo, RunHistoryAnalysisInfo, RunLock
LOG = get_logger('server')
RUN_LOCK_TIMEOUT_IN_DATABASE = 30 * 60 # 30 minutes.
SQLITE_LIMIT_COMPOUND_SELECT = 500
def remove_expired_data(product):
"""Remove information that has timed out from the database."""
remove_expired_run_locks(product)
def remove_unused_data(product):
"""Remove dangling data (files, comments, etc.) from the database."""
remove_unused_files(product)
remove_unused_comments(product)
remove_unused_analysis_info(product)
def update_contextual_data(product, context):
"""
Updates information in the database that comes from potentially changing
contextual configuration of the server package.
"""
upgrade_severity_levels(product, context.checker_labels)
def remove_expired_run_locks(product):
with DBSession(product.session_factory) as session:
LOG.debug("[%s] Garbage collection of expired run locks started...",
product.endpoint)
try:
locks_expired_at = datetime.now() - timedelta(
seconds=RUN_LOCK_TIMEOUT_IN_DATABASE)
count = session.query(RunLock) \
.filter(RunLock.locked_at < locks_expired_at) \
.delete(synchronize_session=False)
if count:
LOG.debug("%d expired run locks deleted.", count)
session.commit()
LOG.debug("[%s] Garbage collection of expired run locks "
"finished.", product.endpoint)
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError) as ex:
LOG.error("[%s] Failed to remove expired run locks: %s",
product.endpoint, str(ex))
def remove_unused_files(product):
# File deletion is a relatively slow operation due to database cascades.
# Removing files in big chunks prevents reaching a potential database
# statement timeout. This hard-coded value is a safe choice according to
# some measurements. Maybe this could be a command-line parameter. But in
# the long terms we are planning to reduce cascade deletes by redesigning
# bug_path_events and bug_report_points tables.
chunk_size = 500_000
with DBSession(product.session_factory) as session:
LOG.debug("[%s] Garbage collection of dangling files started...",
product.endpoint)
try:
bpe_files = session.query(BugPathEvent.file_id) \
.group_by(BugPathEvent.file_id)
brp_files = session.query(BugReportPoint.file_id) \
.group_by(BugReportPoint.file_id)
files_to_delete = session.query(File.id) \
.filter(File.id.notin_(bpe_files), File.id.notin_(brp_files))
files_to_delete = map(lambda x: x[0], files_to_delete)
total_count = 0
for chunk in util.chunks(iter(files_to_delete), chunk_size):
q = session.query(File) \
.filter(File.id.in_(chunk))
count = q.delete(synchronize_session=False)
if count:
total_count += count
if total_count:
LOG.debug("%d dangling files deleted.", total_count)
files = union(
session.query(File.content_hash),
session.query(AnalysisInfoFile.content_hash))
session.query(FileContent) \
.filter(FileContent.content_hash.notin_(files)) \
.delete(synchronize_session=False)
session.commit()
LOG.debug("[%s] Garbage collection of dangling files finished.",
product.endpoint)
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError) as ex:
LOG.error("[%s] Failed to remove unused files: %s",
product.endpoint, str(ex))
def remove_unused_comments(product):
with DBSession(product.session_factory) as session:
LOG.debug("[%s] Garbage collection of dangling comments started...",
product.endpoint)
try:
sub = session.query(Comment.id) \
.join(Report,
Comment.bug_hash == Report.bug_id,
isouter=True) \
.filter(Report.id.is_(None))
count = session.query(Comment) \
.filter(Comment.id.in_(sub)) \
.delete(synchronize_session=False)
if count:
LOG.debug("%d dangling comments deleted.", count)
session.commit()
LOG.debug("[%s] Garbage collection of dangling comments "
"finished.", product.endpoint)
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError) as ex:
LOG.error("[%s] Failed to remove dangling comments: %s",
product.endpoint, str(ex))
def remove_unused_analysis_info(product):
with DBSession(product.session_factory) as session:
LOG.debug("[%s] Garbage collection of dangling analysis info "
"started...", product.endpoint)
try:
# Disable foreign key constraints to avoid slow delete in Postgres
if session.bind.dialect.name == "postgresql":
rh_ai_foreign_keys = get_foreign_keys(
session,
RunHistoryAnalysisInfo.name,
AnalysisInfo.__tablename__
)
drop_foreign_keys(session,
RunHistoryAnalysisInfo.name,
rh_ai_foreign_keys)
rep_ai_foreign_keys = get_foreign_keys(
session,
ReportAnalysisInfo.name,
AnalysisInfo.__tablename__
)
drop_foreign_keys(session,
ReportAnalysisInfo.name,
rep_ai_foreign_keys)
to_delete = session.query(AnalysisInfo.id) \
.join(
RunHistoryAnalysisInfo,
RunHistoryAnalysisInfo.c.analysis_info_id ==
AnalysisInfo.id,
isouter=True) \
.join(
ReportAnalysisInfo,
ReportAnalysisInfo.c.analysis_info_id == AnalysisInfo.id,
isouter=True) \
.filter(
RunHistoryAnalysisInfo.c.analysis_info_id.is_(None),
ReportAnalysisInfo.c.analysis_info_id.is_(None))
count = session.query(AnalysisInfo) \
.filter(AnalysisInfo.id.in_(to_delete)) \
.delete(synchronize_session=False)
if count:
LOG.debug("[%s] %d dangling analysis info deleted.",
product.endpoint, count)
session.commit()
LOG.debug("[%s] Garbage collection of dangling analysis info "
"finished.", product.endpoint)
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError) as ex:
LOG.error("[%s] Failed to remove dangling analysis info: %s",
product.endpoint, str(ex))
finally:
# Re-enable foreign key constraints
if session.bind.dialect.name == "postgresql":
add_foreign_keys(session,
RunHistoryAnalysisInfo.name,
rh_ai_foreign_keys)
add_foreign_keys(session,
ReportAnalysisInfo.name,
rep_ai_foreign_keys)
def upgrade_severity_levels(product, checker_labels):
"""
Updates the potentially changed severities to reflect the data in the
current label configuration files.
"""
with DBSession(product.session_factory) as session:
LOG.debug("[%s] Upgrading severity levels started...",
product.endpoint)
try:
count = 0
for analyzer in sorted(checker_labels.get_analyzers()):
checkers_for_analyzer_in_database = session \
.query(Checker.id,
Checker.checker_name,
Checker.severity) \
.filter(Checker.analyzer_name == analyzer) \
.all()
for checker_row in checkers_for_analyzer_in_database:
checker: str = checker_row.checker_name
old_severity_db: int = checker_row.severity
try:
old_severity: str = \
Severity._VALUES_TO_NAMES[old_severity_db]
except KeyError:
LOG.error("[%s] Checker '%s/%s' contains invalid "
"severity %d, considering as if "
"'UNSPECIFIED' (0)!",
product.endpoint,
analyzer, checker,
old_severity_db)
old_severity_db, old_severity = 0, "UNSPECIFIED"
new_severity: str = \
checker_labels.severity(checker, analyzer)
if old_severity == new_severity:
continue
if new_severity == "UNSPECIFIED":
# No exact match for the checker's name in the
# label config for the analyzer. This can mean that
# the records are older than a change in the checker
# naming scheme (e.g., cppchecker results pre-2021).
LOG.warning("[%s] Checker '%s/%s' (database severity: "
"'%s' (%d)) does not have a corresponding "
"entry in the label config file.",
product.endpoint,
analyzer, checker,
old_severity, old_severity_db)
new_sev_attempts: Dict[str, str] = {
chk_name: severity
for chk_name, severity in
((name_attempt,
checker_labels.severity(name_attempt, analyzer))
for name_attempt in [
f"{analyzer}.{checker}",
f"{analyzer}-{checker}",
f"{analyzer}/{checker}"
])
if severity != "UNSPECIFIED"
}
if len(new_sev_attempts) == 0:
LOG.debug("[%s] %s/%s: Keeping the old severity "
"intact...",
product.endpoint, analyzer, checker)
continue
if len(new_sev_attempts) >= 2 and \
len(set(new_sev_attempts.values())) >= 2:
LOG.error("[%s] %s/%s: Multiple similar checkers "
"WITH CONFLICTING SEVERITIES were "
"found instead: %s",
product.endpoint,
analyzer, checker,
str(list(new_sev_attempts.items())))
LOG.debug("[%s] %s/%s: Keeping the old severity "
"intact...",
product.endpoint, analyzer, checker)
continue
if len(set(new_sev_attempts.values())) == 1:
attempted_name, new_severity = \
next(iter(sorted(new_sev_attempts.items())))
LOG.info("[%s] %s/%s: Found similar checker "
"'%s/%s' (severity: '%s'), using this "
"for the upgrade.",
product.endpoint,
analyzer, checker,
analyzer, attempted_name,
new_severity)
if old_severity == new_severity:
continue
new_severity_db: int = \
Severity._NAMES_TO_VALUES[new_severity]
LOG.info("[%s] Upgrading the severity of checker "
"'%s/%s' from '%s' (%d) to '%s' (%d).",
product.endpoint,
analyzer, checker,
old_severity, old_severity_db,
new_severity, new_severity_db)
session.query(Checker) \
.filter(Checker.id == checker_row.id) \
.update({Checker.severity: new_severity_db})
count += 1
session.flush()
if count:
LOG.debug("[%s] %d checker severities upgraded.",
product.endpoint, count)
session.commit()
LOG.debug("[%s] Upgrading severity levels finished.",
product.endpoint)
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError) as ex:
LOG.error("[%s] Failed to upgrade severity levels: %s",
product.endpoint, str(ex))
def get_foreign_keys(
session,
table_name,
referred_table_name,
constraint_name=None):
inspector = sqlalchemy.inspect(session.connection())
foreign_keys = list(filter(
lambda fk: fk["referred_table"] == referred_table_name
and (fk["name"] == constraint_name if constraint_name else True),
inspector.get_foreign_keys(table_name)
))
return foreign_keys
def drop_foreign_keys(session, table_name, foreign_keys):
for fk in foreign_keys:
session.execute(sqlalchemy.text(
f"ALTER TABLE {table_name} "
f"DROP CONSTRAINT {fk['name']};"
))
session.commit()
def add_foreign_keys(session, table_name, foreign_keys):
for fk in foreign_keys:
constraint_name = fk["name"]
constrained_columns = ", ".join(fk["constrained_columns"])
referred_table = fk["referred_table"]
referred_columns = ", ".join(fk["referred_columns"])
if get_foreign_keys(
session,
table_name,
referred_table,
constraint_name
):
LOG.warning(f"Cannot add {constraint_name} constraint, "
"it is already exists.")
continue
session.execute(sqlalchemy.text(
f"ALTER TABLE {table_name} "
f"ADD CONSTRAINT {constraint_name} "
f"FOREIGN KEY ({constrained_columns}) "
f"REFERENCES {referred_table}({referred_columns});"
))
session.commit()