-
Notifications
You must be signed in to change notification settings - Fork 579
/
cache_service.cc
1996 lines (1768 loc) · 70.7 KB
/
cache_service.cc
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
/*
* Copyright 2021 Redpanda Data, Inc.
*
* Licensed as a Redpanda Enterprise file under the Redpanda Community
* License (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://github.com/redpanda-data/redpanda/blob/master/licenses/rcl.md
*/
#include "base/vassert.h"
#include "base/vlog.h"
#include "bytes/iostream.h"
#include "cloud_storage/access_time_tracker.h"
#include "cloud_storage/logger.h"
#include "cloud_storage/recursive_directory_walker.h"
#include "config/configuration.h"
#include "seastar/util/file.hh"
#include "ssx/future-util.h"
#include "ssx/sformat.h"
#include "utils/human.h"
#include <seastar/core/coroutine.hh>
#include <seastar/core/fstream.hh>
#include <seastar/core/io_priority_class.hh>
#include <seastar/core/seastar.hh>
#include <seastar/core/shard_id.hh>
#include <seastar/core/smp.hh>
#include <seastar/core/sstring.hh>
#include <seastar/util/defer.hh>
#include <cloud_storage/cache_service.h>
#include <re2/re2.h>
#include <algorithm>
#include <exception>
#include <filesystem>
#include <optional>
#include <stdexcept>
#include <string_view>
using namespace std::chrono_literals;
namespace {
// Matches log segments optionally containing a numeric term suffix
const re2::RE2 segment_expr{R"#(.*\.log(\.\d+)?)#"};
} // namespace
namespace cloud_storage {
static constexpr auto access_timer_period = 60s;
static constexpr const char* access_time_tracker_file_name = "accesstime";
static constexpr const char* access_time_tracker_file_name_tmp
= "accesstime.tmp";
std::ostream& operator<<(std::ostream& o, cache_element_status s) {
switch (s) {
case cache_element_status::available:
o << "cache_element_available";
break;
case cache_element_status::not_available:
o << "cache_element_not_available";
break;
case cache_element_status::in_progress:
o << "cache_element_in_progress";
break;
}
return o;
}
static constexpr auto tracker_sync_period = 3600s * 6;
cache::cache(
std::filesystem::path cache_dir,
size_t disk_size,
config::binding<double> disk_reservation,
config::binding<uint64_t> max_bytes_cfg,
config::binding<std::optional<double>> max_percent,
config::binding<uint32_t> max_objects,
config::binding<uint16_t> walk_concurrency) noexcept
: _cache_dir(std::move(cache_dir))
, _disk_size(disk_size)
, _disk_reservation(std::move(disk_reservation))
, _max_bytes_cfg(std::move(max_bytes_cfg))
, _max_percent(std::move(max_percent))
, _max_bytes(_max_bytes_cfg())
, _max_objects(std::move(max_objects))
, _walk_concurrency(std::move(walk_concurrency))
, _cnt(0)
, _total_cleaned(0) {
if (ss::this_shard_id() == ss::shard_id{0}) {
update_max_bytes(); // initialize _max_bytes
_disk_reservation.watch([this]() { update_max_bytes(); });
_max_bytes_cfg.watch([this]() { update_max_bytes(); });
_max_percent.watch([this]() { update_max_bytes(); });
}
}
void cache::update_max_bytes() {
// amount of data disk reserved for non-redpanda use
const uint64_t reservation_size = _disk_size
* (_disk_reservation() / 100.0);
// unreserved data disk space
const auto usable_size = _disk_size - reservation_size;
// percent-based target size
const uint64_t max_size_pct = usable_size
* (_max_percent().value_or(0) / 100.0);
auto max_size_bytes = _max_bytes_cfg();
if (max_size_bytes > usable_size) {
vlog(
cst_log.info,
"Clamping requested max bytes {} to usable size {}",
max_size_bytes,
usable_size);
max_size_bytes = usable_size;
}
if (max_size_pct > 0 && max_size_bytes == 0) {
// only percent target
_max_bytes = max_size_pct;
} else if (max_size_pct == 0 && max_size_bytes > 0) {
// only bytes target
_max_bytes = max_size_bytes;
} else {
_max_bytes = std::min(max_size_pct, max_size_bytes);
}
vlog(
cst_log.info,
"Cache max_bytes adjusted to {} (current size {}). Disk size {} "
"reservation {}% max size {} / {}%",
_max_bytes,
_current_cache_size,
_disk_size,
_disk_reservation(),
_max_bytes_cfg(),
_max_percent());
if (_current_cache_size > _max_bytes) {
ssx::spawn_with_gate(_gate, [this]() { return trim_throttled(); });
}
}
ss::future<bool>
cache::delete_file_and_empty_parents(const std::string_view& key) {
auto guard = _gate.hold();
std::filesystem::path normal_path
= std::filesystem::path(key).lexically_normal();
std::filesystem::path normal_cache_dir = _cache_dir.lexically_normal();
size_t deletions = 0;
auto [p1, p2] = std::mismatch(
normal_cache_dir.begin(), normal_cache_dir.end(), normal_path.begin());
if (p1 != normal_cache_dir.end()) {
throw std::invalid_argument(fmt_with_ctx(
fmt::format,
"Tried to clean up {}, which is outside of cache_dir {}.",
normal_path.native(),
normal_cache_dir.native()));
}
// Delete the specified file, and iterate through parents
// attempting to delete them (will delete empty directories,
// and then drop out when we hit a non-empty directory).
while (normal_path != normal_cache_dir) {
try {
vlog(cst_log.trace, "Removing {}", normal_path);
co_await ss::remove_file(normal_path.native());
deletions++;
} catch (const std::filesystem::filesystem_error& e) {
if (e.code() == std::errc::directory_not_empty) {
// we stop when we find a non-empty directory
co_return deletions > 1;
} else {
throw;
}
}
normal_path = normal_path.parent_path();
}
co_return deletions > 1;
}
uint64_t cache::get_total_cleaned() { return _total_cleaned; }
ss::future<> cache::clean_up_at_start() {
auto guard = _gate.hold();
auto
[walked_size, filtered_out_files, candidates_for_deletion, empty_dirs, _]
= co_await _walker.walk(
_cache_dir.native(), _access_time_tracker, _walk_concurrency());
vassert(
filtered_out_files == 0,
"Start-up cache clean-up should not apply filtering");
// The state of the _access_time_tracker and the actual content of the
// cache directory might diverge over time (if the user removes segment
// files manually). We need to take this into account.
// On startup we perform a bi-directional sync, IE entries found during
// directory walk which are not in tracker are added to it. This covers the
// following scenarios:
// 1. Following an upgrade, the tracker was loaded as empty to discard
// previous serialized data. Now we need to rehydrate the tracker and it is
// easier to do it now than wait for get requests to do this.
// 2. In a previous run the tracker had entries which it was not able to
// write to disk due to a crash. A directory walk will bring the tracker to
// an up to date state.
co_await _access_time_tracker.sync(
candidates_for_deletion, access_time_tracker::add_entries_t::yes);
probe.tracker_sync();
probe.set_tracker_size(_access_time_tracker.size());
uint64_t deleted_bytes{0};
size_t deleted_count{0};
for (const auto& file_item : candidates_for_deletion) {
auto filepath_to_remove = file_item.path;
// delete only tmp files that are left from previous RedPanda run
if (std::string_view(filepath_to_remove)
.ends_with(cache_tmp_file_extension)) {
try {
co_await delete_file_and_empty_parents(filepath_to_remove);
deleted_bytes += file_item.size;
deleted_count++;
} catch (const std::exception& e) {
vlog(
cst_log.error,
"Startup cache cleanup couldn't delete {}: {}.",
filepath_to_remove,
e.what());
}
}
}
for (const auto& path : empty_dirs) {
try {
co_await ss::remove_file(path);
} catch (const std::exception& e) {
// Leaving an empty dir will not prevent progress, so tolerate
// errors on deletion (could be e.g. a permissions error)
vlog(
cst_log.error,
"Startup cache cleanup couldn't delete {}: {}.",
path,
e);
}
}
_total_cleaned = deleted_bytes;
_current_cache_size = walked_size - deleted_bytes;
_current_cache_objects = filtered_out_files + candidates_for_deletion.size()
- deleted_count;
probe.set_size(_current_cache_size - deleted_bytes);
probe.set_num_files(_current_cache_objects);
vlog(
cst_log.debug,
"Clean up at start deleted {} files of total size {}. Size is now {}/{}",
deleted_count,
deleted_bytes,
_current_cache_size,
_current_cache_objects);
}
std::optional<std::chrono::milliseconds> cache::get_trim_delay() const {
auto now = ss::lowres_clock::now();
std::chrono::milliseconds interval
= config::shard_local_cfg().cloud_storage_cache_check_interval_ms();
if (now - _last_clean_up >= interval) {
return std::nullopt;
} else {
auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(
now - _last_clean_up);
return interval - delta;
}
}
ss::future<> cache::trim_throttled_unlocked(
std::optional<uint64_t> size_limit_override,
std::optional<size_t> object_limit_override) {
// If we trimmed very recently then do not do it immediately:
// this reduces load and improves chance of currently promoted
// segments finishing their read work before we demote their
// data from cache.
auto trim_delay = get_trim_delay();
if (trim_delay.has_value()) {
vlog(
cst_log.info,
"Cache trimming throttled, waiting {}ms",
std::chrono::duration_cast<std::chrono::milliseconds>(*trim_delay)
.count());
co_await ss::sleep_abortable(*trim_delay, _as);
}
co_await trim(size_limit_override, object_limit_override);
}
ss::future<> cache::trim_throttled(
std::optional<uint64_t> size_limit_override,
std::optional<size_t> object_limit_override) {
auto units = co_await ss::get_units(_cleanup_sm, 1);
co_await trim_throttled_unlocked(
size_limit_override, object_limit_override);
}
ss::future<> cache::trim_manually(
std::optional<uint64_t> size_limit_override,
std::optional<size_t> object_limit_override) {
vassert(ss::this_shard_id() == 0, "Method can only be invoked on shard 0");
auto units = co_await ss::get_units(_cleanup_sm, 1);
vlog(
cst_log.info,
"Beginning manual trim, requested bytes limit: {}, requested object "
"limit: {}",
size_limit_override,
object_limit_override);
co_return co_await trim(size_limit_override, object_limit_override);
}
ss::future<> cache::trim(
std::optional<uint64_t> size_limit_override,
std::optional<size_t> object_limit_override) {
vassert(ss::this_shard_id() == 0, "Method can only be invoked on shard 0");
auto guard = _gate.hold();
auto size_limit = size_limit_override.value_or(_max_bytes);
auto object_limit = object_limit_override.value_or(_max_objects());
// We aim to trim to within the upper size limit, and additionally
// free enough space for anyone waiting in `reserve_space` to proceed
auto target_size = uint64_t(
(size_limit - std::min(_reservations_pending, size_limit)));
size_t target_objects = static_cast<size_t>(object_limit)
- std::min(
_reservations_pending_objects,
static_cast<size_t>(object_limit));
// Apply _cache_size_low_watermark to the size and/or the object count,
// depending on which is currently the limiting factor for the trim.
if (_current_cache_objects + _reserved_cache_objects > target_objects) {
target_objects *= _cache_size_low_watermark;
}
if (_current_cache_size + _reserved_cache_size > target_size) {
target_size *= _cache_size_low_watermark;
}
// In the extreme case where even trimming to the low watermark wouldn't
// free enough space to enable writing to the cache, go even further.
if (_free_space < config::shard_local_cfg().storage_min_free_bytes()) {
target_size = std::min(
target_size,
_current_cache_size
- std::min(
_current_cache_size,
config::shard_local_cfg().storage_min_free_bytes()));
vlog(
cst_log.warn,
"Critically low space, trimming to {} bytes",
target_size);
}
if (
_current_cache_size + _reserved_cache_size < target_size
&& _current_cache_objects + _reserved_cache_objects < target_objects) {
// Exit early if we are already within the target
co_return;
}
// Calculate how much to delete
auto size_to_delete
= (_current_cache_size + _reserved_cache_size)
- std::min(target_size, _current_cache_size + _reserved_cache_size);
auto objects_to_delete
= _current_cache_objects + _reserved_cache_objects
- std::min(
target_objects, _current_cache_objects + _reserved_cache_objects);
auto tracker_lru_entries = _access_time_tracker.lru_entries();
vlog(
cst_log.debug,
"in-memory trim: set target_size {}/{}, size {}/{}, reserved {}/{}, "
"pending {}/{}, candidates for deletion: {}, size to delete: {}, "
"objects to delete: {}",
target_size,
target_objects,
_current_cache_size,
_current_cache_objects,
_reserved_cache_size,
_reserved_cache_objects,
_reservations_pending,
_reservations_pending_objects,
tracker_lru_entries.size(),
size_to_delete,
objects_to_delete);
auto trim_result = co_await do_trim(
tracker_lru_entries, size_to_delete, objects_to_delete);
probe.in_mem_trim();
vlog(
cst_log.debug,
"in-memory trim result: deleted size: {}, deleted count: {}",
trim_result.deleted_size,
trim_result.deleted_count);
_total_cleaned += trim_result.deleted_size;
probe.set_size(_current_cache_size);
probe.set_num_files(_current_cache_objects);
size_to_delete -= std::min(trim_result.deleted_size, size_to_delete);
objects_to_delete -= std::min(trim_result.deleted_count, objects_to_delete);
// Subsequent calculations require knowledge of how much data cannot
// possibly be deleted (because all trims skip it) in order to decide
// whether the trim worked properly.
static constexpr size_t undeletable_objects = 1;
auto undeletable_bytes = (co_await access_time_tracker_size()).value_or(0);
if (
size_to_delete <= undeletable_bytes
&& objects_to_delete <= undeletable_objects) {
vlog(
cst_log.debug,
"in-memory trim finished: size/objects to delete: {}/{}, undeletable "
"size/objects: {}/{}",
size_to_delete,
objects_to_delete,
undeletable_bytes,
undeletable_objects);
_last_clean_up = ss::lowres_clock::now();
_last_trim_failed = false;
co_return;
}
// We are going to do a walk, rearm the periodic tracker sync if it is about
// to run soon.
_tracker_sync_timer.rearm(ss::lowres_clock::now() + tracker_sync_period);
auto
[walked_cache_size,
filtered_out_files,
candidates_for_deletion,
_,
tmp_files_size]
= co_await _walker.walk(
_cache_dir.native(),
_access_time_tracker,
_walk_concurrency(),
[](std::string_view path) {
return !(
std::string_view(path).ends_with(".tx")
|| std::string_view(path).ends_with(".index"));
});
// Updating the access time tracker in case if some files were removed
// from cache directory by the user manually.
co_await _access_time_tracker.sync(candidates_for_deletion);
probe.tracker_sync();
probe.set_tracker_size(_access_time_tracker.size());
vlog(
cst_log.debug,
"trim: set target_size {}/{}, size {}/{}, walked size {} (max {}/{}), "
" reserved {}/{}, pending {}/{}, candidates for deletion: {}, filtered "
"out: {}",
target_size,
target_objects,
_current_cache_size,
_current_cache_objects,
walked_cache_size,
size_limit,
object_limit,
_reserved_cache_size,
_reserved_cache_objects,
_reservations_pending,
_reservations_pending_objects,
candidates_for_deletion.size(),
filtered_out_files);
// Sort by atime for the subsequent LRU trimming loop
std::ranges::sort(
candidates_for_deletion, {}, &file_list_item::access_time);
vlog(
cst_log.debug,
"trim: removing {}/{} bytes, {}/{} objects ({}% of cache) to reach "
"target {} (tmp size {})",
size_to_delete,
_current_cache_size,
objects_to_delete,
_current_cache_objects,
_current_cache_size > 0 ? (size_to_delete * 100) / _current_cache_size
: 0,
target_size,
tmp_files_size);
// Execute the ordinary trim, prioritize removing
trim_result = co_await trim_fast(
candidates_for_deletion, size_to_delete, objects_to_delete);
// We aim to keep current_cache_size continuously up to date, but
// in case of housekeeping issues, correct it if it apepars to have
// drifted too far from the result of our directory walk.
// This is a lower bound that permits current cache size to deviate
// by the amount of data currently in tmp files, because they may be
// updated while the walk is happening.
uint64_t cache_size_lower_bound = walked_cache_size
- trim_result.deleted_size
- tmp_files_size - undeletable_bytes;
if (_current_cache_size < cache_size_lower_bound) {
vlog(
cst_log.debug,
"Correcting cache size drift ({} -> {})",
_current_cache_size,
cache_size_lower_bound);
_current_cache_size = cache_size_lower_bound;
_current_cache_objects = filtered_out_files
+ candidates_for_deletion.size()
- trim_result.deleted_count;
}
const auto cache_entries_before_trim = candidates_for_deletion.size()
+ filtered_out_files;
vlog(
cst_log.debug,
"trim: deleted {}/{} files of total size {}. Undeletable size {}.",
trim_result.deleted_count,
cache_entries_before_trim,
trim_result.deleted_size,
undeletable_bytes);
_total_cleaned += trim_result.deleted_size;
probe.set_size(_current_cache_size);
probe.set_num_files(cache_entries_before_trim - trim_result.deleted_count);
size_to_delete -= std::min(trim_result.deleted_size, size_to_delete);
objects_to_delete -= std::min(trim_result.deleted_count, objects_to_delete);
// Before we (maybe) proceed to do an exhaustive trim, make sure we're not
// trying to trim more data than was physically seen while walking the
// cache.
size_to_delete = std::min(
walked_cache_size - trim_result.deleted_size, size_to_delete);
// If we were not able to delete enough files and there are some filtered
// out files, force an exhaustive trim. This ensures that if the cache is
// dominated by filtered out files, we do not skip trimming them by reducing
// the objects_to_delete counter next.
bool force_exhaustive_trim = trim_result.deleted_count < objects_to_delete
&& filtered_out_files > 0;
// In the situation where all files in cache are filtered out,
// candidates_for_deletion equals 1 (due to the accesstime tracker file) and
// the following reduction to objects_to_delete ends up setting
// this counter to 1, causing the exhaustive trim to be skipped. The check
// force_exhaustive_trim avoids this.
if (!force_exhaustive_trim) {
objects_to_delete = std::min(
candidates_for_deletion.size() - trim_result.deleted_count,
objects_to_delete);
}
if (
size_to_delete > undeletable_bytes
|| objects_to_delete > undeletable_objects) {
vlog(
cst_log.info,
"trim: fast trim did not free enough space, executing exhaustive "
"trim to free {}/{}...",
size_to_delete,
objects_to_delete);
auto exhaustive_result = co_await trim_exhaustive(
size_to_delete, objects_to_delete);
size_to_delete -= std::min(
exhaustive_result.deleted_size, size_to_delete);
objects_to_delete -= std::min(
exhaustive_result.deleted_count, objects_to_delete);
if ((size_to_delete > undeletable_bytes
|| objects_to_delete > undeletable_objects)) {
const auto msg = fmt::format(
"trim: failed to free sufficient space in exhaustive trim, {} "
"bytes, {} objects still require deletion",
size_to_delete,
objects_to_delete);
if (exhaustive_result.trim_missed_tmp_files) {
vlog(cst_log.info, "{}", msg);
} else {
vlog(cst_log.error, "{}", msg);
}
probe.failed_trim();
}
}
vlog(
cst_log.info,
"trim: post-trim cache size {}/{} (reserved {}/{}, pending {}/{})",
_current_cache_size,
_current_cache_objects,
_reserved_cache_size,
_reserved_cache_objects,
_reservations_pending,
_reserved_cache_objects);
_last_clean_up = ss::lowres_clock::now();
// It is up to callers to set this to true if they determine that after
// trim, we did not free as much space as they needed.
_last_trim_failed = false;
}
ss::future<cache::trim_result>
cache::remove_segment_full(const file_list_item& file_stat) {
trim_result result;
try {
uint64_t this_segment_deleted_bytes{0};
auto deleted_parents = co_await delete_file_and_empty_parents(
file_stat.path);
result.deleted_size += file_stat.size;
this_segment_deleted_bytes += file_stat.size;
_current_cache_size -= file_stat.size;
_current_cache_objects -= 1;
result.deleted_count += 1;
// Determine whether we should delete indices along with the
// object we have just deleted
std::optional<std::string> tx_file;
std::optional<std::string> index_file;
if (RE2::FullMatch(file_stat.path.data(), segment_expr)) {
// If this was a legacy whole-segment item, delete the index
// and tx file along with the segment
tx_file = fmt::format("{}.tx", file_stat.path);
index_file = fmt::format("{}.index", file_stat.path);
} else if (deleted_parents) {
auto immediate_parent = std::string(
std::filesystem::path(file_stat.path).parent_path());
static constexpr std::string_view chunks_suffix{"_chunks"};
if (immediate_parent.ends_with(chunks_suffix)) {
// We just deleted the last chunk from a _chunks segment
// directory. We may delete the index + tx state for
// that segment.
auto base_segment_path = immediate_parent.substr(
0, immediate_parent.size() - chunks_suffix.size());
tx_file = fmt::format("{}.tx", base_segment_path);
index_file = fmt::format("{}.index", base_segment_path);
}
}
if (tx_file.has_value()) {
try {
auto sz = co_await ss::file_size(tx_file.value());
co_await ss::remove_file(tx_file.value());
result.deleted_size += sz;
this_segment_deleted_bytes += sz;
result.deleted_count += 1;
_current_cache_size -= sz;
_current_cache_objects -= 1;
} catch (const std::filesystem::filesystem_error& e) {
if (e.code() != std::errc::no_such_file_or_directory) {
throw;
}
}
}
if (index_file.has_value()) {
try {
auto sz = co_await ss::file_size(index_file.value());
co_await ss::remove_file(index_file.value());
result.deleted_size += sz;
this_segment_deleted_bytes += sz;
result.deleted_count += 1;
_current_cache_size -= sz;
_current_cache_objects -= 1;
} catch (const std::filesystem::filesystem_error& e) {
if (e.code() != std::errc::no_such_file_or_directory) {
throw;
}
}
}
// Remove key if possible to make sure there is no resource
// leak
_access_time_tracker.remove(file_stat.path);
vlog(
cst_log.trace,
"trim: reclaimed(fast) {} bytes from {}",
this_segment_deleted_bytes,
file_stat.path);
} catch (const ss::gate_closed_exception&) {
// We are shutting down, stop iterating and propagate
throw;
} catch (const std::exception& e) {
vlog(
cst_log.error,
"trim: couldn't delete {}: {}.",
file_stat.path,
e.what());
}
co_return result;
}
ss::future<cache::trim_result> cache::trim_fast(
const fragmented_vector<file_list_item>& candidates,
uint64_t size_to_delete,
size_t objects_to_delete) {
probe.fast_trim();
co_return co_await do_trim(candidates, size_to_delete, objects_to_delete);
}
ss::future<cache::trim_result> cache::do_trim(
const fragmented_vector<file_list_item>& candidates,
uint64_t size_to_delete,
size_t objects_to_delete) {
trim_result result;
// Reset carryover list
_last_trim_carryover = std::nullopt;
auto need_to_skip = [this](const file_list_item& file_stat) {
if (is_trim_exempt(file_stat.path)) {
return true;
}
// skip tmp files since someone may be writing to it
if (std::string_view(file_stat.path)
.ends_with(cache_tmp_file_extension)) {
return true;
}
// Doesn't make sense to demote these independent of the segment
// they refer to: we will clear them out along with the main log
// segment file if they exist.
if (
std::string_view(file_stat.path).ends_with(".tx")
|| std::string_view(file_stat.path).ends_with(".index")) {
return true;
}
return false;
};
size_t candidate_i = 0;
while (
candidate_i < candidates.size()
&& (result.deleted_size < size_to_delete || result.deleted_count < objects_to_delete)) {
auto& file_stat = candidates[candidate_i++];
if (need_to_skip(file_stat)) {
continue;
}
auto op_res = co_await this->remove_segment_full(file_stat);
result.deleted_count += op_res.deleted_count;
result.deleted_size += op_res.deleted_size;
}
ssize_t max_carryover_bytes
= config::shard_local_cfg()
.cloud_storage_cache_trim_carryover_bytes.value();
fragmented_vector<file_list_item> tmp;
auto estimated_size = std::min(
static_cast<size_t>(max_carryover_bytes),
candidates.size() - candidate_i);
tmp.reserve(estimated_size);
while (max_carryover_bytes > 0 && candidate_i < candidates.size()) {
const auto& fs = candidates[candidate_i++];
if (need_to_skip(fs)) {
continue;
}
max_carryover_bytes -= static_cast<ssize_t>(
sizeof(fs) + fs.path.size());
tmp.push_back(fs);
}
if (!tmp.empty()) {
_last_trim_carryover = std::move(tmp);
}
co_return result;
}
bool cache::is_trim_exempt(const ss::sstring& path) const {
if (
path == (_cache_dir / access_time_tracker_file_name).string()
|| path == (_cache_dir / access_time_tracker_file_name_tmp).string()) {
return true;
}
return false;
}
ss::future<cache::trim_result>
cache::trim_exhaustive(uint64_t size_to_delete, size_t objects_to_delete) {
probe.exhaustive_trim();
trim_result result;
_last_trim_carryover = std::nullopt;
// Enumerate ALL files in the cache (as opposed to trim_fast that strips out
// indices/tx/tmp files)
auto [walked_cache_size, _filtered_out, candidates, _, tmp_files_size]
= co_await _walker.walk(
_cache_dir.native(), _access_time_tracker, _walk_concurrency());
vlog(
cst_log.debug,
"trim: exhaustive trim of {} candidates, walked size {} (cache size "
"{}/{}), {}/{} to delete",
candidates.size(),
walked_cache_size,
_current_cache_size,
_current_cache_objects,
size_to_delete,
objects_to_delete);
// Sort by atime
std::sort(candidates.begin(), candidates.end(), [](auto& a, auto& b) {
return a.access_time < b.access_time;
});
size_t candidate_i = 0;
while (
candidate_i < candidates.size()
&& (result.deleted_size < size_to_delete || result.deleted_count < objects_to_delete)) {
auto& file_stat = candidates[candidate_i++];
if (is_trim_exempt(file_stat.path)) {
continue;
}
// Unlike the fast trim, we *do not* skip .tmp files. This is to handle
// the case where we have some abandoned tmp files, and have hit the
// exhaustive trim because they are occupying too much space.
try {
co_await delete_file_and_empty_parents(file_stat.path);
_access_time_tracker.remove(file_stat.path);
_current_cache_size -= std::min(
file_stat.size, _current_cache_size);
_current_cache_objects -= std::min(
size_t{1}, _current_cache_objects);
result.deleted_count += 1;
result.deleted_size += file_stat.size;
vlog(
cst_log.trace,
"trim: reclaimed(exhaustive) {} bytes from {}",
file_stat.size,
file_stat.path);
} catch (const ss::gate_closed_exception&) {
// We are shutting down, stop iterating and propagate
throw;
} catch (const std::filesystem::filesystem_error& e) {
if (likely(file_stat.path.ends_with(cache_tmp_file_extension))) {
// In exhaustive scan we might hit a .part file and get ENOENT,
// this is expected behavior occasionally.
result.trim_missed_tmp_files = true;
vlog(
cst_log.info,
"trim: couldn't delete temp file {}: {}.",
file_stat.path,
e.what());
} else {
vlog(
cst_log.error,
"trim: couldn't delete {}: {}.",
file_stat.path,
e.what());
}
} catch (const std::exception& e) {
vlog(
cst_log.error,
"trim: couldn't delete {}: {}.",
file_stat.path,
e.what());
}
}
co_return result;
}
ss::future<std::optional<uint64_t>> cache::access_time_tracker_size() const {
auto path = _cache_dir / access_time_tracker_file_name;
try {
co_return static_cast<uint64_t>(co_await ss::file_size(path.string()));
} catch (const std::filesystem::filesystem_error& e) {
if (e.code() == std::errc::no_such_file_or_directory) {
co_return std::nullopt;
} else {
throw;
}
}
}
ss::future<> cache::load_access_time_tracker() {
ss::gate::holder guard{_gate};
vassert(ss::this_shard_id() == 0, "Method can only be invoked on shard 0");
auto source = _cache_dir / access_time_tracker_file_name;
auto present = co_await ss::file_exists(source.native());
if (!present) {
vlog(cst_log.info, "Access time tracker doesn't exist at '{}'", source);
co_return;
}
vlog(
cst_log.info, "Trying to hydrate access time tracker from '{}'", source);
ss::file_open_options open_opts;
ss::file_input_stream_options input_opts{};
input_opts.buffer_size = config::shard_local_cfg().storage_read_buffer_size;
input_opts.read_ahead
= config::shard_local_cfg().storage_read_readahead_count;
input_opts.io_priority_class
= priority_manager::local().shadow_indexing_priority();
auto exists = co_await ss::file_exists(source.string());
if (exists) {
try {
co_await ss::util::with_file_input_stream(
source,
[this](ss::input_stream<char>& in) {
return _access_time_tracker.read(in);
},
open_opts,
input_opts);
} catch (...) {
vlog(
cst_log.warn,
"Failed to materialize access time tracker '{}'. Error: {}",
source,
std::current_exception());
}
} else {
vlog(
cst_log.info, "Access time tracker is not available at '{}'", source);
}
}
/**
* Inner part of save_access_time_tracker, to be called with a file
* that the caller will close for us after we return.
*/
ss::future<> cache::_save_access_time_tracker(ss::file f) {
auto out = co_await ss::make_file_output_stream(std::move(f));
co_await _access_time_tracker.write(out);
co_await out.flush();
}
ss::future<> cache::save_access_time_tracker() {
ss::gate::holder guard{_gate};
vassert(ss::this_shard_id() == 0, "Method can only be invoked on shard 0");
auto tmp_path = _cache_dir / access_time_tracker_file_name_tmp;
// Protect the file from concurrent writes.
auto lock_guard = co_await ss::get_units(_access_tracker_writer_sm, 1);
ss::file_open_options open_opts;
co_await ss::with_file(
ss::open_file_dma(
tmp_path.string(),
ss::open_flags::create | ss::open_flags::wo,
open_opts),
[this](ss::file f) -> ss::future<> {
return _save_access_time_tracker(std::move(f));
});
auto final_path = _cache_dir / access_time_tracker_file_name;
co_await ss::rename_file(tmp_path.string(), final_path.string());
lock_guard.return_all();
}
ss::future<> cache::maybe_save_access_time_tracker() {
vassert(ss::this_shard_id() == 0, "Method can only be invoked on shard 0");
if (_access_time_tracker.is_dirty() && !_gate.is_closed()) {
co_await save_access_time_tracker();
}
}
ss::future<> cache::start() {
vlog(
cst_log.debug,
"Starting archival cache service, data directory: {}",
_cache_dir);