-
Notifications
You must be signed in to change notification settings - Fork 457
Expand file tree
/
Copy pathmass_store_run.py
More file actions
1823 lines (1564 loc) · 75.3 KB
/
mass_store_run.py
File metadata and controls
1823 lines (1564 loc) · 75.3 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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -------------------------------------------------------------------------
#
# 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
#
# -------------------------------------------------------------------------
"""
Implementation of the ``massStoreRunAsynchronous()`` API function that store
run data to a product's report database.
Called via `report_server`, but factored out here for readability.
"""
import base64
from collections import defaultdict
from datetime import datetime, timedelta
import fnmatch
import hashlib
from hashlib import sha256
import json
import os
from pathlib import Path
import sqlalchemy
from sqlalchemy.orm import Session as SA_Session
import tempfile
import time
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union, \
cast
import zipfile
import zlib
from codechecker_api_shared.ttypes import DBStatus, ErrorCode, RequestFailed
from codechecker_api.codeCheckerDBAccess_v6 import ttypes
from codechecker_common import skiplist_handler
from codechecker_common.logger import get_logger
from codechecker_common.review_status_handler import ReviewStatusHandler, \
SourceReviewStatus
from codechecker_common.util import format_size, load_json, path_for_fake_root
from codechecker_report_converter import twodim
from codechecker_report_converter.util import trim_path_prefixes
from codechecker_report_converter.report import \
FakeChecker, Report, UnknownChecker, report_file
from codechecker_report_converter.report.hash import get_report_path_hash
from ..database import db_cleanup
from ..database.config_db_model import Product
from ..database.database import DBSession
from ..database.run_db_model import \
AnalysisInfo, AnalysisInfoChecker, AnalysisInfoFile, AnalyzerStatistic, \
BugPathEvent, BugReportPoint, \
Checker, \
ExtendedReportData, \
File, FileContent, \
Report as DBReport, ReportAnnotations, ReviewStatus as ReviewStatusRule, \
Run, RunLock as DBRunLock, RunHistory, \
SourceComponent, SourceComponentFile
from ..metadata import checker_is_unavailable, MetadataInfoParser
from .report_annotations import report_annotation_types
from ..product import Product as ServerProduct
from ..session_manager import SessionManager
from ..task_executors.abstract_task import AbstractTask, TaskCancelHonoured
from ..task_executors.task_manager import TaskManager
from .thrift_enum_helper import report_extended_data_type_str
LOG = get_logger('server')
class StepLog:
"""
Simple context manager that logs an arbitrary step's comment and time
taken annotated with a run name.
"""
def __init__(self, run_name: str, message: str):
self._run_name = run_name
self._msg = message
self._start_time = time.time()
def __enter__(self, *_args):
LOG.info("[%s] %s...", self._run_name, self._msg)
def __exit__(self, *_args):
LOG.info("[%s] %s. Done. (Duration: %.2f sec)",
self._run_name, self._msg, time.time() - self._start_time)
class RunLock:
def __init__(self, session: DBSession, run_name: str):
self.__session = session
self.__run_name = run_name
self.__run_lock = None
def __enter__(self, *_args):
# Load the lock record for "FOR UPDATE" so that the transaction that
# handles the run's store operations has a lock on the database row
# itself.
self.__run_lock = self.__session.query(DBRunLock) \
.filter(DBRunLock.name == self.__run_name) \
.with_for_update(nowait=True) \
.one()
# Do *NOT* remove this seemingly dummy print. The query functions on
# result in a **proxy** object, essentially a weak pointer, without(!)
# the execution of any underlying SQL statements. Which means that
# without the evaluation of the member of this query (with the
# . operator) there would be no actual DBMS-level lock in place.
# (Not having debug logs enabled is not a problem: the evaluation of
# the arguments still take place even if the logging configuration
# prevents the actual printing of the log line.)
LOG.debug("Acquired exclusive lock for run '%s' that was originally "
"locked at '%s'.",
self.__run_name, self.__run_lock.locked_at)
return self
def __exit__(self, *_args):
self.__run_lock = None
self.__session = None
def store_run_lock_in_db(self, associated_user: str):
"""
Stores a `DBRunLock` record for the given run name into the database.
"""
try:
# If the run can be stored, we need to lock it first. If there is
# already a lock in the database for the given run name which is
# expired and multiple processes are trying to get this entry from
# the database for update we may get the following exception:
# could not obtain lock on row in relation "run_locks"
# This is the reason why we have to wrap this query to a try/except
# block.
run_lock: Optional[DBRunLock] = self.__session.query(DBRunLock) \
.filter(DBRunLock.name == self.__run_name) \
.with_for_update(nowait=True) \
.one_or_none()
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError) as ex:
LOG.error("Failed to get run lock for '%s': %s",
self.__run_name, ex)
raise RequestFailed(
ErrorCode.DATABASE,
"Someone is already storing to the same run. Please wait "
"while the other storage is finished and try it again.") \
from ex
if not run_lock:
# If there is no lock record for the given run name, the run
# is not locked -> create a new lock.
self.__session.add(DBRunLock(self.__run_name, associated_user))
LOG.debug("Acquiring 'run_lock' for '%s' on run '%s' ...",
associated_user, self.__run_name)
elif run_lock.has_expired(
db_cleanup.RUN_LOCK_TIMEOUT_IN_DATABASE):
# There can be a lock in the database, which has already
# expired. In this case, we assume that the previous operation
# has failed, and thus, we can re-use the already present lock.
run_lock.touch()
run_lock.username = associated_user
LOG.debug("Reusing existing, stale 'run_lock' record on "
"run '%s' ...",
self.__run_name)
else:
# In case the lock exists and it has not expired, we must
# consider the run a locked one.
when = run_lock.when_expires(
db_cleanup.RUN_LOCK_TIMEOUT_IN_DATABASE)
username = run_lock.username or "another user"
LOG.info("Refusing to store into run '%s' as it is locked by "
"%s. Lock will expire at '%s'.",
self.__run_name, username, when)
raise RequestFailed(
ErrorCode.DATABASE,
f"The run named '{self.__run_name}' is being stored into by "
f"{username}. If the other store operation has failed, this "
f"lock will expire at '{when}'.")
# At any rate, if the lock has been created or updated, commit it
# into the database.
try:
self.__session.commit()
except (sqlalchemy.exc.IntegrityError,
sqlalchemy.orm.exc.StaleDataError) as ex:
# The commit of this lock can fail.
#
# In case two store ops attempt to lock the same run name at the
# same time, committing the lock in the transaction that commits
# later will result in an IntegrityError due to the primary key
# constraint.
#
# In case two store ops attempt to lock the same run name with
# reuse and one of the operation hangs long enough before COMMIT
# so that the other operation commits and thus removes the lock
# record, StaleDataError is raised. In this case, also consider
# the run locked, as the data changed while the transaction was
# waiting, as another run wholly completed.
LOG.info("Run '%s' got locked while current transaction "
"tried to acquire a lock. Considering run as locked.",
self.__run_name)
raise RequestFailed(
ErrorCode.DATABASE,
f"The run named '{self.__run_name}' is being stored into by "
"another user.") from ex
LOG.debug("Successfully acquired 'run_lock' for '%s' on run '%s'.",
associated_user, self.__run_name)
def drop_run_lock_from_db(self):
"""Remove the run_lock row from the database for the current run."""
# Using with_for_update() here so the database (in case it supports
# this operation) locks the lock record's row from any other access.
LOG.debug("Releasing 'run_lock' from run '%s' ...")
run_lock: Optional[DBRunLock] = self.__session.query(DBRunLock) \
.filter(DBRunLock.name == self.__run_name) \
.with_for_update(nowait=True).one()
if not run_lock:
raise KeyError(
f"No 'run_lock' in database for run '{self.__run_name}'")
locked_at = run_lock.locked_at
username = run_lock.username
self.__session.delete(run_lock)
self.__session.commit()
LOG.debug("Released 'run_lock' (originally acquired by '%s' on '%s') "
"from run '%s'.",
username, str(locked_at), self.__run_name)
def unzip(run_name: str, b64zip: str, output_dir: Path) -> int:
"""
This function unzips a Base64 encoded and ZLib-compressed ZIP file.
This ZIP is extracted to a temporary directory and the ZIP is then deleted.
The function returns the size of the extracted decompressed ZIP file.
"""
if not b64zip:
return 0
with tempfile.NamedTemporaryFile(
suffix=".zip", dir=output_dir) as zip_file:
LOG.debug("Decompressing input massStoreRun() ZIP to '%s' ...",
zip_file.name)
start_time = time.time()
zip_file.write(zlib.decompress(base64.b64decode(b64zip)))
zip_file.flush()
end_time = time.time()
size = os.stat(zip_file.name).st_size
LOG.debug("Decompressed input massStoreRun() ZIP '%s' -> '%s' "
"(compression ratio: %.2f%%) in '%s'.",
format_size(len(b64zip)), format_size(size),
(size / len(b64zip)),
timedelta(seconds=end_time - start_time))
with StepLog(run_name, "Extract massStoreRun() ZIP contents"), \
zipfile.ZipFile(zip_file, 'r', allowZip64=True) as zip_handle:
LOG.debug("Extracting massStoreRun() ZIP '%s' to '%s' ...",
zip_file.name, output_dir)
try:
zip_handle.extractall(output_dir)
return size
except Exception:
LOG.error("Failed to extract received ZIP.")
import traceback
traceback.print_exc()
raise
def get_file_content(file_path: str) -> bytes:
"""Return the file content for the given `file_path`."""
with open(file_path, 'rb') as f:
return f.read()
def assign_file_to_source_components(
session: DBSession,
file_id: int,
filepath: str
):
"""
Checks all Source Components and links the file if it matches.
"""
components = session.query(SourceComponent).all()
associations = []
from .report_server import get_component_values
for component in components:
include, skip = get_component_values(component)
# If no patterns are defined, the component matches nothing.
if not skip and not include:
continue
is_included = False
if include:
for pattern in include:
if fnmatch.fnmatch(filepath, pattern):
is_included = True
break
else:
# If only skip is defined, it matches everything except skips.
is_included = True
is_skipped = False
if skip:
for pattern in skip:
if fnmatch.fnmatch(filepath, pattern):
is_skipped = True
break
if is_included and not is_skipped:
associations.append({
'source_component_name': component.name,
'file_id': file_id
})
if associations:
session.bulk_insert_mappings(SourceComponentFile, associations)
def add_file_record(
session: DBSession,
file_path: str,
content_hash: str
) -> Optional[int]:
"""
Add the necessary file record pointing to an already existing content.
Returns the added file record id or None, if the content_hash is not
found.
This function must not be called between add_checker_run() and
finish_checker_run() functions when SQLite database is used!
add_checker_run() function opens a transaction which is closed by
finish_checker_run() and since SQLite doesn't support parallel
transactions, this API call will wait until the other transactions
finish. In the meantime the run adding transaction times out.
This function doesn't insert blame info in the File objects because those
are added by __add_blame_info(). In previous CodeChecker versions git info
was not stored at all, so upgrading to a new CodeChecker results the
storage of git blame info even for files that are already stored. For this
reason we can't avoid an update on File and FileContent tables, but we can
avoid double reading of blame info json files.
"""
file_record = session.query(File) \
.filter(File.content_hash == content_hash,
File.filepath == file_path) \
.one_or_none()
if file_record:
return file_record.id
try:
# Parallel storage of runs containing common file paths results a
# "duplicate key violation" error. This is handled by CodeChecker, so
# practically it causes no problem. The INSERT command of the second
# transaction will be thrown away. However, some DB systems are
# supporting "ON CONFLICT DO NOTHING" clause in INSERT statement which
# solves the same issue gracefully.
# TODO: "ON CONFLICT DO NOTHING" feature is available for SQLite engine
# too in SQLAlchemy 1.4.
if session.bind.dialect.name == 'postgresql':
insert_stmt = sqlalchemy.dialects.postgresql.insert(File).values(
filepath=file_path,
filename=os.path.basename(file_path),
content_hash=content_hash).on_conflict_do_nothing(
index_elements=['filepath', 'content_hash'])
file_id = session.execute(insert_stmt).inserted_primary_key[0]
assign_file_to_source_components(session, file_id, file_path)
session.commit()
return file_id
file_record = File(file_path, content_hash, None, None)
session.add(file_record)
session.flush()
assign_file_to_source_components(session, file_record.id, file_path)
session.commit()
except sqlalchemy.exc.IntegrityError as ex:
LOG.error(ex)
# Other transaction might have added the same file in the
# meantime.
session.rollback()
file_record = session.query(File) \
.filter(File.content_hash == content_hash,
File.filepath == file_path).one_or_none()
return file_record.id if file_record else None
def get_blame_file_data(
blame_file: Path
) -> Tuple[Optional[str], Optional[str], Optional[str]]:
"""
Get blame information from the given file.
It will return a tuple of 'blame information', 'remote url' and
'tracking branch'.
"""
blame_info = None
remote_url = None
tracking_branch = None
if blame_file.is_file():
data = load_json(blame_file)
if data:
remote_url = data.get("remote_url")
tracking_branch = data.get("tracking_branch")
blame_info = data
# Remove fields which are not needed anymore from the blame info.
del blame_info["remote_url"]
del blame_info["tracking_branch"]
return blame_info, remote_url, tracking_branch
def checker_name_for_report(report: Report) -> Tuple[str, str]:
return (report.analyzer_name or UnknownChecker[0],
report.checker_name or UnknownChecker[1])
class MassStoreRunInputHandler:
"""Prepares a `MassStoreRunTask` from an API input."""
# Note: The implementation of this class is executed in the "foreground",
# in the context of an API handler process!
# **DO NOT** put complex logic here that would take too much time to
# validate.
# Long-running actions of a storage process should be in
# MassStoreRunImplementation instead!
def __init__(self,
session_manager: SessionManager,
config_db_sessionmaker,
product_db_sessionmaker,
task_manager: TaskManager,
package_context,
product_id: int,
run_name: str,
run_description: Optional[str],
store_tag: Optional[str],
client_version: str,
force_overwrite_of_run: bool,
path_prefixes_to_trim: Optional[List[str]],
zipfile_contents_base64: str,
user_name: str):
self._input_handling_start_time = time.time()
self._session_manager = session_manager
self._config_db = config_db_sessionmaker
self._product_db = product_db_sessionmaker
self._tm = task_manager
self._package_context = package_context
self._input_zip_blob = zipfile_contents_base64
self.client_version = client_version
self.force_overwrite_of_run = force_overwrite_of_run
self.path_prefixes_to_trim = path_prefixes_to_trim
self.run_name = run_name
self.run_description = run_description
self.store_tag = store_tag
self.user_name = user_name
with DBSession(self._config_db) as session:
product: Optional[Product] = session.get(Product, product_id)
if not product:
raise KeyError(f"No product with ID '{product_id}'")
self._product = product
def check_store_input_validity_at_face_value(self):
"""
Performs semantic checks of a ``massStoreRunAsynchronous()`` Thrift
call that can be done with trivial amounts of work (i.e., without
actually parsing the full input ZIP).
"""
self._check_run_limit()
self._store_run_lock() # Fails if the run can not be stored into.
def create_mass_store_task(self,
is_actually_asynchronous=False) \
-> "MassStoreRunTask":
"""
Constructs the `MassStoreRunTask` for the handled and verified input.
Calling this function results in observable changes outside the
process's memory, as it records the task into the database and
extracts things to the server's storage area.
"""
token = self._tm.allocate_task_record(
"report_server::massStoreRunAsynchronous()"
if is_actually_asynchronous
else "report_server::massStoreRun()",
("Legacy s" if not is_actually_asynchronous else "S") +
f"tore of results to '{self._product.endpoint}' - "
f"'{self.run_name}'",
self.user_name,
self._product)
temp_dir = self._tm.create_task_data(token)
extract_dir = temp_dir / "store_zip"
os.makedirs(extract_dir, exist_ok=True)
try:
with StepLog(self.run_name,
"Save massStoreRun() ZIP data to server storage"):
zip_size = unzip(self.run_name,
self._input_zip_blob,
extract_dir)
if not zip_size:
raise RequestFailed(ErrorCode.GENERAL,
"The uploaded ZIP file is empty!")
except Exception:
LOG.error("Failed to extract massStoreRunAsynchronous() ZIP!")
import traceback
traceback.print_exc()
raise
self._input_handling_end_time = time.time()
try:
with open(temp_dir / "store_configuration.json", 'w',
encoding="utf-8") as cfg_f:
json.dump({
"client_version": self.client_version,
"force_overwrite": self.force_overwrite_of_run,
"path_prefixes_to_trim": self.path_prefixes_to_trim,
"run_name": self.run_name,
"run_description": self.run_description,
"store_tag": self.store_tag,
"user_name": self.user_name,
}, cfg_f)
except Exception:
LOG.error("Failed to write massStoreRunAsynchronous() "
"configuration!")
import traceback
traceback.print_exc()
raise
task = MassStoreRunTask(token, temp_dir,
self._package_context,
self._product.id,
zip_size,
self._input_handling_end_time -
self._input_handling_start_time)
if not is_actually_asynchronous:
self._tm.add_comment(
task,
"WARNING!\nExecuting a legacy 'massStoreRun()' API call!",
"SYSTEM")
return task
def _check_run_limit(self):
"""
Checks the maximum allowed number of uploadable runs for the current
product.
"""
run_limit: Optional[int] = self._session_manager.get_max_run_count()
if self._product.run_limit:
run_limit = self._product.run_limit
if not run_limit:
# Allowing the user to upload an unlimited number of runs.
return
LOG.debug("Checking the maximum number of allowed runs in '%s', "
"which is %d.",
self._product.endpoint, run_limit)
with DBSession(self._product_db) as session:
existing_run: Optional[Run] = session.query(Run) \
.filter(Run.name == self.run_name) \
.one_or_none()
run_count = session.query(Run.id).count()
if not existing_run and run_count >= run_limit:
raise RequestFailed(
ErrorCode.GENERAL,
"You reached the maximum number of allowed runs "
f"({run_count}/{run_limit})! "
f"Please remove at least {run_count - run_limit + 1} "
"run(s) before you try again!")
def _store_run_lock(self):
"""Commits a `DBRunLock` for the to-be-stored `Run`, if available."""
with DBSession(self._product_db) as session:
RunLock(session, self.run_name) \
.store_run_lock_in_db(self.user_name)
class MassStoreRunTask(AbstractTask):
"""Executes `MassStoreRun` as a background job."""
def __init__(self, token: str, data_path: Path,
package_context,
product_id: int,
input_zip_size: int,
preparation_time_elapsed: float):
"""
Creates the `AbstractTask` implementation for
``massStoreRunAsynchronous()``.
`preparation_time_elapsed` records how much time was spent by the
input handling that prepared the task.
This time will be added to the total time spent processing the results
in the background.
(The time spent in waiting between task enschedulement and task
execution is not part of the total time.)
"""
super().__init__(token, data_path)
self._package_context = package_context
self._product_id = product_id
self.input_zip_size = input_zip_size
self.time_spent_on_task_preparation = preparation_time_elapsed
def _implementation(self, tm: TaskManager):
try:
with open(self.data_path / "store_configuration.json", 'r',
encoding="utf-8") as cfg_f:
self.store_configuration = json.load(cfg_f)
except Exception:
LOG.error("Invalid or unusable massStoreRunAsynchronous() "
"configuration!")
raise
with DBSession(tm.configuration_database_session_factory) as session:
db_product: Optional[Product] = \
session.get(Product, self._product_id)
if not db_product:
raise KeyError(f"No product with ID '{self._product_id}'")
self._product = ServerProduct(db_product.id,
db_product.endpoint,
db_product.display_name,
db_product.connection,
self._package_context,
tm.environment)
self._product.connect()
if self._product.db_status != DBStatus.OK:
raise EnvironmentError("Database for product "
f"'{self._product.endpoint}' is in "
"a bad shape!")
def __cancel_if_needed():
tm.heartbeat(self)
if tm.should_cancel(self):
raise TaskCancelHonoured(self)
m = MassStoreRun(__cancel_if_needed,
self.data_path / "store_zip",
self._package_context,
tm.configuration_database_session_factory,
self._product,
self.store_configuration["run_name"],
self.store_configuration["store_tag"],
self.store_configuration["client_version"],
self.store_configuration["force_overwrite"],
self.store_configuration["path_prefixes_to_trim"],
self.store_configuration["run_description"],
self.store_configuration["user_name"],
)
m.store(self.input_zip_size, self.time_spent_on_task_preparation)
class MassStoreRun:
"""Implementation for ``massStoreRunAsynchronous()``."""
# Note: The implementation of this class is called from MassStoreRunTask
# and it is executed in the background, in the context of a Task worker
# process.
# This is the place where complex implementation logic must go, but be
# careful, there is no way to communicate with the user's client anymore!
def __init__(self,
graceful_cancel: Callable[[], None],
zip_dir: Path,
package_context,
config_db,
product: ServerProduct,
name: str,
tag: Optional[str],
version: Optional[str],
force: bool,
trim_path_prefix_list: Optional[List[str]],
description: Optional[str],
user_name: str,
):
self._zip_dir = zip_dir
self._name = name
self._tag = tag
self._version = version
self._force = force
self._trim_path_prefixes = trim_path_prefix_list
self._description = description
self._user_name = user_name
self.__config_db = config_db
self.__package_context = package_context
self.__product = product
self.__graceful_cancel_if_requested = graceful_cancel
self.__mips: Dict[str, MetadataInfoParser] = {}
self.__analysis_info: Dict[str, AnalysisInfo] = {}
self.__checker_row_cache: Dict[Tuple[str, str], Checker] = {}
self.__duration: int = 0
self.__report_count: int = 0
self.__report_limit: int = 0
self.__wrong_src_code_comments: List[str] = []
self.__already_added_report_hashes: Set[str] = set()
self.__new_report_hashes: Dict[str, Tuple] = {}
self.__all_report_checkers: Set[str] = set()
self.__added_reports: List[Tuple[DBReport, Report]] = []
self.__reports_with_fake_checkers: Dict[
# Either a DBReport *without* an ID, or the ID of a committed
# DBReport.
str, Tuple[Report, Union[DBReport, int]]] = {}
with DBSession(config_db) as session:
product = session.get(Product, self.__product.id)
self.__report_limit = product.report_limit
def __store_source_files(
self,
source_root: Path,
filename_to_hash: Dict[str, str]
) -> Dict[str, int]:
""" Storing file contents from plist. """
file_path_to_id = {}
for file_name, file_hash in filename_to_hash.items():
self.__graceful_cancel_if_requested()
source_file_path = path_for_fake_root(file_name, str(source_root))
LOG.debug("Storing source file: %s", source_file_path)
trimmed_file_path = trim_path_prefixes(
file_name, self._trim_path_prefixes)
if not os.path.isfile(source_file_path):
# The file was not in the ZIP file, because we already
# have the content. Let's check if we already have a file
# record in the database or we need to add one.
LOG.debug('%s not found or already stored.', trimmed_file_path)
with DBSession(self.__product.session_factory) as session:
fid = add_file_record(
session, trimmed_file_path, file_hash)
if fid:
file_path_to_id[trimmed_file_path] = fid
LOG.debug("%d fileid found", fid)
else:
LOG.error("File ID for %s is not found in the DB with "
"content hash %s. Missing from ZIP?",
source_file_path, file_hash)
continue
with DBSession(self.__product.session_factory) as session:
self.__add_file_content(session, source_file_path, file_hash)
file_path_to_id[trimmed_file_path] = add_file_record(
session, trimmed_file_path, file_hash)
return file_path_to_id
def __add_blame_info(
self,
blame_root: Path,
filename_to_hash: Dict[str, str]
):
"""
This function updates blame info in File and FileContent tables if
these were NULL. This function exists only because in earlier
CodeChecker versions blame info was not stored in these tables and
in a subsequent storage we can't update the tables for an unchanged
file since __store_source_files() updates only the ones that are in the
.zip file. This function stores blame info even if the corresponding
source file is not in the .zip file.
"""
with DBSession(self.__product.session_factory) as session:
for subdir, _, files in os.walk(blame_root):
for f in files:
self.__graceful_cancel_if_requested()
blame_file = Path(subdir) / f
file_path = f"/{str(blame_file.relative_to(blame_root))}"
blame_info, remote_url, tracking_branch = \
get_blame_file_data(blame_file)
compressed_blame_info = None
if blame_info:
compressed_blame_info = zlib.compress(
json.dumps(blame_info).encode('utf-8'),
zlib.Z_BEST_COMPRESSION)
session \
.query(FileContent) \
.filter(FileContent.blame_info.is_(None)) \
.filter(FileContent.content_hash ==
filename_to_hash.get(file_path)) \
.update({"blame_info": compressed_blame_info})
session \
.query(File) \
.filter(File.remote_url.is_(None)) \
.filter(File.filepath == file_path) \
.update({
"remote_url": remote_url,
"tracking_branch": tracking_branch})
session.commit()
def __add_file_content(
self,
session: DBSession,
source_file_name: str,
content_hash: Optional[str] = None
) -> str:
"""
Add the necessary file contents. If content_hash in None then this
function calculates the content hash. Or if it's available at the
caller and it's provided then it will not be calculated again.
This function must not be called between add_checker_run() and
finish_checker_run() functions when SQLite database is used!
add_checker_run() function opens a transaction which is closed by
finish_checker_run() and since SQLite doesn't support parallel
transactions, this API call will wait until the other transactions
finish. In the meantime the run adding transaction times out.
This function doesn't insert blame info in the FileContent objects
because those are added by __add_blame_info(). In previous CodeChecker
versions git info was not stored at all, so upgrading to a new
CodeChecker results the storage of git blame info even for files that
are already stored. For this reason we can't avoid an update on File
and FileContent tables, but we can avoid double reading of blame info
json files.
"""
source_file_content = None
if not content_hash:
source_file_content = get_file_content(source_file_name)
hasher = sha256()
hasher.update(source_file_content)
content_hash = hasher.hexdigest()
file_content = session.get(FileContent, content_hash)
if not file_content:
if not source_file_content:
source_file_content = get_file_content(source_file_name)
try:
compressed_content = zlib.compress(
source_file_content, zlib.Z_BEST_COMPRESSION)
if session.bind.dialect.name == 'postgresql':
insert_stmt = sqlalchemy.dialects.postgresql \
.insert(FileContent).values(
content_hash=content_hash,
content=compressed_content,
blame_info=None).on_conflict_do_nothing(
index_elements=['content_hash'])
session.execute(insert_stmt)
else:
fc = FileContent(content_hash, compressed_content, None)
session.add(fc)
session.commit()
except sqlalchemy.exc.IntegrityError:
# Other transaction moght have added the same content in
# the meantime.
session.rollback()
return content_hash
def __store_checker_identifiers(self, checkers: Set[Tuple[str, str]]):
"""
Stores the identifiers "(analyzer, checker_name)" in the database into
a look-up table where each unique checker is given a unique numeric
identifier.
Due to the use of an M-to-N connection table
(see `AnalysisInfoChecker`) one side of the joins must have their IDs
eagerly populated, otherwise the Python bindings will fail.
However, eager population will result in exceptions that a flush was
created before the transaction was complete.
Moreover, this is performed separately from the storing of the details
of a run to reduce contention if two parallel stores, especially across
server instances (in a distributed/load-balanced environment) want to
store the same identifier(s).
"""
max_tries, tries, wait_time = 3, 0, timedelta(seconds=30)
# The "fake" checker is a temporary row that is needed intermittently
# during report storage because there might be reports that point to
# checkers which are not found in a preemptively parsed
# 'metadata.json', or, in the worst case, there might simply not be
# a 'metadata.json' at all in the to-be-stored structure.
all_checkers = {FakeChecker, UnknownChecker} | checkers
while tries < max_tries:
tries += 1
try:
LOG.debug("[%s] Begin attempt %d...", self._name, tries)
with DBSession(self.__product.session_factory) as session:
known_checkers = {(r.analyzer_name, r.checker_name)
for r in session
.query(Checker.analyzer_name,
Checker.checker_name)
.all()}
for analyzer, checker in \
sorted(all_checkers - known_checkers):
s = self.__package_context.checker_labels \
.severity(checker)
s = ttypes.Severity._NAMES_TO_VALUES[s]
session.add(Checker(analyzer, checker, s))
LOG.debug("Acquiring ID for checker '%s/%s' "
"for the first time.", analyzer, checker)
session.commit()
return
except (sqlalchemy.exc.OperationalError,
sqlalchemy.exc.ProgrammingError,
sqlalchemy.exc.IntegrityError) as ex:
LOG.error("Storing checkers of run '%s' failed: %s.\n"
"Waiting %d before trying again...",
self._name, ex, wait_time)
time.sleep(wait_time.total_seconds())
wait_time *= 2
except Exception as ex:
LOG.error("Failed to store checkers due to some other error: "
"%s", ex)
import traceback
traceback.print_exc()
raise
raise ConnectionRefusedError("Storing the names of the checkers in "
"the run failed due to excessive "
"contention!")
def __store_analysis_statistics(
self,
session: DBSession,
run_history_id: int
):
"""
Store analysis statistics for the given run history.
It will unique the statistics for each analyzer type based on the
metadata information.
"""
stats = defaultdict(lambda: {
"versions": set(),
"failed_sources": set(),
"successful_sources": set(),
"successful": 0
})
for mip in self.__mips.values():
self.__duration += int(sum(mip.check_durations))
for analyzer_type, res in mip.analyzer_statistics.items():
if "version" in res:
stats[analyzer_type]["versions"].add(res["version"])
if "failed_sources" in res:
if self._version == '6.9.0':
stats[analyzer_type]["failed_sources"].add(
'Unavailable in CodeChecker 6.9.0!')
else:
stats[analyzer_type]["failed_sources"].update(
res["failed_sources"])
if "successful_sources" in res:
stats[analyzer_type]["successful_sources"].update(
res["successful_sources"])
if "successful" in res:
stats[analyzer_type]["successful"] += res["successful"]
for analyzer_type, stat in stats.items():
analyzer_version = None
if stat["versions"]:
analyzer_version = zlib.compress(
"; ".join(stat["versions"]).encode('utf-8'),
zlib.Z_BEST_COMPRESSION)
failed = 0
compressed_files = None
if stat["failed_sources"]:
compressed_files = zlib.compress(
'\n'.join(stat["failed_sources"]).encode('utf-8'),
zlib.Z_BEST_COMPRESSION)
failed = len(stat["failed_sources"])
successful = len(stat["successful_sources"]) \
if stat["successful_sources"] else stat["successful"]