forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclang_tidy_cache
executable file
·1449 lines (1221 loc) · 54.6 KB
/
clang_tidy_cache
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
#!/usr/bin/env python3
# coding: UTF-8
# Copyright (c) 2019-2024 Matus Chochlik
# Distributed under the Boost Software License, Version 1.0.
# See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt
import os
import re
import sys
import errno
import getpass
import logging
import hashlib
import tempfile
import subprocess
import json
import shlex
import time
import traceback
import typing as tp
try:
import redis
except ImportError:
redis = None
# ------------------------------------------------------------------------------
def getenv_boolean_flag(name):
return os.getenv(name, "0").lower() in ["true", "1", "yes", "y", "on"]
# ------------------------------------------------------------------------------
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as os_error:
if os_error.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
# ------------------------------------------------------------------------------
class ClangTidyCacheOpts(object):
# --------------------------------------------------------------------------
def __init__(self, log, args):
self._log = log
if len(args) < 1:
self._log.error("Missing arguments")
self._original_args = args
self._clang_tidy_args = []
self._compiler_args = []
self._cache_dir = None
self._compile_commands_db = None
self._strip_list = os.getenv("CTCACHE_STRIP", "").split(os.pathsep)
args = self._split_compiler_clang_tidy_args(args)
self._adjust_compiler_args(args)
# --------------------------------------------------------------------------
def __repr__(self):
return \
f"ClangTidyCacheOpts(" \
f"clang_tidy_args:{self._clang_tidy_args}," \
f"compiler_args:{self._compiler_args}," \
f"original_args:{self._original_args}" \
f")"
# --------------------------------------------------------------------------
def running_on_msvc(self):
if self._compiler_args:
return os.path.basename(self._compiler_args[0]) == "cl.exe"
return False
# --------------------------------------------------------------------------
def running_on_clang_cl(self):
if self._compiler_args:
return os.path.basename(self._compiler_args[0]) == "clang-cl.exe"
return False
# --------------------------------------------------------------------------
def _split_compiler_clang_tidy_args(self, args):
# splits arguments starting with - on the first =
args = [arg.split('=', 1) if arg.startswith('-p') else [arg] for arg in args]
args = [arg for sub in args for arg in sub]
if args.count("--") == 1:
# Invoked with compiler args on the actual command line
i = args.index("--")
self._clang_tidy_args = args[:i]
self._compiler_args = args[i+1:]
elif args.count("-p") == 1:
# Invoked with compiler args in a compile commands json db
i = args.index("-p")
self._clang_tidy_args = args
i += 1
if i >= len(args):
return
cdb_path = args[i]
if os.path.isdir(cdb_path):
cdb_path = os.path.join(cdb_path, "compile_commands.json")
self._load_compile_command_db(cdb_path)
i += 1
if i >= len(args):
return
# This assumes that the filename occurs after the -p <cdb path>
# and that there is only one of them
filenames = [arg for arg in args[i:] if not arg.startswith("-")]
if len(filenames) > 0:
self._compiler_args = self._compiler_args_for(filenames[0])
else:
# Invoked as pure clang-tidy command
self._clang_tidy_args = args[1:]
return args
# --------------------------------------------------------------------------
def _adjust_compiler_args(self, args):
if self._compiler_args:
pos = next((pos for pos, arg in enumerate(self._compiler_args) if arg.startswith('-D')), 1)
self._compiler_args.insert(pos, "-D__clang_analyzer__=1")
for i in range(1, len(self._compiler_args)):
if self._compiler_args[i-1] in ["-o", "--output"]:
self._compiler_args[i] = "-"
if self._compiler_args[i-1] in ["-c"]:
self._compiler_args[i-1] = "-E"
for i in range(1, len(self._compiler_args)):
if self._compiler_args[i-1] in ["-E"]:
if self.running_on_msvc():
self._compiler_args[i-1] = "-EP"
else:
self._compiler_args.insert(i, "-P")
if self.keep_comments():
self._compiler_args.insert(i, "-C")
# --------------------------------------------------------------------------
def _load_compile_command_db(self, filename):
try:
with open(filename) as f:
cdb = f.read()
try:
js = cdb.replace(r'\\\"', "'").replace("\\", "\\\\")
self._compile_commands_db = json.loads(js)
except JSONDecodeError:
self._compile_commands_db = json.loads(cdb)
except Exception as err:
self._log.error("Loading compile command DB failed: {0}".format(repr(err)))
return False
# --------------------------------------------------------------------------
def _compiler_args_for(self, filename):
if self._compile_commands_db is None:
return []
filename = os.path.expanduser(filename)
filename = os.path.realpath(filename)
for command in self._compile_commands_db:
db_filename = command["file"]
try:
if os.path.samefile(filename, db_filename):
try:
return shlex.split(command["command"])
except KeyError:
try:
return shlex.split(command["arguments"][0])
except:
return "clang-tidy"
except FileNotFoundError:
continue
return []
# --------------------------------------------------------------------------
def should_print_dir(self):
try:
return self._original_args[0] == "--cache-dir"
except IndexError:
return False
# --------------------------------------------------------------------------
def should_print_stats(self):
try:
return self._original_args[0] == "--show-stats"
except IndexError:
return False
# --------------------------------------------------------------------------
def should_print_stats_raw(self):
try:
return self._original_args[0] == "--print-stats"
except IndexError:
return False
# --------------------------------------------------------------------------
def should_remove_dir(self):
try:
return self._original_args[0] == "--clean"
except IndexError:
return False
# --------------------------------------------------------------------------
def should_zero_stats(self):
try:
return self._original_args[0] == "--zero-stats"
except IndexError:
return False
# --------------------------------------------------------------------------
def should_print_usage(self):
return len(self.original_args()) < 1
# --------------------------------------------------------------------------
def original_args(self):
return self._original_args
# --------------------------------------------------------------------------
def clang_tidy_args(self):
return self._clang_tidy_args
# --------------------------------------------------------------------------
def compiler_args(self):
return self._compiler_args
# --------------------------------------------------------------------------
@property
def cache_dir(self):
if self._cache_dir:
return self._cache_dir
try:
user = getpass.getuser()
except KeyError:
user = "unknown"
self._cache_dir = os.getenv(
"CTCACHE_DIR",
os.path.join(
tempfile.tempdir if tempfile.tempdir else "/tmp", "ctcache-" + user
),
)
return self._cache_dir
# --------------------------------------------------------------------------
def strip_paths(self, input):
for item in self._strip_list:
input = re.sub(item, '', input)
return input
# --------------------------------------------------------------------------
def adjust_chunk(self, x):
x = x.strip()
r = str().encode("utf8")
if not x.startswith("# "):
for w in x.split():
w = w.strip('"')
if os.path.exists(w):
w = os.path.realpath(w)
w = self.strip_paths(w)
w.strip()
if w:
r += w.encode("utf8")
return r
# --------------------------------------------------------------------------
def has_s3(self):
return "CTCACHE_S3_BUCKET" in os.environ
# --------------------------------------------------------------------------
def s3_bucket(self):
return os.getenv("CTCACHE_S3_BUCKET")
# --------------------------------------------------------------------------
def s3_bucket_folder(self):
return os.getenv("CTCACHE_S3_FOLDER", 'clang-tidy-cache')
# --------------------------------------------------------------------------
def s3_no_credentials(self):
return os.getenv("CTCACHE_S3_NO_CREDENTIALS", "")
# --------------------------------------------------------------------------
def s3_read_only(self):
return getenv_boolean_flag("CTCACHE_S3_READ_ONLY")
# --------------------------------------------------------------------------
def has_gcs(self):
return "CTCACHE_GCS_BUCKET" in os.environ
# --------------------------------------------------------------------------
def gcs_bucket(self):
return os.getenv("CTCACHE_GCS_BUCKET")
# --------------------------------------------------------------------------
def gcs_bucket_folder(self):
return os.getenv("CTCACHE_GCS_FOLDER", 'clang-tidy-cache')
# --------------------------------------------------------------------------
def gcs_no_credentials(self):
return os.getenv("CTCACHE_GCS_NO_CREDENTIALS", None)
# --------------------------------------------------------------------------
def gcs_read_only(self):
return getenv_boolean_flag("CTCACHE_GCS_READ_ONLY")
# --------------------------------------------------------------------------
def cache_locally(self):
return getenv_boolean_flag("CTCACHE_LOCAL")
# --------------------------------------------------------------------------
def no_local_stats(self):
return getenv_boolean_flag("CTCACHE_NO_LOCAL_STATS")
# --------------------------------------------------------------------------
def no_local_writeback(self):
return getenv_boolean_flag("CTCACHE_NO_LOCAL_WRITEBACK")
# --------------------------------------------------------------------------
def has_host(self):
return os.getenv("CTCACHE_HOST") is not None
# --------------------------------------------------------------------------
def rest_host(self):
return os.getenv("CTCACHE_HOST", "localhost")
# --------------------------------------------------------------------------
def rest_proto(self):
return os.getenv("CTCACHE_PROTO", "http")
# --------------------------------------------------------------------------
def rest_port(self):
return int(os.getenv("CTCACHE_PORT", 5000))
# --------------------------------------------------------------------------
def rest_host_read_only(self):
return getenv_boolean_flag("CTCACHE_HOST_READ_ONLY")
# --------------------------------------------------------------------------
def save_output(self) -> bool:
return getenv_boolean_flag("CTCACHE_SAVE_OUTPUT")
# --------------------------------------------------------------------------
def ignore_output(self) -> bool:
return self.save_output() or "CTCACHE_IGNORE_OUTPUT" in os.environ
# --------------------------------------------------------------------------
def save_all(self) -> bool:
return self.save_output() or "CTCACHE_SAVE_ALL" in os.environ
# --------------------------------------------------------------------------
def debug_enabled(self):
return getenv_boolean_flag("CTCACHE_DEBUG")
# --------------------------------------------------------------------------
def dump_enabled(self):
return getenv_boolean_flag("CTCACHE_DUMP")
# --------------------------------------------------------------------------
def dump_dir(self):
return os.getenv("CTCACHE_DUMP_DIR", tempfile.gettempdir())
# --------------------------------------------------------------------------
def strip_src(self):
return getenv_boolean_flag("CTCACHE_STRIP_SRC")
# --------------------------------------------------------------------------
def keep_comments(self):
return getenv_boolean_flag("CTCACHE_KEEP_COMMENTS")
# --------------------------------------------------------------------------
def exclude_hash_regex(self):
return os.getenv("CTCACHE_EXCLUDE_HASH_REGEX")
# --------------------------------------------------------------------------
def exclude_hash(self, chunk):
return self.exclude_hash_regex() is not None and \
re.match(self.exclude_hash_regex(), chunk.decode("utf8"))
# --------------------------------------------------------------------------
def exclude_user_config(self):
return getenv_boolean_flag("CTCACHE_EXCLUDE_USER_CONFIG")
# --------------------------------------------------------------------------
def has_redis_host(self) -> bool:
return "CTCACHE_REDIS_HOST" in os.environ
# --------------------------------------------------------------------------
def redis_host(self) -> str:
return os.getenv("CTCACHE_REDIS_HOST", "")
# --------------------------------------------------------------------------
def redis_port(self) -> int:
return int(os.getenv("CTCACHE_REDIS_PORT", "6379"))
# --------------------------------------------------------------------------
def redis_db(self) -> int:
return int(os.getenv("CTCACHE_REDIS_DB", "0"))
# --------------------------------------------------------------------------
def redis_username(self) -> str:
return os.getenv("CTCACHE_REDIS_USERNAME", "")
# --------------------------------------------------------------------------
def redis_password(self) -> str:
return os.getenv("CTCACHE_REDIS_PASSWORD", "")
# --------------------------------------------------------------------------
def redis_connect_timeout(self) -> float:
return float(os.getenv("CTCACHE_REDIS_CONNECT_TIMEOUT", "0.1"))
# --------------------------------------------------------------------------
def redis_socket_timeout(self) -> float:
return float(os.getenv("CTCACHE_REDIS_OPERATION_TIMEOUT", "10.0"))
# --------------------------------------------------------------------------
def redis_cache_ttl(self) -> float:
ttl = int(os.getenv("CTCACHE_REDIS_CACHE_TTL", "-1"))
if ttl < 0:
return None
return ttl
# --------------------------------------------------------------------------
def redis_namespace(self) -> str:
return os.getenv("CTCACHE_REDIS_NAMESPACE", "ctcache/")
# --------------------------------------------------------------------------
def redis_read_only(self):
return getenv_boolean_flag("CTCACHE_REDIS_READ_ONLY")
# ------------------------------------------------------------------------------
class ClangTidyCacheHash(object):
# --------------------------------------------------------------------------
def _opendump(self, opts):
return open(os.path.join(opts.dump_dir(), "ctcache.dump"), "ab")
# --------------------------------------------------------------------------
def __init__(self, opts):
self._hash = hashlib.sha1()
if opts.dump_enabled():
self._dump = self._opendump(opts)
else:
self._dump = None
assert self._dump or not opts.dump_enabled()
# --------------------------------------------------------------------------
def __del__(self):
if self._dump:
self._dump.close()
# --------------------------------------------------------------------------
def update(self, content):
if content:
self._hash.update(content)
if self._dump:
self._dump.write(content)
# --------------------------------------------------------------------------
def hexdigest(self):
return self._hash.hexdigest()
# ------------------------------------------------------------------------------
class ClangTidyServerCache(object):
def __init__(self, log, opts):
import requests
self._requests = requests
self._log = log
self._opts = opts
# --------------------------------------------------------------------------
def is_cached(self, digest):
try:
query = self._requests.get(self._make_query_url(digest), timeout=3)
if query.status_code == 200:
if query.json() is True:
return True
elif query.json() is False:
return False
else:
self._log.error("is_cached: Can't connect to server {0}, error {1}".format(
self._opts.rest_host(), query.status_code))
except:
pass
return False
# --------------------------------------------------------------------------
def get_cache_data(self, digest) -> tp.Optional[bytes]:
try:
query = self._requests.get(self._make_data_url(digest), timeout=3)
if query.status_code == 200:
return query.text.encode('UTF-8')
except:
pass
return None
# --------------------------------------------------------------------------
def store_in_cache(self, digest):
self.store_in_cache_with_data(digest, bytes())
# --------------------------------------------------------------------------
def store_in_cache_with_data(self, digest, data: bytes):
if self._opts.rest_host_read_only():
return
try:
query = self._requests.put(self._make_data_url(digest), data={'data': data}, timeout=3)
if query.status_code != 200:
self._log.error("store_in_cache: Can't store data in server {0}, error {1}".format(
self._opts.rest_host(), query.status_code))
except:
pass
# --------------------------------------------------------------------------
def query_stats(self, options):
try:
query = self._requests.get(self._make_stats_url(), timeout=3)
if query.status_code == 200:
return query.json()
else:
self._log.error("query_stats: Can't connect to server {0}, error {1}".format(
self._opts.rest_host(), query.status_code))
except:
pass
return None
# --------------------------------------------------------------------------
def clear_stats(self, options):
# Not implemented
pass
# --------------------------------------------------------------------------
def _make_query_url(self, digest):
return "%(proto)s://%(host)s:%(port)d/is_cached/%(digest)s" % {
"proto": self._opts.rest_proto(),
"host": self._opts.rest_host(),
"port": self._opts.rest_port(),
"digest": digest
}
# --------------------------------------------------------------------------
def _make_data_url(self, digest):
return "%(proto)s://%(host)s:%(port)d/cache/%(digest)s" % {
"proto": self._opts.rest_proto(),
"host": self._opts.rest_host(),
"port": self._opts.rest_port(),
"digest": digest
}
# --------------------------------------------------------------------------
def _make_stats_url(self):
return "%(proto)s://%(host)s:%(port)d/stats" % {
"proto": self._opts.rest_proto(),
"host": self._opts.rest_host(),
"port": self._opts.rest_port()
}
# ------------------------------------------------------------------------------
class MultiprocessLock:
# --------------------------------------------------------------------------
def __init__(self, lock_path, timeout=3): # timeout 3 seconds
self._lock_path = os.path.abspath(os.path.expanduser(lock_path))
self._timeout = timeout
self._lock_handle = None
# --------------------------------------------------------------------------
def acquire(self):
start_time = time.time()
while True:
try:
# Attempt to create the lock file exclusively
self._lock_handle = os.open(self._lock_path, os.O_CREAT | os.O_EXCL)
return self
except FileExistsError:
# File is locked, check if the timeout has been exceeded
if time.time() - start_time > self._timeout:
msg = f"Timeout ({self._timeout} seconds) exceeded while acquiring lock."
raise RuntimeError(msg)
# Wait and try again
time.sleep(0.1)
except FileNotFoundError:
# The path to the lock file doesn't exist, create it and retry
os.makedirs(os.path.dirname(self._lock_path), exist_ok=True)
# --------------------------------------------------------------------------
def release(self):
if self._lock_handle is not None:
try:
os.close(self._lock_handle)
os.unlink(self._lock_path) # Remove the lock file upon release
except OSError:
pass # Ignore errors if the file doesn't exist or has already been released
finally:
self._lock_handle = None
# --------------------------------------------------------------------------
def __enter__(self):
return self.acquire()
# --------------------------------------------------------------------------
def __exit__(self, exc_type, exc_value, traceback):
self.release()
# ------------------------------------------------------------------------------
class ClangTidyCacheStats(object):
# --------------------------------------------------------------------------
def __init__(self, log, opts, name):
self._log = log
self._opts = opts
self._name = name
# --------------------------------------------------------------------------
def stats_file(self, digest):
return os.path.join(self._opts.cache_dir, digest[:2], self._name)
# --------------------------------------------------------------------------
def read(self):
hits, misses = 0, 0
for i in range(0, 256):
digest = f'{i:x}'
file = self.stats_file(digest)
if os.path.isfile(file):
h, m = self._read(file)
hits += h
misses += m
return hits, misses
# --------------------------------------------------------------------------
def _read(self, file):
with MultiprocessLock(file + ".lock") as _:
if os.path.isfile(file):
with open(file, 'r') as f:
return self.read_from_file(f)
return 0,0
# --------------------------------------------------------------------------
def read_from_file(self, f):
content = f.read().split()
if len(content) == 2:
return int(content[0]), int(content[1])
else:
self._log.error(f"Invalid stats content in: {f.name}")
return 0,0
# --------------------------------------------------------------------------
def write_to_file(self, f, hits, misses, hit):
if hit:
hits += 1
else:
misses += 1
f.write(f"{hits} {misses}\n")
# --------------------------------------------------------------------------
def update(self, digest, hit):
try:
file = self.stats_file(digest)
mkdir_p(os.path.dirname(file))
with MultiprocessLock(file + ".lock") as _:
try:
if os.path.isfile(file):
with open(file, 'r+') as fh:
hits, misses = self.read_from_file(fh)
fh.seek(0)
self.write_to_file(fh, hits, misses, hit)
fh.truncate()
else:
with open(file, 'w') as fh:
self.write_to_file(fh, 0, 0, hit)
except IOError as e:
self._log.error(f"Error writing to file: {e}")
except Exception as e:
traceback.print_exc(file=sys.stdout)
raise
# --------------------------------------------------------------------------
def clear(self):
for i in range(0, 256):
digest = f'{i:x}'
file = self.stats_file(digest)
if os.path.isfile(file):
os.unlink(file)
# ------------------------------------------------------------------------------
class ClangTidyLocalCache(object):
# --------------------------------------------------------------------------
def __init__(self, log, opts):
self._log = log
self._opts = opts
self._hash_regex = re.compile(r'^[0-9a-f]{38}$')
# --------------------------------------------------------------------------
def is_cached(self, digest):
path = self._make_path(digest)
if os.path.isfile(path):
os.utime(path, None)
return True
return False
# --------------------------------------------------------------------------
def get_cache_data(self, digest) -> tp.Optional[bytes]:
path = self._make_path(digest)
if os.path.isfile(path):
os.utime(path, None)
with open(path, "rb") as stream:
return stream.read()
else:
return None
# --------------------------------------------------------------------------
def store_in_cache(self, digest):
p = self._make_path(digest)
mkdir_p(os.path.dirname(p))
open(p, "w").close()
# --------------------------------------------------------------------------
def store_in_cache_with_data(self, digest, data: bytes):
p = self._make_path(digest)
mkdir_p(os.path.dirname(p))
with open(p, "wb") as stream:
stream.write(data)
# --------------------------------------------------------------------------
def _list_cached_files(self, options, prefix):
for root, dirs, files in os.walk(prefix):
for prefix in dirs:
for filename in self._list_cached_files(options, prefix):
if self._hash_regex.match(filename):
yield root, prefix, filename
for filename in files:
if self._hash_regex.match(filename):
yield root, prefix, filename
# --------------------------------------------------------------------------
def query_stats(self, options):
hash_count = sum(1 for x in self._list_cached_files(options, options.cache_dir))
return {"cached_count": hash_count}
# --------------------------------------------------------------------------
def clear_stats(self, options):
pass
# --------------------------------------------------------------------------
def _make_path(self, digest):
return os.path.join(self._opts.cache_dir, digest[:2], digest[2:])
# ------------------------------------------------------------------------------
class ClangTidyRedisCache(object):
# --------------------------------------------------------------------------
def __init__(self, log, opts: ClangTidyCacheOpts):
self._log = log
self._opts = opts
assert redis
self._cli = redis.Redis(
host=opts.redis_host(),
port=opts.redis_port(),
db=opts.redis_db(),
username=opts.redis_username(),
password=opts.redis_password(),
socket_connect_timeout=opts.redis_connect_timeout(),
socket_timeout=opts.redis_socket_timeout(),
# the two settings below are used to avoid sending any commands to the Redis
# server other than AUTH, GET, and SET (to let the ctcache operate with a
# server configuration giving only minimal permissions to the given user)
lib_name=None,
lib_version=None)
self._namespace = opts.redis_namespace()
# --------------------------------------------------------------------------
def _get_key_from_digest(self, digest) -> str:
return self._namespace + digest
# --------------------------------------------------------------------------
def is_cached(self, digest) -> bool:
n_digest = self._get_key_from_digest(digest)
return self._cli.get(n_digest) is not None
# --------------------------------------------------------------------------
def get_cache_data(self, digest) -> tp.Optional[bytes]:
n_digest = self._get_key_from_digest(digest)
data = self._cli.get(n_digest)
ttl = self._opts.redis_cache_ttl()
if not self._opts.redis_read_only() and data is not None and ttl is not None:
# try to extend TTL on cache hits
self._cli.expire(n_digest, ttl, xx=True)
return data
# --------------------------------------------------------------------------
def store_in_cache(self, digest):
self.store_in_cache_with_data(digest, bytes())
# --------------------------------------------------------------------------
def store_in_cache_with_data(self, digest, data: bytes):
if self._opts.redis_read_only():
return
n_digest = self._get_key_from_digest(digest)
self._cli.set(n_digest, data, ex=self._opts.redis_cache_ttl())
# --------------------------------------------------------------------------
def query_stats(self, options):
# TODO
pass
# --------------------------------------------------------------------------
def clear_stats(self, options):
# TODO
pass
# ------------------------------------------------------------------------------
class ClangTidyS3Cache(object):
# --------------------------------------------------------------------------
def __init__(self, log, opts):
from boto3 import client
from botocore.exceptions import ClientError
from botocore.config import Config
from botocore.session import UNSIGNED
self._ClientError = ClientError
self._log = log
self._opts = opts
if self._opts.s3_no_credentials():
self._client = client("s3", config=Config(signature_version=UNSIGNED))
else:
self._client = client("s3")
self._bucket = opts.s3_bucket()
self._bucket_folder = opts.s3_bucket_folder()
# --------------------------------------------------------------------------
def is_cached(self, digest):
try:
path = self._make_path(digest)
self._client.get_object(Bucket=self._bucket, Key=path)
except self._ClientError as e:
if e.response['Error']['Code'] == "NoSuchKey":
return False
else:
self._log.error(
"Error calling S3:get_object {}".format(str(e)))
raise
return True
# --------------------------------------------------------------------------
def get_cache_data(self, digest) -> tp.Optional[bytes]:
# TODO
return None
# --------------------------------------------------------------------------
def store_in_cache(self, digest):
if self._opts.s3_no_credentials() or self._opts.s3_read_only():
return
try:
path = self._make_path(digest)
self._client.put_object(Bucket=self._bucket, Key=path, Body=digest)
except self._ClientError as e:
self._log.error("Error calling S3:put_object {}".format(str(e)))
raise
# --------------------------------------------------------------------------
def store_in_cache_with_data(self, digest, data: bytes):
# TODO
pass
# --------------------------------------------------------------------------
def query_stats(self, options):
# TODO
pass
# --------------------------------------------------------------------------
def clear_stats(self, options):
# TODO
pass
# --------------------------------------------------------------------------
def _make_path(self, digest):
return os.path.join(self._bucket_folder, digest[:2], digest[2:])
# ------------------------------------------------------------------------------
class ClangTidyGcsCache(object):
# --------------------------------------------------------------------------
def __init__(self, log, opts):
import google.cloud.storage as gcs
self._log = log
self._opts = opts
if self._opts.gcs_no_credentials():
self._client = gcs.Client.create_anonymous_client()
else:
self._client = gcs.Client()
self._bucket = self._client.bucket(opts.gcs_bucket())
self._bucket_folder = opts.gcs_bucket_folder()
# --------------------------------------------------------------------------
def is_cached(self, digest):
try:
path = self._make_path(digest)
blob = self._bucket.blob(path)
t = blob.exists()
return t
except Exception as e:
self._log.error("Error calling GCS:blob.exists {}".format(str(e)))
raise
# --------------------------------------------------------------------------
def get_cache_data(self, digest) -> tp.Optional[bytes]:
try:
path = self._make_path(digest)
blob = self._bucket.blob(path)
return blob.download_as_bytes()
except Exception as e:
return None
# --------------------------------------------------------------------------
def store_in_cache(self, digest):
if self._opts.gcs_no_credentials() or self._opts.gcs_read_only():
return
try:
path = self._make_path(digest)
blob = self._bucket.blob(path)
blob.upload_from_string(digest)
except Exception as e:
self._log.error(
"Error calling GCS:blob.upload_from_string {}".format(str(e)))
raise
# --------------------------------------------------------------------------
def store_in_cache_with_data(self, digest, data: bytes):
if self._opts.gcs_no_credentials() or self._opts.gcs_read_only():
return
try:
path = self._make_path(digest)
blob = self._bucket.blob(path)
blob.upload_from_string(data, content_type="application/octet-stream")
except Exception as e:
self._log.error(
"Error calling GCS:blob.upload_from_string {}".format(str(e)))
raise
# --------------------------------------------------------------------------
def query_stats(self, options):
# TODO
pass
# --------------------------------------------------------------------------
def clear_stats(self, options):
# TODO
pass
# --------------------------------------------------------------------------
def _make_path(self, digest):
return os.path.join(self._bucket_folder, digest[:2], digest[2:])
# ------------------------------------------------------------------------------
class ClangTidyMultiCache(object):
# --------------------------------------------------------------------------
def __init__(self, log, caches):
self._log = log
self._caches = caches
# --------------------------------------------------------------------------
def is_cached(self, digest):
for cache in self._caches:
if cache.is_cached(digest):
return True
return False
# --------------------------------------------------------------------------
def get_cache_data(self, digest) -> tp.Optional[bytes]:
for cache in self._caches:
data = cache.get_cache_data(digest)
if data is not None:
return data
return None
# --------------------------------------------------------------------------
def store_in_cache(self, digest):
for cache in self._caches:
cache.store_in_cache(digest)
# --------------------------------------------------------------------------
def store_in_cache_with_data(self, digest, data: bytes):
for cache in self._caches:
cache.store_in_cache_with_data(digest, data)
# --------------------------------------------------------------------------
def query_stats(self, options):
for cache in self._caches:
stats = cache.query_stats(options)
if stats:
return stats
return {}
# --------------------------------------------------------------------------
def clear_stats(self, options):