-
Notifications
You must be signed in to change notification settings - Fork 319
Expand file tree
/
Copy pathCacheAllocatorConfig.h
More file actions
1337 lines (1130 loc) · 48.6 KB
/
CacheAllocatorConfig.h
File metadata and controls
1337 lines (1130 loc) · 48.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <folly/Optional.h>
#include <folly/json/DynamicConverter.h>
#include <folly/json/json.h>
#include <chrono>
#include <functional>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include "cachelib/allocator/BackgroundMoverStrategy.h"
#include "cachelib/allocator/Cache.h"
#include "cachelib/allocator/MM2Q.h"
#include "cachelib/allocator/MemoryMonitor.h"
#include "cachelib/allocator/MemoryTierCacheConfig.h"
#include "cachelib/allocator/NvmAdmissionPolicy.h"
#include "cachelib/allocator/PoolOptimizeStrategy.h"
#include "cachelib/allocator/RebalanceStrategy.h"
#include "cachelib/allocator/Util.h"
#include "cachelib/common/EventInterface.h"
#include "cachelib/common/Throttler.h"
namespace facebook {
namespace cachelib {
// Config class for CacheAllocator.
template <typename CacheT>
class CacheAllocatorConfig {
public:
using AccessConfig = typename CacheT::AccessConfig;
using ChainedItemMovingSync = typename CacheT::ChainedItemMovingSync;
using RemoveCb = typename CacheT::RemoveCb;
using ItemDestructor = typename CacheT::ItemDestructor;
using NvmCacheEncodeCb = typename CacheT::NvmCacheT::EncodeCB;
using NvmCacheDecodeCb = typename CacheT::NvmCacheT::DecodeCB;
using NvmCacheMakeBlobCb = typename CacheT::NvmCacheT::MakeBlobCB;
using NvmCacheMakeObjCb = typename CacheT::NvmCacheT::MakeObjCB;
using NvmCacheDeviceEncryptor = typename CacheT::NvmCacheT::DeviceEncryptor;
using MoveCb = typename CacheT::MoveCb;
using NvmCacheConfig = typename CacheT::NvmCacheT::Config;
using MemoryTierConfigs = std::vector<MemoryTierCacheConfig>;
using Key = typename CacheT::Key;
using EventTrackerSharedPtr = std::shared_ptr<typename CacheT::EventTracker>;
using Item = typename CacheT::Item;
// Set cache name as a string
CacheAllocatorConfig& setCacheName(const std::string&);
// Set cache size in bytes. If size is smaller than 60GB (64'424'509'440),
// then we will enable full coredump. Otherwise, we will disable it. The
// reason we disable full coredump for large cache is because it takes a
// long time to dump, and also we might not have enough local storage.
CacheAllocatorConfig& setCacheSize(size_t _size);
// Set default allocation sizes for a cache pool
CacheAllocatorConfig& setDefaultAllocSizes(std::set<uint32_t> allocSizes);
// Set default allocation sizes based on arguments
CacheAllocatorConfig& setDefaultAllocSizes(
double _allocationClassSizeFactor,
uint32_t _maxAllocationClassSize,
uint32_t _minAllocationClassSize,
bool _reduceFragmentationInAllocationClass);
// Set the access config for cachelib's access container. Refer to our
// user guide for how to tune access container (configure hashtable).
CacheAllocatorConfig& setAccessConfig(AccessConfig config);
// Set the access config for cachelib's access container based on the
// number of estimated cache entries.
CacheAllocatorConfig& setAccessConfig(size_t numEntries);
// RemoveCallback is invoked for each item that is evicted or removed
// explicitly from RAM
CacheAllocatorConfig& setRemoveCallback(RemoveCb cb);
// ItemDestructor is invoked for each item that is evicted or removed
// explicitly from cache (both RAM and NVM)
CacheAllocatorConfig& setItemDestructor(ItemDestructor destructor);
// Config for NvmCache. If enabled, cachelib will also make use of flash.
CacheAllocatorConfig& enableNvmCache(NvmCacheConfig config);
// enable the reject first admission policy through its parameters
// @param numEntries the number of entries to track across all splits
// @param numSplits the number of splits. we drop a whole split by
// FIFO
// @param suffixIgnoreLength the suffix of the key to ignore for tracking.
// disabled when set to 0
//
// @param useDramHitSignal use hits in DRAM as signal for admission
CacheAllocatorConfig& enableRejectFirstAPForNvm(uint64_t numEntries,
uint32_t numSplits,
size_t suffixIgnoreLength,
bool useDramHitSignal);
// enable an admission policy for NvmCache. If this is set, other supported
// options like enableRejectFirstAP etc are overlooked.
//
// @throw std::invalid_argument if nullptr is passed.
CacheAllocatorConfig& setNvmCacheAdmissionPolicy(
std::shared_ptr<NvmAdmissionPolicy<CacheT>> policy);
// enables encoding items before they go into nvmcache
CacheAllocatorConfig& setNvmCacheEncodeCallback(NvmCacheEncodeCb cb);
// enables decoding items before they get back into ram cache
CacheAllocatorConfig& setNvmCacheDecodeCallback(NvmCacheDecodeCb cb);
// Set callback to create blobs to be copied into NvmItem from the Item being
// evicted from DRAM. This is useful for cases where we need to change the
// data. For example, we can use it to encrypt data before writing it into
// NVM.
CacheAllocatorConfig& setNvmCacheMakeBlobCallback(NvmCacheMakeBlobCb cb);
// Set callback override logic to propagate the content of Item with the Blobs
// retrieved from NvmItem. This is useful for cases where we need to change
// the data. For example, we can use it to decrypt data before loading it into
// DRAM.
CacheAllocatorConfig& setNvmCacheMakeObjCallback(NvmCacheMakeObjCb cb);
// enable encryption support for NvmCache. This will encrypt every byte
// written to the device.
CacheAllocatorConfig& enableNvmCacheBlockEncryption(
std::shared_ptr<NvmCacheDeviceEncryptor> encryptor);
// return if NvmCache encryption is enabled
bool isNvmCacheEncryptionEnabled() const;
// If enabled, it means we'll only store user-requested size into NvmCache
// instead of the full usable size returned by CacheAllocator::getUsableSize()
CacheAllocatorConfig& enableNvmCacheTruncateAllocSize();
// return if truncate-alloc-size is enabled. If true, it means we'll only
// store user-requested size into NvmCache instead of the full usable size
// returned by CacheAllocator::getUsableSize()
bool isNvmCacheTruncateAllocSizeEnabled() const;
// Enable compact cache support. Refer to our user guide for how ccache works.
CacheAllocatorConfig& enableCompactCache();
// Configure chained items. Refer to our user guide for how chained items
// work.
//
// @param config Config for chained item's access container, it's similar to
// the main access container but only used for chained items
// @param lockPower this controls the number of locks (2^lockPower) for
// synchronizing operations on chained items.
CacheAllocatorConfig& configureChainedItems(AccessConfig config = {},
uint32_t lockPower = 10);
// Configure chained items. Refer to our user guide for how chained items
// work. This function calculates the optimal bucketsPower and locksPower for
// users based on estimated chained items number.
//
// @param numEntries number of estimated chained items
// @param lockPower this controls the number of locks (2^lockPower) for
// synchronizing operations on chained items.
CacheAllocatorConfig& configureChainedItems(size_t numEntries,
uint32_t lockPower = 10);
// enable tracking tail hits
CacheAllocatorConfig& enableTailHitsTracking();
// Turn on full core dump which includes all the cache memory.
// This is not recommended for production as it can significantly slow down
// the coredumping process.
CacheAllocatorConfig& setFullCoredump(bool enable);
// Sets the configuration that controls whether nvmcache is recovered if
// possible when dram cache is not recovered. By default nvmcache is
// recovered even when dram cache is not recovered.
CacheAllocatorConfig& setDropNvmCacheOnShmNew(bool enable);
// Turn off fast shutdown mode, which interrupts any releaseSlab operations
// in progress, so that workers in the process of releaseSlab may be
// completed sooner for shutdown to take place fast.
CacheAllocatorConfig& disableFastShutdownMode();
// when disabling full core dump, turning this option on will enable
// cachelib to track recently accessed items and keep them in the partial
// core dump. See CacheAllocator::madviseRecentItems()
CacheAllocatorConfig& setTrackRecentItemsForDump(bool enable);
// Page in all the cache memory asynchronously when cache starts up.
// This helps ensure the system actually has enough memory to page in all of
// the cache. We'll fail early if there isn't enough memory.
//
// If memory monitor is enabled, this is not usually needed.
CacheAllocatorConfig& setMemoryLocking(bool enable);
// This allows cache to be persisted across restarts. One example use case is
// to preserve the cache when releasing a new version of your service. Refer
// to our user guide for how to set up cache persistence.
CacheAllocatorConfig& enableCachePersistence(std::string directory,
void* baseAddr = nullptr);
// uses posix shm segments instead of the default sys-v shm segments.
// @throw std::invalid_argument if called without enabling
// cachePersistence()
CacheAllocatorConfig& usePosixForShm();
// Configures cache memory tiers. Each tier represents a cache region inside
// byte-addressable memory such as DRAM, Pmem, CXLmem.
// Accepts vector of MemoryTierCacheConfig. Each vector element describes
// configuration for a single memory cache tier. Tier sizes are specified as
// ratios, the number of parts of total cache size each tier would occupy.
// @throw std::invalid_argument if:
// - the size of configs is 0
// - the size of configs is greater than kMaxCacheMemoryTiers
CacheAllocatorConfig& configureMemoryTiers(const MemoryTierConfigs& configs);
// Return reference to MemoryTierCacheConfigs.
const MemoryTierConfigs& getMemoryTierConfigs() const noexcept;
// This turns on a background worker that periodically scans through the
// access container and look for expired items and remove them.
CacheAllocatorConfig& enableItemReaperInBackground(
std::chrono::milliseconds interval, util::Throttler::Config config = {});
// When using free memory monitoring mode, CacheAllocator shrinks the cache
// size when the system is under memory pressure. Cache will grow back when
// the memory pressure goes down.
//
// When using resident memory monitoring mode, typically when the
// application runs inside containers, the lowerLimit and upperLimit are the
// opposite to that of the free memory monitoring mode.
// "upperLimit" refers to the upper bound of application memory.
// Cache size will actually decrease once an application reaches past it
// and grows when drops below "lowerLimit".
//
// @param interval waits for an interval between each run
// @param config memory monitoring config
// @param RebalanceStrategy an optional strategy to customize where the slab
// to give up when shrinking cache
CacheAllocatorConfig& enableMemoryMonitor(
std::chrono::milliseconds interval,
MemoryMonitor::Config config,
std::shared_ptr<RebalanceStrategy> = {});
// Enable pool rebalancing. This allows each pool to internally rebalance
// slab memory distributed across different allocation classes. For example,
// if the 64 bytes allocation classes are receiving for allocation requests,
// eventually CacheAllocator will move more memory to it from other allocation
// classes. The rebalancing is triggered every specified interval and
// optionally on allocation failures. For more details, see our user guide.
CacheAllocatorConfig& enablePoolRebalancing(
std::shared_ptr<RebalanceStrategy> defaultRebalanceStrategy,
std::chrono::milliseconds interval,
bool disableForcedWakeup = false);
// This lets you change pool size during runtime, and the pool resizer
// will slowly adjust each pool's memory size to the newly configured sizes.
CacheAllocatorConfig& enablePoolResizing(
std::shared_ptr<RebalanceStrategy> resizeStrategy,
std::chrono::milliseconds interval,
uint32_t slabsToReleasePerIteration);
// Enable pool size optimizer, which automatically adjust pool sizes as
// traffic changes or new memory added.
// For now we support different intervals between regular pools and compact
// caches.
CacheAllocatorConfig& enablePoolOptimizer(
std::shared_ptr<PoolOptimizeStrategy> optimizeStrategy,
std::chrono::seconds regularInterval,
std::chrono::seconds ccacheInterval,
uint32_t ccacheStepSizePercent);
// Enable the background evictor - scans a tier to look for objects
// to evict to the next tier
CacheAllocatorConfig& enableBackgroundEvictor(
std::shared_ptr<BackgroundMoverStrategy> backgroundMoverStrategy,
std::chrono::milliseconds regularInterval,
size_t threads);
CacheAllocatorConfig& enableBackgroundPromoter(
std::shared_ptr<BackgroundMoverStrategy> backgroundMoverStrategy,
std::chrono::milliseconds regularInterval,
size_t threads);
// This enables an optimization for Pool rebalancing and resizing.
// The rough idea is to ensure only the least useful items are evicted when
// we move slab memory around. Come talk to Cache Library team if you think
// this can help your service.
CacheAllocatorConfig& enableMovingOnSlabRelease(
MoveCb cb,
ChainedItemMovingSync sync = {},
uint32_t movingAttemptsLimit = 10);
// Specify a threshold for detecting slab release stuck
CacheAllocatorConfig& setSlabReleaseStuckThreashold(
std::chrono::milliseconds threshold);
// This customizes how many items we try to evict before giving up.s
// We may fail to evict if someone else (another thread) is using an item.
// Setting this to a high limit leads to a higher chance of successful
// evictions but it can lead to higher allocation latency as well.
// Unless you're very familiar with caching, come talk to Cache Library team
// before you start customizing this option.
CacheAllocatorConfig& setEvictionSearchLimit(uint32_t limit);
// Specify a threshold for per-item outstanding references, beyond which,
// shared_ptr will be allocated instead of handles to support having more
// outstanding iobuf
// The default behavior is always using handles
CacheAllocatorConfig& setRefcountThresholdForConvertingToIOBuf(uint32_t);
// This throttles various internal operations in cachelib. It may help
// improve latency in allocation and find paths. Come talk to Cache
// Library team if you find yourself customizing this.
CacheAllocatorConfig& setThrottlerConfig(util::Throttler::Config config);
// Passes in a callback to initialize an event tracker when the allocator
// starts
CacheAllocatorConfig& setEventTracker(EventTrackerSharedPtr&&);
// Set the minimum TTL for an item to be admitted into NVM cache.
// If nvmAdmissionMinTTL is set to be positive, any item with configured TTL
// smaller than this will always be rejected by NvmAdmissionPolicy.
CacheAllocatorConfig& setNvmAdmissionMinTTL(uint64_t ttl);
// Skip promote children items in chained when parent fail to promote
CacheAllocatorConfig& setSkipPromoteChildrenWhenParentFailed();
// We will delay worker start until user explicitly calls
// CacheAllocator::startCacheWorkers()
CacheAllocatorConfig& setDelayCacheWorkersStart();
// Set numShards to use for CacheAllocator locks
CacheAllocatorConfig& setNumShards(size_t shards);
// skip promote children items in chained when parent fail to promote
bool isSkipPromoteChildrenWhenParentFailed() const noexcept {
return skipPromoteChildrenWhenParentFailed;
}
// @return whether compact cache is enabled
bool isCompactCacheEnabled() const noexcept { return enableZeroedSlabAllocs; }
// @return whether pool resizing is enabled
bool poolResizingEnabled() const noexcept {
return poolResizeInterval.count() > 0 && poolResizeSlabsPerIter > 0;
}
// @return whether pool rebalancing is enabled
bool poolRebalancingEnabled() const noexcept {
return poolRebalanceInterval.count() > 0 &&
defaultPoolRebalanceStrategy != nullptr;
}
// @return whether pool optimizing is enabled
bool poolOptimizerEnabled() const noexcept {
return (regularPoolOptimizeInterval.count() > 0 ||
compactCacheOptimizeInterval.count() > 0) &&
poolOptimizeStrategy != nullptr;
}
// @return whether background evictor thread is enabled
bool backgroundEvictorEnabled() const noexcept {
return backgroundEvictorInterval.count() > 0 &&
backgroundEvictorStrategy != nullptr;
}
bool backgroundPromoterEnabled() const noexcept {
return backgroundPromoterInterval.count() > 0 &&
backgroundPromoterStrategy != nullptr;
}
// @return whether memory monitor is enabled
bool memMonitoringEnabled() const noexcept {
return memMonitorConfig.mode != MemoryMonitor::Disabled &&
memMonitorInterval.count() > 0;
}
// @return whether reaper is enabled
bool itemsReaperEnabled() const noexcept {
return reaperInterval.count() > 0;
}
const std::string& getCacheDir() const noexcept { return cacheDir; }
const std::string& getCacheName() const noexcept { return cacheName; }
size_t getCacheSize() const noexcept { return size; }
bool isUsingPosixShm() const noexcept { return usePosixShm; }
// validate the config, and return itself if valid
const CacheAllocatorConfig& validate() const;
// check whether the RebalanceStrategy can be used with this config
bool validateStrategy(
const std::shared_ptr<RebalanceStrategy>& strategy) const;
// check whether the PoolOptimizeStrategy can be used with this config
bool validateStrategy(
const std::shared_ptr<PoolOptimizeStrategy>& strategy) const;
// check that memory tier ratios are set properly
const CacheAllocatorConfig& validateMemoryTiers() const;
// @return a map representation of the configs
std::map<std::string, std::string> serialize() const;
// The max number of memory cache tiers
inline static const size_t kMaxCacheMemoryTiers = 2;
// Cache name for users to indentify their own cache.
std::string cacheName{""};
// Amount of memory for this cache instance (sum of all memory tiers' sizes)
size_t size = 1 * 1024 * 1024 * 1024;
// Directory for shared memory related metadata
std::string cacheDir;
// if true, uses posix shm; if not, uses sys-v (default)
bool usePosixShm{false};
// Attach shared memory to a fixed base address
void* slabMemoryBaseAddr = nullptr;
// User defined default alloc sizes. If empty, we'll generate a default one.
// This set of alloc sizes will be used for pools that user do not supply
// a custom set of alloc sizes.
std::set<uint32_t> defaultAllocSizes;
// whether to detach allocator memory upon a core dump
bool disableFullCoredump{true};
// whether to enable fast shutdown, that would interrupt on-going slab
// release process, or not.
bool enableFastShutdown{true};
// if we want to track recent items for dumping them in core when we disable
// full core dump.
bool trackRecentItemsForDump{false};
// if enabled ensures that nvmcache is not persisted when dram cache is not
// presisted.
bool dropNvmCacheOnShmNew{false};
// TODO:
// BELOW are the config for various cache workers
// Today, they're set before CacheAllocator is created and stay
// fixed for the lifetime of CacheAllocator. Going foward, this
// will be allowed to be changed dynamically during runtime and
// trigger updates to the cache workers
// time interval to sleep between iterations of resizing the pools.
std::chrono::milliseconds poolResizeInterval{std::chrono::seconds(0)};
// number of slabs to be released per pool that is over the limit in each
// iteration.
unsigned int poolResizeSlabsPerIter{5};
// the rebalance strategy for the pool resizing if enabled.
std::shared_ptr<RebalanceStrategy> poolResizeStrategy;
// the strategy to be used when advising memory to pick a donor
std::shared_ptr<RebalanceStrategy> poolAdviseStrategy;
// time interval to sleep between iterators of rebalancing the pools.
std::chrono::milliseconds poolRebalanceInterval{std::chrono::seconds{1}};
// disable waking up the PoolRebalancer on alloc failures
bool poolRebalancerDisableForcedWakeUp{false};
// Free slabs pro-actively if the ratio of number of freeallocs to
// the number of allocs per slab in a slab class is above this
// threshold
// A value of 0 means, this feature is disabled.
unsigned int poolRebalancerFreeAllocThreshold{0};
// rebalancing strategy for all pools. By default the strategy will
// rebalance to avoid alloc fialures.
std::shared_ptr<RebalanceStrategy> defaultPoolRebalanceStrategy{
new RebalanceStrategy{}};
// The slab release process is considered as being stuck if it does not
// make any progress for the below threshold
std::chrono::milliseconds slabReleaseStuckThreshold{std::chrono::seconds(60)};
// the background eviction strategy to be used
std::shared_ptr<BackgroundMoverStrategy> backgroundEvictorStrategy{nullptr};
// the background promotion strategy to be used
std::shared_ptr<BackgroundMoverStrategy> backgroundPromoterStrategy{nullptr};
// time interval to sleep between runs of the background evictor
std::chrono::milliseconds backgroundEvictorInterval{
std::chrono::milliseconds{1000}};
// time interval to sleep between runs of the background promoter
std::chrono::milliseconds backgroundPromoterInterval{
std::chrono::milliseconds{1000}};
// number of thread used by background evictor
size_t backgroundEvictorThreads{1};
// number of thread used by background promoter
size_t backgroundPromoterThreads{1};
// time interval to sleep between iterations of pool size optimization,
// for regular pools and compact caches
std::chrono::seconds regularPoolOptimizeInterval{0};
std::chrono::seconds compactCacheOptimizeInterval{0};
// step size for compact cache size optimization: how many percents of the
// victim to move
unsigned int ccacheOptimizeStepSizePercent{1};
// optimization strategy
std::shared_ptr<PoolOptimizeStrategy> poolOptimizeStrategy{nullptr};
// Callback for initializing the eventTracker on CacheAllocator construction.
EventTrackerSharedPtr eventTracker{nullptr};
// whether to allow tracking tail hits in MM2Q
bool trackTailHits{false};
// when doing tail hits tracking for MM2Q, do we consider cold tail hits only or both cold and warm tail hits
bool countColdTailHitsOnly{false};
// Memory monitoring config
MemoryMonitor::Config memMonitorConfig;
// time interval to sleep between iterations of monitoring memory.
// Set to 0 to disable memory monitoring
std::chrono::milliseconds memMonitorInterval{0};
// throttler config of items reaper for iteration
util::Throttler::Config reaperConfig{};
// time to sleep between each reaping period.
std::chrono::milliseconds reaperInterval{5000};
// interval during which we adjust dynamically the refresh ratio.
std::chrono::milliseconds mmReconfigureInterval{0};
//
// TODO:
// ABOVE are the config for various cache workers
//
// the number of tries to search for an item to evict
// 0 means it's infinite
unsigned int evictionSearchTries{50};
// If refcount is larger than this threshold, we will use shared_ptr
// for handles in IOBuf chains.
unsigned int thresholdForConvertingToIOBuf{
std::numeric_limits<unsigned int>::max()};
// number of attempts to move an item before giving up and try to
// evict the item
unsigned int movingTries{10};
// Config that specifes how throttler will behave
// How much time it will sleep and how long an interval between each sleep
util::Throttler::Config throttleConfig{};
// Access config for chained items, Only used if chained items are enabled
AccessConfig chainedItemAccessConfig{};
// User level synchronization function object. This will be held while
// executing the moveCb. This is only needed when using and moving is
// enabled for chained items.
ChainedItemMovingSync movingSync{};
// determines how many locks we have for synchronizing chained items
// add/pop and between moving during slab rebalancing
uint32_t chainedItemsLockPower{10};
// Configuration for the main access container which manages the lookup
// for all normal items
AccessConfig accessConfig{};
// user defined callback invoked when an item is being evicted or freed from
// RAM
RemoveCb removeCb{};
// user defined item destructor invoked when an item is being
// evicted or freed from cache (both RAM and NVM)
ItemDestructor itemDestructor{};
// user defined call back to move the item. This is executed while holding
// the user provided movingSync. For items without chained allocations,
// there is no specific need for explicit movingSync and user can skip
// providing a movingSync and do explicit synchronization just in the
// moveCb if needed to protect the data being moved with concurrent
// readers.
MoveCb moveCb{};
// custom user provided admission policy
std::shared_ptr<NvmAdmissionPolicy<CacheT>> nvmCacheAP{nullptr};
// Config for nvmcache type
folly::Optional<NvmCacheConfig> nvmConfig;
// configuration for reject first admission policy to nvmcache. 0 indicates
// a disabled policy.
uint64_t rejectFirstAPNumEntries{0};
uint32_t rejectFirstAPNumSplits{20};
// if non zero specifies the suffix of the key to be ignored when tracking.
// this enables tracking group of keys that have common prefix.
size_t rejectFirstSuffixIgnoreLength{0};
// if enabled, uses the fact that item got a hit in DRAM as a signal to
// admit
bool rejectFirstUseDramHitSignal{true};
// Must enable this in order to call `allocateZeroedSlab`.
// Otherwise, it will throw.
// This is required for compact cache
bool enableZeroedSlabAllocs = false;
// Asynchronously page in the cache memory before they are accessed by the
// application. This can ensure all of cache memory is accounted for in the
// RSS even if application does not access all of it, avoiding any
// surprises (i.e. OOM).
//
// This can only be turned on the first time we're creating the cache.
// This option has no effect when attaching to existing cache.
bool lockMemory{false};
// These configs configure how MemoryAllocator will be generating
// allocation class sizes for each pool by default
double allocationClassSizeFactor{1.25};
uint32_t maxAllocationClassSize{Slab::kSize};
uint32_t minAllocationClassSize{72};
bool reduceFragmentationInAllocationClass{false};
// The minimum TTL an item need to have in order to be admitted into NVM
// cache.
uint64_t nvmAdmissionMinTTL{0};
// Skip promote children items in chained when parent fail to promote
bool skipPromoteChildrenWhenParentFailed{false};
// If true, we will delay worker start until user explicitly calls
// CacheAllocator::startCacheWorkers()
bool delayCacheWorkersStart{false};
size_t numShards{8192};
friend CacheT;
private:
void mergeWithPrefix(
std::map<std::string, std::string>& configMap,
const std::map<std::string, std::string>& configMapToMerge,
const std::string& prefix) const;
std::string stringifyAddr(const void* addr) const;
std::string stringifyRebalanceStrategy(
const std::shared_ptr<RebalanceStrategy>& strategy) const;
// Configuration for memory tiers.
MemoryTierConfigs memoryTierConfigs{
{MemoryTierCacheConfig::fromShm().setRatio(1)}};
};
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setCacheName(
const std::string& _cacheName) {
cacheName = _cacheName;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setCacheSize(size_t _size) {
size = _size;
constexpr size_t maxCacheSizeWithCoredump = 64'424'509'440; // 60GB
if (size <= maxCacheSizeWithCoredump) {
return setFullCoredump(true);
}
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setDefaultAllocSizes(
std::set<uint32_t> allocSizes) {
defaultAllocSizes = allocSizes;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setDefaultAllocSizes(
double _allocationClassSizeFactor,
uint32_t _maxAllocationClassSize,
uint32_t _minAllocationClassSize,
bool _reduceFragmentationInAllocationClass) {
allocationClassSizeFactor = _allocationClassSizeFactor;
maxAllocationClassSize = _maxAllocationClassSize;
minAllocationClassSize = _minAllocationClassSize;
reduceFragmentationInAllocationClass = _reduceFragmentationInAllocationClass;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setAccessConfig(
AccessConfig config) {
accessConfig = std::move(config);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setAccessConfig(
size_t numEntries) {
AccessConfig config{};
config.sizeBucketsPowerAndLocksPower(numEntries);
accessConfig = std::move(config);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setRemoveCallback(
RemoveCb cb) {
removeCb = std::move(cb);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setItemDestructor(
ItemDestructor destructor) {
itemDestructor = std::move(destructor);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableRejectFirstAPForNvm(
uint64_t numEntries,
uint32_t numSplits,
size_t suffixIgnoreLength,
bool useDramHitSignal) {
if (numEntries == 0) {
throw std::invalid_argument(
"Enalbing reject first AP needs non zero numEntries");
}
rejectFirstAPNumEntries = numEntries;
rejectFirstAPNumSplits = numSplits;
rejectFirstSuffixIgnoreLength = suffixIgnoreLength;
rejectFirstUseDramHitSignal = useDramHitSignal;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableNvmCache(
NvmCacheConfig config) {
nvmConfig.assign(config);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setNvmCacheAdmissionPolicy(
std::shared_ptr<NvmAdmissionPolicy<T>> policy) {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache admission policy callback can not be set unless nvmcache is "
"used");
}
if (!policy) {
throw std::invalid_argument("Setting a null admission policy");
}
nvmCacheAP = std::move(policy);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setNvmCacheEncodeCallback(
NvmCacheEncodeCb cb) {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache filter callback can not be set unless nvmcache is used");
}
nvmConfig->encodeCb = std::move(cb);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setNvmCacheDecodeCallback(
NvmCacheDecodeCb cb) {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache filter callback can not be set unless nvmcache is used");
}
nvmConfig->decodeCb = std::move(cb);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setNvmCacheMakeBlobCallback(
NvmCacheMakeBlobCb cb) {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache filter callback can not be set unless nvmcache is used");
}
nvmConfig->makeBlobCb = std::move(cb);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setNvmCacheMakeObjCallback(
NvmCacheMakeObjCb cb) {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache filter callback can not be set unless nvmcache is used");
}
nvmConfig->makeObjCb = std::move(cb);
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableNvmCacheBlockEncryption(
std::shared_ptr<NvmCacheDeviceEncryptor> encryptor) {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache encrytion/decrytion callbacks can not be set unless nvmcache "
"is used");
}
if (!encryptor) {
throw std::invalid_argument("Set a nullptr encryptor is NOT allowed");
}
nvmConfig->deviceEncryptor = std::move(encryptor);
return *this;
}
template <typename T>
bool CacheAllocatorConfig<T>::isNvmCacheEncryptionEnabled() const {
return nvmConfig && nvmConfig->deviceEncryptor;
}
template <typename T>
CacheAllocatorConfig<T>&
CacheAllocatorConfig<T>::enableNvmCacheTruncateAllocSize() {
if (!nvmConfig) {
throw std::invalid_argument(
"NvmCache mode can not be adjusted unless nvmcache is used");
}
nvmConfig->truncateItemToOriginalAllocSizeInNvm = true;
return *this;
}
template <typename T>
bool CacheAllocatorConfig<T>::isNvmCacheTruncateAllocSizeEnabled() const {
return nvmConfig && nvmConfig->truncateItemToOriginalAllocSizeInNvm;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableCompactCache() {
enableZeroedSlabAllocs = true;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::configureChainedItems(
AccessConfig config, uint32_t lockPower) {
chainedItemAccessConfig = config;
chainedItemsLockPower = lockPower;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::configureChainedItems(
size_t numEntries, uint32_t lockPower) {
AccessConfig config{};
config.sizeBucketsPowerAndLocksPower(numEntries);
chainedItemAccessConfig = std::move(config);
chainedItemsLockPower = lockPower;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableTailHitsTracking() {
trackTailHits = true;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setFullCoredump(bool enable) {
disableFullCoredump = !enable;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setDropNvmCacheOnShmNew(
bool enable) {
dropNvmCacheOnShmNew = enable;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::disableFastShutdownMode() {
enableFastShutdown = false;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setTrackRecentItemsForDump(
bool enable) {
trackRecentItemsForDump = enable;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::setMemoryLocking(
bool enable) {
lockMemory = enable;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableCachePersistence(
std::string cacheDirectory, void* baseAddr) {
cacheDir = cacheDirectory;
slabMemoryBaseAddr = baseAddr;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::usePosixForShm() {
if (cacheDir.empty()) {
throw std::invalid_argument(
"Posix shm can be set only when cache persistence is enabled");
}
usePosixShm = true;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableItemReaperInBackground(
std::chrono::milliseconds interval, util::Throttler::Config config) {
reaperInterval = interval;
reaperConfig = config;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::configureMemoryTiers(
const MemoryTierConfigs& config) {
if (config.size() > kMaxCacheMemoryTiers) {
throw std::invalid_argument(folly::sformat(
"Too many memory tiers. The number of supported tiers is {}.",
kMaxCacheMemoryTiers));
}
if (!config.size()) {
throw std::invalid_argument(
"There must be at least one memory tier config.");
}
memoryTierConfigs = config;
return *this;
}
template <typename T>
const typename CacheAllocatorConfig<T>::MemoryTierConfigs&
CacheAllocatorConfig<T>::getMemoryTierConfigs() const noexcept {
return memoryTierConfigs;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enableMemoryMonitor(
std::chrono::milliseconds interval,
MemoryMonitor::Config config,
std::shared_ptr<RebalanceStrategy> adviseStrategy) {
memMonitorInterval = interval;
memMonitorConfig = std::move(config);
poolAdviseStrategy = adviseStrategy;
return *this;
}
template <typename T>
CacheAllocatorConfig<T>& CacheAllocatorConfig<T>::enablePoolOptimizer(
std::shared_ptr<PoolOptimizeStrategy> strategy,
std::chrono::seconds regularPoolInterval,
std::chrono::seconds compactCacheInterval,
uint32_t ccacheStepSizePercent) {
if (validateStrategy(strategy)) {
regularPoolOptimizeInterval = regularPoolInterval;
compactCacheOptimizeInterval = compactCacheInterval;