Repository navigation
Expand file tree
/
Copy paths3gc.py
More file actions
1164 lines (1044 loc) · 36.6 KB
/
Copy paths3gc.py
File metadata and controls
1164 lines (1044 loc) · 36.6 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
"""
The script removes orphaned objects from s3 object storage
Ones that are not mentioned in system.remote_data_paths table
There are two stages:
1. Collecting.
Paths of all objects found in object storage are put in auxiliary ClickHouse table.
It's name is a concatenation of 's3objects_for_' and disk name by default.
Created in the same ClickHouse instance where data from system.remote_data_paths selected
2. Removing.
All objects that exist in s3 and not used according to system.remote_data_paths
are removed from object storage.
It is possible to split these stages or do everything at one go.
"""
import os
import sys
from io import StringIO
from minio import Minio
from minio.deleteobjects import DeleteObject
from minio.credentials import IamAwsProvider
from minio.error import S3Error
from contextlib import redirect_stdout
import clickhouse_connect
from jsonargparse import (
ArgumentParser,
ActionConfigFile,
)
from jsonargparse.typing import Optional
import urllib3
import logging
import datetime
usage = """
s3 garbage collector for ClickHouse
example: $ ./s3gc.py
"""
def strtobool(value):
"""Minimal stdlib-compatible replacement for distutils.util.strtobool."""
normalized = value.lower()
if normalized in {"y", "yes", "t", "true", "on", "1"}:
return 1
if normalized in {"n", "no", "f", "false", "off", "0"}:
return 0
raise ValueError(f"invalid truth value {value!r}")
def coerce_bool(value):
"""Normalise anything an option may arrive as into a real bool.
Flags declared with action="store_true" are set to a real bool on the command
line, but jsonargparse populates them from the environment as the RAW STRING.
Every non-empty string is truthy in Python, so S3GC_DRYRUN_FLAG=false used to
mean *true*. Treat unset/empty as false and parse the usual spellings.
"""
if isinstance(value, bool):
return value
if value is None or value == "":
return False
if isinstance(value, (int, float)):
return bool(value)
return bool(strtobool(str(value)))
parser = ArgumentParser(
usage=usage, env_prefix="S3GC", default_env=True, exit_on_error=False
)
parser.add_argument(
"--chhost",
"--ch-host",
dest="chhost",
default="localhost",
help="ClickHouse host to connect to",
)
parser.add_argument(
"--chport",
"--ch-port",
dest="chport",
default=8123,
help="ClickHouse port to connect to",
)
parser.add_argument(
"--chuser",
"--ch-user-name",
"--chusername",
dest="chuser",
default="default",
help="ClickHouse user name",
)
parser.add_argument(
"--chpass",
"--ch-pass",
"--ch-password",
dest="chpass",
default="",
help="ClickHouse user password",
)
parser.add_argument(
"--s3ip",
"--s3-ip",
dest="s3ip",
default="127.0.0.1",
help="S3 API ip address or host",
)
parser.add_argument(
"--s3port", "--s3-port", dest="s3port", default=9001, help="S3 API port"
)
parser.add_argument(
"--s3bucket", "--s3-bucket", dest="s3bucket", default="root", help="S3 bucket name"
)
parser.add_argument(
"--s3path", "--s3-path", dest="s3path", default="data/", help="S3 path prefix"
)
parser.add_argument(
"--s3-access-key",
"--s3accesskey",
dest="s3accesskey",
default="",
help="S3 access key",
)
parser.add_argument(
"--s3-secret-key",
"--s3secretkey",
dest="s3secretkey",
default="",
help="S3 secret key",
)
parser.add_argument(
"--s3-session-token",
"--s3sessiontoken",
dest="s3sessiontoken",
default="",
help="S3 session token for explicit temporary credentials",
)
parser.add_argument(
"--s3auth",
"--s3-auth",
dest="s3auth",
default="static",
help=(
"S3 auth mode: static, aws or iam. static uses explicit keys (optionally with a "
"session token); aws uses the boto3 credential chain, including AWS SSO profiles; "
"iam uses MinIO's workload identity provider (IRSA/IMDS/ECS) and needs no boto3"
),
)
parser.add_argument(
"--s3profile",
"--s3-profile",
dest="s3profile",
default="",
help="AWS profile name for S3 auth. Setting this enables aws auth mode",
)
parser.add_argument(
"--s3secure",
"--s3-secure",
action="store_true",
dest="s3secure_flag",
default=False,
help="S3 secure mode",
)
parser.add_argument(
"--s3secureflag",
"--s3-secure-flag",
type=coerce_bool,
dest="s3secure_flag",
default=False,
help="S3 secure mode",
)
parser.add_argument(
"--s3sslcertfile",
"--s3-ssl-cert-file",
dest="s3sslcertfile",
default="",
help="SSL certificate for S3",
)
parser.add_argument(
"--s3region",
"--s3-region",
dest="s3region",
type=Optional[str],
help="S3 Region",
)
parser.add_argument(
"--s3diskname",
"--s3-disk-name",
dest="s3diskname",
default="s3",
help="S3 disk name",
)
parser.add_argument(
"--keepdata",
"--keep-data",
action="store_true",
dest="keepdata_flag",
default=False,
help="keep auxiliary data in ClickHouse table",
)
parser.add_argument(
"--keepdataflag",
"--keep-data-flag",
type=coerce_bool,
dest="keepdata_flag",
default=False,
help="keep auxiliary data in ClickHouse table",
)
parser.add_argument(
"--collectonly",
"--collect-only",
action="store_true",
dest="collectonly_flag",
default=False,
help="put object names to auxiliary table",
)
parser.add_argument(
"--collectonlyflag",
"--collect-only-flag",
type=coerce_bool,
dest="collectonly_flag",
default=False,
help="put object names to auxiliary table",
)
parser.add_argument(
"--usecollected",
"--use-collected",
action="store_true",
dest="usecollected_flag",
default=False,
help="auxiliary data is already collected in ClickHouse table",
)
parser.add_argument(
"--usecollectedflag",
"--use-collected-flag",
type=coerce_bool,
dest="usecollected_flag",
default=False,
help="auxiliary data is already collected in ClickHouse table",
)
parser.add_argument(
"--collecttableprefix",
"--collect-table-prefix",
dest="collecttableprefix",
default="s3objects_for_",
help="prefix for table name to keep data about objects (database is allowed, if not exists, specify --create-database)",
)
parser.add_argument(
"--collectbatchsize",
"--collect-batch-size",
dest="collectbatchsize",
type=int,
default=1024,
help="number of rows to insert to ClickHouse at once",
)
parser.add_argument(
"--total",
"--collecttotal",
"--collect-total",
"--total-num",
dest="total",
type=Optional[int],
help="Number of objects to collect. Can be used in conjunction with start-after",
)
parser.add_argument(
"--collectafter",
"--collect-after",
dest="collectafter",
type=Optional[str],
help="Object name to start after. If not specified, traversing objects from the beginning",
)
parser.add_argument(
"--useafter",
"--use-after",
dest="useafter",
type=Optional[str],
help="Object name to start processing already collected objects after. If not specified, traversing objects from the beginning",
)
parser.add_argument(
"--usetotal",
"--use-total",
dest="usetotal",
type=Optional[int],
help="Number of already collected objects to process. Can be used in conjunction with use-after",
)
parser.add_argument(
"--dryrun",
"--dry-run",
action="store_true",
dest="dryrun_flag",
help="Calculate objects to remove without actual removing",
)
parser.add_argument(
"--dryrunflag",
"--dryrun-flag",
"--dry-run-flag",
type=coerce_bool,
dest="dryrun_flag",
default=False,
help="Calculate objects to remove without actual removing",
)
parser.add_argument(
"--cluster",
"--cluster-name",
"--clustername",
dest="clustername",
default="",
help="Consider an objects unused if there is no host in the cluster refers the object",
)
parser.add_argument(
"--expected-replicas",
dest="expected_replicas",
type=Optional[int],
help="Fail before deleting when clusterAllReplicas() does not return this many replicas",
)
parser.add_argument(
"--age",
"--hours",
"--age-hours",
"--collectage",
"--collecthours",
"--age-hours",
dest="age",
type=int,
default=0,
help="Process only objects older than specified number of hours",
)
parser.add_argument(
"--useage",
"--usehours",
"--useage-hours",
dest="useage",
type=int,
default=0,
help="Process only already collected objects older than specified number of hours",
)
parser.add_argument(
"--samples",
dest="samples",
type=int,
default=4,
help="Number of partitions in auxiliary table",
)
parser.add_argument(
"--deletebatchsize",
"--delete-batch-size",
dest="deletebatchsize",
type=int,
default=1000,
help="S3 objects to delete and checkpoint per progress batch",
)
parser.add_argument(
"--order-by-objpath",
action="store_true",
dest="order_by_objpath",
default=False,
help="Order anti-join output by object path (costly for large Kubernetes Jobs)",
)
parser.add_argument(
"--order-by-objpath-flag",
dest="order_by_objpath",
type=coerce_bool,
default=False,
help="Order anti-join output by object path (costly for large Kubernetes Jobs)",
)
parser.add_argument(
"--s3-connect-timeout",
dest="s3_connect_timeout",
type=int,
default=15,
help="S3 connection timeout in seconds",
)
parser.add_argument(
"--s3-read-timeout",
dest="s3_read_timeout",
type=int,
default=120,
help="S3 read timeout in seconds",
)
parser.add_argument(
"--s3-retries",
dest="s3_retries",
type=int,
default=3,
help="S3 HTTP retries for transient failures",
)
parser.add_argument(
"--chtimeout",
"--ch-timeout",
"--send-receive-timeout",
"--ch-send-receive-timeout",
dest="chtimeout",
type=int,
default=1800,
help="clickhouse send/receive timeout in seconds",
)
parser.add_argument(
"--create-database",
"--createdatabase",
action="store_true",
dest="createdatabase_flag",
default=False,
help="create database for collecttable",
)
parser.add_argument(
"--create-database-flag",
"--createdatabase-flag",
dest="createdatabase_flag",
type=coerce_bool,
default=False,
help="create database for collecttable",
)
parser.add_argument(
"--drop-collecttable",
"--dropcollecttable",
action="store_true",
dest="drop_collecttable_flag",
default=False,
help="drop collecttable and recreate; beware of ClickHouse DROP TABLE constraints",
)
parser.add_argument(
"--drop-collecttable-flag",
"--dropcollecttable-flag",
dest="drop_collecttable_flag",
type=coerce_bool,
default=False,
help="drop collecttable and recreate; beware of ClickHouse DROP TABLE constraints",
)
parser.add_argument(
"--useremoveobjects",
"--use-remove-objects",
dest="use_remove_objects",
type=coerce_bool,
default=True,
help="use remove_objects (not supported by GCE). Set it to false to use remove_object",
)
parser.add_argument(
"--non-interactive",
"--noninteractive",
action="store_false",
dest="interactive_flag",
default=True,
help="confirm deleting",
)
parser.add_argument(
"--interactive-flag",
dest="interactive_flag",
type=coerce_bool,
default=True,
help="confirm deleting",
)
parser.add_argument(
"--verbose",
action="store_true",
dest="verbose_flag",
default=False,
help="debug output",
)
parser.add_argument(
"--verboseflag",
"--verbose-flag",
type=coerce_bool,
dest="verbose_flag",
default=False,
help="debug output",
)
parser.add_argument(
"--debug",
action="store_true",
dest="debug_flag",
default=False,
help="trace output (more verbose)",
)
parser.add_argument(
"--debugflag",
"--debug-flag",
type=coerce_bool,
dest="debug_flag",
default=False,
help="trace output (more verbose)",
)
parser.add_argument(
"--silent", action="store_true", dest="silent_flag", default=False, help="no log"
)
parser.add_argument(
"--silentflag",
"--silent-flag",
dest="silent_flag",
type=coerce_bool,
default=False,
help="no log",
)
parser.add_argument(
"--listoptions",
"--list-options",
action="store_true",
dest="listoptions",
default=False,
help="list all command line options for internal purposes",
)
parser.add_argument("--cfg", action=ActionConfigFile)
# out = get_parse_args_stdout(parser, ["--print_config"])
# print(out)
args = parser.parse_args()
# Every flag declared with action="store_true" arrives from the environment as a
# raw string, and every non-empty string is truthy. Normalise all boolean
# options in one place, immediately after parsing, so the rest of the program
# can rely on real bools.
BOOLEAN_DESTS = (
"s3secure_flag",
"use_remove_objects",
"keepdata_flag",
"collectonly_flag",
"usecollected_flag",
"dryrun_flag",
"order_by_objpath",
"createdatabase_flag",
"drop_collecttable_flag",
"verbose_flag",
"debug_flag",
"silent_flag",
"listoptions",
)
for _dest in BOOLEAN_DESTS:
if not hasattr(args, _dest):
continue
_raw = getattr(args, _dest)
try:
setattr(args, _dest, coerce_bool(_raw))
except ValueError:
parser.error(
f"invalid boolean value {_raw!r} for {_dest} "
f"(environment variable S3GC_{_dest.upper()}); "
"use one of true/false, yes/no, on/off, 1/0"
)
if args.listoptions:
with redirect_stdout(StringIO()) as f:
try:
parser.parse_args(["--print_config"])
except SystemExit:
pass
print("ENV ", end="")
backslash = False
for ln in f.getvalue().splitlines():
(key, value) = ln.split(": ")
# if (key in ['listoptions', 'verbose', 'debug', 'silent', 'keepdata', 'collectonly', 'usecollected']):
if key in ["listoptions"]:
continue
if backslash:
print(" \\")
print(f" S3GC_{key.upper()}={value}", end="")
backslash = True
print()
exit()
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING) # set logger level
if args.verbose_flag:
logger.setLevel(logging.INFO)
if args.debug_flag:
logger.setLevel(logging.DEBUG)
if args.silent_flag:
logger.setLevel(logging.CRITICAL)
##############################################################
class LogFormatter(logging.Formatter):
"""Formatter that wipes passwords if they are longer than 3 characters."""
def get_filter_strings():
filter_strings = []
for secret in [
args.chpass,
args.s3accesskey,
args.s3secretkey,
args.s3sessiontoken,
]:
if len(secret) > 3:
filter_strings.append(secret)
return filter_strings
filter_strings = get_filter_strings()
@staticmethod
def _filter(s):
for fs in LogFormatter.filter_strings:
s = s.replace(fs, "****")
return s
def format(self, record):
original = logging.Formatter.format(self, record)
return self._filter(original) if len(self.filter_strings) else original
logFormatter = LogFormatter("%(asctime)s %(levelname)s %(message)s")
def graceful_exit():
if not args.silent_flag:
print("s3gc: OK")
exit()
##############################################################
consoleHandler = logging.StreamHandler(sys.stdout) # set streamhandler to stdout
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
logger.debug(f"Parameters: {args}")
tname = ""
dbname = None
dbparts = args.collecttableprefix.split(".")
if len(dbparts) > 2:
ra
10BC8
ise ValueError("invalid collecttableprefix")
elif len(dbparts) == 2:
dbname = f"`{dbparts[0]}`"
tname = f"{dbname}.`{dbparts[1]}{args.s3diskname}`"
else:
tname = f"`{dbparts[0]}{args.s3diskname}`"
minio_client = None
ch_client = None
class S3DeletionError(RuntimeError):
"""A delete failed after successful deletions were checkpointed."""
def _query_single_value(query):
result = ch_client.query(query)
if not result.result_rows or not result.result_rows[0]:
raise RuntimeError(f"ClickHouse returned no result for preflight query: {query}")
return result.result_rows[0][0]
def preflight_cluster():
"""Make destructive cluster-wide cleanup fail closed when topology is unexpected."""
if not args.expected_replicas:
return
if not args.clustername:
raise ValueError("--expected-replicas requires --cluster")
actual_cluster = _query_single_value("SELECT getMacro('cluster')")
if actual_cluster != args.clustername:
raise RuntimeError(
f"cluster preflight failed: expected local cluster macro {args.clustername!r}, "
f"got {actual_cluster!r}"
)
cluster_name = args.clustername.replace("'", "\\\\'")
actual_replicas = _query_single_value(
f"SELECT count() FROM clusterAllReplicas('{cluster_name}', system.one)"
)
if actual_replicas != args.expected_replicas:
raise RuntimeError(
f"replica preflight failed: expected {args.expected_replicas}, got {actual_replicas}"
)
logger.info(
f"cluster preflight passed: cluster={args.clustername}, replicas={actual_replicas}"
)
class UserVisibleError(RuntimeError):
"""An operator-facing failure: reported without a traceback."""
def connect_to_ch():
logger.info(
f"Connecting to ClickHouse, host={args.chhost}, port={args.chport}, username={args.chuser}, password={args.chpass}, s3path={args.s3path}, bucket={args.s3bucket}, s3path={args.s3path}"
)
global ch_client
ch_client = clickhouse_connect.get_client(
host=args.chhost,
port=args.chport,
username=args.chuser,
password=args.chpass,
send_receive_timeout=args.chtimeout,
)
def resolve_static_s3_credentials():
if bool(args.s3accesskey) != bool(args.s3secretkey):
raise ValueError("s3accesskey and s3secretkey must be specified together")
if args.s3sessiontoken and not args.s3accesskey:
raise ValueError("s3sessiontoken requires s3accesskey and s3secretkey")
if args.s3accesskey:
return args.s3accesskey, args.s3secretkey, args.s3sessiontoken or None, args.s3region, "static"
return None, None, None, args.s3region, "anonymous"
def resolve_aws_s3_credentials():
if args.s3accesskey or args.s3secretkey or args.s3sessiontoken:
raise ValueError("s3auth=aws cannot be combined with explicit S3 access keys")
try:
import boto3
except ImportError as exc:
raise UserVisibleError("boto3 is required for s3auth=aws") from exc
session = boto3.Session(
profile_name=args.s3profile or None,
region_name=args.s3region,
)
credentials = session.get_credentials()
if credentials is None:
profile_hint = f" profile {args.s3profile}" if args.s3profile else ""
raise UserVisibleError(f"unable to resolve AWS credentials{profile_hint}")
frozen_credentials = credentials.get_frozen_credentials()
if not frozen_credentials.access_key or not frozen_credentials.secret_key:
profile_hint = f" profile {args.s3profile}" if args.s3profile else ""
raise UserVisibleError(f"resolved AWS credentials{profile_hint} are incomplete")
return (
frozen_credentials.access_key,
frozen_credentials.secret_key,
frozen_credentials.token,
args.s3region or session.region_name,
"aws",
)
AUTH_MODES = ("static", "aws", "iam")
def resolve_iam_s3_credentials():
"""Workload identity via MinIO's own provider — IRSA, IMDS or ECS task role.
Kept as a first-class mode rather than folded into `aws`: it needs no boto3,
and it is what the validated Kubernetes deployments use. `credentials=` is
returned instead of keys so MinIO can refresh the temporary credentials.
"""
return None, None, None, args.s3region, "iam"
def resolve_s3_credentials():
auth_mode = args.s3auth.lower()
if auth_mode not in AUTH_MODES:
raise ValueError(f"s3auth must be one of {', '.join(AUTH_MODES)}")
# Implied modes. Both are conveniences, so a contradiction is an error rather
# than a silent winner: picking one would send credentials nobody asked for.
if args.s3profile:
if auth_mode not in ("static", "aws"):
raise ValueError(f"s3profile implies s3auth=aws, which conflicts with s3auth={auth_mode}")
auth_mode = "aws"
if auth_mode == "aws":
return resolve_aws_s3_credentials()
if auth_mode == "iam":
return resolve_iam_s3_credentials()
return resolve_static_s3_credentials()
def connect_to_s3():
if args.s3secure_flag:
logger.debug(f"using SSL certificate {args.s3sslcertfile}")
os.environ["SSL_CERT_FILE"] = args.s3sslcertfile
access_key, secret_key, session_token, s3_region, s3_auth = resolve_s3_credentials()
logger.info(
f"Connecting to S3, host:port={args.s3ip}:{args.s3port}, auth={s3_auth}, "
f"secure={args.s3secure_flag}, region={s3_region}"
)
# Google Cloud Storage's S3-compatible API has no batch DeleteObjects, so
# remove_objects() fails there. Switch to the per-object path automatically
# rather than letting every delete fail at run time.
if "storage.googleapis.com" in args.s3ip and args.use_remove_objects:
logger.warning(
"GCS endpoint detected: batch remove_objects is not supported there, "
"falling back to per-object remove_object. This is markedly slower "
"(one request per object); pass --use-remove-objects false to silence this."
)
args.use_remove_objects = False
global minio_client
connection_options = {
"secure": args.s3secure_flag,
"region": s3_region,
"http_client": urllib3.PoolManager(
cert_reqs="CERT_NONE",
timeout=urllib3.Timeout(
connect=args.s3_connect_timeout, read=args.s3_read_timeout
),
retries=urllib3.Retry(
total=args.s3_retries,
connect=args.s3_retries,
read=args.s3_retries,
status=args.s3_retries,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=frozenset({"DELETE", "GET", "HEAD", "POST"}),
),
),
}
if s3_auth == "iam":
# Hand MinIO the provider, not frozen keys, so it can refresh the
# temporary credentials for the lifetime of a long collect or delete.
connection_options["credentials"] = IamAwsProvider()
else:
# static, aws and anonymous all arrive here as resolved values;
# session_token is None unless temporary credentials were supplied.
connection_options["access_key"] = access_key
connection_options["secret_key"] = secret_key
connection_options["session_token"] = session_token
minio_client = Minio(
f"{args.s3ip}:{args.s3port}",
**connection_options,
)
def remove_objects_reconnecting(batch_rows):
"""Delete one batch, reconnecting once if the S3 transport is stale.
DeleteObject requests are idempotent: retrying after an interrupted response
can only leave the object absent, never delete a different object.
"""
for attempt in range(2):
try:
return list(
minio_client.remove_objects(
args.s3bucket, [DeleteObject(row[0]) for row in batch_rows]
)
)
except (S3Error, urllib3.exceptions.HTTPError) as exc:
if attempt:
raise
logger.warning(
"S3 delete transport failed (%s); reconnecting and retrying once", exc
)
connect_to_s3()
raise AssertionError("unreachable")
def format_s3_list_error(exc):
code = getattr(exc, "code", "unknown")
message = getattr(exc, "message", str(exc))
profile_arg = f" --profile {args.s3profile}" if args.s3profile else ""
return (
f"unable to list S3 objects for bucket={args.s3bucket!r}, prefix={args.s3path!r}: "
f"{code}: {message}. "
f"s3gc collection requires s3:ListBucket on arn:aws:s3:::{args.s3bucket} "
f"for this prefix, even with --dry-run. Verify the same credentials with: "
f"aws sts get-caller-identity{profile_arg}; "
f"aws s3api list-objects-v2 --bucket {args.s3bucket} --prefix {args.s3path} --max-keys 1{profile_arg}"
)
def next_s3_object(objects):
try:
return next(objects)
except S3Error as exc:
raise UserVisibleError(format_s3_list_error(exc)) from exc
def do_collect():
logger.debug(f"start_after {args.collectafter}")
objects = minio_client.list_objects(
args.s3bucket, args.s3path, recursive=True, start_after=args.collectafter
)
if args.createdatabase_flag:
parts = args.collecttableprefix.split(".")
if dbname:
logger.info(f"creating database {dbname}")
ch_client.command(f"CREATE DATABASE IF NOT EXISTS {dbname}")
logger.debug(f"database created")
else:
raise ValueError(
"database must be a part of collecttableprefix if createdatabase flag is set&quo
A0D5
t;
)
if args.drop_collecttable_flag:
logger.info(f"dropping table {tname}")
ch_client.command(f"DROP TABLE IF EXISTS {tname}")
logger.debug(f"table dropped")
logger.info(f"creating table {tname}")
ch_client.command(
f"CREATE TABLE IF NOT EXISTS {tname} (objpath String, size Int64, last_modified DateTime, active Bool) ENGINE ReplacingMergeTree ORDER BY objpath PARTITION BY CRC32(objpath) % {args.samples}"
)
logger.debug(f"table created")
go_on = True
rest_row_nums = args.total # None if not set
num_inserted = 0
total_size = 0
while go_on:
objs = []
for batch_element in range(0, args.collectbatchsize):
try:
obj = next_s3_object(objects)
delta = datetime.datetime.now(datetime.timezone.utc) - obj.last_modified
# total_seconds(), not .seconds: the latter is the sub-day
# remainder (0..86399), so any object older than a day reported
# at most 23 hours and --age 24 collected nothing at all.
hours = int(delta.total_seconds() // 3600)
if hours >= args.age:
objs.append([obj.object_name, obj.size, obj.last_modified, True])
total_size += obj.size
except StopIteration:
go_on = False
ch_client.insert(tname, objs, column_names=["objpath", "size", "last_modified", "active"])
logger.debug(f"{len(objs)} rows inserted in {tname}")
num_inserted += len(objs)
if rest_row_nums is not None:
rest_row_nums -= len(objs)
if rest_row_nums == 0 or go_on == False:
go_on = False
if not args.silent_flag:
if len(objs):
print(f"s3gc: {objs[-1]}")
else:
print(f"s3gc: No object")
break
logger.info(
f"information about {num_inserted} objects of total size {total_size} is inserted in {tname}"
)
def check_samples_match_partitioning():
"""Warn when --samples disagrees with the aux table's PARTITION BY.
The table is created as PARTITION BY CRC32(objpath) % <samples> at COLLECT
time. Running the use phase with a different --samples silently loses
partition pruning: on one production cluster the matching case scanned a
sample in ~2 min where the mismatching case took ~26 min.
"""
try:
rows = ch_client.query(
"SELECT partition_key FROM system.tables "
f"WHERE database = currentDatabase() AND name = '{tname.strip('`').split('.')[-1]}'"
).result_rows
except Exception as exc:
logger.debug(f"could not read partition_key for {tname}: {exc}")
return
if not rows or not rows[0][0]:
return
partition_key = rows[0][0]
expected = f"% {args.samples}"
if "CRC32" in partition_key and expected not in partition_key.replace(" ", " "):
logger.warning(
f"--samples {args.samples} does not match the auxiliary table's "
f"partitioning ({partition_key}). Partition pruning will be lost; "
"use the same --samples value that the collect phase used."
)
def do_use():
if not args.dryrun_flag:
preflight_cluster()
srdp = "system.remote_data_paths"
if args.clustername:
srdp = f"clusterAllReplicas('{args.clustername}', {srdp})"
num_rows = 0
try:
count_query = f"SELECT COUNT(1) FROM {tname}"
logger.debug(count_query)
result = ch_client.command(count_query)
num_rows = result
except Exception as exc:
logger.info(f"exception selecting from {tname}, {exc}")
pass
if num_rows == 0:
# Exiting 0 here reads as success, but with --usecollected an absent or
# empty auxiliary table means the collect never ran, ran against another
# host, or was truncated. The table is a NODE-LOCAL ReplacingMergeTree, so
# a load-balanced ClickHouse Service can collect on one replica and land
# here on the other. Fail loudly instead of reporting a clean bucket.
raise RuntimeError(
f"auxiliary table {tname} does not exist or is empty on {args.chhost}. "
"Run the collect phase first, and make sure every phase targets the SAME "
"replica: the table is node-local, so a load-balanced Service will not do."
)
check_samples_match_partitioning()
def make_antijoin(calc_only=False, sample=None):