Compare commits

..
Author SHA1 Message Date
Malavan Sotheeswaran f80f4b2e24 need to include stdint for uintptr_t 2022-03-31 19:47:13 -07:00
Malavan Sotheeswaran 44206187a2 cannot mod a pointer 2022-03-31 18:55:12 -07:00
Malavan Sotheeswaran 34ac7488eb remove nullptr subtraction 2022-03-31 18:51:40 -07:00
Malavan Sotheeswaran 60cbb0f1d1 remove unused var in networking.cpp 2022-03-31 18:40:17 -07:00
John Sully ff580de3a2 Eliminate firewall dialogs on mac for regular and cluster tests. There are still issues with the sentinel tests but attempting to bind only to localhost causes failures 2022-03-08 18:20:03 -05:00
John Sully 4b3e23e2fb Fix module test break 2022-03-07 20:20:47 -05:00
John Sully 1f0679da36 Fix MALLOC=memkind build issues 2022-03-06 20:38:00 -05:00
benschermel 2ae3dd6b0a update README resource links 2022-03-06 15:42:48 -05:00
Malavan Sotheeswaran d591df1529 set thread as offline when waiting for time thread lock 2022-02-18 12:46:37 -05:00
Malavan Sotheeswaran cf799eae84 time thread lock uses fastlock instead of std::mutex 2022-02-18 12:46:37 -05:00
Malavan Sotheeswaran 5c816db669 only need to include readwritelock in ae 2022-02-18 12:46:37 -05:00
Malavan Sotheeswaran 7bbd6d73c8 hide forklock object in ae 2022-02-18 12:46:37 -05:00
malavan 0d5b349744 fork lock for all threads, use fastlock for readwritelock 2022-02-18 12:46:37 -05:00
John Sully ccf8d42e4b Update ci.yml
Change min tested version to 18.04
2022-01-31 18:43:54 -05:00
Malavan Sotheeswaran 93a748f86b remove unused lambda capture 2022-01-19 13:15:40 -08:00
MalavanEQAlpha 3e774999e7 Merge pull request #386 from EQ-Alpha/fix_rdb_hang
add readwrite lock for forking
2022-01-14 16:17:32 -05:00
MalavanEQAlpha 83563f6bb2 Merge branch 'unstable' into fix_rdb_hang 2022-01-12 21:13:45 -05:00
Christian Legge 875a82bdf8 Save and restore master info in rdb to allow active replica partial sync (#371)
* save replid for all masters in rdb

* expanded rdbSaveInfo to hold multiple master structs

* parse repl-masters from rdb

* recover replid info from rdb in active replica mode, attempt partial sync

* save offset from rdb into correct variable

* don't change replid based on master in active rep

* save and load psync info from correct fields
2022-01-12 19:49:15 -05:00
malavan 1e3fe8cab3 forklock only for time thread 2022-01-12 23:41:06 +00:00
malavan 127becc9e0 catch exceptions and relock in executeWithoutGlobalLock 2022-01-02 11:09:21 +00:00
malavan b57b1c8ff8 don't read query if waiting on fork 2021-12-24 18:00:07 +00:00
malavan bb83aef1da add latency monitor for forklock and expose writeWaiting status 2021-12-24 17:54:19 +00:00
malavan cbb9ac38d2 reduce work done outside global lock 2021-12-24 17:08:27 +00:00
malavan 6749c2bcf0 add functions to upgrade/downgrade read to/from write in readWriteLock 2021-12-24 06:54:54 +00:00
malavan 9957c11e2d restore assert that client is safe to unlock 2021-12-24 03:02:51 +00:00
malavan b4b30dcf9d add write waiting to readWriteLock to avoid starvation 2021-12-23 21:08:25 +00:00
malavan cddd3b6896 add executeWithoutGlobalLock function 2021-12-23 20:59:08 +00:00
John Sully b4528b797d Remove double free in keydb-benchmark 2021-12-23 14:20:41 -05:00
John Sully e070651039 Fix deadlock issue #183 cause by lock inversion 2021-12-23 13:17:14 -05:00
John Sully 7a32ec39fd Apple build break fix 2021-12-23 13:12:59 -05:00
John Sully 50dfee2039 Fix module test break 2021-12-23 13:12:34 -05:00
Malavan Sotheeswaran 9e92c038b8 reset cycle count on cvwait and name constant 2021-12-22 15:18:45 -05:00
Malavan Sotheeswaran c167902cbf reacquire fork lock every 500 time thread loops 2021-12-22 14:42:14 -05:00
Malavan Sotheeswaran c8bd5dbb4f timethread only releases forklock when waiting 2021-12-22 14:37:41 -05:00
Malavan Sotheeswaran 2c932d7b80 release fork lock on thread end 2021-12-22 14:08:00 -05:00
Malavan Sotheeswaran 8dff4f3437 need to acquire forklock on thread start 2021-12-22 14:06:55 -05:00
Malavan Sotheeswaran eec6b5142e explain deadlock possibility in acquireWrite 2021-12-22 14:05:46 -05:00
Malavan Sotheeswaran d2c080d923 further generalize readWrite lock and use it for moduleGIL 2021-12-22 13:59:58 -05:00
Malavan Sotheeswaran 754d5a3ba1 move fork lock management within redisFork 2021-12-22 11:19:24 -05:00
Malavan Sotheeswaran 4aaa7b7bd7 add forklock to time thread, wake time thread after acquiring locks 2021-12-22 11:06:15 -05:00
Malavan Sotheeswaran b93938914d add readwrite lock for forking 2021-12-21 18:11:51 -05:00
Vivek Saini 4b6bdcbcce Merge pull request #375 from VivekSainiEQ/time_thread_backport
Backport the time thread code from the enterprise version of KeyDB.

Also fix an issue with clustering where connections are potentially written to after being closed.
2021-11-15 12:57:15 -05:00
benschermel 31c0e38d86 Merge pull request #345 from EQ-Alpha/pkg_update_tools
add keydb-diagnostic-tool to packaging
2021-11-10 22:16:09 -05:00
benschermel 8f5b94c75f Merge pull request #376 from EQ-Alpha/systemd_build
Systemd build
2021-11-10 22:14:24 -05:00
benschermel d1fc7b96ed fix typo 2021-11-11 02:36:20 +00:00
benschermel b253a7aa8d update license 2021-11-11 02:19:56 +00:00
benschermel 1625c74a36 Merge branch 'unstable' into systemd_build 2021-11-11 00:59:33 +00:00
Vivek Saini 3c716ee33d Security fixes (#373)
Fixing potential buffer overflows when using the bitop shift and cron commands, as well as comparing ACL user passwords in constant time.
2021-11-09 19:00:01 -05:00
VivekSainiEQ b03eab2a06 Backported time thread code from enterprise 2021-11-05 00:30:34 +00:00
VivekSainiEQ 6a0a005ff2 Check that cluster connection is valid before setting write handler 2021-11-02 17:43:17 +00:00
malavan 51216ee433 null check for delete override 2021-10-29 15:59:21 +00:00
Vivek Saini 5f7ca6a2f6 Merge pull request #372 from VivekSainiEQ/Redis_626_Merge
Redis 6.2.6 merge
2021-10-28 17:21:14 -04:00
VivekSainiEQ 79bdcf0b3d Cast pointer correctly and fixed MVCC not updating correctly 2021-10-27 17:08:37 +00:00
VivekSainiEQ b88f06b16f Resolved merge conflicts in prior commit 2021-10-21 22:35:15 +00:00
VivekSainiEQ e6d7e01be6 Merge tag '6.2.6' into Redis_626_Merge 2021-10-21 22:33:55 +00:00
noobpwnftw 889bcd1bf1 Fix incorrect counting of client connections
This affects later distribution of clients among threads if there had been many connection attempts during loading phase.
2021-10-12 21:47:15 -04:00
Alexis 9637887264 Fix alignment of #ifndef USE_ALIGNED_ACCESS 2021-10-12 14:27:53 -04:00
Maxime de Roucy a9eaf0a130 syslog: enforce syslog identity and facility as soon as possible 2021-09-16 17:29:55 -04:00
Maxime de Roucy a1680fa612 use LL_… log level instead of syslog LOG_… log level
Else there is an out of bound access in syslogLevelMap.

For example if we use `serverLog(LOG_INFO,…`, later in the code
it tries to access `syslogLevelMap[LOG_INFO]`.
LOG_INFO == 6 but syslogLevelMap only have 4 elements.
2021-09-16 17:29:07 -04:00
benschermel d7bd4f7a1c update deb packaging to build with systemd flag 2021-09-08 02:28:17 +00:00
benschermel 0be40b9fd4 update pkg conf file 2021-08-22 22:21:34 +00:00
MalavanEQAlpha 9e5e6c2f86 Merge pull request #313 from MalavanEQAlpha/fixissue295
Resolve Issue #295 by speeding up keyIsExpired and setting timeout on subkey expires.
2021-08-18 17:34:18 -04:00
malavan 1ab19b445f should use LLONG_MAX for INVALID_EXPIRE not LLONG_MIN and add better comments 2021-08-18 20:59:01 +00:00
VivekSainiEQ ee32ed045c Include gperftools/tcmalloc.h instead of google/tcmalloc.h 2021-08-18 15:40:09 -04:00
John Sully 82ba449dd0 Solo tests should work with loopn 2021-08-18 15:08:10 -04:00
malavan 9b7febb538 Remove duplicate code 2021-08-16 22:55:46 +00:00
malavan fae6bfb80b don't use flags that aren't supported by certain versions of OPENSSL 2021-08-16 22:55:46 +00:00
benschermel 45bb6e801f add keydb-diagnostic-tool to packaging 2021-08-16 22:10:31 +00:00
christianEQ b08aa26a76 install 32bit libraries in github action 2021-08-13 11:05:12 -04:00
christianEQ 8dacbed556 github runner for 32bit build 2021-08-13 11:05:12 -04:00
christianEQ b44df43fcb changed keys counter variable to unsigned to fix signedness comparison warning 2021-08-13 11:05:12 -04:00
christianEQ 84af829053 %zu for printing type size_t 2021-08-13 11:05:12 -04:00
christianEQ f5ee64f9aa fixed 32bit compatibility in Makefile 2021-08-13 11:05:12 -04:00
christianEQ ce4891b33d fixed overly strict assert for 32bit 2021-08-13 11:05:12 -04:00
MalavanEQAlpha ffa46b8f0b Merge pull request #318 from VivekSainiEQ/redisearch_fixes
Initialized serverTL in more places in module.cpp
2021-08-11 15:47:30 -04:00
Vivek Saini bf05c261d2 Merge pull request #296 from VivekSainiEQ/systemd_fix
Fixed bug where make USE_SYSTEMD=yes would not pass in correct flags
2021-08-11 15:39:50 -04:00
VivekSainiEQ 952ae9fbe3 Merge remote-tracking branch 'upstream/unstable' into redisearch_fixes 2021-08-11 19:28:04 +00:00
VivekSainiEQ 6f2dbb0011 Prevent invalid mvcc timestamps from causing critical errors 2021-08-11 15:06:14 -04:00
Paweł Sacawa f77980fce8 Add: zsh completions with descriptions
This commit add zsh completions for the keydb `client`. They have contextual host completion and full argument descriptions.
Vendor-distributed completions for zsh should end up in `/usr/share/zsh/vendor-completions`, but unfortunatly I'm not familiar with the packaging method for *.deb archives, so these completions will need to be moved to the appropriate directory.
2021-08-11 15:05:11 -04:00
MalavanEQAlpha d90c1e6eae Merge pull request #340 from EQ-Alpha/update_keydb.conf
update keydb.conf with new configs from redis unstable
2021-08-11 15:04:22 -04:00
MalavanEQAlpha d987f463eb Merge pull request #341 from EQ-Alpha/pkg_config
update packaging config files
2021-08-11 15:01:37 -04:00
benschermel 89beaf2460 add script to compare all active config parameters of any 2 config files 2021-08-10 20:10:28 -04:00
benschermel 0c5d12b914 update packaging config files 2021-08-10 20:08:39 -04:00
malavan 32ca2e8a73 update keydb.conf with new configs from redis unstable 2021-08-10 21:34:52 +00:00
Christian Legge d7f6bc1614 Add REPLPING command for use during replication (#329)
* added replping command for initiating replication

* backwards compatibility for replping (retry if not recognized)

* don't allow ping during loading (load balancer fix)

* changed replping warning to notice
2021-07-29 15:50:30 -04:00
MalavanEQAlpha 83d878f111 Merge pull request #328 from EQ-Alpha/backtrace_for_alpine
Backtrace for alpine using libunwind
2021-07-28 17:17:06 -04:00
malavan 0fc6441c96 add some comments 2021-07-28 20:32:18 +00:00
malavan 81cf9979ed remove duplicate function 2021-07-21 16:00:24 +00:00
malavan 5be1620629 add stacktrace message 2021-07-19 23:17:18 +00:00
malavan 685b87e2ef dd comment and set eip unused 2021-07-19 17:32:38 +00:00
malavan 72429c2106 dd comment and set eip unused 2021-07-19 17:31:24 +00:00
malavan 7707fe15a9 dd comment and set eip unused 2021-07-19 17:29:43 +00:00
malavan c583ffff41 add backtrace for alpine using libunwind 2021-07-19 17:20:52 +00:00
Christian Legge 7c1ab8b8e2 Merge pull request #321 from EQ-Alpha/ci-flags-fix
Requested changes from 6.2.2 merge
2021-07-15 16:42:02 -04:00
christianEQ 570fbd0149 fix warnings for mac build 2021-07-15 20:14:14 +00:00
christianEQ da1f09e9b5 Merge remote-tracking branch 'origin/unstable' into ci-flags-fix 2021-07-14 22:56:15 +00:00
malavan 9e45984a97 use INVALID_EXPIRE instead of -1 2021-07-14 22:13:29 +00:00
christianEQ b2fb4f4b9b added REDIS_CFLAGS to makefile for backwards compatibility 2021-07-14 21:51:44 +00:00
malavan 51277b17a7 cleanup based on 6.2.2 merge review 2021-07-14 15:22:27 -04:00
Christian Legge 32f5ef864e Merge pull request #322 from EQ-Alpha/diagnostic-tool
Basic first iteration of Diagnostic Tool
2021-07-14 14:19:44 -04:00
Christian Legge a8f28297ec Merge pull request #327 from EQ-Alpha/issue323_fix
fix for #323: seg fault on expiremember
2021-07-12 16:54:31 -04:00
christianEQ 0ae13c9731 tabs -> spaces 2021-07-12 18:55:44 +00:00
John Sully 1895dbb768 Merge tag '6.2.3' into unstable 2021-07-09 04:40:31 +00:00
christianEQ a6cbbd0f31 added eq alpha copyright 2021-07-08 02:58:18 +00:00
christianEQ f1f52af9cf fix for #323: seg fault on expiremember 2021-07-08 02:50:05 +00:00
christianEQ e3c619eca4 various branding and cleanup fixes 2021-07-08 02:46:42 +00:00
christianEQ 57e59d97db removed unused command line options 2021-06-22 17:13:35 +00:00
christianEQ d7cada0f38 changed --ms to --time 2021-06-21 19:57:14 +00:00
christianEQ fd2ac1fcfc added more verbose options 2021-06-21 18:40:37 +00:00
christianEQ 0181b0e7a1 -t threads option 2021-06-21 18:36:21 +00:00
christianEQ 2b5e5cfa4c added starting line so diagnostic tool doesnt look frozen at first 2021-06-18 20:21:47 +00:00
christianEQ bfb0d02622 Merge remote-tracking branch 'origin/unstable' into diagnostic-tool 2021-06-18 20:19:31 +00:00
christianEQ 534b70643b detect stagnating server load before 100% (diagnostic tool) 2021-06-18 19:01:51 +00:00
christianEQ 3d0f729572 added config option for time to spin up new client threads (diagnostic tool) 2021-06-18 16:58:16 +00:00
christianEQ fd4ed1e425 detect full load + server threads (diagnostic tool) 2021-06-18 16:49:25 +00:00
christianEQ 693450393c detect client cpu usage in diagnostic tool 2021-06-17 20:40:10 +00:00
christianEQ 8ee7584cff accurate cpu usage in diagnostic tool 2021-06-17 18:32:11 +00:00
John Sully 0a56a73bd9 Prevent test code crash due to no log data 2021-06-14 22:06:36 +00:00
John Sully 3a1d3090f2 active defrag tests need to run single threaded because jemalloc has seperate mempools per thread and the numbers won't match otherwise 2021-06-14 16:32:47 +00:00
christianEQ 0727393627 changed redis_flags names to keydb in makefile 2021-06-14 16:09:42 +00:00
christianEQ d2ef059471 several redis->keydb changes in sentinel.conf 2021-06-11 19:16:33 +00:00
christianEQ 2e894a512b renamed redis mentions in runtest files 2021-06-11 19:11:12 +00:00
christianEQ 34b0209f05 renamed redis mention in readme 2021-06-11 19:10:35 +00:00
christianEQ 046f575632 renamed workspace gitignore 2021-06-11 19:10:12 +00:00
christianEQ 1c77104b5e renamed redis test files 2021-06-11 19:09:40 +00:00
christianEQ 386be8990a removed unreliable musl test and left only accurate new one 2021-06-11 18:19:59 +00:00
christianEQ 76d9c7c82a changed redis.pid to keydb.pid where necessary 2021-06-11 18:19:02 +00:00
christianEQ 98f08034a1 removed outdated comment in server.cpp 2021-06-11 18:17:18 +00:00
christianEQ 308cf77437 updated pkg/deb/conf/keydb.conf to use keydb name throughout 2021-06-11 18:15:50 +00:00
christianEQ ce64f469f4 removed the question issue template - doesn't seem necessary for us 2021-06-11 18:08:19 +00:00
christianEQ e632c3db1b fixed flag var names in ci 2021-06-11 17:04:33 +00:00
christianEQ 239d22ed72 don't enforce upper limit for requests issued; tool will run indefinitely 2021-06-11 16:28:29 +00:00
christianEQ fefbe96816 working diag tool prototype 2021-06-01 20:54:48 +00:00
John Sully b1f662d639 Don't pass on flags indicating membership in a list 2021-05-30 05:11:18 +00:00
John Sully aa5b27b040 Fix a leak in the benchmark 2021-05-30 02:55:39 +00:00
John Sully 10d254ec1b Fix merge issue with module test script 2021-05-30 02:45:06 +00:00
John Sully e8a44821d0 Ensure our connections are touched only on the right thread 2021-05-30 02:08:30 +00:00
John Sully 92e48f0717 Handle race where a different thread cancels the replication but we haven't closed the connection 2021-05-30 02:08:02 +00:00
John Sully 9742c44db5 Delete pipe on the right thread so event handlers are cleaned up 2021-05-30 02:07:31 +00:00
John Sully 5d16f51950 Don't leave dangling client pointers in the process list 2021-05-30 02:06:47 +00:00
John Sully 1ed2e8b5bc Don't leak AE control pipes to fork children 2021-05-30 02:06:20 +00:00
John Sully b20803b766 Fix branding 2021-05-29 07:08:01 +00:00
John Sully 8cf1daf823 Fix cluster test failures 2021-05-29 07:07:54 +00:00
John Sully 083b54472c Mac build break fixes 2021-05-28 22:40:03 -04:00
John Sully 1b9fea0669 Prevent partial sync in test that requires only full syncs 2021-05-29 02:22:20 +00:00
John Sully d3c37c7159 Fix failover command test failures 2021-05-29 01:19:12 +00:00
John Sully 807f020184 Remove dup'd code from merge 2021-05-29 01:08:52 +00:00
John Sully b400be68b7 ProcessingEventsWhileBlocked is relevant only to the current thread 2021-05-29 01:08:43 +00:00
John Sully e39bdb58ec Make processClients reentrant 2021-05-29 01:08:14 +00:00
John Sully 83c8977033 Don't have dangling expires 2021-05-29 01:07:46 +00:00
John Sully 682990eeb3 Use correct make flags 2021-05-29 01:07:35 +00:00
John Sully 7ee766aee1 Ensure multi-thread handling of cached master is equivalent to single thread case 2021-05-26 17:29:47 +00:00
John Sully 848c5ad784 Avoid differences between single thread and multi-thread 2021-05-26 17:29:01 +00:00
John Sully a41fb1b036 Eliminate test issue while clients wait for async free 2021-05-26 01:18:47 +00:00
John Sully 915117ae7b Fix failure sending deferred aggregate lengths to clients on other threads (merge bug) 2021-05-25 20:51:18 +00:00
John Sully de5fa78762 Remove duplicate code 2021-05-25 20:50:40 +00:00
John Sully b0c8efd840 Fix TLS test failure due to tls-port not marked as runtime configurable 2021-05-25 20:50:23 +00:00
John Sully 1dcd5edbf9 Fix crash in TLS due to merge 2021-05-25 18:52:27 +00:00
John Sully 87d7fc8e5d Build break fix: Remove dependency on future C++ feature 2021-05-25 18:52:08 +00:00
John Sully 100a747eab More OS X build breaks 2021-05-25 18:35:45 +00:00
John Sully 105fd03ef8 OS X build break fix 2021-05-25 18:32:31 +00:00
John Sully 9395a9c1d9 Fix uninitialized variable 2021-05-25 18:30:07 +00:00
John Sully 02f7efd9d4 Fix duplicate checks (resolve PR comments) 2021-05-25 16:57:49 +00:00
John Sully aea86c5977 Fix TLS Build Errors 2021-05-25 16:55:59 +00:00
VivekSainiEQ 8d81592bec Initialized serverTL in more places in module.cpp 2021-05-25 16:55:47 +00:00
John Sully 93ebb31b17 Merge tag '6.2.2' into unstable 2021-05-21 05:54:39 +00:00
John Sully bfed57e3e0 Merge tag '6.2.1' into unstable 2021-05-19 02:59:48 +00:00
Malavan a6bbbeffcf Fix issue with INVALID_EXPIRE overlapping with mask 2021-05-17 21:38:42 +00:00
Malavan 9110747194 Merge remote-tracking branch 'upstream/unstable' into fixissue295 2021-05-17 21:35:43 +00:00
Malavan 693b209cb4 merge when and whenFull 2021-05-15 05:48:23 +00:00
Malavan a01564158e Speedup keyIsExpired by removing subkey search 2021-05-07 09:40:23 +00:00
John Sully 23647390e6 Fix test hang 2021-05-07 00:28:10 +00:00
VivekSainiEQ 96bca72bb4 Changed branding in various locations 2021-05-06 20:13:45 -04:00
Malavan 5d6da23108 add lookup limit to active subkey expire 2021-05-04 22:28:03 +00:00
Malavan b44f504ced add lookup limit to active subkey expire 2021-05-04 21:34:25 +00:00
benschermel 6163e7b13a update README with community slack info 2021-04-29 03:11:54 +00:00
christianEQ 66547bd28a fixed diagnostic tool to use correct obj files 2021-04-28 16:02:44 +00:00
christianEQ e6ab823473 updated makefile vars to keydb names 2021-04-27 21:14:05 +00:00
christianEQ a2c0bce4cc added keydb-diagnostic-tool binary (copy of benchmark) 2021-04-27 20:56:37 +00:00
christianEQ 2c8239f9cb check for musl in logging.tcl as backtrace() is not available with it 2021-04-05 11:09:49 -04:00
John Sully e9551c9e8d Fix issue #300 2021-03-30 23:30:41 +00:00
Hanif Ariffin 0ac80086bc Fix typo in error string 2021-03-30 13:52:47 -04:00
VivekSainiEQ 9ab36ddc36 Added logic back to only acquire/release GIL if modules are enabled, without causing deadlocks 2021-03-30 13:46:03 -04:00
VivekSainiEQ a6bc34c09b now acquire and release GIL every time you go to/wake from sleep 2021-03-30 13:46:03 -04:00
VivekSainiEQ 3bb6b16c4a Created and initialized seperate thread variables for modules 2021-03-30 13:46:03 -04:00
VivekSainiEQ 1cde2442aa Readded getkeys to module build 2021-03-30 13:46:03 -04:00
John Sully 2910cee32b Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2021-03-29 00:49:34 +00:00
VivekSainiEQ 7fefc7b245 Updated jemalloc to version 5.2.1 2021-03-19 20:10:27 +00:00
VivekSainiEQ 68d213f4c9 Removed hasModuleGIL boolean and added fix from PR #292 2021-03-19 20:10:24 +00:00
VivekSainiEQ 7d9a2ce827 added lock releasing w/ hasModuleGIL, changed module serverTL, and moved module_blocking_pipe to global scope to fix issue #276 2021-03-19 20:08:28 +00:00
benschermel c6ef287452 update rpm script for centos8 2021-03-18 19:31:54 +00:00
VivekSainiEQ e6091a2b7e Updated module tests to default to multithreaded and added tests for RM_CreateTimer while loading .rdb 2021-03-04 23:33:01 +00:00
VivekSainiEQ 69dc0a06bf Fixed bug where make USE_SYSTEMD=yes would not pass in correct flags, issue #226 2021-03-01 21:31:33 +00:00
John Sully dfea168499 Fix polarity issue in async rehash 2021-02-09 05:10:22 +00:00
John Sully 241d1bd7e1 Fix bug in fastlock stack metadata 2021-02-07 19:11:05 -05:00
John Sully 56addcd172 Disable multithreaded rehash when active defrag is enabled. The two are not compatible 2021-02-07 19:11:05 -05:00
John Sully 8d8e1810d4 The server should recalibrate periodically. Also reduce log noise 2021-02-07 19:11:05 -05:00
John Sully b5ddc11c46 Ensure the C lock implementation behaves the same as the ASM 2021-02-07 19:11:05 -05:00
John Sully f107746e90 Ensure rehash completes even when we're in a long running task 2021-02-07 19:11:05 -05:00
John Sully f68a26381a Implement rehash during spinlock 2021-02-07 19:11:05 -05:00
John Sully 5a2cc90786 Allow multiple threads to rehash simultaneously 2021-02-07 19:11:05 -05:00
John Sully 3881d5c1f2 Fix races in free 2021-02-07 19:11:05 -05:00
John Sully 958f2c00c8 Initial implementation 2021-02-07 19:11:05 -05:00
John Sully 165333b0fc Fix memory leak in mvccRestore 2021-02-07 23:38:49 +00:00
John Sully cc827e157a Module test reliability 2021-02-01 22:21:49 +00:00
John Sully 7b4e25008a Simplify the handling of CreateTimer 2021-02-01 15:51:22 -05:00
VivekSainiEQ f66e5a9c3d Modified RM_CreateTimer to prevent more that one function being posted at a time 2021-02-01 15:51:22 -05:00
VivekSainiEQ 9954f5b4a4 Changed RM_CreateTimer to only call aePostFunction is existing aePostFunction isn't in flight 2021-02-01 15:51:22 -05:00
VivekSainiEQ 53936661c8 Now post entire timer installation process as one function to make atomic with respect to global locks 2021-02-01 15:51:22 -05:00
VivekSainiEQ e2552ff8a9 Updated header file to remove fSynchronous flag 2021-02-01 15:51:22 -05:00
VivekSainiEQ 6ab08cc3e1 Removed more uses of fSynchronous and the use of condition variable and mutex on the control struct. 2021-02-01 15:51:22 -05:00
VivekSainiEQ 3205373bb3 Added fix for scenario where module thread waiting for s_mutexModule in acquireGIL can deadlock with module thread waiting for s_mutex in releaseGIL 2021-02-01 15:51:22 -05:00
VivekSainiEQ 3b8d1f7076 removed synchronous calls to aePostFunction and changed scope of g_fModuleThread in order to prevent module related deadlocks, issue #214 2021-02-01 15:51:22 -05:00
John Sully 5832c25ad1 ARM build fix 2021-01-31 21:22:23 +00:00
John Sully 569a3d9ff8 Fix test failure caused by allowing pings during load 2021-01-31 07:15:55 +00:00
John Sully 69bc7108bd Reduce intermittent failures by giving tests more time 2021-01-31 06:33:13 +00:00
christianEQ 8a557e9d71 added exception to allow pings during loading 2021-01-31 00:12:49 -05:00
christianEQ fe0f071993 added severity levels for afterErrorReply 2021-01-31 00:12:49 -05:00
John Sully effa53339c Improve multithreaded test reliability 2021-01-31 04:33:27 +00:00
John Sully f6fb0e4620 Fix test failure due to bad merge 2021-01-31 03:40:57 +00:00
John Sully cf46a014c1 Fix CI failure due to missing package 2021-01-31 02:36:30 +00:00
John Sully d72b5fa16d Fix crash on shutdown command 2021-01-31 02:30:28 +00:00
christianEQ 0151507cef Merge pull request #284 from christianEQ/redismerge_2021-01-20
Merge Redis 6.0.10 into KeyDB
2021-01-29 10:59:36 -05:00
christianEQ 0fea781f8f killMainThread -> killServerThreads 2021-01-28 23:57:19 +00:00
christianEQ 3c4cadc020 compare_exchange in connSocketRead, explicitly enforce memory order (even if redundant) 2021-01-28 23:17:48 +00:00
christianEQ e2615ccf88 fixed replicaof no one config, added test case 2021-01-28 19:49:22 +00:00
christianEQ 595deb0e13 updated version num to 255.255.255 2021-01-28 16:54:22 +00:00
christianEQ 5372d1aab2 Merge remote-tracking branch 'john/unstable' into redismerge_2021-01-20 2021-01-27 22:25:14 +00:00
christianEQ 52eca14ca6 arm locker before checking zmalloc_used_memory 2021-01-27 22:24:06 +00:00
Daniel Dai 1155f5ac63 Fix Swapdb crash 2021-01-27 15:24:10 -05:00
christianEQ 7319953ae3 fixed uninitialized variables in ACLSetUserCommandBit 2021-01-26 23:29:15 +00:00
christianEQ b8e106a72e fixed strncpy off-by-one errors 2021-01-26 23:27:28 +00:00
christianEQ f30f8eba2f removed unimplemented killIOThreads function declaration 2021-01-26 22:27:22 +00:00
christianEQ 7ed2296fc5 fixed server.cpp mentions 2021-01-26 22:22:19 +00:00
christianEQ 0691a46669 added note about io-threads to keydb.conf 2021-01-26 22:10:53 +00:00
christianEQ d7f01c1f7d fixed race condition in connSocketWrite 2021-01-26 22:08:07 +00:00
christianEQ 4d71929c60 Removed Redis-specific things from conf file 2021-01-26 21:50:45 +00:00
christianEQ dadce055f8 Merge tag 'tags/6.0.10' into redismerge_2021-01-20 2021-01-26 21:43:09 +00:00
christianEQ d2867580ab changed loading process config types to be consistent across environments 2021-01-14 21:12:36 -05:00
christianEQ 8dc238efae renamed loaded key counter to be more clear 2021-01-14 13:06:57 -05:00
christianEQ 7cd4b5e11c removed 'comment arguments' from config options (doesn't ignore inline comments) 2021-01-14 13:06:57 -05:00
christianEQ 00043f9509 fixed signedness warning 2021-01-14 13:06:57 -05:00
christianEQ 9b81f3f263 added section to keydb.conf for new options, tweaked default 2021-01-14 13:06:57 -05:00
christianEQ 2747d1a1a9 ping replicas during key load 2021-01-14 13:06:57 -05:00
christianEQ 9f7ed0b232 added config option for loading callback interval keys 2021-01-14 13:06:57 -05:00
christianEQ c176ea7366 configurized loading_process_events_interval_bytes 2021-01-14 13:06:57 -05:00
John Sully d50e4bb819 Fix intermittent module test failure, resizing the repl backlog is not good enough to clear the backlog 2021-01-12 00:29:07 +00:00
benschermel 4485ca74f6 update perf chart, build info, job post link 2021-01-11 11:40:00 -05:00
benschermel 7f72b214e5 created ascii logo image 2021-01-11 11:40:00 -05:00
John Sully bc8cc1adb3 Merge branch 'repl_perf' into unstable 2020-12-24 02:22:57 +00:00
John Sully d03c2de901 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-12-11 03:59:50 +00:00
John Sully 7d3c5f1e64 don't try and free a client that can't be freed 2020-12-11 03:59:39 +00:00
John Sully 81573de393 Prevent use after free 2020-12-11 03:59:26 +00:00
John Sully a80dd5d001 Remove AE_ASSERT and use the proper assert infra 2020-12-11 00:24:27 +00:00
John Sully 7e0077f293 Prevent test crash due to unimplemented save for nested hash 2020-12-11 00:23:44 +00:00
John Sully 1eb035e6ad Fix crash freeing nested hash with list 2020-12-11 00:23:14 +00:00
Kajaruban Surendran bdd14ac517 Addressing PR comments 2020-12-04 14:54:06 -05:00
Kajaruban Surendran 63e5d00bdf Addressing PR comments 2020-12-04 14:54:06 -05:00
Kajaruban Surendran c25fb3d74f Handling of aeResizeSetSize's return code for current thread 2020-12-04 14:54:06 -05:00
Kajaruban Surendran 572d41325b check the aeResizeSetSize return code 2020-12-04 14:54:06 -05:00
Kajaruban Surendran e02120cdf7 Adding thread index to the error message 2020-12-04 14:54:06 -05:00
Kajaruban Surendran 7b1221a74d Call aePostFunction to change the setsize of each threads by that thread 2020-12-04 14:54:06 -05:00
Kajaruban Surendran d6b4f994ad Calling initServerThread function cserver.cthreads(server-threads) times than MAX_EVENT_LOOPS(constant) 2020-12-04 14:52:28 -05:00
christianEQ 66a41dafc4 Issue: #204 Allocate 8 MB to thread stack 2020-12-01 14:50:03 -05:00
John Sully f19b9c155e Issue: #260 Don't use C++ static_assert in C files 2020-11-30 23:01:20 +00:00
John Sully 5d016fdb6b code coverage reports should test multithreaded 2020-11-30 22:59:00 +00:00
VivekSainiEQ cae9924fd9 Added module data type load/save tests 2020-11-30 17:47:04 -05:00
VivekSainiEQ 089f28e8ba Removed use of module datatypes, now should work if tests/modules is not built 2020-11-30 17:47:04 -05:00
VivekSainiEQ dcb44d3a09 Added tests for saving various data types to disk and loading them back, and for loading data types from redis to maintain compatibility 2020-11-30 17:47:04 -05:00
VivekSainiEQ f99cba0b92 Added remainder of runtest scripts to make lcov command. Code coverage goes from 57.9% to 72.1% 2020-11-30 17:47:04 -05:00
VivekSainiEQ e10dc0dace Added KeyDB.info to .gitignore file 2020-11-30 17:47:04 -05:00
Kajaruban Surendran 49a89d636b Configurable option for MOTD 2020-11-30 10:42:48 -05:00
VivekSainiEQ b94f91b9b2 Added references to KeyDB.info instead of redis.info 2020-11-25 18:49:20 -05:00
VivekSainiEQ 06a17c8511 Properly escaped $ in lcov command 2020-11-25 18:49:20 -05:00
VivekSainiEQ eebd70aaa6 Updated 'make lcov' command to exclude external dependancies and generate final code coverage percentage 2020-11-25 18:49:20 -05:00
VivekSainiEQ 779c775df9 Added test for issue #257 2020-11-25 17:21:37 -05:00
VivekSainiEQ 1d4d2925c2 Made NULL pointer check explicit, issue #257 2020-11-25 17:21:37 -05:00
VivekSainiEQ b67db7c2d5 Added NULL check to function objFromAllocPtr, now NULL input will map to NULL output even if active replica is enabled 2020-11-25 17:21:37 -05:00
John Sully 18953b2998 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-11-23 02:01:54 +00:00
John Sully 527b7eb074 Fix issue where active replication doesn't replicate RDB data 2020-11-23 02:01:40 +00:00
Kajaruban Surendran 34a97c447f fix for the server crash when the maxclients increased via config set 2020-11-20 15:20:46 -05:00
John Sully 1c525e20b1 Blocking clients should not crash if an active replica loads a remote RDB with a key in the blocklist 2020-11-19 23:28:01 +00:00
John Sully 0bcce50285 Ensure multithreaded tests pass 2020-11-13 21:08:10 +00:00
John Sully 96e0b2a2b1 Improve replication performance in multithreaded scenarios 2020-11-13 21:08:10 +00:00
John Sully f3794d2c42 Add ability to compile KeyDB without MOTD and curl 2020-11-13 20:51:30 +00:00
John Sully 97fd736923 Add missing file 2020-11-11 03:29:38 +00:00
John Sully ba950a3d1f Second implementation of nested hashes 2020-11-06 19:24:48 +00:00
John Sully dad5a902d3 Additional test reliability fixes 2020-10-27 07:25:43 +00:00
John Sully 3e33fbcd35 Disarm not release D'oh 2020-10-27 06:41:33 +00:00
John Sully 444555d3e4 Active replica test reliability enhancements 2020-10-27 06:23:14 +00:00
John Sully 6a74f524e5 Prevent crashes on shutdown due to lock being held 2020-10-27 04:53:19 +00:00
John Sully 9c5b59ac01 Ensure MVCC timestamp is incremented after the real time is updated 2020-10-27 04:52:35 +00:00
John Sully 1840601f8e Fix multithreaded test failure 2020-10-27 01:54:13 +00:00
John Sully 88962af8b2 Avoid unnecessary memory fences 2020-10-26 02:28:38 +00:00
John Sully df22cdf6e9 Remove addReply*Async methods since we already know if its async or not. This is just a source of bugs 2020-10-24 02:18:03 +00:00
John Sully 041446005b Allow the locker to be used even without a client 2020-10-23 20:21:49 +00:00
John Sully 7c39a9b0e1 Fix multithread test failures 2020-10-23 15:57:39 +00:00
John Sully 05cd92f766 Remove leak warning with ASAN in the CLI 2020-10-21 21:16:08 +00:00
John Sully d724e7226c run when necessary 2020-10-16 07:00:03 +00:00
John Sully 738c782f02 Fix replica buffer overflows 2020-10-16 06:47:40 +00:00
John Sully 33b05c859a Avoid locking if we won't run a time event 2020-10-16 06:19:52 +00:00
John Sully ed369d7223 Reduce async write copies 2020-10-15 23:10:17 +00:00
John Sully fb32bb12b1 Fix branding 2020-10-15 20:15:35 +00:00
John Sully 3e996035ea Relax memory order where possible 2020-10-13 06:35:16 +00:00
John Sully ae8a94d615 Significantly improve perf in replication scenarios 2020-10-12 15:27:03 +00:00
John Sully 69a74a567b Avoid excess locking, seeing up to 8% performance improvements 2020-10-12 05:50:58 +00:00
John Sully 1b46d4f09a Perf: remove unnecessary vector operations 2020-10-12 04:28:39 +00:00
John Sully c6f13892e0 Remove dead code 2020-10-09 21:02:09 +00:00
Hanif Bin Ariffin 05e0f32345 Fixed non-empty check in src/Makefile
Per [GNU Make Manual](https://www.gnu.org/software/make/manual/html_node/Conditional-Syntax.html).
To properly check for non-empty variable, one must strip whitespaces.

Signed-off-by: Hanif Bin Ariffin <hanif.ariffin.4326@gmail.com>
2020-10-05 10:58:49 -04:00
Hanif Bin Ariffin 8171e6de13 Removed dead code from a macro in zmalloc.cpp
I think the compiler would have removed this no-op anyways but it
definitely wasted me some 30 minutes on this :(

I was hoping I could remove the branch through some bit-hacking but
apparently its dead code :). Oh well, its 30 minutes of refreshing
bit hacking.

Signed-off-by: Hanif Bin Ariffin <hanif.ariffin.4326@gmail.com>
2020-10-03 20:41:26 -04:00
John Sully b042495f37 Delete CONTRIBUTING 2020-10-01 11:17:56 -04:00
John Sully 420ccdfbae Fix module test failures due to locking 2020-10-01 00:08:54 +00:00
John Sully 41466a4147 Fix TLS test failure due to bad merge 2020-09-30 20:21:40 +00:00
John Sully 9798f2d711 Keep redis-cli.c C89 compatible 2020-09-30 20:17:51 +00:00
John Sully 5f3543921b Mac build break fix 2020-09-30 20:17:02 +00:00
John Sully a41366cc3a Fix stream replication failure with active replication, issue #238 2020-09-30 20:12:54 +00:00
John Sully 4c7e4b91a6 Merge tag '6.0.8' into unstable 2020-09-30 19:47:55 +00:00
John Sully 28183f4b66 Test RDB merge on load with active replication 2020-09-29 03:26:06 +00:00
John Sully a0abc1eddd Drop min-clients-per-thread to a more reasonable number 2020-09-28 19:17:36 +00:00
John Sully 676644f2db Support read only replicas attaching to active replicas (Bug #229) 2020-09-23 04:16:08 +00:00
John Sully 22ac56d62d Active replicas memory leak 2020-09-22 21:38:35 +00:00
John Sully 143f7f634d Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-09-21 04:42:46 +00:00
Dmitry Dorofeev 955faef23a Fix to support FreeBSD pthread_getthreadid_np call 2020-09-21 00:41:41 -04:00
John Sully 2e159e6ea3 Fix TSAN errors in fastlock 2020-09-21 03:26:50 +00:00
John Sully 02b533fec3 Fix issue #222 2020-09-21 01:09:58 +00:00
John Sully de3099e6d8 Make multimaster replication info statelessly paresable 2020-09-20 23:57:06 +00:00
John Sully 368f67f422 Dramatically improve the performance of subkey expires 2020-09-20 23:30:21 +00:00
John Sully 13c9a094d1 Reduce test noise 2020-09-19 22:00:17 +00:00
John Sully 0f8b7a19ef Fix CI failure due to apt host changes 2020-09-19 21:49:59 +00:00
John Sully 8f7d977f90 Avoid memory overhead in situations it won't be used (active rep only) 2020-09-19 21:44:59 +00:00
John Sully 064440ee84 Update endurance test for ubuntu 20 2020-09-17 02:10:18 +00:00
John Sully 50641d0569 Fix build break 2020-09-17 00:53:56 +00:00
John Sully f5ecc77e29 master_global_link_status should respect the quorum 2020-09-17 00:31:10 +00:00
John Sully 655bb6e21c Allow reads during an active replica load, optionally allow writes as an experimental feature 2020-09-17 00:13:03 +00:00
John Sully ab4cdd2ed4 Implement replica-quorum config 2020-09-16 03:26:31 +00:00
Yossi Gottlieb d3834c5069 TLS: Session caching configuration support. (#7420)
* TLS: Session caching configuration support.
* TLS: Remove redundant config initialization.
2020-09-16 02:10:29 +00:00
John Sully 7a1b2c58c3 Protocol error in client command 2020-09-11 20:48:18 +00:00
John Sully 7fc6d6c6b1 Fix more protocol errors 2020-09-11 20:47:27 +00:00
John Sully dec5db4e71 Fix protocol difference with Redis 2020-09-11 20:08:26 +00:00
John Sully d47aeb1fc8 Fix whitespace 2020-09-07 03:35:46 +00:00
John Sully e47584b286 Dramatically improve perf by blocking commands 2020-09-07 00:49:53 +00:00
John Sully f17d178d03 Add build flag to disable MVCC tstamps 2020-08-10 06:10:24 +00:00
John Sully d88fd1588d Fix lock after free in module API 2020-08-10 06:10:24 +00:00
John Sully 119797014c Remove gitter, we don't check it often enough 2020-07-13 21:14:03 -04:00
John Sully e8f568644b Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-07-13 01:05:17 +00:00
John Sully b736a95b0d Merge tag '6.0.5' into unstable
Redis 6.0.5
2020-07-13 00:55:23 +00:00
benschermel d909d12cb3 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-07-12 18:04:40 -04:00
benschermel 201ffa9d62 update rpm permissions 2020-07-12 18:03:21 -04:00
John Sully 5619f51528 Add the KEYDB.MEXISTS command, see issue #203 2020-07-12 21:42:11 +00:00
John Sully d99d06b125 Add multi-master-no-forward command to reduce bus traffic with multi-master 2020-07-12 19:25:19 +00:00
John Sully 1b9ade7f65 Document min-clients-per-thread 2020-07-12 18:49:02 +00:00
John Sully e01312642b Prevent deadlock in RM_ThreadSafeContextLock() when triggered as part of a module callback in a server thread 2020-07-12 18:17:53 +00:00
John Sully cd9514f4c8 Fix failure to merge databases on active replica sync, due to bad merge with Redis 6 2020-07-12 01:13:22 +00:00
John Sully f111c23415 Support missing Redis 6 config options 2020-07-11 21:39:20 +00:00
John Sully 6857c4c208 Latency fixes 2020-07-01 21:59:38 -04:00
Muhammad Zahalqa 52897f8f9a replace memcpy with cctor on objects 2020-06-24 23:20:59 -04:00
Muhammad Zahalqa 8bc70e9840 unique lock used with cv.wait already owns mutex 2020-06-24 23:18:53 -04:00
Muhammad Zahalqa 5b81303f04 Fix bug in condition_variabe.wait usage
consition variable wait should always be called with a locked mutex.
This code break the pre-conditions of using wait.
2020-06-24 23:18:53 -04:00
Muhammad Zahalqa ede524c064 fixes for robj_sharedptr
1. fix cases where null pointer might be accessed
2. make assignmnet op safe
3. make operator bool explicit (safe bool idiom)
4. make comparison operators symetric

fix robj_sharedptr use in rdb.cpp
2020-06-24 23:18:27 -04:00
Muhammad Zahalqa aeed09c346 aeCommand objects no need for memset and missing init of some memebers. 2020-06-24 23:15:29 -04:00
John Sully 70b80aa5fa Implement replicaof remove as requested in issue #192 2020-06-09 12:43:58 -04:00
John Sully e8d4d095cc Update gcov for C++ 2020-06-08 16:48:44 -04:00
Ben Schermel c50a3568a5 update Dockerfile 2020-06-08 15:34:22 -04:00
Ben Schermel 17e96b91b5 updating changelog 2020-06-08 15:34:22 -04:00
Ben Schermel c5e7a8517b dh9 for stretch deb pkg 2020-06-08 15:34:22 -04:00
Ben Schermel c36773777d fix missing sentinel 2020-06-08 15:34:22 -04:00
Ben Schermel d69e0b8561 update changelog 2020-06-08 15:34:22 -04:00
Ben Schermel 19ccc22a43 update changelog 2020-06-08 15:34:22 -04:00
Ben Schermel 6968a0cfcb update changelog 2020-06-08 15:34:22 -04:00
Ben Schermel df618fbd9f include support for dists < dh11 2020-06-08 15:34:22 -04:00
Ben Schermel 94acd43340 fix rpmbuild dirs 2020-06-08 15:34:22 -04:00
Ben Schermel 14bdd745d1 fix rpmbuild dirs 2020-06-08 15:34:22 -04:00
Ben Schermel aa3f5de16f adding dh_installsystemd 2020-06-08 15:34:22 -04:00
Ben Schermel 9f7890cb1a strip unused from deb source 2020-06-08 15:34:22 -04:00
benschermel 1dc34c16b5 add deb/rpm/docker support 2020-06-08 15:34:22 -04:00
benschermel b0e7be7ce2 add deb/rpm/docker support 2020-06-08 15:34:22 -04:00
benschermel 026ab4c922 update github CI for deb 2020-06-08 15:34:22 -04:00
Ben Schermel 07ba64c200 update rpm versioning 2020-06-08 15:34:22 -04:00
benschermel b4b35cf904 add package utilities 2020-06-08 15:34:22 -04:00
John Sully ba974c9810 Some valgrind fixes 2020-06-07 23:20:10 -04:00
John Sully 9817db7edd fix valgrind false error 2020-06-07 20:17:47 -04:00
John Sully 515bb0e6bd Endurance mode for tests ignore flaky ones 2020-06-07 16:59:59 -04:00
John Sully bc7ea8fb20 Solo tests should work with loopn 2020-06-07 15:06:50 -04:00
John Sully 2caf8e4c80 Stream tests rely on deferring clients, mitigate races caused by them 2020-06-07 13:59:41 -04:00
John Sully e1f3cd6ec3 replication test race 2020-06-07 01:14:57 -04:00
John Sully 02e821530a fix race in test 2020-06-07 00:44:11 -04:00
John Sully b6c3d80edb Make lazyfree more reliable 2020-06-07 00:40:58 -04:00
John Sully 0042586190 Detect issues like #189 2020-06-05 22:18:28 -04:00
John Sully c6dce838b7 Ensure CRON jobs run in a clean environment 2020-06-05 21:35:47 -04:00
John Sully 5b885bb164 Undecorated new is OK to use 2020-06-01 23:36:01 -04:00
John Sully 95f46e6077 maxmem tests should be run solo for higher reliability 2020-06-01 16:50:30 -04:00
John Sully 31f58311e3 Remove debug logs that shouldn't have been checked in 2020-06-01 16:34:05 -04:00
John Sully 130613e166 PSYNC test shouldn't wait forever 2020-06-01 16:13:58 -04:00
John Sully 50fd4fa7e6 PSYNC test reliability improvements (test only issue) 2020-06-01 16:01:26 -04:00
John Sully e6a9a6b428 Fix for issue #187 we need to properly handle the case where a key with a subkey expirey itself expires during load 2020-06-01 15:33:19 -04:00
John Sully d6be93537e Update endurance.yml 2020-06-01 00:25:31 -04:00
John Sully 1ef35cf466 Fix module multithreaded test failures 2020-05-31 23:46:12 -04:00
John Sully 1eb0e3c1c6 sendfile has high latency in some scenarios, don't use it 2020-05-31 23:22:25 -04:00
John Sully e50313b207 we must always respect the output of sdscat, also change the string so its not a substring of other config params 2020-05-31 23:22:10 -04:00
John Sully ac3f8d1ac7 Do another iteration for endurance 2020-05-31 22:51:02 -04:00
John Sully 202b97eff7 Don't start multimaster tests until all nodes are connected 2020-05-31 22:50:30 -04:00
John Sully f25aebf269 Fix client race in test (test only issue) 2020-05-31 21:39:50 -04:00
John Sully 9b1e636a66 --loop should run forever 2020-05-31 21:27:15 -04:00
John Sully 5147f0153a PUBSUB test reliability: A client race was erroneously failing tests (test only issue) 2020-05-31 21:27:15 -04:00
John Sully 88f7739ae0 Update endurance.yml 2020-05-31 17:50:02 -04:00
John Sully c0c033a0c1 Active replicas referencing eachother should connect one at a time 2020-05-31 16:03:50 -04:00
John Sully 73300c5700 Fix race in futex_sleep 2020-05-31 16:03:50 -04:00
John Sully 37033179fe Update endurance.yml 2020-05-31 14:18:12 -04:00
John Sully 3e6a5ac9cf Update endurance.yml 2020-05-31 03:43:06 -04:00
John Sully dcd297eb5b Endurance tests need more cores 2020-05-30 22:16:56 -04:00
John Sully 4a9742e696 Update endurance.yml 2020-05-30 20:03:04 -04:00
John Sully 8edbae2e04 Auto tune lock for high CPU tension scenarios 2020-05-30 18:22:27 -04:00
John Sully 63c6735ffc Ensure endurance run can complete in an hour 2020-05-30 15:31:54 -04:00
John Sully 8a0441c144 We only want one master connection in progress at a time, ensure that if the connection fails we try a different master 2020-05-30 15:13:28 -04:00
John Sully 460c5ed2b3 daily CI config fix 2020-05-30 03:27:37 -04:00
John Sully 8f44f0937b More clients for endurance 2020-05-30 03:13:04 -04:00
John Sully 1803b1587b Endurance tests need to be faster, reduce loops 2020-05-30 02:40:44 -04:00
John Sully a5325061f2 Only CI ARM daily 2020-05-30 02:34:37 -04:00
John Sully a10a0df09f Also test with multiple threads 2020-05-30 02:10:00 -04:00
John Sully 031044c7ea Reduce clients for endurance test 2020-05-30 02:07:30 -04:00
John Sully ca755e4905 Fix cron syntax 2020-05-30 01:53:21 -04:00
John Sully 3063a028b3 Add endurance CI tests 2020-05-30 01:47:26 -04:00
John Sully 2c659acc7d Update daily CI job 2020-05-30 01:21:50 -04:00
John Sully 341a8caef9 TLS requires we explicitly marshal connected sockets when using them on a different thread 2020-05-30 01:14:53 -04:00
John Sully 366f8c2dc6 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-05-30 00:06:23 -04:00
John Sully 5803540422 Fix memory test failures with multithreading enabled 2020-05-30 00:06:15 -04:00
Ben Schermel f17c492a63 centos build fix 2020-05-29 22:23:48 -04:00
John Sully aad6a7ce15 sendFile blocks too long for use with active replication 2020-05-29 20:27:45 -04:00
John Sully 1cb48c7bf6 Unify beforeSleep handling 2020-05-29 17:44:55 -04:00
John Sully f25c405ad2 Cluster crash 2020-05-29 03:40:52 -04:00
John Sully c9920849dd active replica tests on slow computers 2020-05-29 01:58:15 -04:00
John Sully 81b240f81d Fix test issue with TLS 2020-05-29 01:44:52 -04:00
John Sully 6a902b29e1 Fix CI 2020-05-29 01:01:41 -04:00
John Sully 9c31ac7925 Merge tag '6.0.4' into unstable
Redis 6.0.4.
2020-05-29 00:57:07 -04:00
John Sully f0d8d1680f Fix TLS tests 2020-05-29 00:16:06 -04:00
John Sully 6dcbcacb10 gencert its own step 2020-05-28 23:49:13 -04:00
John Sully 3196717cee CI yml syntax error 2020-05-28 23:18:02 -04:00
John Sully f95578ac02 Fix TLS tests in CI 2020-05-28 23:16:42 -04:00
John Sully 57ca6facc3 fix TLS test failure 2020-05-28 23:16:27 -04:00
John Sully 561a1f8d8a Test TLS as part of CI 2020-05-26 01:39:54 -04:00
John Sully 1449c8b9fe Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-05-26 01:29:08 -04:00
John Sully 1938af27f5 Fix client tracking, also ensure tracking tests are enabled 2020-05-26 01:28:52 -04:00
Maxime de Roucy 123bc125cf acl: @replication command group
containing mandatory commands for replication (used by masteruser user)
2020-05-25 02:35:22 -04:00
John Sully ecbe168b54 Fix issue #170. Intermittent crash destroying fastlock due to implicit type conversion in assert 2020-05-25 02:13:57 -04:00
John Sully 00cef78858 Fix infinite logs of Error in rreplay 2020-05-24 20:05:22 -04:00
John Sully d05da0fabd Enable TLS connections 2020-05-24 19:57:16 -04:00
John Sully 4db3f2a443 don't keep feeding data to clients pending close 2020-05-24 12:46:11 -04:00
John Sully fd710d590a Quiet TSAN during exit 2020-05-24 12:45:10 -04:00
John Sully 9b98c9edd3 Install deps for daily workflow 2020-05-24 11:19:53 -04:00
John Sully 4893eedacb Hold the AE lock until we process the repl backlog after a command 2020-05-24 11:19:23 -04:00
John Sully fb50163b47 Add standardized way to post client dependent functions 2020-05-24 02:46:39 -04:00
John Sully 3b8463f9d2 remove unnecessary cplusplus guard 2020-05-24 02:45:55 -04:00
John Sully 42c7677690 race in connection state when setting a handler on a different thread 2020-05-24 02:45:11 -04:00
John Sully 8665f25031 Fix ASAN races 2020-05-24 01:58:33 -04:00
John Sully 1c6b573147 Incorrect locking in replication error paths 2020-05-24 01:57:49 -04:00
John Sully 90162da1a6 Incorrect memory order on weak ordered architectures 2020-05-24 01:57:18 -04:00
John Sully 1ca6c1dd56 If we request shutdown from a client on a different thread than a blocking lua script we fail to actually shutdown until the script completes 2020-05-24 01:56:23 -04:00
John Sully 2d27c8ecdb race calculating client overhead 2020-05-24 01:53:43 -04:00
John Sully 59cda9cfb9 During RDB load we can only handle clients on the main thread as our workers are not yet created. This change also unifies the accept logic across the socket types 2020-05-23 16:03:24 -04:00
John Sully 091af64003 Diskless replication handler needs to run on the main thread 2020-05-23 15:15:42 -04:00
ShooterIT a12210c875 Fix reply bytes calculation error
Fix #7275.
2020-05-23 13:02:55 -04:00
John Sully 43649fc5b4 Merge tag '6.0.3' into unstable
Redis 6.0.3
2020-05-22 16:53:10 -04:00
John Sully 01cc25653a Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-05-22 16:45:27 -04:00
John Sully a010e4a4b2 Merge tag '6.0.2' into unstable
Redis 6.0.2
2020-05-22 16:45:18 -04:00
John Sully 817a11ff11 Merge commit 'cb683a84f7a9d530bec629f2b656e7d0842a0f75' into unstable 2020-05-22 15:56:35 -04:00
John Sully c52e1fc78c Merge commit '3a441c7d95c8757d2ab12ff730cc7ca8899538c9' into unstable 2020-05-22 15:42:50 -04:00
John Sully d74871da40 Merge commit 'c57d9146f41f4b661d9d2cb48b83b3abc757ba0e' into unstable 2020-05-22 15:36:44 -04:00
John Sully a25cf15ecd Update README.md 2020-05-22 14:03:29 -04:00
John Sully c505df8830 Merge tag '6.0.1' into unstable
Redis 6.0.1.
2020-05-21 23:41:36 -04:00
John Sully f214ada545 Missing noexcept 2020-05-21 23:25:50 -04:00
John Sully c10aa3b8b0 build failure on macos 2020-05-21 23:24:34 -04:00
John Sully 6311d709c3 Fix bad merge in CI.yml 2020-05-21 22:09:06 -04:00
John Sully 8ab77465db Merge commit 'bec68bff2978de88b23140f41b6a943162333b11' into unstable 2020-05-21 19:37:42 -04:00
John Sully 201bf73ef7 Merge commit '414debfd04d21c0b19d5f6bb5249398d83670f3d' into unstable 2020-05-21 18:57:28 -04:00
John Sully 49784c8122 Merge commit 'cbcd07777dc569618a34f59e5fd0de53178f4f1d' into unstable 2020-05-21 18:48:49 -04:00
John Sully 3e03f308b5 Merge commit '5719b3054a534e62c25ae97680ecd4f7238ba484' into unstable 2020-05-21 17:55:09 -04:00
John Sully 95cecb0229 Merge commit '026cc11b056f063631d990f1a9db45b4e583974e' into unstable 2020-05-21 17:45:15 -04:00
John Sully 7676f5b15f Merge commit '024c380b9da02bc4112822c0f5f9ac1388b4205b' into unstable 2020-05-21 17:36:53 -04:00
John Sully d5b057534a Merge commit 'eba28e2cea0b2632cf751426ada02adf24f273db' into unstable 2020-05-21 17:32:53 -04:00
John Sully 7a15f6dfc7 Merge commit 'c35a53169ffdbdf73f91224b6e62f6129fb9a838' into unstable 2020-05-21 17:30:56 -04:00
John Sully 712d825c23 Override missing new, fix new/delete mismatch 2020-05-20 15:57:08 -04:00
John Sully 4073758874 Remove debugging logs 2020-05-14 22:18:29 -04:00
John 3543a3c763 more reliability fixes for multimaster 2020-05-11 05:38:21 -04:00
John 3122912920 Make multimaster tests more reliable 2020-05-11 05:23:47 -04:00
John Sully f11fdf6717 Update access LFU/LRU access times when overwriting key 2020-05-11 00:42:46 -04:00
John Sully 572bcca9c2 We should still send replies even if an async close is pending 2020-05-10 23:56:29 -04:00
John Sully 10fa064109 Fix race on clients_to_close 2020-05-10 23:14:15 -04:00
John Sully 7cd779d304 Fix crash in client unblock command 2020-05-10 22:08:50 -04:00
John Sully 628d168049 Fix crash during hook module test 2020-05-10 21:57:16 -04:00
John Sully 37423757b5 Fix crash in module tests 2020-05-10 21:06:38 -04:00
John Sully 58752bb8fe Run sentinel and module tests under CI 2020-05-10 18:05:05 -04:00
John Sully 7e7f70ff3e add help for hrename 2020-05-10 17:41:01 -04:00
John Sully f77c227b2d hrename tests 2020-05-10 17:14:44 -04:00
John Sully 21d842b0b0 Implement keydb.hrename command 2020-05-10 17:04:22 -04:00
John Sully 86f9ed6248 Disable cluster tests
They are unreliable on slow hardware.
2020-05-07 01:49:04 -04:00
Diab Neiroukh dcd7b684bb Clang requires libatomic to be linked via LDFLAGS
Clang requires the libatomic to be linked via LDFLAGS or else the linker
will fail to recognise __atomic macros.

An error as a result of not passing -latomic to the linker can be seen
below:

ld.lld: error: undefined symbol: __atomic_fetch_add_2
>>> referenced by sds.c:185
>>>               lto.tmp:(sdsdupshared)
clang-10: error: linker command failed with exit code 1 (use -v to see invocation)
make[1]: *** [Makefile:276: keydb-server] Error 1
2020-04-30 15:06:10 -04:00
John Sully f715d0b860 cluster tests should be a named task 2020-04-29 18:43:55 -04:00
John Sully 98d690b849 Run cluster tests as part of CI 2020-04-29 18:41:51 -04:00
John Sully 45535e8a63 use serverAssert() instead of assert() to get callstacks in fastlock 2020-04-28 22:41:07 -04:00
John Sully c78895aaea Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-04-28 22:24:45 -04:00
John Sully d5ede50b04 shared pointer comparisons with other pointers 2020-04-24 22:20:26 -04:00
John Sully fab6132cb3 EMBSTR size is lower than it needs to be 2020-04-24 22:19:55 -04:00
John Sully e0a8709c09 Default yes in apt install 2020-04-22 02:17:28 -04:00
John Sully 17795fd5ce Run arm CI builds 2020-04-22 02:13:02 -04:00
John Sully d6738ffa5d MacOS Build Break Fix 2020-04-22 01:21:35 -04:00
John Sully e72642667f Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-04-16 20:12:14 -04:00
John Sully 3785b1efd4 Fix some clang warnings 2020-04-16 20:12:05 -04:00
John Sully 7aeae62f84 Always link libatomic 2020-04-16 20:01:24 -04:00
John Sully e5e33f8cb7 Fix warning in cluster.cpp 2020-04-16 20:01:13 -04:00
John Sully a836d5947d quiet TSAN in serverLog 2020-04-16 17:06:25 -04:00
John Sully 7cdd5d9e41 Update Readme to use github CI badge 2020-04-15 23:21:10 -04:00
John Sully 3f5d3fec36 update TLS readme for KeyDB 2020-04-15 23:19:05 -04:00
John Sully 90094a2dca Deprecate travis and finish setting up github CI 2020-04-15 23:04:04 -04:00
John Sully cc9924ffa6 Merge branch 'unstable' into redis_6_merge 2020-04-15 23:00:13 -04:00
John Sully 5e6b4ab99e OS X build break 2020-04-15 22:43:40 -04:00
John Sully 2d6d374162 more dependencies for CI 2020-04-15 22:39:47 -04:00
John Sully 3137d4f35c Add CI dependency 2020-04-15 22:36:16 -04:00
John Sully 6ff9d23fd4 During AOF reload we can erroneously read incorrect aof_state values, so this variable must be read with the global lock acquired 2020-04-15 22:30:19 -04:00
John Sully d4939c838b Quiet test only ASAN fd race 2020-04-15 22:27:45 -04:00
John Sully cd306f1d23 Run all KeyDB instances in testmode during tests 2020-04-15 22:27:04 -04:00
John Sully 5fd07e0889 Fix race in sendBulk 2020-04-15 22:26:00 -04:00
John Sully b0796ff5fd Convert variables accessed outside lock to atomics 2020-04-15 22:25:17 -04:00
John Sully 9dfa074cd6 ASAN races in leak checker 2020-04-15 22:24:12 -04:00
John Sully 033761c5f9 Multithreading reliability, force single thread for test relying on internal behavior 2020-04-15 20:52:25 -04:00
John Sully 2926ac494e rename to KeyDB (merge) 2020-04-15 16:44:06 -04:00
John Sully 06143c2e8c Log stdout and stderr for cluster tests 2020-04-15 16:35:24 -04:00
John Sully f00d28fdab Fix TSAN race 2020-04-15 16:34:38 -04:00
John Sully 4705f29e2f Fix incorrect cluster slot tracking (regression from merge) 2020-04-15 16:34:07 -04:00
John Sully b2cb10de5f Merge tag '6.0-rc3' into redis_6_merge
Redis 6.0 RC3.
2020-04-14 22:56:19 -04:00
John Sully 1005a725d4 Fix merge issues and move timeout to C++ 2020-04-14 22:37:26 -04:00
John Sully 50768cd242 Merge commit 'c3b268a0bcded2d730790a772176483efb7c31fb' into redis_6_merge 2020-04-14 22:25:44 -04:00
John Sully cc3ebbe519 Merge commit '0f7dfc378ce5ab0524ac28b6142545bc41435386' into redis_6_merge 2020-04-14 22:19:29 -04:00
John Sully 8056e349e0 Merge commit '7c07841632500dfdff31f5a69e5bd140abea646c' into redis_6_merge 2020-04-14 21:26:51 -04:00
John Sully 0001f59c8d Merge commit 'b3e0305448422239ba3cb8d125681bccdb809cd3' into redis_6_merge 2020-04-14 21:16:38 -04:00
John Sully 2941792a85 Merge commit 'e628f94436f2ffb38dd6305f18956f309838a8d6' into redis_6_merge 2020-04-14 21:13:42 -04:00
John Sully 320bc3c032 Merge commit '76d57161d960f27ac92765118e3b80fef8847b8f' into redis_6_merge 2020-04-14 21:04:42 -04:00
John Sully 2825e51550 Merge commit 'e74e68c84f5eba8013769087c9a46cab811b8417' into redis_6_merge 2020-04-14 20:55:29 -04:00
John Sully cbdd47d056 Merge commit 'baaf869fc3e138cfcb4cfda09f09fd3c87c8f924' into redis_6_merge 2020-04-14 20:44:27 -04:00
John Sully 516c8c6e23 Merge commit 'be4bc1a5be26a7fde2fd05acd8187f5f0ed59f25' into redis_6_merge 2020-04-14 20:42:48 -04:00
John Sully ef1236b600 Merge commit '973297336fc05a601e17be70aba88e5dca6480ae' into redis_6_merge 2020-04-14 20:19:48 -04:00
John Sully 28cbed1d13 Merge commit '349aa24511253b3e323064b95cefb4414f31726c' into redis_6_merge 2020-04-14 20:09:53 -04:00
John Sully cde199a797 Merge commit 'df83892760d19b1b7e92d76e72daf4834ad2df6c' into redis_6_merge 2020-04-14 19:43:04 -04:00
John Sully 5589a0a69c Merge commit 'f42ce57d0f7eee6705fb0a81714cabe97a4f2c0a' into redis_6_merge 2020-04-14 19:22:44 -04:00
John Sully 09e8fb17cd Merge commit '51c1a9f8fbc12a9276489178242e498bb6ccbdba' into redis_6_merge 2020-04-14 18:44:42 -04:00
John Sully d71c4c2215 Merge commit '6fe55c2f299bbb306533af39cb28346bf5d473d3' into redis_6_merge 2020-04-14 18:30:26 -04:00
John Sully 6f621e6480 Merge commit '721a39ddff0eb9be822d27dba80267f6da149aff' into redis_6_merge 2020-04-14 18:29:03 -04:00
John Sully 8e33c2d301 Merge commit 'cbabf779c24fd107ca8e4fe6369e4677ad0eda10' into redis_6_merge 2020-04-14 18:05:10 -04:00
John Sully 52aca124c3 Merge commit 'ecd17e819cbb05110a49d81c6fda10e6770a7838' into redis_6_merge 2020-04-14 18:04:51 -04:00
antirez c7159d58f1 Jump to right label on AOF parsing error.
Related to #6054.
2020-04-14 18:03:22 -04:00
antirez 5d6e8fe3e3 PSYNC2: meaningful offset implemented.
A very commonly signaled operational problem with Redis master-replicas
sets is that, once the master becomes unavailable for some reason,
especially because of network problems, many times it wont be able to
perform a partial resynchronization with the new master, once it rejoins
the partition, for the following reason:

1. The master becomes isolated, however it keeps sending PINGs to the
replicas. Such PINGs will never be received since the link connection is
actually already severed.
2. On the other side, one of the replicas will turn into the new master,
setting its secondary replication ID offset to the one of the last
command received from the old master: this offset will not include the
PINGs sent by the master once the link was already disconnected.
3. When the master rejoins the partion and is turned into a replica, its
offset will be too advanced because of the PINGs, so a PSYNC will fail,
and a full synchronization will be required.

Related to issue #7002 and other discussion we had in the past around
this problem.
2020-04-14 17:56:09 -04:00
Oran Agra 99762dac23 reduce repeated calls to use_diskless_load
this function possibly iterates on the module list
2020-04-14 17:34:36 -04:00
John Sully 57956b3fd2 Fix merge conflicts from cherry-pick 2020-04-14 17:33:54 -04:00
antirez b323645227 Remove RDB files used for replication in persistence-less instances. 2020-04-14 17:27:05 -04:00
Johannes Truschnigg dd9502f373 Signal systemd readiness atfer Partial Resync
"Partial Resynchronization" is a special variant of replication success
that we have to tell systemd about if it is managing redis-server via a
Type=Notify service unit.
2020-04-14 17:22:30 -04:00
Guy Benoish aa8a3077a2 Diskless-load emptyDb-related fixes
1. Call emptyDb even in case of diskless-load: We want modules
   to get the same FLUSHDB event as disk-based replication.
2. Do not fire any module events when flushing the backups array.
3. Delete redundant call to signalFlushedDb (Called from emptyDb).
2020-04-14 17:21:10 -04:00
John Sully 8e81e5f29e Cache fake client in replicaFeedSlaves 2020-04-13 22:45:15 -04:00
John Sully 63dd1fb599 Don't do active replica work if we're not an active replica 2020-04-13 22:35:06 -04:00
John Sully 32561a9912 Optimize replicaFeedSlaves by removing use of snprintf 2020-04-13 22:11:34 -04:00
John Sully 3fdc8608f3 Fix failure to AUTH with master when masterauth is set last 2020-04-06 01:24:59 -04:00
John Sully 9e2e2067c6 Add the ability to set a starting core # when setting thread affinity 2020-04-04 22:58:17 -04:00
John Sully f112c77fcc Fix issue #164 2020-04-04 22:45:12 -04:00
John Sully 888d69a87a Role command protocol corruption with multiple masters 2020-04-04 22:32:15 -04:00
John Sully bd183cdee1 Fix subkey expires not replicating correctly, and AOF issues 2020-04-04 21:52:27 -04:00
John Sully 95b4f899c5 Merge branch 'redis_6_merge' of https://github.com/JohnSully/KeyDB into redis_6_merge 2020-03-30 00:52:43 -04:00
John Sully 2946155313 Merge branch 'unstable' into redis_6_merge 2020-03-30 00:52:12 -04:00
John Sully f2ca2aa1f7 Allow active replicas to connect to each other when replica-serve-stale-data is set 2020-03-30 00:51:40 -04:00
John Sully b20bf10fda Don't send build log to stderr 2020-03-28 23:36:57 -04:00
John Sully 208c15bc16 Merge branch 'unstable' into redis_6_merge 2020-03-27 14:50:37 -04:00
John Sully c3d3c82f3a Raspberry Pi fixes (compile and replication) 2020-03-27 12:46:25 -04:00
John Sully b22d9cc27d Fix merge issues 2020-03-25 22:26:27 -04:00
John Sully 908cf5042e Merge branch 'unstable' into redis_6_merge 2020-03-25 22:12:22 -04:00
John Sully 6ec1641294 Fix issue #143 2020-03-25 21:55:31 -04:00
John Sully 7b79ec360b Give a better error when handling std::terminate 2020-03-25 16:27:24 -04:00
John Sully 718aee242d Merge branch 'unstable' into redis_6_merge 2020-03-25 15:47:12 -04:00
John Sully 56fc6b7deb Add roundtrip test for subkey expires 2020-03-25 15:34:30 -04:00
John Sully 528a43bd6c Fix failure to load subkey expires 2020-03-25 01:38:58 -04:00
John Sully b357803362 Expire entry needs to be resorted after a subkey expires 2020-03-25 01:06:40 -04:00
John Sully 448808529a Unstable branch should always be version 0.0.0 2020-03-19 15:52:24 -04:00
John Sully a0bc208412 Merge branch 'RELEASE_5' into unstable 2020-03-19 15:38:16 -04:00
John Sully 6b0172b9bf Print stack traces of other threads in the deadlock detector 2020-03-19 15:37:49 -04:00
John Sully bc1eccb66d Log which thread a message came from 2020-03-19 15:37:24 -04:00
John Sully a9249d4a82 Fix lock inversion in processEventsWhileBlocked 2020-03-19 15:28:39 -04:00
John Sully 3c373494d6 Prevent dangling lock when we can't free the client 2020-03-19 14:34:23 -04:00
John Sully 40761e4031 Merge branch 'unstable' into redis_6_merge 2020-03-17 00:09:48 -04:00
John Sully 5aef606d3b Fix issue #153: Config get replicaof returns a corrupt response 2020-03-16 20:43:46 -04:00
John Sully 4671cd6002 Merge branch 'unstable' into redis_6_merge 2020-03-15 18:47:27 -04:00
John Sully 2ec0b2cd20 Handle HTTP error codes with MOTD 2020-03-15 18:47:01 -04:00
John Sully 07effa3925 Merge branch 'unstable' into redis_6_merge 2020-03-15 18:33:24 -04:00
John Sully cd76a71de3 Update MOTD URL 2020-03-15 18:32:05 -04:00
John Sully 5e63c0955d Fix CLANG build break 2020-03-04 17:24:17 -05:00
John Sully e523afa741 Fix CLANG build break 2020-03-04 17:24:00 -05:00
John Sully c2a98a60f9 Fix CLANG build break 2020-03-04 17:23:40 -05:00
John Sully 6bc92d6d31 Merge branch 'unstable' into redis_6_merge 2020-03-04 17:13:50 -05:00
John Sully 13cf8bbeb7 Merge branch 'unstable' into RELEASE_5 2020-03-04 17:13:32 -05:00
John Sully 60c0d4104d Add missing files from last checkin 2020-03-04 17:13:18 -05:00
John Sully 52fd4445a4 Merge branch 'unstable' into redis_6_merge 2020-03-04 17:13:01 -05:00
John Sully 693ba4ed4a Merge branch 'unstable' into RELEASE_5 2020-03-04 17:09:29 -05:00
John Sully 5397f0b033 Add extra logging when reporting errors from masters - especially in rreplay 2020-03-04 17:09:12 -05:00
John Sully 6c78ec7c41 MOTD refactor 2020-03-04 16:22:55 -05:00
John Sully fed4bd5269 min-clients-per-thread needs to use the new config code 2020-03-04 15:14:41 -05:00
John Sully c0882864f2 Update README.md 2020-03-03 13:58:48 -08:00
John Sully 1a7e2e663e Merge branch 'unstable' into redis_6_merge 2020-03-01 21:48:51 -05:00
John Sully faa87ed839 Merge branch 'unstable' into RELEASE_5 2020-03-01 21:43:21 -05:00
John Sully 83f585e30a Update tests to reflect new CRON name (keydb.cron) 2020-03-01 21:42:01 -05:00
benschermel 7a244bb847 Merge branch 'unstable' into RELEASE_5 2020-03-01 19:53:32 -05:00
John Sully 1b925119b5 Rename cron command to KEYDB.CRON and add help 2020-03-01 19:18:21 -05:00
John Sully 3eb847e28f Rename cron command to KEYDB.CRON and add help 2020-03-01 19:17:58 -05:00
John Sully 9dc8f30e47 Merge branch 'unstable' into redis_6_merge 2020-02-28 23:56:26 -05:00
John Sully 3ce6441a0c Bump version 2020-02-28 23:53:54 -05:00
John Sully 6d00a1a5cf Merge branch 'unstable' into RELEASE_5 2020-02-28 23:53:00 -05:00
John Sully aaca32a5cd Fix compile failure on raspberry pi machines, issue #141 2020-02-28 23:49:17 -05:00
John Sully 54c96d1995 Fix not respecting max clients config, issue #147 2020-02-28 22:04:42 -05:00
John Sully e5a2d59446 Fix issue #146 2020-02-28 21:21:05 -05:00
John Sully d95bead383 Fix crash propogating stale keys 2020-02-26 21:49:40 -05:00
John Sully 51ea3cf30c Change Redis to KeyDB 2020-02-17 23:46:01 -05:00
John Sully 6ad6c1d780 Change Redis to KeyDB 2020-02-17 23:45:40 -05:00
John Sully 32f34f63fd Merge branch 'unstable' into redis_6_merge 2020-02-17 19:55:29 -05:00
John Sully 98aefac09b Add double unlock detection and improve fastlock_unlock assmebly 2020-02-17 19:54:05 -05:00
John Sully 5dc84850ad Incorrect use of std::atomic 2020-02-17 19:07:13 -05:00
John Sully 45b711f9d1 processEventsWhileBlocked not exception safe 2020-02-17 19:04:11 -05:00
John Sully 1ef187533c processEventsWhileBlocked not exception safe 2020-02-17 19:03:49 -05:00
John Sully 6a71de7835 Merge branch 'unstable' into redis_6_merge 2020-02-16 19:14:51 -05:00
John Sully 18496b6285 Support C++14 and remove dependency on future standard 2a 2020-02-16 19:04:56 -05:00
John Sully b9db899f6c Graceful shutdown of server threads when quit is requested 2020-02-16 18:53:46 -05:00
John Sully 4e9d2f08b1 Fix memory leak in RDB load 2020-02-16 18:42:14 -05:00
John Sully 06ad1c15d7 Fix memory leak in RDB load 2020-02-16 18:41:50 -05:00
John Sully 30a603ce05 Merge branch 'unstable' into redis_6_merge 2020-02-16 18:18:24 -05:00
John Sully 63ae679fe1 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-02-16 18:12:11 -05:00
John Sully b92bbf4de8 Memory leak fix on config, and redisDb dtor 2020-02-16 17:08:00 -05:00
John Sully 4781eda722 Fix memory leak of ReplicaNestState on shutdown 2020-02-16 03:43:29 -05:00
John Sully 2fd93c5789 aeDeleteEventLoop use after free and leak fixes 2020-02-16 03:34:25 -05:00
John Sully 329519d4aa Merge branch 'unstable' into redis_6_merge 2020-02-11 03:48:08 -05:00
John Sully 52434a583a Fix race condition in allocating connections to threads 2020-02-11 03:44:28 -05:00
John Sully 18a5f46b61 Merge branch 'unstable' into redis_6_merge 2020-02-11 02:39:08 -05:00
John Sully 16a019dba0 Implement an error handler so bug #125 can't happen 2020-02-11 01:41:00 -05:00
John Sully 1a4c3224c9 Fix higher latency at low load by grouping clients to threads. This fixes slow perf in cluster benchmarks mentioned in issue #102 2020-02-11 01:00:21 -05:00
John Sully c3317686f8 Fix cases where duplicate RREPLAY is applied 2020-02-11 00:59:07 -05:00
John Sully 4622472123 Fix issue #119 2020-02-10 19:52:57 -05:00
John Sully f1748f8c76 Fix memory leak in cron 2020-02-10 18:26:04 -05:00
John Sully 0c101dccc8 Add missing test file 2020-02-10 18:15:29 -05:00
John Sully dc78bf1ccb CLANG build fix 2020-02-10 00:29:26 -05:00
John Sully a7cc3aac28 Ensure multi-master works for ring topologies 2020-02-10 00:25:03 -05:00
John Sully 339631530a Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-02-09 02:25:20 -05:00
John Sully fb2bdf7d05 Addmissing test file 2020-02-08 16:49:41 -05:00
John Sully c45f1328ac merge 5.0 unstable 2020-02-07 16:45:59 -05:00
John Sully 050d58007f Fix issue #137 and #132 2020-02-06 23:31:31 -05:00
John Sully 49d86746ed Add test to detect issue #137 and #132 2020-02-06 23:31:12 -05:00
John Sully ef4e11ecb8 module fixes 2020-02-04 01:22:25 -05:00
John Sully fd702e43f1 Fix cluster test failures from Redis 6 merge 2020-02-03 20:00:09 -05:00
John Sully 249e0fdd36 addRef memory model too restrictive 2020-02-01 21:52:17 -05:00
John Sully 6208118b13 RDB memory leaks 2020-01-30 17:57:10 -05:00
John Sully 73020b6a93 replication memory leaks 2020-01-30 17:56:24 -05:00
John Sully a9667e84ad Fix memory leak in cron 2020-01-30 17:55:48 -05:00
John Sully ab1524ff1a Merge branch 'redis_merge' into unstable 2020-01-30 16:05:40 -05:00
John Sully 1069d0b4bf CRON jobs were running half as often as required 2020-01-28 21:40:40 -05:00
John Sully 4a980f4ddb More threading fixes from merge 2020-01-28 17:54:00 -05:00
John Sully 9fbb9a551e reenable multithreading after merge 2020-01-27 19:59:04 -05:00
John Sully c24a7c03c2 cron reliability 2020-01-27 18:31:02 -05:00
John Sully 5a8280d577 fix expire test failures during overwrite 2020-01-27 18:26:23 -05:00
John Sully da83e84125 Fix most tests (still some failures) 2020-01-27 18:16:19 -05:00
John Sully ef9a3cadcf Merge remote-tracking branch 'redis/6.0' into redis_merge 2020-01-27 02:55:48 -05:00
John Sully c983d57f73 Missing cron files 2020-01-21 19:51:16 -05:00
John Sully 3204a39ada Initial implementation of the CRON command 2020-01-21 19:50:28 -05:00
John Sully f4319c1280 Bump version 2020-01-20 19:20:50 -05:00
John Sully 762396d997 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-01-11 16:35:06 -05:00
John Sully c575e7df94 Avoid crash due to excessive posted functions for AOF rewrite 2020-01-11 16:34:30 -05:00
John Sully aa6409f2e8 Avoid crash due to excessive posted functions for AOF rewrite 2020-01-11 16:34:09 -05:00
John Sully e603e57588 Merge branch 'unstable' into RELEASE_5 2020-01-10 17:46:23 -05:00
John Sully 049b48ef79 Ignore other flags after pro is enabled since we won't understand them 2020-01-10 17:46:02 -05:00
John Sully 0ba0a6ab0a Update README.md 2020-01-10 14:21:11 -05:00
John Sully 7475ea1b0b Update graphs 2020-01-10 14:19:44 -05:00
John Sully d0654af74f Merge branch 'unstable' into RELEASE_5 2020-01-06 14:24:49 -05:00
John Sully d5f8df5997 pro launch should respect KEYDB_PRO_DIRECTORY 2020-01-06 14:24:37 -05:00
John Sully 39acb312ef Bump version 2020-01-06 12:07:57 -05:00
John Sully b643c38204 Merge branch 'unstable' into RELEASE_5 2020-01-06 12:07:11 -05:00
John Sully dd70f5efd7 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2020-01-06 12:04:00 -05:00
John Sully bb38628f0e Add new flags to example configuration file 2020-01-05 20:19:28 -05:00
John Sully 0cf3af6857 subkey expire testes 2020-01-03 16:50:13 -05:00
John Sully edb993d52b Drop severity of master disconnect log when multimaster is enabled 2020-01-02 15:36:02 -05:00
John Sully aea333bb78 Fix issue where expire is lost when performing a defrag 2020-01-01 20:41:17 -05:00
John Sully 45817db8c3 C++ wrapper classes for SDS 2020-01-01 19:13:48 -05:00
John Sully dbef17c2e1 Fix issue #130 due to fastlock timeout reduction 2020-01-01 11:52:00 -05:00
John Sully 42a8f22c21 Fix some static analysis warnings 2019-12-27 18:17:22 -05:00
John Sully 6e06e0dfc7 Ignore dependency files 2019-12-27 17:45:56 -05:00
John Sully bf500ab44b Make incremental building work with header files 2019-12-27 17:34:41 -05:00
John Sully 4d4eca5433 Multimaster requires Active Replication 2019-12-21 18:24:02 -05:00
Petr Vaněk 4b01ad1e30 Rename redis.conf to keydb.conf 2019-12-21 15:00:24 -05:00
Petr Vaněk 3b60929bdc Rename default pid file 2019-12-21 15:00:24 -05:00
John Sully a45d141597 Implement subkey expires for sorted sets 2019-12-18 00:10:05 -05:00
John Sully 8cbe254491 Implement subkey expire for hashes 2019-12-18 00:04:48 -05:00
John Sully ab365ce3da Launch the pro binary with --enable-pro 2019-12-17 23:52:19 -05:00
John Sully aa3e70f9a0 Fix type in makefile 2019-12-17 18:23:19 -05:00
John Sully cda8d42a76 Enusre CXXFLAGS has the same settings as CFLAGS 2019-12-17 17:49:51 -05:00
Petr Vaněk 67f32bf1b1 Correct C++ related makefile variables
FINAL_CXXFLAGS should not inherit CFLAGS because they can contain C
specific options unsupported by C++.

REDIS_CXX should point to the C++ compiler rather than C.
2019-12-17 17:43:15 -05:00
Petr Vaněk 7a3f363f34 readme: fix typo 2019-12-16 15:40:09 -05:00
Tais P. Hansen 91eac2cdb3 Fix keydb-cli crashing on read-only filesystem 2019-12-09 14:23:10 -05:00
John Sully 98a928147f Fix Issue #107 2019-12-01 18:17:33 -05:00
John Sully 8a9045c028 Fix deadlock in spinlock (mfence) also spin for less time before sleeping 2019-11-30 00:51:58 -05:00
John Sully 6c65a11b8d Fastlock should yield in ARM 2019-11-28 14:26:43 -05:00
John Sully 7dd53182e0 Bump version 2019-11-21 20:16:42 -05:00
John Sully 53b95d830a Merge branch 'unstable' into RELEASE_5 2019-11-21 20:16:23 -05:00
John Sully 3028a890ef Fix issue #83 2019-11-21 20:05:16 -05:00
John Sully 39c6fbddb1 Add missing dependency to dockerfile 2019-11-20 20:35:14 -05:00
John Sully 704cb4e929 Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2019-11-20 19:44:43 -05:00
John Sully 8e4f323439 Fix issue #107, active replicas do their own expires 2019-11-20 19:44:31 -05:00
John Sully 937702ea1d Additional asserts ensuring the client is creating on the correct thread 2019-11-20 17:00:40 -05:00
John Sully 3ea56ffb38 Update issue templates 2019-11-20 16:25:33 -05:00
John Sully becd3fc5a3 Update issue templates 2019-11-20 16:24:23 -05:00
John Sully 4c8603815c Fix failure to wakeup from futex sleep due to fastlock_unlock reading the wrong offset in the asm version. Also fix false sharing in spinlock 2019-11-17 16:06:49 -05:00
John Sully 3ae75c2d2b Revert "Debug sleep should apply to all threads"
This reverts commit 41b678814b.
2019-11-17 15:39:47 -05:00
John Sully 9371c005aa Improve perf of reading cluster bitfield 2019-11-17 14:52:12 -05:00
John Sully 16bd6b3f5d Merge branch 'unstable' of https://github.com/JohnSully/KeyDB into unstable 2019-11-14 21:21:46 -05:00
John Sully 3dd78a6101 Cluster multithreading fixes 2019-11-14 20:14:24 -05:00
John Sully 41b678814b Debug sleep should apply to all threads 2019-11-14 19:57:29 -05:00
John Sully d0ccb074d5 killing clients should take effect ASAP 2019-11-14 19:49:32 -05:00
John Sully cb0fc7cca2 Improve AE Assert message 2019-11-14 19:34:13 -05:00
John Sully 5e40ea6ee7 Fix test failure with tcl8.5 (test only issue) 2019-11-04 17:31:29 -08:00
John Sully 427c5999f1 Fix potential race in pubsub 2019-10-25 02:50:30 -04:00
John Sully a91f58b8fd Fix potential race in pubsub 2019-10-25 02:44:14 -04:00
John Sully 3013799664 bump version 2019-10-25 01:00:28 -04:00
John Sully f8220a658e Merge branch 'unstable' into RELEASE_5 2019-10-24 23:39:18 -04:00
John Sully f1d2b29450 Signals can happen on any thread, so look for the signal handler not the command on the callstack 2019-10-24 23:30:08 -04:00
John Sully cb93752aff Two fixes: 1) Remove race conditions by not locking clients when async writing. 2) Don't derefence dangling pointers in lambda 2019-10-24 23:07:02 -04:00
John Sully 549cad378d Sanitizers work with GCC too 2019-10-24 23:05:39 -04:00
John Sully 631f863dd8 Remove the DB lock, its unnecessary 2019-10-24 20:18:48 -04:00
John Sully 4396682c07 Remove unlocked KEYS command support, we will do this with snapshotting 2019-10-24 20:18:11 -04:00
John Sully ca4ee4e3e4 Build break, ensure C99 compatibility 2019-10-23 13:38:07 -04:00
John Sully 2da09e0732 Fix build break in TravisCI 2019-10-23 13:31:39 -04:00
John Sully 4986dc6da9 If a replica is about to be closed, don't wait on its lock (potential deadlock) 2019-10-23 13:20:23 -04:00
John Sully 1a70af2ae1 processEventsWhileBlocked needs to release the lock in a safe way 2019-10-23 13:19:57 -04:00
John Sully 5a8cb77d0d Remove race conditions 2019-10-22 23:26:37 -04:00
John Sully 600fc241cf Optimize deadlock detection, fix callstack for ASM, and annotate locks
Note: This change moves our assembly code to use the GNU Assembler because NASM seems to be incapable of emitting the necessary debug information for callstack unwinding to work.
2019-10-22 21:34:51 -04:00
John Sully fa797408d9 Implement deadlock detection 2019-10-22 00:43:32 -04:00
John Sully 3fac516950 Disable multithreaded KEYS due to bugs 2019-10-21 12:21:46 -04:00
John Sully 2f65aa2337 Merge branch 'unstable' into RELEASE_5 2019-10-16 12:47:06 -04:00
john@csquare.ca f5210a8fb0 Fix: ExpireMember does not update MVCC timestamp 2019-10-16 12:38:15 -04:00
John Sully 8f1295c00f expiremember should return the same results as expire 2019-10-16 12:27:04 -04:00
John Sully 18a3768e07 Fix crash adding expire to key with a subkey expire already set 2019-10-16 12:26:48 -04:00
eric-weaver 95e3dbc104 add missing dependency 2019-10-13 21:30:06 +02:00
Segmond 40355eac3e Update README.md
Typo, focuses spelled as focusses
2019-10-13 21:29:15 +02:00
John Sully 3a3b59a054 Implement the lastmodified query for the OBJECT command 2019-10-13 14:12:09 -04:00
John Sully 12e17cfd6e You are not allowed to set a subkey expire if the subkey does not exist 2019-10-13 14:11:43 -04:00
John Sully 203e341bf4 Implement the EXPIREMEMBERAT command 2019-10-13 13:15:13 -04:00
John Sully 6e6cd84ad7 Add millisecond support for EXPIREMEMBER command 2019-10-13 12:57:50 -04:00
John Sully 252725d50f Update more slave instances to use replica (Issue #75) 2019-10-13 12:29:20 -04:00
John Sully c15633ea9e Update a few uses of slave to use the new replica terminology (Issue #75) 2019-10-13 12:12:05 -04:00
John Sully 27c9ae667e Fix an intermittent crash when replicationCron happens before slavesdb is update 2019-10-13 12:04:54 -04:00
John Sully 16f96efbe7 Implement TTL and PERSIST commands for subkeys. Also ensure expiremember replaces any old subkey expiries 2019-10-13 12:03:25 -04:00
John Sully 5787e7adc7 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-10-13 10:03:01 -04:00
John Sully 4631119179 Fix issue #88 - don't let seperate KeyDB processes listen on the same port 2019-10-13 10:02:21 -04:00
John Sully 0a0c2146c8 Bump version 2019-10-01 17:53:48 -04:00
Edgard Lorraine Messias cedea7e400 Fixed "Provides" name in chkconfig info 2019-10-01 13:44:58 -04:00
John Sully 66cef6646c Merge branch 'unstable' into RELEASE_5 2019-09-30 00:28:12 -04:00
John Sully 64aa4b80e6 Expire DEL command place holder 2019-09-30 00:01:23 -04:00
John Sully 551a3cb1aa Fuzz mode is now an argument not based on the exe name 2019-09-30 00:00:29 -04:00
John Sully 0942188b0a finish up the RDB fuzz 2019-09-28 17:38:46 -04:00
John Sully 070c481871 Fix double free in RDB load 2019-09-28 17:38:26 -04:00
John Sully 6df4d29422 RDB fuzz test cases 2019-09-28 17:04:08 -04:00
John Sully 6e1e5bd08b RREPLAY command now takes a DB argument 2019-09-28 14:59:44 -04:00
John Sully ba365298ed Implement left and right shift BITOP operators 2019-09-28 00:10:46 -04:00
John Sully e1c9620951 Fix leaking stale RDBs during multimaster sync 2019-09-27 13:17:29 -04:00
John Sully e776474f68 Fix multi master bugs: 1. we fail to create the temp file. 2. We use a master RDB as our backup even though we merged databases (and therefore it is not representitive) 2019-09-26 20:35:51 -04:00
John Sully 4589e861ab Fix issue where AOF events are posted to the wrong event loop and not properly cleaned up 2019-09-19 15:40:09 -04:00
John Sully 55324aa56a Fix issue where AOF events are posted to the wrong event loop and not properly cleaned up 2019-09-19 15:39:52 -04:00
John Sully 18d42a5c35 KEYS now only blocks one database 2019-09-12 18:51:10 -04:00
John Sully 71d5a10621 bump version 2019-09-06 13:31:40 -04:00
John Sully ac595ebe37 Fix issue where Active Replicas were commiting data to the wrong database under load 2019-09-06 13:30:28 -04:00
John Sully 50a6a3ca38 Fix issue where Active Replicas were commiting data to the wrong database under load 2019-09-06 13:30:15 -04:00
John Sully f83a89f82a Acquire the lock for modules that don't acquire it before calling like they are supposed to 2019-08-29 15:41:03 -04:00
John Sully bf905a78f0 Bump version 2019-08-27 15:32:24 -04:00
John Sully fad9483fc9 Fix race condition in PUB/SUB and other async reply commands where the client can be freed before our handler is executed on the client thread. When this occurs the client pointer is dangling 2019-08-27 15:31:47 -04:00
John Sully 46a78c69e7 Fix race condition in PUB/SUB and other async reply commands where the client can be freed before our handler is executed on the client thread. When this occurs the client pointer is dangling 2019-08-26 20:18:52 -04:00
John Sully 33e0b3e1c0 Fix warnings on newer compilers 2019-08-14 01:03:24 -04:00
benschermel 4e9bfcf84b update readme (#71)
* update readme

* KeyDB must acknowledge its Redis origin and that while we have different opinions we are greatful to Antirez and Redis for the work they've done in this space.

* Update README.md
2019-08-06 19:25:13 -04:00
John Sully 75c6b4c64a Optimize the new expire code 2019-08-02 21:31:05 -04:00
John Sully 8536854266 Fix test failures: Non active replicas are allowed to use shared int values 2019-07-30 17:11:15 -04:00
John Sully 6016dd0f8b Acquire the lock for modules that don't acquire it before calling like they are supposed to 2019-07-30 16:54:25 -04:00
John Sully 47ef9e5cbd Fix HLL corruption 2019-07-29 18:08:45 -04:00
John Sully 4858fd893c Fix crash setting expire on a key with an existing subkey expiration 2019-07-29 17:09:51 -04:00
John Sully 6b6e6f6c1e Fix crash in RediSearch 2019-07-29 15:08:57 -04:00
John Sully cbe5c04a0f Fix crash in RediSearch 2019-07-29 15:08:41 -04:00
John Sully b0a0f03b96 RREPLAY failures should be logged 2019-07-24 22:49:55 -04:00
John Sully 08b6a04055 RREPLAY failures should be logged 2019-07-24 22:49:30 -04:00
John Sully f1982ca63d Issue #64 RREPLAY isn't binary safe. Add fix and test. 2019-07-24 22:31:44 -04:00
John Sully afe66288fe Issue #64 RREPLAY isn't binary safe. Add fix and test. 2019-07-24 22:31:02 -04:00
John Sully 2794cfced4 We can't set FExpire() on shared objects, issue #66 2019-07-23 23:39:47 -04:00
John Sully d6b45a56e7 Merge pull request #65 from JohnSully/subexpire
EXPIREMEMBER Command Implementation
2019-07-23 19:06:57 -04:00
John Sully a55d980436 Subexpire entries should load/save 2019-07-23 18:53:59 -04:00
John Sully 6037d1f326 Fix buggy rebase 2019-07-23 18:53:59 -04:00
John Sully 0b43b51a2e Fix merge conflict 2019-07-23 18:53:59 -04:00
John Sully 184abac694 Plumb support for sub expires to all expire related code 2019-07-23 18:53:59 -04:00
John Sully 0ba5b2c3d6 Fix crash with traditional expiration 2019-07-23 18:53:58 -04:00
John Sully 0b3d74ea67 Initial prototype of EXPIREMEMBER command 2019-07-23 18:53:58 -04:00
John Sully ea3bd614b8 New expire datastructure and algorithm. Allows us to expire in sublinear time 2019-07-23 18:49:31 -04:00
John Sully d45edc493d Merge pull request #50 from JohnSully/expire
New Expire Datastructure which is faster and more memory efficient.  This allows us to process expiries in sublinear time.
2019-07-23 18:40:48 -04:00
John Sully 271df3dad4 Support TTL stats with the new expire datastructure 2019-07-23 18:30:10 -04:00
John Sully 5a193872f8 Implement hash table stats and fixup the hash function based on the results 2019-07-23 18:30:10 -04:00
John Sully b5512d77a1 Add back missing file lost in rebase 2019-07-23 18:30:10 -04:00
John Sully 42bda8eaba Add back file erroniously deleted in rebase 2019-07-23 18:30:10 -04:00
John Sully 7e5d3f4f16 never make last minute changes before commiting 2019-07-23 18:30:10 -04:00
John Sully 5f3920e491 Fix a few potential assert crashes 2019-07-23 18:30:10 -04:00
John Sully 3880d2616c New expire datastructure and algorithm. Allows us to expire in sublinear time 2019-07-23 18:30:10 -04:00
John Sully 156e596f9c Any +x bit is acceptable 2019-07-19 15:26:17 -04:00
John Sully fc58516cca Any +x bit is acceptable 2019-07-19 01:42:05 -04:00
John Sully a4efcd35af Modules must have execute permissions to load 2019-07-19 01:31:10 -04:00
antirez 27fe1658a2 RDB: make sure to abort on LZF encoding error. 2019-07-19 01:03:16 -04:00
antirez 47feb2719c RDB: handle encoding errors with rdbExitReportCorruptRDB().
Without such change, the diskless replicas, when loading RDB files from
the socket will not abort when a broken RDB file gets loaded. This is
potentially unsafe, because right now Redis is not able to guarantee
that encoding errors are safe from the POV of memory corruptions (for
instance the LZF library may not be safe against untrusted data?) so
better to abort when the RDB file we are going to load is corrupted.

Instead I/O errors are still returned to the caller without aborting,
so that in case of short read the diskless replica can try again.
2019-07-19 01:02:49 -04:00
John Sully c21af6b351 Fix bad merge in SCAN KEYS command 2019-07-19 00:43:23 -04:00
John Sully 821c12c482 Merge commit '722446510faf0debf0d309708b2ed4fe4d939319' into unstable 2019-07-19 00:32:43 -04:00
John Sully 4602f8c391 Merge commit '677e95e2f5ee903682ce44a7bfd9558a22577926' into unstable 2019-07-19 00:01:56 -04:00
John Sully 27a927fe00 Fix compile errors from merges 2019-07-18 23:35:51 -04:00
Angus Pearson 3cdc6e8d84 Add char* typeNameCanonicalize(robj*) to remove duplicate code between SCAN and TYPE commands,
and to keep OBJ_* enum to string canonicalization in one place.
2019-07-18 23:31:31 -04:00
John Sully 89b52da387 Merge commit '0cabe0cfa7290d9b14596ec38e0d0a22df65d1df' into unstable 2019-07-18 23:28:56 -04:00
Madelyn Olson 50ad880ad5 Fixed some spelling issues in ACL codepath including user facing error 2019-07-18 23:28:36 -04:00
John Sully 15bed4bbcc Merge commit 'de035c94816722dd923e4aedd852869de79a5185' into unstable 2019-07-18 23:26:46 -04:00
John Sully 10986ae3a8 Merge commit 'bf963253ecfd367b49081a26c1b5c410558aecfc' into unstable 2019-07-18 23:22:36 -04:00
John Sully 2baa76b2ee Merge commit '7fababd44e8b8b2df53cad0906ec5ab7c678dd44' into unstable 2019-07-18 23:21:13 -04:00
John Sully ee460301fd Merge commit '074d24df1e82b5c794a5da9fb6cda5b77b60b27b' into unstable 2019-07-18 23:20:46 -04:00
John Sully 8ebe2fce3d Merge commit 'caf74e507e6535dab58ce6f3db19f8b594b5f7ca' into unstable 2019-07-18 23:18:42 -04:00
antirez 8198a697fd Test: fix slowlog test false positive.
In fast systems "SLOWLOG RESET" is fast enough to don't be logged even
when the time limit is "1" sometimes. Leading to false positives such
as:

[err]: SLOWLOG - can be disabled in tests/unit/slowlog.tcl
Expected '1' to be equal to '0'
2019-07-18 23:12:52 -04:00
antirez 35acae360a Make comment in getClientOutputBufferMemoryUsage() describing the present. 2019-07-18 23:12:39 -04:00
antirez 8aaa8b0b11 Fix test false positive introduced by threaded I/O.
Now clients that are ready to be terminated asynchronously are processed
more often in beforeSleep() instead of being processed in serverCron().
This means that the test will not be able to catch the moment the client
was terminated, also note that the 'omem' figure now changes in big
steps, because of the new client output buffers layout.

So we have to change the test range in order to accomodate for that.
Yet the test is useful enough to be worth taking, even if its precision
is reduced by this commit. Probably if we get more problems, a thing
that makes sense is just to check that the limit is < 200k. That's more
than enough actually.
2019-07-18 23:12:05 -04:00
John Sully 25e18a7de9 Release version 5 2019-07-18 20:50:40 -04:00
John Sully bb090b6d20 Active Replicas should always use their own slaveseldb variable when sending/saving rdbs - never those of their masters. This is because the Active Replica is also simultaneously a master 2019-07-18 20:50:20 -04:00
John Sully a9c4e3970f remove unnecessary variables 2019-07-18 19:37:49 -04:00
John Sully d5ecc2347a Fix issue #59 - Test replicaof config variable 2019-07-18 19:22:49 -04:00
John Sully 58971a430d Add support for sanitizers and fix issues they have found 2019-07-18 18:39:42 -04:00
John Sully 1512274f4c Resolve race on neterr variable 2019-07-18 17:11:28 -04:00
John Sully e310d33c12 Make object refcounts atomic, technically it doesn't need to be currently but the semantics are complicated and error prone. This is much safer with little performance impact 2019-07-18 15:49:12 -04:00
John Sully ad32ba0343 Suppress initialized data sanitizer warnings 2019-07-18 15:49:03 -04:00
John Sully 4e30a5b4e5 Another RESP3 regression 2019-07-17 22:57:52 -04:00
John Sully c8516f3dc4 Fix Issue #58 2019-07-17 02:34:02 -04:00
John Sully aae0fdc114 Shared objects should be marked as such 2019-07-16 18:32:01 -04:00
John Sully a19d0f67b9 Crash when aborting SYNC with a master on a thread other than main 2019-07-15 14:55:41 -04:00
John Sully 971f69fe1f Implement test mode to make finding bugs easier 2019-07-15 14:55:18 -04:00
John Sully 7468c691ad Blocked clients can stall when under low load 2019-07-13 16:44:11 -04:00
John Sully 620c2ec141 Give the active-rep more time to sync for test reliability 2019-07-12 23:52:07 -04:00
John Sully 3081b6f98b Fix more locking deadlocks 2019-07-12 23:51:45 -04:00
John Sully 8630339e43 Fix deadlock with client and ae locks 2019-07-12 20:46:50 -04:00
John Sully 528d10091f Add Active Replication tests 2019-07-12 03:54:41 -04:00
John Sully 149c3cf3dd FIX: The dabase count configuration is not respected 2019-07-12 02:13:37 -04:00
John Sully f12c3cf9dd Update README.md 2019-07-11 20:29:47 -04:00
John Sully 1f08a0efb3 Fix compile errors on GCC v5 2019-07-11 20:20:01 -04:00
John Sully 6cf85d1d01 Fix more accounting errors with active replication and the replication offset. Specifically we don't update repl_ack_off as frequently as we do reploff_skipped 2019-07-11 19:20:12 -04:00
John Sully b5101a460d Active Replicas are not slaves 2019-07-11 18:51:20 -04:00
John Sully a5784ef09e Fix active replication offset synchronization accounting, and enable the wait command 2019-07-11 17:00:23 -04:00
John Sully 122ec25bf0 lazyfree needs to consume more memory to be detectable 2019-07-06 00:53:40 -04:00
John Sully d013ad9eba Redis only does this in beforeSleep function - doing extra calls like we do causes test issues 2019-07-06 00:53:20 -04:00
John Sully d918ca6fa5 Add back user space buffering of RDB save 2019-07-06 00:36:23 -04:00
John Sully 852819180f We can use less memory in the client output buffers. Its OK 2019-07-05 23:43:01 -04:00
John Sully 218111eb72 Fix additional warning related to new() overloads 2019-07-05 23:42:39 -04:00
John Sully 1531cfb7ee Fix additional warnings 2019-06-27 16:29:36 -04:00
John Sully 16a89f21dc Fix mac build breaks 2019-06-27 15:04:09 -04:00
John Sully 79e5160e37 Fix libcxxabi clang compile failure in travis, as well as bool issue due to old clang 2019-06-18 00:42:01 -04:00
John Sully 510e966dc0 Bump travis compiler version 2019-06-18 00:42:01 -04:00
John Sully 8238d3207e Fix Travis CI issue 2019-06-17 23:56:23 -04:00
John Sully e37bc4ad40 Fix issues with relaxed memory model architectures 2019-06-17 23:00:12 -04:00
John Sully 0f78b8b917 Remove unnecessary recursive lock 2019-06-17 23:00:12 -04:00
John Sully 19061fe04f missing file :) 2019-06-17 23:00:12 -04:00
John Sully 9c901eb65f Fix test failures due to assert 2019-06-17 23:00:12 -04:00
John Sully ae33ff3a6e convert the pending write list to a vector for better performance and less cache thrashing 2019-06-17 23:00:12 -04:00
John Sully 59dbd625c1 Move more code out of the GIL 2019-06-17 23:00:12 -04:00
John Sully 8eb4e355b9 Remove an unnecessary lock that eats performance 2019-06-17 23:00:12 -04:00
John Sully 8b76b01bfe Even the next up thread should sleep in the futex 2019-06-17 23:00:12 -04:00
John Sully ec57b4b024 Fallback to a futex if we spin for a long time 2019-06-17 23:00:12 -04:00
John Sully 46d6caa47c Enable load balancing of UNIX sockets across threads 2019-06-11 01:34:36 -04:00
John Sully 97b65ce19c Fix crash adding duplicate replica. Just send an error instead 2019-06-02 15:50:50 -04:00
John Sully 55d0ef40b0 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-06-01 03:23:21 -04:00
John Sully a6c56416fc Implement MOTD feature in keydb-cli 2019-05-21 15:12:12 -04:00
John Sully cd3c482d5e Update README.md 2019-05-21 00:04:12 -04:00
John Sully c5cbb77fc7 Fix regressions from RESP3 changes in commit 317f8b9d38 2019-05-20 23:39:44 -04:00
John Sully d7f21f02b3 The unstable branch doesn't have a version # 2019-05-20 16:12:26 -04:00
John Sully 87dc8ce9b3 Fix double unlock 2019-05-20 15:52:04 -04:00
John Sully 2e22aa1a9c Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-05-20 10:57:59 -04:00
John Sully 8c56dbf971 Protocol regression from RESP3 work 2019-05-20 10:57:37 -04:00
Qix a78169e9e0 cast void data pointer to const char * to fix gcc 2019-05-19 16:24:39 -04:00
John Sully 39a60c8120 Fix build breaks on some older compilers 2019-05-18 20:58:48 -04:00
John Sully c57d8760bd Fix build break on some compilers 2019-05-18 20:41:05 -04:00
John Sully 3eed2a8780 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-05-18 20:25:23 -04:00
John Sully 23b0268a7f Print nicer error messages for uncaught exceptions 2019-05-18 20:24:29 -04:00
John Sully 3d0de946bb Fix: Active replication falls behind under high load 2019-05-18 20:23:20 -04:00
John Sully 866b8ead91 Update Active Replication wiki links 2019-05-11 21:53:30 -04:00
John Sully aa274960ff Fix a few issues from the merge 2019-05-11 19:26:59 -04:00
John Sully 54d6eb851b Make lazy free test more reliable 2019-05-11 17:57:35 -04:00
John Sully 86d7276f24 Merge branch 'unstable' of https://github.com/antirez/redis into MergeRedis
Note: some tests failing
2019-05-11 02:20:34 -04:00
John Sully 0918651438 Add byline to logo 2019-05-10 23:48:14 -04:00
John Sully 272d9297b6 Fix CentOS build failure 2019-05-09 19:54:34 -04:00
John Sully f5bfc71899 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-05-09 19:16:50 -04:00
John Sully 42e1ded55f build break fix 2019-05-09 19:16:31 -04:00
John Sully 6c410af5a8 Fix issue #11 2019-05-09 19:14:10 -04:00
John Sully 57ae676181 Fix typo 2019-05-09 19:06:58 -04:00
John Sully 7896ca6e52 Add missing file 2019-05-09 19:05:09 -04:00
John Sully c4a315dd5e Change debug messages to reference KeyDB 2019-05-09 19:03:50 -04:00
John Sully bf26959b72 Fix module locking issues 2019-05-09 19:00:27 -04:00
John Sully 37b2d046be refactor server global into a pointer (so that threadsafe commands can set this to NULL to prove they don't rely on it 2019-04-21 14:01:10 -04:00
John Sully fa2e407873 Factor out some normally const globals 2019-04-21 13:20:45 -04:00
John Sully c61cf57db5 additional fix to rreplay forward compat 2019-04-20 01:36:23 -04:00
John Sully ef3690f2db Make rreplay forward compatible with extra future args 2019-04-20 01:15:01 -04:00
John Sully 14d01ec7bd Tweak mvcc time format so rollovers are not an issue 2019-04-20 01:03:08 -04:00
John Sully 5dc9f70386 Timestamp writes to objects so we can be smarter about merging databases 2019-04-20 00:52:07 -04:00
John Sully 88e593bf96 Fix use uninitialized 2019-04-19 23:41:40 -04:00
John Sully efde2e6be6 Additional MVCC work and fix memory leak loading objects from rdb 2019-04-19 22:54:42 -04:00
John Sully 5a78a3bc46 Add version override command for users that need compatibility with Redis 2019-04-19 19:57:11 -04:00
John Sully b276d803d4 RREPLAY PERF: The UUID stack is unnecessary, RREPLAY itself can detect the cycle and call cancel() 2019-04-19 19:36:47 -04:00
John Sully da51ac430b Detect cycles in mesh networks with multi master 2019-04-19 19:31:11 -04:00
John Sully 01eb0a3c7f Fix crash near boot when adding replicas and dumping database 2019-04-19 17:08:54 -04:00
John Sully dc2b3cf4f8 Replication fake connection should inhereit the user and permission of the real connection 2019-04-18 22:07:35 -04:00
John Sully c4621a5ed2 Start of MVCC support (and more C++) 2019-04-16 23:16:03 -04:00
John Sully 1c953a4d5b Fix module linking and crashing issues 2019-04-16 13:34:22 -04:00
John Sully c64ce7aa9c Fix replica authentication failure when masterauth is below replicaof in the config file 2019-04-15 22:31:02 -04:00
John Sully acdc4fdfec Fix memory leak unsetting master 2019-04-11 19:55:44 -04:00
John Sully 7ef9c18b72 Fix compile errors when MALLOC=memkind 2019-04-11 19:40:45 -04:00
John Sully a69b4e79db Fix failure to respect masterauth issue #26 2019-04-11 19:08:12 -04:00
John Sully 740fc6c2b8 Fix addition RESP3 regressions (return empty set) 2019-04-08 16:52:57 -04:00
John Sully 42202c868d Fix protocol break with hgetall and family 2019-04-08 13:52:02 -04:00
John Sully 8c133b605c Move remaning files dependent on server.h over to C++ 2019-04-08 01:00:48 -04:00
John Sully b50acd7238 Move dict to C++ 2019-04-07 17:23:59 -04:00
John Sully 54db278695 Port db to C++ 2019-04-07 17:13:14 -04:00
John Sully 011948bcef Move a bunch of files to C++ 2019-04-07 16:54:56 -04:00
John Sully 9f95d8b38f Make t_string C++ 2019-04-07 15:24:23 -04:00
John Sully 3d394a6fa2 Fix clang compile error 2019-04-06 00:20:17 -04:00
John Sully 68d2b648e0 Add RREPLAY command and put the issue of packet storms to rest. Fixes issue #24 2019-04-06 00:14:27 -04:00
John Sully 283998404f Fix regression in active replication caused by multimaster PR 2019-04-04 16:50:40 -04:00
John Sully a7b4d0fea6 Merge pull request #23 from JohnSully/wip-multimaster
Wip multimaster
2019-04-04 11:40:58 -07:00
John Sully 59051dd59d All tests runs pass! YAYgit add src/cluster.c src/config.c ! 2019-04-04 01:02:19 -04:00
John Sully cd836a37e7 Fix some more failing tests 2019-04-04 00:25:30 -04:00
John Sully 4326d22380 Merge branch 'unstable' into wip-multimaster 2019-04-03 00:12:13 -04:00
John Sully 161d3a35ff Fix cluster test failure (not real issue) 2019-04-03 00:11:34 -04:00
John Sully 20a9d21dfb Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-04-03 00:09:51 -04:00
John Sully e902789aa7 Fix failing tests due to build issue inhereted from Redis 2019-04-03 00:09:26 -04:00
John Sully 3745bbd95b Merge branch 'unstable' of https://github.com/antirez/redis into unstable 2019-04-03 00:00:38 -04:00
John Sully e63b2880b0 Cluster tests shouldn't crash (note: still not passing either) 2019-04-02 22:32:10 -04:00
John Sully a9b70e1ef7 Multiple masters is no good if we keep dropping the database 2019-04-02 21:47:21 -04:00
John Sully e300f753c5 Tests are passing! YAY! 2019-04-02 21:36:04 -04:00
John Sully efaeca5887 It compiles and doesn't crash immediately! 2019-04-02 16:47:05 -04:00
John Sully 4d67305661 Link to GUI 2019-03-31 14:37:54 -04:00
John Sully 853bb6ca3e Commit missing file 2019-03-28 17:56:14 -04:00
John Sully b16f23ae8e Travis needs to install uuid-dev 2019-03-28 16:18:26 -04:00
John Sully 91e6368de0 Implement database merging for Active Replicas 2019-03-28 15:12:43 -04:00
John Sully e4451b9628 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-27 22:59:38 -04:00
John Sully 770bb8ef5f If no rdb file is specified and no s3 file is specified use the default RDB filename. If only S3 is specified use diskless sync 2019-03-27 22:59:12 -04:00
John Sully 87b958a210 Update README.md 2019-03-27 21:52:08 -04:00
John Sully 314ac90ba9 Update README.md 2019-03-27 15:39:25 -04:00
John Sully 9f33822083 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-26 20:39:56 -04:00
John Sully 10a4b35bc5 SIGALRM should happen on a worker thread to make our tests happy 2019-03-26 20:39:30 -04:00
John Sully 7b1dd0b60d Make PSYNC2 tests more reliable on slower hardware 2019-03-26 18:59:31 -04:00
John Sully 7a650741f7 Merge pull request #18 from DevopsDood/unstable
Update Readme for missing docker flag
2019-03-26 09:49:53 -04:00
Richard Silver 2ce5f1b944 Update Readme for missing docker flag 2019-03-25 15:55:23 -07:00
John Sully 063a14372d Give information on dependencies that need installation. 2019-03-25 16:22:10 -04:00
John Sully dd70e1b571 Add depenednecy on uuid-dev to dockerfile 2019-03-25 02:09:53 -04:00
John Sully 1840b893c2 Talk about active replica 2019-03-25 00:12:04 -04:00
John Sully 8bcde757ce We don't corretly terminate our varargs 2019-03-24 18:57:25 -04:00
John Sully 1dff223c71 OS X build fixes 2019-03-24 18:06:57 -04:00
John Sully a7aa2b0740 Active Replica Support 2019-03-24 15:39:10 -04:00
John Sully fb45fefbca Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-21 23:11:55 -04:00
John Sully 7b914c2531 Fix kqueue build error 2019-03-21 23:11:19 -04:00
John Sully 75d517a27f Merge pull request #16 from gitter-badger/gitter-badge
Add a Gitter chat badge to README.md
2019-03-21 21:57:25 -04:00
John Sully 4c98bc690e Update README.md 2019-03-21 21:26:00 -04:00
John Sully 550b3a3a99 Update README.md 2019-03-21 21:25:49 -04:00
The Gitter Badger ef7e89352d Add Gitter badge 2019-03-22 01:24:32 +00:00
John Sully 9322d604ee Merge branch 'unstable' of https://github.com/antirez/redis into unstable 2019-03-21 20:15:59 -04:00
John Sully 5d92110630 Merge pull request #15 from DevopsDood/unstable
Added docker builder for those that want it
2019-03-21 19:54:00 -04:00
Richard Silver 4056037cc2 Merge branch 'unstable' of github.com:JohnSully/KeyDB into unstable 2019-03-21 16:19:45 -07:00
Richard Silver 677ae5487f updated readme and Dockerfile to allow for tests to be run in container 2019-03-21 16:18:37 -07:00
John Sully 19956b3807 comment issue 2019-03-21 22:18:48 +00:00
John Sully ab9122f2cb Polarity of the weak flag was wrong. We want to use the strong variant of atomic_compare_exchange always 2019-03-21 22:17:04 +00:00
Richard Silver e62c6b0ed0 Added build Dockerfile 2019-03-21 15:15:11 -07:00
John Sully 27a420fbc2 Compile issues at O0 optimization 2019-03-21 21:57:18 +00:00
John Sully b775ebb382 ARM build fix: Don't use X64 asm here 2019-03-20 04:14:33 +00:00
John Sully ac80a5c6a6 Add debugging stats to the INFO command 2019-03-19 22:04:33 -04:00
John Sully c74100a552 Add release badge 2019-03-19 20:54:36 -04:00
John Sully 03379106d6 Add CI badge 2019-03-19 20:46:25 -04:00
John Sully 9ad229f663 Getting close! Maybe there was a better way to do this than checking in travis.yml files repeatedly but alas it works and doesn't affect people building locally 2019-03-19 20:40:17 -04:00
John Sully 0900edf776 Clang build with libc malloc 2019-03-19 20:34:09 -04:00
John Sully ea520027b9 more clang travis fixes 2019-03-19 20:26:35 -04:00
John Sully 04679b3b3b Fix race condition building dependencies with multithreaded builds 2019-03-19 20:25:30 -04:00
John Sully 2bf5c1324a Will clang build now with travis? 2019-03-19 20:00:52 -04:00
John Sully 3d93ca1bf6 clang build failure 2019-03-19 19:55:03 -04:00
John Sully c548431611 Travis clang dependencies 2019-03-19 19:50:28 -04:00
John Sully 0ab29f7394 Makefile ignores env CXXFLAGS 2019-03-19 19:29:14 -04:00
John Sully 30dab7ad14 No underscore 2019-03-19 19:22:27 -04:00
John Sully 0c5fa59221 Maybe this will make travis-ci stop using GCC headers when compiling with clang 2019-03-19 19:12:15 -04:00
John Sully 267e84f97d Feature gate SO_INCOMING_CPU so we compile on older kernels 2019-03-19 18:55:42 -04:00
John Sully 344cca75c6 typo 2019-03-19 18:40:50 -04:00
John Sully 0dd8e682f4 It would be nice if our CI actually called make... 2019-03-19 18:37:53 -04:00
John Sully da7e54819a Fix issues with travis config 2019-03-19 18:31:45 -04:00
John Sully 4e70215307 Let's try travis-ci 2019-03-19 18:27:54 -04:00
John 6aa162f6ff Fix linker errors on some compilers due to sdslen() 2019-03-19 22:08:20 +00:00
John Sully d380074569 KeyDB has different aims than the Redis project.
We believe software is for the user.  If a feature requires complicating the codebase
but simplifies our user's lives we will do it any time.  This should not be taken
as an outright rejection of the manifesto, as we agree on many points.
2019-03-19 01:36:03 -04:00
John Sully c406e7ff51 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-19 01:26:22 -04:00
John Sully 31ff6cffee Merge branch 'unstable' of https://github.com/antirez/redis into unstable 2019-03-19 01:26:10 -04:00
John Sully a9e525c81e Hack to prevent build errors on some machines due to missing throw() 2019-03-15 05:28:20 +00:00
John Sully 6157a5fc1b Merge /home/john/repos/redis_clean into unstable 2019-03-14 14:22:41 -04:00
John Sully be3cb1ad33 Merge branch 'unstable' of https://github.com/antirez/redis into unstable 2019-03-14 14:22:27 -04:00
John Sully 966f4a8144 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-13 18:08:59 -04:00
John Sully 261cf24efc Merge branch 'unstable' of https://github.com/antirez/redis into unstable
Lots of fixes and improvements from upstream.
2019-03-13 18:08:22 -04:00
JohnSully a3da10f4eb Update README.md 2019-03-13 16:57:40 -04:00
John Sully 6cb8063497 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-13 16:53:55 -04:00
John Sully a45f212693 Implement load database dumps from S3. We already save. 2019-03-13 16:53:37 -04:00
JohnSully 7c72cd5471 Merge pull request #9 from 0xflotus/patch-1
fixed guarantees
2019-03-13 12:22:29 -04:00
0xflotus 66f2032708 fixed guarantees 2019-03-13 15:14:34 +01:00
JohnSully 7546c7d8b4 Update README.md 2019-03-12 14:38:03 -04:00
JohnSully 703e4ad2fe formatting fixes 2019-03-12 00:59:28 -04:00
JohnSully 0b98280a1f Add charts to readme
Hotlink from medium, hope they don't mind.
2019-03-12 00:55:03 -04:00
John Sully 4609bed6a4 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into RELEASE_0_9 2019-03-11 20:54:14 -04:00
John Sully 99ccb11d89 Werror is good for me, but not for people compiling on other compilers 2019-03-11 20:53:57 -04:00
JohnSully 8a5a513662 Explain how multithreading works 2019-03-11 20:37:57 -04:00
JohnSully bf0fd22309 Update README.md 2019-03-11 19:38:20 -04:00
John Sully cc98d10fc6 Make storage.h C++ safe 2019-03-09 13:42:08 -05:00
John Sully a6a022faa2 sizeof is too big 2019-03-09 13:41:49 -05:00
John Sully a864ad1c9c bump version 2019-03-07 19:13:59 -05:00
John Sully 0bc586933f Merge branch 'unstable' into RELEASE_0_9 2019-03-07 19:13:33 -05:00
John Sully 2785a8b4d4 Module threading fixes 2019-03-07 19:13:01 -05:00
John Sully d5d5f6ae06 Merge branch 'unstable' into RELEASE_0_9 2019-03-06 16:39:15 -05:00
John Sully be3ba1d53e Limit server-threads to cores in the machine 2019-03-06 16:39:02 -05:00
John Sully 09e6a4fee0 port server.c to server.cpp 2019-03-06 16:29:30 -05:00
John Sully efc60dd8c5 Set version 2019-03-06 15:25:28 -05:00
John Sully a52cd974b9 Don't send replies to slaves after we've queued them to be closed 2019-03-06 15:21:05 -05:00
John Sully de4217489c defer free 2019-03-05 15:46:19 -05:00
John Sully 3c658b5012 Fix crash with paused clients (accessed when global lock is not acquired) 2019-03-03 22:24:12 -05:00
John Sully f6814aa825 Crash in Memory Doctor when all clients are slaves 2019-03-03 13:56:47 -05:00
John Sully 01a529cbda Fix issue #2, check posix return values 2019-03-02 20:43:03 -05:00
John Sully a1475af1e4 sds copies uninitialized data wasting time for everyone 2019-03-02 19:27:52 -05:00
John Sully 07594d4f95 Merge branch 'unstable' of https://github.com/antirez/redis into unstable
We want that awesome multithreaded benchmark
2019-03-02 18:07:18 -05:00
John Sully bad73faf28 write fastlock_unlock in ASM... because its faster 2019-03-02 16:47:27 -05:00
John Sully 8d3704d93b Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-03-01 16:40:20 -05:00
John Sully 8bd56fadd6 tighten up the spinlock loop, and some other bikeshedding 2019-03-01 13:29:21 -05:00
John Sully 23f9b584a8 remove unnecessary logs 2019-02-28 13:57:58 -05:00
JohnSully 141557963e Update README.md 2019-02-26 15:16:46 -05:00
John Sully ffabf3c5b7 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-02-26 15:14:50 -05:00
John Sully 9b1e95809c Thread affinity feature (default disabled) 2019-02-26 15:14:35 -05:00
JohnSully b8776bb001 Link to detailed benchmarking results and methodology. 2019-02-26 15:11:25 -05:00
JohnSully 84c20e8337 More fine tuning help. Hopefully we can automate this. 2019-02-26 03:30:37 -05:00
JohnSully bae2409cce Update benchmarking notes. 2019-02-26 02:30:03 -05:00
John Sully 8f7c44257b test code shouldn't be commited 2019-02-26 00:21:37 -05:00
John Sully 2772ce249c Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-02-26 00:20:11 -05:00
John Sully bcfd9327cb writes shouldn't be under the global lock 2019-02-26 00:19:38 -05:00
John Sully 01ff36fc28 Option to disable ASM spinlock 2019-02-26 00:00:04 -05:00
John Sully 6466b09fdc Fix build break 2019-02-26 01:10:07 +00:00
John Sully 40d7a701fe Rewrite our spinlock in assembly, pretty big performance improvement 2019-02-25 18:21:27 -05:00
JohnSully 78b9d303d3 Formatting (more) 2019-02-23 03:08:24 -05:00
John Sully d912013d1b Update copyright to include additional authorship 2019-02-23 02:27:19 -05:00
John Sully 898e6519d1 Merge branch 'unstable' of https://github.com/JohnSully/redis2 into unstable 2019-02-23 02:25:00 -05:00
John Sully 8c074a7d01 Merge branch 'Multithread' into unstable 2019-02-23 02:24:23 -05:00
JohnSully 6e69b4a795 More edits 2019-02-23 01:48:05 -05:00
JohnSully 1c36b46cb4 type 2019-02-23 01:33:27 -05:00
JohnSully 73abd04b95 Formatting 2019-02-23 01:32:50 -05:00
JohnSully 29d6845d1f Initial rewrite of Readme 2019-02-23 01:28:44 -05:00
John Sully da84b26785 Fastlock fixes 2019-02-10 22:00:19 -05:00
John Sully eb9070c833 move ae to C++ 2019-02-10 20:24:11 -05:00
John Sully b7b503d3ce Keep pool allocator up to date (even though we aren't enabling it) 2019-02-10 19:33:07 -05:00
John Sully 327bbec981 Prevent so many copies of sdslen getting added 2019-02-10 19:31:46 -05:00
John Sully 7175a8e4eb Performance enhancements! 2019-02-09 13:05:06 -05:00
John Sully 9aefc183c6 Reduce memory usage for in place strings by 8 bytes 2019-02-09 13:04:18 -05:00
John Sully 3e9b867709 complete rebranding with tests passing 2019-02-09 10:11:46 -05:00
John Sully e8b5bbf7a1 Fix bug where we try to load a database with no name 2019-02-09 07:56:45 -05:00
John Sully 79ef18e885 remove Redis branding 2019-02-08 17:56:32 -05:00
John Sully 23a91df9f6 Support AWS S3 saving via the s3 cli tools 2019-02-06 01:06:48 -05:00
John Sully d8741595ae Merge branch 'unstable' of https://github.com/antirez/redis into unstable 2019-02-06 00:09:39 -05:00
John Sully 3c9dd6ffc2 Make main headers C++ safe, and change rdb to use file descriptor instead of FILE pointer 2019-02-05 23:36:40 -05:00
John Sully 42d28c9ff6 complete malloc memory class work, and pass tests 2019-02-04 16:56:13 -05:00
John Sully 82372cbce8 Properly integrate memkind 2019-02-01 15:21:00 -05:00
John Sully 69b07c5cc2 Merge commit '09a263e6076b3fd0fe3b094a2bfad7f93fc997d6' as 'deps/memkind/src' 2019-02-01 14:45:39 -05:00
John Sully a6d27dc02c template config 2019-02-01 14:01:35 -05:00
John Sully bbcaf48cb0 Support configurable file backed scratch 2019-02-01 13:54:59 -05:00
John Sully 85194d99da crash fixes 2019-01-30 01:15:10 -05:00
John Sully 5c86d2faa2 Custom flash heap 2019-01-29 18:10:46 -05:00
214 changed files with 2504 additions and 23007 deletions

No files matched your search

+20 -22
View File
@@ -8,52 +8,41 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: make
run: |
sudo apt-get update
sudo apt-get -y remove libzstd || true
sudo apt-get -y install uuid-dev libcurl4-openssl-dev libbz2-dev zlib1g-dev libsnappy-dev liblz4-dev libzstd-dev libgflags-dev
make BUILD_TLS=yes -j2 KEYDB_CFLAGS='-Werror' KEYDB_CXXFLAGS='-Werror'
sudo apt-get -y install uuid-dev libcurl4-openssl-dev
make KEYDB_CFLAGS='-Werror' KEYDB_CXXFLAGS='-Werror' BUILD_TLS=yes -j2
- name: gen-cert
run: ./utils/gen-test-certs.sh
- name: test-tls
run: |
sudo apt-get -y install tcl tcl-tls
./runtest --clients 1 --verbose --tls --config server-threads 3
./runtest --clients 2 --verbose --tls
- name: cluster-test
run: |
./runtest-cluster --tls --config server-threads 3
./runtest-cluster --tls
- name: sentinel test
run: |
./runtest-sentinel
- name: module tests
run: |
./runtest-moduleapi
- name: rotation test
run: |
./runtest-rotation
build-ubuntu-old:
runs-on: ubuntu-20.04
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- uses: actions/checkout@v1
- name: make -j2
run: |
sudo apt-get update
sudo apt-get -y remove libzstd || true
sudo apt-get -y install uuid-dev libcurl4-openssl-dev libbz2-dev zlib1g-dev libsnappy-dev liblz4-dev libzstd-dev libgflags-dev
sudo apt-get -y install uuid-dev libcurl4-openssl-dev
make -j2
build-macos-latest:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: make
run: make KEYDB_CFLAGS='-Werror' KEYDB_CXXFLAGS='-Werror' -j2
@@ -61,11 +50,20 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: make
run: |
sudo apt-get update
sudo apt-get -y remove libzstd || true
sudo apt-get -y install uuid-dev libcurl4-openssl-dev libbz2-dev zlib1g-dev libsnappy-dev liblz4-dev libzstd-dev libgflags-dev
sudo apt-get -y install uuid-dev libcurl4-openssl-dev
make KEYDB_CFLAGS='-Werror' KEYDB_CXXFLAGS='-Werror' MALLOC=libc -j2
build-ubuntu-32bit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: make
run: |
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get -y install gcc-multilib g++-multilib libc6-dev-i386 lib32z1 uuid-dev:i386 libcurl4-openssl-dev:i386
make KEYDB_CFLAGS='-Werror' KEYDB_CXXFLAGS='-Werror' 32bit -j2
+22
View File
@@ -0,0 +1,22 @@
name: Endurance
on:
schedule:
- cron: '30 * * * *'
jobs:
test-endurance:
runs-on: octocore
timeout-minutes: 60
steps:
- uses: actions/checkout@v1
- name: make
run: |
sudo apt-get -y install uuid-dev libcurl4-openssl-dev
make -j8
- name: test-multithread (5X)
run: |
sudo apt-get install -y tcl tcl-tls
./runtest --loopn 5 --config server-threads 3 --clients 5 --endurance
+2 -1
View File
@@ -15,6 +15,7 @@ src/keydb-server
**/app/keydb-server
*.deb
*.rpm
keydb-pro-server
src/keydb-cli
**/bin/keydb-cli
**/app/keydb-cli
@@ -48,7 +49,7 @@ src/nodes.conf
deps/lua/src/lua
deps/lua/src/luac
deps/lua/src/liblua.a
tests/tls*/*
tests/tls/*
.make-*
.prerequisites
*.dSYM
-3
View File
@@ -1,6 +1,3 @@
[submodule "deps/rocksdb"]
path = deps/rocksdb
url = https://github.com/facebook/rocksdb.git
[submodule "deps/depot_tools"]
path = deps/depot_tools
url = https://chromium.googlesource.com/chromium/tools/depot_tools.git
-1
View File
@@ -1,7 +1,6 @@
Copyright (c) 2006-2020, Salvatore Sanfilippo
Copyright (C) 2019-2021, John Sully
Copyright (C) 2020-2021, EQ Alpha Technology Ltd.
Copyright (C) 2022 Snap Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+1 -1
View File
@@ -1,4 +1,4 @@
# Top level makefile, this just calls into src/Makefile where the real work is done. Changes should be made there.
# Top level makefile, the real shit is at src/Makefile
default: all
+47 -68
View File
@@ -2,20 +2,16 @@
![CI](https://github.com/JohnSully/KeyDB/workflows/CI/badge.svg?branch=unstable)
[![StackShare](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](https://stackshare.io/eq-alpha-technology-inc/eq-alpha-technology-inc)
##### KeyDB is now a part of Snap Inc! Check out the announcement [here](https://docs.keydb.dev/news/2022/05/12/keydb-joins-snap)
##### [Release v6.3.0](https://github.com/EQ-Alpha/KeyDB/releases/tag/v6.3.0) is here with major improvements as we consolidate our Open Source and Enterprise offerings into a single BSD-3 licensed project. See our [roadmap](https://docs.keydb.dev/docs/coming-soon) for details.
##### Want to extend KeyDB with Javascript? Try [ModJS](https://github.com/JohnSully/ModJS)
##### Need Help? Check out our extensive [documentation](https://docs.keydb.dev).
##### KeyDB is on Slack. Click [here](https://docs.keydb.dev/slack/) to learn more and join the KeyDB Community Slack workspace.
##### NEW!!! KeyDB now has a Slack Community Workspace. Click [here](https://docs.keydb.dev/slack/) to learn more and join the KeyDB Community Slack workspace.
What is KeyDB?
--------------
KeyDB is a high performance fork of Redis with a focus on multithreading, memory efficiency, and high throughput. In addition to performance improvements, KeyDB offers features such as Active Replication, FLASH Storage and Subkey Expires. KeyDB has a MVCC architecture that allows you to execute queries such as KEYS and SCAN without blocking the database and degrading performance.
KeyDB is a high performance fork of Redis with a focus on multithreading, memory efficiency, and high throughput. In addition to multithreading, KeyDB also has features only available in Redis Enterprise such as [Active Replication](https://github.com/JohnSully/KeyDB/wiki/Active-Replication), [FLASH storage](https://github.com/JohnSully/KeyDB/wiki/FLASH-Storage) support, and some not available at all such as direct backup to AWS S3.
KeyDB maintains full compatibility with the Redis protocol, modules, and scripts. This includes the atomicity guarantees for scripts and transactions. Because KeyDB keeps in sync with Redis development KeyDB is a superset of Redis functionality, making KeyDB a drop in replacement for existing Redis deployments.
@@ -34,81 +30,48 @@ KeyDB has a different philosophy on how the codebase should evolve. We feel tha
Because of this difference of opinion features which are right for KeyDB may not be appropriate for Redis. A fork allows us to explore this new development path and implement features which may never be a part of Redis. KeyDB keeps in sync with upstream Redis changes, and where applicable we upstream bug fixes and changes. It is our hope that the two projects can continue to grow and learn from each other.
Project Support
-------------------
The KeyDB team maintains this project as part of Snap Inc. KeyDB is used by Snap as part of its caching infrastructure and is fully open sourced. There is no separate commercial product and no paid support options available. We really value collaborating with the open source community and welcome PRs, bug reports, and open discussion. For community support or to get involved further with the project check out our community support options [here](https://docs.keydb.dev/docs/support) (slack, forum, meetup, github issues). Our team monitors these channels regularly.
Additional Resources
--------------------
Try the KeyDB [Docker Image](https://hub.docker.com/r/eqalpha/keydb)
Check out KeyDB's [Docker Image](https://hub.docker.com/r/eqalpha/keydb)
Join us on [Slack](https://docs.keydb.dev/slack/)
Learn more using KeyDB's extensive [documentation](https://docs.keydb.dev)
Post to the [Community Forum](https://community.keydb.dev)
Post to our [Community Forum](https://community.keydb.dev)
See the [KeyDB Roadmap](https://docs.keydb.dev/docs/coming-soon) to see what's in store
Learn more through KeyDB's [Documentation & Learning Center](https://docs.keydb.dev)
Benchmarking KeyDB
------------------
Please note keydb-benchmark and redis-benchmark are currently single threaded and too slow to properly benchmark KeyDB. We recommend using a redis cluster benchmark tool such as [memtier](https://github.com/RedisLabs/memtier_benchmark). Please ensure your machine has enough cores for both KeyDB and memtier if testing locally. KeyDB expects exclusive use of any cores assigned to it.
Please note keydb-benchmark and redis-benchmark are currently single threaded and too slow to properly benchmark KeyDB. We recommend using a redis cluster benchmark tool such as [memtier](https://github.com/RedisLabs/memtier_benchmark). Please ensure your machine has enough cores for both KeyDB and memteir if testing locally. KeyDB expects exclusive use of any cores assigned to it.
For more details on how we benchmarked KeyDB along with performance numbers check out our blog post: [Redis Should Be Multithreaded](https://medium.com/@john_63123/redis-should-be-multi-threaded-e28319cab744?source=friends_link&sk=7ce8e9fe3ec8224a4d27ef075d085457)
New Configuration Options
-------------------------
With new features comes new options. All other configuration options behave as you'd expect. Your existing configuration files should continue to work unchanged.
With new features comes new options:
```
server-threads N
server-thread-affinity [true/false]
```
The number of threads used to serve requests. This should be related to the number of queues available in your network hardware, *not* the number of cores on your
machine. Because KeyDB uses spinlocks to reduce latency; making this too high will reduce performance. We recommend using 4 here. By default this is set to two.
```
min-clients-per-thread 50
```
The minimum number of clients on a thread before KeyDB assigns new connections to a different thread. Tuning this parameter is a tradeoff between locking overhead and distributing the workload over multiple cores
The number of threads used to serve requests. This should be related to the number of queues available in your network hardware, *not* the number of cores on your machine. Because KeyDB uses spinlocks to reduce latency; making this too high will reduce performance. We recommend using 4 here. By default this is set to one.
```
replica-weighting-factor 2
```
KeyDB will attempt to balance clients across threads evenly; However, replica clients are usually much more expensive than a normal client, and so KeyDB will try to assign fewer clients to threads with a replica. The weighting factor below is intented to help tune this behavior. A replica weighting factor of 2 means we treat a replica as the equivalent of two normal clients. Adjusting this value may improve performance when replication is used. The best weighting is workload specific - e.g. read heavy workloads should set this to 1. Very write heavy workloads may benefit from higher numbers.
scratch-file-path /path
```
active-client-balancing yes
```
Should KeyDB make active attempts at balancing clients across threads? This can impact performance accepting new clients. By default this is enabled. If disabled there is still a best effort from the kernel to distribute across threads with SO_REUSEPORT but it will not be as fair. By default this is enabled
```
active-replica yes
```
If you are using active-active replication set `active-replica` option to “yes”. This will enable both instances to accept reads and writes while remaining synced. [Click here](https://docs.keydb.dev/docs/active-rep/) to see more on active-rep in our docs section. There are also [docker examples]( https://docs.keydb.dev/docs/docker-active-rep/) on docs.
```
multi-master-no-forward no
```
Avoid forwarding RREPLAY messages to other masters? WARNING: This setting is dangerous! You must be certain all masters are connected to eachother in a true mesh topology or data loss will occur! This command can be used to reduce multimaster bus traffic
```
If you would like to use the [FLASH backed](https://github.com/JohnSully/KeyDB/wiki/FLASH-Storage) storage this option configures the directory for KeyDB's temporary files. This feature relies on snapshotting to work so must be used on a BTRFS filesystem. ZFS may also work but is untested. With this feature KeyDB will use RAM as a cache and page to disk as necessary. NOTE: This requires special compilation options, see Building KeyDB below.
db-s3-object /path/to/bucket
```
If you would like KeyDB to dump and load directly to AWS S3 this option specifies the bucket. Using this option with the traditional RDB options will result in KeyDB backing up twice to both locations. If both are specified KeyDB will first attempt to load from the local dump file and if that fails load from S3. This requires the AWS CLI tools to be installed and configured which are used under the hood to transfer the data.
active-replica yes
```
storage-provider flash /path/to/flash
```
If you would like to use KeyDB FLASH storage, specify the storage medium followed by the directory path on your local SSD volume. Note that this feature is still considered experimental and should be used with discretion. See [FLASH Documentation](https://docs.keydb.dev/docs/flash) for more details on configuration and setting up your FLASH volume.
If you are using active-active replication set `active-replica` option to “yes”. This will enable both instances to accept reads and writes while remaining synced. [Click here](https://docs.keydb.dev/docs/active-rep/) to see more on active-rep in our docs section. There are also [docker examples]( https://docs.keydb.dev/docs/docker-active-rep/) on docs.
All other configuration options behave as you'd expect. Your existing configuration files should continue to work unchanged.
Building KeyDB
--------------
@@ -117,18 +80,19 @@ KeyDB can be compiled and is tested for use on Linux. KeyDB currently relies on
More on CentOS/Archlinux/Alpine/Debian/Ubuntu dependencies and builds can be found here: https://docs.keydb.dev/docs/build/
Init and clone submodule dependencies:
% git submodule init && git submodule update
Install dependencies:
% sudo apt install build-essential nasm autotools-dev autoconf libjemalloc-dev tcl tcl-dev uuid-dev libcurl4-openssl-dev libbz2-dev libzstd-dev liblz4-dev libsnappy-dev libssl-dev
% sudo apt install build-essential nasm autotools-dev autoconf libjemalloc-dev tcl tcl-dev uuid-dev libcurl4-openssl-dev
Compiling is as simple as:
% make
To build with TLS support, you'll need OpenSSL development libraries (e.g.
libssl-dev on Debian/Ubuntu) and run:
% make BUILD_TLS=yes
To build with systemd support, you'll need systemd development libraries (such
as libsystemd-dev on Debian/Ubuntu or systemd-devel on CentOS) and run:
@@ -141,21 +105,18 @@ To append a suffix to KeyDB program names, use:
***Note that the following dependencies may be needed:
% sudo apt-get install autoconf autotools-dev libnuma-dev libtool
KeyDB by default is built with TLS enabled. To build without TLS support, use:
% make BUILD_TLS=no
Running the tests with TLS enabled (you will need `tcl-tls`
If TLS is built, running the tests with TLS enabled (you will need `tcl-tls`
installed):
% ./utils/gen-test-certs.sh
% ./runtest --tls
To build with KeyDB FLASH support, use:
% make ENABLE_FLASH=yes
If TLS is built, running the tests with TLS enabled (you will need `tcl-tls`
installed):
***Note that the KeyDB FLASH feature is considered experimental (beta) and should used with discretion
% ./utils/gen-test-certs.sh
% ./runtest --tls
Fixing build problems with dependencies or cached build options
@@ -253,11 +214,11 @@ All the options in keydb.conf are also supported as options using the command
line, with exactly the same name.
Running KeyDB with TLS:
Running Redis with TLS:
------------------
Please consult the [TLS.md](TLS.md) file for more information on
how to use KeyDB with TLS.
how to use Redis with TLS.
Playing with KeyDB
@@ -317,6 +278,24 @@ KeyDB works by running the normal Redis event loop on multiple threads. Network
Unlike most databases the core data structure is the fastest part of the system. Most of the query time comes from parsing the REPL protocol and copying data to/from the network.
Future work:
- Allow rebalancing of connections to different threads after the connection
- Allow multiple readers access to the hashtable concurrently
Docker Build
------------
Build the latest binaries from the github unstable branch within a docker container. Note this is built for Ubuntu 18.04.
Simply make a directory you would like to have the latest binaries dumped in, then run the following commmand with your updated path:
```
$ docker run -it --rm -v /path-to-dump-binaries:/keydb_bin eqalpha/keydb-build-bin
```
You should receive the following files: keydb-benchmark, keydb-check-aof, keydb-check-rdb, keydb-cli, keydb-sentinel, keydb-server
If you are looking to enable flash support with the build (make MALLOC=memkind) then use the following command:
```
$ docker run -it --rm -v /path-to-dump-binaries:/keydb_bin eqalpha/keydb-build-bin:flash
```
Please note that you will need libcurl4-openssl-dev in order to run keydb. With flash version you may need libnuma-dev and libtool installed in order to run the binaries. Keep this in mind especially when running in a container. For a copy of all our Dockerfiles, please see them on [docs]( https://docs.keydb.dev/docs/dockerfiles/).
Code contributions
-----------------
+4 -1
View File
@@ -6,7 +6,10 @@ Getting Started
### Building
TLS support is enabled in the default build. To build without TLS, run `make BUILD_TLS=no`.
To build with TLS support you'll need OpenSSL development libraries (e.g.
libssl-dev on Debian/Ubuntu).
Run `make BUILD_TLS=yes`.
### Tests
-70
View File
@@ -1,70 +0,0 @@
# Doc: https://wiki.sc-corp.net/pages/viewpage.action?pageId=121500284
version: 1
machamp:
keydb-build:
# Optional - build counter is linked to the build def
tag_template: "0.0.%build.counter%-%sha%"
# Optional - value in seconds before a build is terminated, default is 3600 seconds
timeout: 3600
# Optional - update ghe or not, default to true
update_ghe: true
code_coverage: false
# Required
steps:
make-build:
type: cmd
# https://github.sc-corp.net/Snapchat/img/tree/master/keydb/ubuntu-20-04
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/keydb/keydb-ubuntu-20-04@sha256:cf869a3f5d1de1e1d976bb906689c37b7031938eb68661b844a38c532f27248c
command: ./machamp_scripts/build.sh
tls-test:
type: cmd
parent: make-build
# https://github.sc-corp.net/Snapchat/img/tree/master/keydb/ubuntu-20-04
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/keydb/keydb-ubuntu-20-04@sha256:cf869a3f5d1de1e1d976bb906689c37b7031938eb68661b844a38c532f27248c
command: ./runtest --clients 4 --verbose
cluster-test:
type: cmd
parent: make-build
# https://github.sc-corp.net/Snapchat/img/tree/master/keydb/ubuntu-20-04
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/keydb/keydb-ubuntu-20-04@sha256:cf869a3f5d1de1e1d976bb906689c37b7031938eb68661b844a38c532f27248c
command: ./runtest-cluster
sentinel-test:
type: cmd
parent: make-build
# https://github.sc-corp.net/Snapchat/img/tree/master/keydb/ubuntu-20-04
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/keydb/keydb-ubuntu-20-04@sha256:cf869a3f5d1de1e1d976bb906689c37b7031938eb68661b844a38c532f27248c
command: ./runtest-sentinel
module-test:
type: cmd
parent: make-build
# https://github.sc-corp.net/Snapchat/img/tree/master/keydb/ubuntu-20-04
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/keydb/keydb-ubuntu-20-04@sha256:cf869a3f5d1de1e1d976bb906689c37b7031938eb68661b844a38c532f27248c
command: ./runtest-moduleapi
rotation-test:
type: cmd
parent: make-build
# https://github.sc-corp.net/Snapchat/img/tree/master/keydb/ubuntu-20-04
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/keydb/keydb-ubuntu-20-04@sha256:cf869a3f5d1de1e1d976bb906689c37b7031938eb68661b844a38c532f27248c
command: ./runtest-rotation
keydb-docker-build:
# Optional - build counter is linked to the build def
tag_template: "%sha%"
# Optional - value in seconds before a build is terminated, default is 3600 seconds
timeout: 3600
# Optional - update ghe or not, default to true
update_ghe: true
code_coverage: false
# Required
steps:
# to ensure a clearer docker build env
code-checkout:
type: cmd
command: echo checkout
# default machamp builder image does not work for multi arch
builder_image: us.gcr.io/snapchat-build-artifacts/prod/snapchat/img/ubuntu/ubuntu-23-04@sha256:bd43177a80e6ce1c3583e8ea959b88a9081c0f56b765ec9c5a157c27a637c23b
docker:
parent: code-checkout
type: docker # published images can be found in https://console.cloud.google.com/gcr/images/machamp-prod/global/keydb
dockerfile: machamp_scripts/Dockerfile
image_name: keydb # git commit sha will be deafult tag in the final image
workspace_context: ./ # This is the workspace context that your Dockerfile will use to move files around. <Root of checkout repository>/<Workspace Context>/<Dockerfile> If the workspace context is just the root of the repository, you can just use "./".
-35
View File
@@ -1,35 +0,0 @@
# Doc: https://wiki.sc-corp.net/display/TOOL/ci.yaml+User+Guide
version: 1
on:
# https://wiki.sc-corp.net/display/TOOL/Onboard+Machamp+Build+By+ci.yaml+Configuration
# on pull_request is used for any pr build
pull_request:
- branches: ['!!main', '*'] # this branch pattern means any branch but not main branch will trigger this pr build
workflows:
# All builds that use machamp should use the defined `backend_workflow`
- workflow_type: backend_workflow
# references a build defined in build.yaml
build_name: keydb-build
arch_types: ["amd64", "arm64"]
- workflow_type: backend_workflow
# references a build defined in build.yaml
build_name: keydb-docker-build
arch_types: ["amd64", "arm64"]
# on push is used for release branch, meaning: trigger this build when there is commit pushed to this branch
push:
- branches: [main]
workflows:
- workflow_type: backend_workflow
build_name: keydb-build
arch_types: ["amd64", "arm64"]
- workflow_type: backend_workflow
# references a build defined in build.yaml
build_name: keydb-docker-build
arch_types: ["amd64", "arm64"]
# below defines which branch is release branch / release tag
machamp:
releases:
# Note: machamp will only respect the ci.yaml file from default branch for "release branch" definition (most repositories using master/main as default branch)
# https://wiki.sc-corp.net/display/TOOL/Onboard+Machamp+Build+By+ci.yaml+Configuration
- branch_name: ^main$
+1 -13
View File
@@ -1,7 +1,6 @@
# Redis dependency Makefile
uname_S:= $(shell sh -c 'uname -s 2>/dev/null || echo not')
uname_M := $(shell sh -c 'uname -m 2>/dev/null || echo not')
CCCOLOR="\033[34m"
LINKCOLOR="\033[34;1m"
@@ -38,7 +37,6 @@ distclean:
-(cd linenoise && $(MAKE) clean) > /dev/null || true
-(cd lua && $(MAKE) clean) > /dev/null || true
-(cd jemalloc && [ -f Makefile ] && $(MAKE) distclean) > /dev/null || true
-(cd rocksdb && $(MAKE) clean) > /dev/null || true
-(cd hdr_histogram && $(MAKE) clean) > /dev/null || true
-(rm -f .make-*)
@@ -95,17 +93,7 @@ JEMALLOC_LDFLAGS= $(LDFLAGS)
jemalloc: .make-prerequisites
@printf '%b %b\n' $(MAKECOLOR)MAKE$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR)
cd jemalloc && ./configure --with-version=5.2.1-0-g0 --with-lg-quantum=3 --disable-cxx CFLAGS="$(JEMALLOC_CFLAGS)" LDFLAGS="$(JEMALLOC_LDFLAGS)"
cd jemalloc && ./configure --with-version=5.2.1-0-g0 --with-lg-quantum=3 --with-jemalloc-prefix=je_ CFLAGS="$(JEMALLOC_CFLAGS)" LDFLAGS="$(JEMALLOC_LDFLAGS)"
cd jemalloc && $(MAKE) CFLAGS="$(JEMALLOC_CFLAGS)" LDFLAGS="$(JEMALLOC_LDFLAGS)" lib/libjemalloc.a
.PHONY: jemalloc
rocksdb: .make-prerequisites
@printf '%b %b\n' $(MAKECOLOR)MAKE$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR)
ifeq ($(uname_M),x86_64)
cd rocksdb && CFLAGS=-Wno-error PORTABLE=1 USE_SSE=1 FORCE_SSE42=1 $(MAKE) static_lib
else
cd rocksdb && PORTABLE=1 $(MAKE) static_lib
endif
.PHONY: rocksdb
-583
View File
@@ -1,583 +0,0 @@
// Provides an efficient blocking version of moodycamel::ConcurrentQueue.
// ©2015-2020 Cameron Desrochers. Distributed under the terms of the simplified
// BSD license, available at the top of concurrentqueue.h.
// Also dual-licensed under the Boost Software License (see LICENSE.md)
// Uses Jeff Preshing's semaphore implementation (under the terms of its
// separate zlib license, see lightweightsemaphore.h).
#pragma once
#include "concurrentqueue.h"
#include "lightweightsemaphore.h"
#include <type_traits>
#include <cerrno>
#include <memory>
#include <chrono>
#include <ctime>
namespace moodycamel
{
// This is a blocking version of the queue. It has an almost identical interface to
// the normal non-blocking version, with the addition of various wait_dequeue() methods
// and the removal of producer-specific dequeue methods.
template<typename T, typename Traits = ConcurrentQueueDefaultTraits>
class BlockingConcurrentQueue
{
private:
typedef ::moodycamel::ConcurrentQueue<T, Traits> ConcurrentQueue;
typedef ::moodycamel::LightweightSemaphore LightweightSemaphore;
public:
typedef typename ConcurrentQueue::producer_token_t producer_token_t;
typedef typename ConcurrentQueue::consumer_token_t consumer_token_t;
typedef typename ConcurrentQueue::index_t index_t;
typedef typename ConcurrentQueue::size_t size_t;
typedef typename std::make_signed<size_t>::type ssize_t;
static const size_t BLOCK_SIZE = ConcurrentQueue::BLOCK_SIZE;
static const size_t EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD = ConcurrentQueue::EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD;
static const size_t EXPLICIT_INITIAL_INDEX_SIZE = ConcurrentQueue::EXPLICIT_INITIAL_INDEX_SIZE;
static const size_t IMPLICIT_INITIAL_INDEX_SIZE = ConcurrentQueue::IMPLICIT_INITIAL_INDEX_SIZE;
static const size_t INITIAL_IMPLICIT_PRODUCER_HASH_SIZE = ConcurrentQueue::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE;
static const std::uint32_t EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE = ConcurrentQueue::EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE;
static const size_t MAX_SUBQUEUE_SIZE = ConcurrentQueue::MAX_SUBQUEUE_SIZE;
public:
// Creates a queue with at least `capacity` element slots; note that the
// actual number of elements that can be inserted without additional memory
// allocation depends on the number of producers and the block size (e.g. if
// the block size is equal to `capacity`, only a single block will be allocated
// up-front, which means only a single producer will be able to enqueue elements
// without an extra allocation -- blocks aren't shared between producers).
// This method is not thread safe -- it is up to the user to ensure that the
// queue is fully constructed before it starts being used by other threads (this
// includes making the memory effects of construction visible, possibly with a
// memory barrier).
explicit BlockingConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE)
: inner(capacity), sema(create<LightweightSemaphore, ssize_t, int>(0, (int)Traits::MAX_SEMA_SPINS), &BlockingConcurrentQueue::template destroy<LightweightSemaphore>)
{
assert(reinterpret_cast<ConcurrentQueue*>((BlockingConcurrentQueue*)1) == &((BlockingConcurrentQueue*)1)->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member");
if (!sema) {
MOODYCAMEL_THROW(std::bad_alloc());
}
}
BlockingConcurrentQueue(size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers)
: inner(minCapacity, maxExplicitProducers, maxImplicitProducers), sema(create<LightweightSemaphore, ssize_t, int>(0, (int)Traits::MAX_SEMA_SPINS), &BlockingConcurrentQueue::template destroy<LightweightSemaphore>)
{
assert(reinterpret_cast<ConcurrentQueue*>((BlockingConcurrentQueue*)1) == &((BlockingConcurrentQueue*)1)->inner && "BlockingConcurrentQueue must have ConcurrentQueue as its first member");
if (!sema) {
MOODYCAMEL_THROW(std::bad_alloc());
}
}
// Disable copying and copy assignment
BlockingConcurrentQueue(BlockingConcurrentQueue const&) MOODYCAMEL_DELETE_FUNCTION;
BlockingConcurrentQueue& operator=(BlockingConcurrentQueue const&) MOODYCAMEL_DELETE_FUNCTION;
// Moving is supported, but note that it is *not* a thread-safe operation.
// Nobody can use the queue while it's being moved, and the memory effects
// of that move must be propagated to other threads before they can use it.
// Note: When a queue is moved, its tokens are still valid but can only be
// used with the destination queue (i.e. semantically they are moved along
// with the queue itself).
BlockingConcurrentQueue(BlockingConcurrentQueue&& other) MOODYCAMEL_NOEXCEPT
: inner(std::move(other.inner)), sema(std::move(other.sema))
{ }
inline BlockingConcurrentQueue& operator=(BlockingConcurrentQueue&& other) MOODYCAMEL_NOEXCEPT
{
return swap_internal(other);
}
// Swaps this queue's state with the other's. Not thread-safe.
// Swapping two queues does not invalidate their tokens, however
// the tokens that were created for one queue must be used with
// only the swapped queue (i.e. the tokens are tied to the
// queue's movable state, not the object itself).
inline void swap(BlockingConcurrentQueue& other) MOODYCAMEL_NOEXCEPT
{
swap_internal(other);
}
private:
BlockingConcurrentQueue& swap_internal(BlockingConcurrentQueue& other)
{
if (this == &other) {
return *this;
}
inner.swap(other.inner);
sema.swap(other.sema);
return *this;
}
public:
// Enqueues a single item (by copying it).
// Allocates memory if required. Only fails if memory allocation fails (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
// or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(T const& item)
{
if ((details::likely)(inner.enqueue(item))) {
sema->signal();
return true;
}
return false;
}
// Enqueues a single item (by moving it, if possible).
// Allocates memory if required. Only fails if memory allocation fails (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
// or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(T&& item)
{
if ((details::likely)(inner.enqueue(std::move(item)))) {
sema->signal();
return true;
}
return false;
}
// Enqueues a single item (by copying it) using an explicit producer token.
// Allocates memory if required. Only fails if memory allocation fails (or
// Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(producer_token_t const& token, T const& item)
{
if ((details::likely)(inner.enqueue(token, item))) {
sema->signal();
return true;
}
return false;
}
// Enqueues a single item (by moving it, if possible) using an explicit producer token.
// Allocates memory if required. Only fails if memory allocation fails (or
// Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(producer_token_t const& token, T&& item)
{
if ((details::likely)(inner.enqueue(token, std::move(item)))) {
sema->signal();
return true;
}
return false;
}
// Enqueues several items.
// Allocates memory if required. Only fails if memory allocation fails (or
// implicit production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
// is 0, or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Note: Use std::make_move_iterator if the elements should be moved instead of copied.
// Thread-safe.
template<typename It>
inline bool enqueue_bulk(It itemFirst, size_t count)
{
if ((details::likely)(inner.enqueue_bulk(std::forward<It>(itemFirst), count))) {
sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
return true;
}
return false;
}
// Enqueues several items using an explicit producer token.
// Allocates memory if required. Only fails if memory allocation fails
// (or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Note: Use std::make_move_iterator if the elements should be moved
// instead of copied.
// Thread-safe.
template<typename It>
inline bool enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{
if ((details::likely)(inner.enqueue_bulk(token, std::forward<It>(itemFirst), count))) {
sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
return true;
}
return false;
}
// Enqueues a single item (by copying it).
// Does not allocate memory. Fails if not enough room to enqueue (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
// is 0).
// Thread-safe.
inline bool try_enqueue(T const& item)
{
if (inner.try_enqueue(item)) {
sema->signal();
return true;
}
return false;
}
// Enqueues a single item (by moving it, if possible).
// Does not allocate memory (except for one-time implicit producer).
// Fails if not enough room to enqueue (or implicit production is
// disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
// Thread-safe.
inline bool try_enqueue(T&& item)
{
if (inner.try_enqueue(std::move(item))) {
sema->signal();
return true;
}
return false;
}
// Enqueues a single item (by copying it) using an explicit producer token.
// Does not allocate memory. Fails if not enough room to enqueue.
// Thread-safe.
inline bool try_enqueue(producer_token_t const& token, T const& item)
{
if (inner.try_enqueue(token, item)) {
sema->signal();
return true;
}
return false;
}
// Enqueues a single item (by moving it, if possible) using an explicit producer token.
// Does not allocate memory. Fails if not enough room to enqueue.
// Thread-safe.
inline bool try_enqueue(producer_token_t const& token, T&& item)
{
if (inner.try_enqueue(token, std::move(item))) {
sema->signal();
return true;
}
return false;
}
// Enqueues several items.
// Does not allocate memory (except for one-time implicit producer).
// Fails if not enough room to enqueue (or implicit production is
// disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
// Note: Use std::make_move_iterator if the elements should be moved
// instead of copied.
// Thread-safe.
template<typename It>
inline bool try_enqueue_bulk(It itemFirst, size_t count)
{
if (inner.try_enqueue_bulk(std::forward<It>(itemFirst), count)) {
sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
return true;
}
return false;
}
// Enqueues several items using an explicit producer token.
// Does not allocate memory. Fails if not enough room to enqueue.
// Note: Use std::make_move_iterator if the elements should be moved
// instead of copied.
// Thread-safe.
template<typename It>
inline bool try_enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{
if (inner.try_enqueue_bulk(token, std::forward<It>(itemFirst), count)) {
sema->signal((LightweightSemaphore::ssize_t)(ssize_t)count);
return true;
}
return false;
}
// Attempts to dequeue from the queue.
// Returns false if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename U>
inline bool try_dequeue(U& item)
{
if (sema->tryWait()) {
while (!inner.try_dequeue(item)) {
continue;
}
return true;
}
return false;
}
// Attempts to dequeue from the queue using an explicit consumer token.
// Returns false if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename U>
inline bool try_dequeue(consumer_token_t& token, U& item)
{
if (sema->tryWait()) {
while (!inner.try_dequeue(token, item)) {
continue;
}
return true;
}
return false;
}
// Attempts to dequeue several elements from the queue.
// Returns the number of items actually dequeued.
// Returns 0 if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename It>
inline size_t try_dequeue_bulk(It itemFirst, size_t max)
{
size_t count = 0;
max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
while (count != max) {
count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count);
}
return count;
}
// Attempts to dequeue several elements from the queue using an explicit consumer token.
// Returns the number of items actually dequeued.
// Returns 0 if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename It>
inline size_t try_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max)
{
size_t count = 0;
max = (size_t)sema->tryWaitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
while (count != max) {
count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count);
}
return count;
}
// Blocks the current thread until there's something to dequeue, then
// dequeues it.
// Never allocates. Thread-safe.
template<typename U>
inline void wait_dequeue(U& item)
{
while (!sema->wait()) {
continue;
}
while (!inner.try_dequeue(item)) {
continue;
}
}
// Blocks the current thread until either there's something to dequeue
// or the timeout (specified in microseconds) expires. Returns false
// without setting `item` if the timeout expires, otherwise assigns
// to `item` and returns true.
// Using a negative timeout indicates an indefinite timeout,
// and is thus functionally equivalent to calling wait_dequeue.
// Never allocates. Thread-safe.
template<typename U>
inline bool wait_dequeue_timed(U& item, std::int64_t timeout_usecs)
{
if (!sema->wait(timeout_usecs)) {
return false;
}
while (!inner.try_dequeue(item)) {
continue;
}
return true;
}
// Blocks the current thread until either there's something to dequeue
// or the timeout expires. Returns false without setting `item` if the
// timeout expires, otherwise assigns to `item` and returns true.
// Never allocates. Thread-safe.
template<typename U, typename Rep, typename Period>
inline bool wait_dequeue_timed(U& item, std::chrono::duration<Rep, Period> const& timeout)
{
return wait_dequeue_timed(item, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
}
// Blocks the current thread until there's something to dequeue, then
// dequeues it using an explicit consumer token.
// Never allocates. Thread-safe.
template<typename U>
inline void wait_dequeue(consumer_token_t& token, U& item)
{
while (!sema->wait()) {
continue;
}
while (!inner.try_dequeue(token, item)) {
continue;
}
}
// Blocks the current thread until either there's something to dequeue
// or the timeout (specified in microseconds) expires. Returns false
// without setting `item` if the timeout expires, otherwise assigns
// to `item` and returns true.
// Using a negative timeout indicates an indefinite timeout,
// and is thus functionally equivalent to calling wait_dequeue.
// Never allocates. Thread-safe.
template<typename U>
inline bool wait_dequeue_timed(consumer_token_t& token, U& item, std::int64_t timeout_usecs)
{
if (!sema->wait(timeout_usecs)) {
return false;
}
while (!inner.try_dequeue(token, item)) {
continue;
}
return true;
}
// Blocks the current thread until either there's something to dequeue
// or the timeout expires. Returns false without setting `item` if the
// timeout expires, otherwise assigns to `item` and returns true.
// Never allocates. Thread-safe.
template<typename U, typename Rep, typename Period>
inline bool wait_dequeue_timed(consumer_token_t& token, U& item, std::chrono::duration<Rep, Period> const& timeout)
{
return wait_dequeue_timed(token, item, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
}
// Attempts to dequeue several elements from the queue.
// Returns the number of items actually dequeued, which will
// always be at least one (this method blocks until the queue
// is non-empty) and at most max.
// Never allocates. Thread-safe.
template<typename It>
inline size_t wait_dequeue_bulk(It itemFirst, size_t max)
{
size_t count = 0;
max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
while (count != max) {
count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count);
}
return count;
}
// Attempts to dequeue several elements from the queue.
// Returns the number of items actually dequeued, which can
// be 0 if the timeout expires while waiting for elements,
// and at most max.
// Using a negative timeout indicates an indefinite timeout,
// and is thus functionally equivalent to calling wait_dequeue_bulk.
// Never allocates. Thread-safe.
template<typename It>
inline size_t wait_dequeue_bulk_timed(It itemFirst, size_t max, std::int64_t timeout_usecs)
{
size_t count = 0;
max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs);
while (count != max) {
count += inner.template try_dequeue_bulk<It&>(itemFirst, max - count);
}
return count;
}
// Attempts to dequeue several elements from the queue.
// Returns the number of items actually dequeued, which can
// be 0 if the timeout expires while waiting for elements,
// and at most max.
// Never allocates. Thread-safe.
template<typename It, typename Rep, typename Period>
inline size_t wait_dequeue_bulk_timed(It itemFirst, size_t max, std::chrono::duration<Rep, Period> const& timeout)
{
return wait_dequeue_bulk_timed<It&>(itemFirst, max, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
}
// Attempts to dequeue several elements from the queue using an explicit consumer token.
// Returns the number of items actually dequeued, which will
// always be at least one (this method blocks until the queue
// is non-empty) and at most max.
// Never allocates. Thread-safe.
template<typename It>
inline size_t wait_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max)
{
size_t count = 0;
max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max);
while (count != max) {
count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count);
}
return count;
}
// Attempts to dequeue several elements from the queue using an explicit consumer token.
// Returns the number of items actually dequeued, which can
// be 0 if the timeout expires while waiting for elements,
// and at most max.
// Using a negative timeout indicates an indefinite timeout,
// and is thus functionally equivalent to calling wait_dequeue_bulk.
// Never allocates. Thread-safe.
template<typename It>
inline size_t wait_dequeue_bulk_timed(consumer_token_t& token, It itemFirst, size_t max, std::int64_t timeout_usecs)
{
size_t count = 0;
max = (size_t)sema->waitMany((LightweightSemaphore::ssize_t)(ssize_t)max, timeout_usecs);
while (count != max) {
count += inner.template try_dequeue_bulk<It&>(token, itemFirst, max - count);
}
return count;
}
// Attempts to dequeue several elements from the queue using an explicit consumer token.
// Returns the number of items actually dequeued, which can
// be 0 if the timeout expires while waiting for elements,
// and at most max.
// Never allocates. Thread-safe.
template<typename It, typename Rep, typename Period>
inline size_t wait_dequeue_bulk_timed(consumer_token_t& token, It itemFirst, size_t max, std::chrono::duration<Rep, Period> const& timeout)
{
return wait_dequeue_bulk_timed<It&>(token, itemFirst, max, std::chrono::duration_cast<std::chrono::microseconds>(timeout).count());
}
// Returns an estimate of the total number of elements currently in the queue. This
// estimate is only accurate if the queue has completely stabilized before it is called
// (i.e. all enqueue and dequeue operations have completed and their memory effects are
// visible on the calling thread, and no further operations start while this method is
// being called).
// Thread-safe.
inline size_t size_approx() const
{
return (size_t)sema->availableApprox();
}
// Returns true if the underlying atomic variables used by
// the queue are lock-free (they should be on most platforms).
// Thread-safe.
static bool is_lock_free()
{
return ConcurrentQueue::is_lock_free();
}
private:
template<typename U, typename A1, typename A2>
static inline U* create(A1&& a1, A2&& a2)
{
void* p = (Traits::malloc)(sizeof(U));
return p != nullptr ? new (p) U(std::forward<A1>(a1), std::forward<A2>(a2)) : nullptr;
}
template<typename U>
static inline void destroy(U* p)
{
if (p != nullptr) {
p->~U();
}
(Traits::free)(p);
}
private:
ConcurrentQueue inner;
std::unique_ptr<LightweightSemaphore, void (*)(LightweightSemaphore*)> sema;
};
template<typename T, typename Traits>
inline void swap(BlockingConcurrentQueue<T, Traits>& a, BlockingConcurrentQueue<T, Traits>& b) MOODYCAMEL_NOEXCEPT
{
a.swap(b);
}
} // end namespace moodycamel
File diff suppressed because it is too large. Load diff
-412
View File
@@ -1,412 +0,0 @@
// Provides an efficient implementation of a semaphore (LightweightSemaphore).
// This is an extension of Jeff Preshing's sempahore implementation (licensed
// under the terms of its separate zlib license) that has been adapted and
// extended by Cameron Desrochers.
#pragma once
#include <cstddef> // For std::size_t
#include <atomic>
#include <type_traits> // For std::make_signed<T>
#if defined(_WIN32)
// Avoid including windows.h in a header; we only need a handful of
// items, so we'll redeclare them here (this is relatively safe since
// the API generally has to remain stable between Windows versions).
// I know this is an ugly hack but it still beats polluting the global
// namespace with thousands of generic names or adding a .cpp for nothing.
extern "C" {
struct _SECURITY_ATTRIBUTES;
__declspec(dllimport) void* __stdcall CreateSemaphoreW(_SECURITY_ATTRIBUTES* lpSemaphoreAttributes, long lInitialCount, long lMaximumCount, const wchar_t* lpName);
__declspec(dllimport) int __stdcall CloseHandle(void* hObject);
__declspec(dllimport) unsigned long __stdcall WaitForSingleObject(void* hHandle, unsigned long dwMilliseconds);
__declspec(dllimport) int __stdcall ReleaseSemaphore(void* hSemaphore, long lReleaseCount, long* lpPreviousCount);
}
#elif defined(__MACH__)
#include <mach/mach.h>
#elif defined(__unix__)
#include <semaphore.h>
#endif
namespace moodycamel
{
namespace details
{
// Code in the mpmc_sema namespace below is an adaptation of Jeff Preshing's
// portable + lightweight semaphore implementations, originally from
// https://github.com/preshing/cpp11-on-multicore/blob/master/common/sema.h
// LICENSE:
// Copyright (c) 2015 Jeff Preshing
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgement in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#if defined(_WIN32)
class Semaphore
{
private:
void* m_hSema;
Semaphore(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
Semaphore& operator=(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
public:
Semaphore(int initialCount = 0)
{
assert(initialCount >= 0);
const long maxLong = 0x7fffffff;
m_hSema = CreateSemaphoreW(nullptr, initialCount, maxLong, nullptr);
assert(m_hSema);
}
~Semaphore()
{
CloseHandle(m_hSema);
}
bool wait()
{
const unsigned long infinite = 0xffffffff;
return WaitForSingleObject(m_hSema, infinite) == 0;
}
bool try_wait()
{
return WaitForSingleObject(m_hSema, 0) == 0;
}
bool timed_wait(std::uint64_t usecs)
{
return WaitForSingleObject(m_hSema, (unsigned long)(usecs / 1000)) == 0;
}
void signal(int count = 1)
{
while (!ReleaseSemaphore(m_hSema, count, nullptr));
}
};
#elif defined(__MACH__)
//---------------------------------------------------------
// Semaphore (Apple iOS and OSX)
// Can't use POSIX semaphores due to http://lists.apple.com/archives/darwin-kernel/2009/Apr/msg00010.html
//---------------------------------------------------------
class Semaphore
{
private:
semaphore_t m_sema;
Semaphore(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
Semaphore& operator=(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
public:
Semaphore(int initialCount = 0)
{
assert(initialCount >= 0);
kern_return_t rc = semaphore_create(mach_task_self(), &m_sema, SYNC_POLICY_FIFO, initialCount);
assert(rc == KERN_SUCCESS);
(void)rc;
}
~Semaphore()
{
semaphore_destroy(mach_task_self(), m_sema);
}
bool wait()
{
return semaphore_wait(m_sema) == KERN_SUCCESS;
}
bool try_wait()
{
return timed_wait(0);
}
bool timed_wait(std::uint64_t timeout_usecs)
{
mach_timespec_t ts;
ts.tv_sec = static_cast<unsigned int>(timeout_usecs / 1000000);
ts.tv_nsec = static_cast<int>((timeout_usecs % 1000000) * 1000);
// added in OSX 10.10: https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/modules/Darwin.html
kern_return_t rc = semaphore_timedwait(m_sema, ts);
return rc == KERN_SUCCESS;
}
void signal()
{
while (semaphore_signal(m_sema) != KERN_SUCCESS);
}
void signal(int count)
{
while (count-- > 0)
{
while (semaphore_signal(m_sema) != KERN_SUCCESS);
}
}
};
#elif defined(__unix__)
//---------------------------------------------------------
// Semaphore (POSIX, Linux)
//---------------------------------------------------------
class Semaphore
{
private:
sem_t m_sema;
Semaphore(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
Semaphore& operator=(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
public:
Semaphore(int initialCount = 0)
{
assert(initialCount >= 0);
int rc = sem_init(&m_sema, 0, static_cast<unsigned int>(initialCount));
assert(rc == 0);
(void)rc;
}
~Semaphore()
{
sem_destroy(&m_sema);
}
bool wait()
{
// http://stackoverflow.com/questions/2013181/gdb-causes-sem-wait-to-fail-with-eintr-error
int rc;
do {
rc = sem_wait(&m_sema);
} while (rc == -1 && errno == EINTR);
return rc == 0;
}
bool try_wait()
{
int rc;
do {
rc = sem_trywait(&m_sema);
} while (rc == -1 && errno == EINTR);
return rc == 0;
}
bool timed_wait(std::uint64_t usecs)
{
struct timespec ts;
const int usecs_in_1_sec = 1000000;
const int nsecs_in_1_sec = 1000000000;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += (time_t)(usecs / usecs_in_1_sec);
ts.tv_nsec += (long)(usecs % usecs_in_1_sec) * 1000;
// sem_timedwait bombs if you have more than 1e9 in tv_nsec
// so we have to clean things up before passing it in
if (ts.tv_nsec >= nsecs_in_1_sec) {
ts.tv_nsec -= nsecs_in_1_sec;
++ts.tv_sec;
}
int rc;
do {
rc = sem_timedwait(&m_sema, &ts);
} while (rc == -1 && errno == EINTR);
return rc == 0;
}
void signal()
{
while (sem_post(&m_sema) == -1);
}
void signal(int count)
{
while (count-- > 0)
{
while (sem_post(&m_sema) == -1);
}
}
};
#else
#error Unsupported platform! (No semaphore wrapper available)
#endif
} // end namespace details
//---------------------------------------------------------
// LightweightSemaphore
//---------------------------------------------------------
class LightweightSemaphore
{
public:
typedef std::make_signed<std::size_t>::type ssize_t;
private:
std::atomic<ssize_t> m_count;
details::Semaphore m_sema;
int m_maxSpins;
bool waitWithPartialSpinning(std::int64_t timeout_usecs = -1)
{
ssize_t oldCount;
int spin = m_maxSpins;
while (--spin >= 0)
{
oldCount = m_count.load(std::memory_order_relaxed);
if ((oldCount > 0) && m_count.compare_exchange_strong(oldCount, oldCount - 1, std::memory_order_acquire, std::memory_order_relaxed))
return true;
std::atomic_signal_fence(std::memory_order_acquire); // Prevent the compiler from collapsing the loop.
}
oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
if (oldCount > 0)
return true;
if (timeout_usecs < 0)
{
if (m_sema.wait())
return true;
}
if (timeout_usecs > 0 && m_sema.timed_wait((std::uint64_t)timeout_usecs))
return true;
// At this point, we've timed out waiting for the semaphore, but the
// count is still decremented indicating we may still be waiting on
// it. So we have to re-adjust the count, but only if the semaphore
// wasn't signaled enough times for us too since then. If it was, we
// need to release the semaphore too.
while (true)
{
oldCount = m_count.load(std::memory_order_acquire);
if (oldCount >= 0 && m_sema.try_wait())
return true;
if (oldCount < 0 && m_count.compare_exchange_strong(oldCount, oldCount + 1, std::memory_order_relaxed, std::memory_order_relaxed))
return false;
}
}
ssize_t waitManyWithPartialSpinning(ssize_t max, std::int64_t timeout_usecs = -1)
{
assert(max > 0);
ssize_t oldCount;
int spin = m_maxSpins;
while (--spin >= 0)
{
oldCount = m_count.load(std::memory_order_relaxed);
if (oldCount > 0)
{
ssize_t newCount = oldCount > max ? oldCount - max : 0;
if (m_count.compare_exchange_strong(oldCount, newCount, std::memory_order_acquire, std::memory_order_relaxed))
return oldCount - newCount;
}
std::atomic_signal_fence(std::memory_order_acquire);
}
oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
if (oldCount <= 0)
{
if ((timeout_usecs == 0) || (timeout_usecs < 0 && !m_sema.wait()) || (timeout_usecs > 0 && !m_sema.timed_wait((std::uint64_t)timeout_usecs)))
{
while (true)
{
oldCount = m_count.load(std::memory_order_acquire);
if (oldCount >= 0 && m_sema.try_wait())
break;
if (oldCount < 0 && m_count.compare_exchange_strong(oldCount, oldCount + 1, std::memory_order_relaxed, std::memory_order_relaxed))
return 0;
}
}
}
if (max > 1)
return 1 + tryWaitMany(max - 1);
return 1;
}
public:
LightweightSemaphore(ssize_t initialCount = 0, int maxSpins = 10000) : m_count(initialCount), m_maxSpins(maxSpins)
{
assert(initialCount >= 0);
assert(maxSpins >= 0);
}
bool tryWait()
{
ssize_t oldCount = m_count.load(std::memory_order_relaxed);
while (oldCount > 0)
{
if (m_count.compare_exchange_weak(oldCount, oldCount - 1, std::memory_order_acquire, std::memory_order_relaxed))
return true;
}
return false;
}
bool wait()
{
return tryWait() || waitWithPartialSpinning();
}
bool wait(std::int64_t timeout_usecs)
{
return tryWait() || waitWithPartialSpinning(timeout_usecs);
}
// Acquires between 0 and (greedily) max, inclusive
ssize_t tryWaitMany(ssize_t max)
{
assert(max >= 0);
ssize_t oldCount = m_count.load(std::memory_order_relaxed);
while (oldCount > 0)
{
ssize_t newCount = oldCount > max ? oldCount - max : 0;
if (m_count.compare_exchange_weak(oldCount, newCount, std::memory_order_acquire, std::memory_order_relaxed))
return oldCount - newCount;
}
return 0;
}
// Acquires at least one, and (greedily) at most max
ssize_t waitMany(ssize_t max, std::int64_t timeout_usecs)
{
assert(max >= 0);
ssize_t result = tryWaitMany(max);
if (result == 0 && max > 0)
result = waitManyWithPartialSpinning(max, timeout_usecs);
return result;
}
ssize_t waitMany(ssize_t max)
{
ssize_t result = waitMany(max, -1);
assert(result > 0);
return result;
}
void signal(ssize_t count = 1)
{
assert(count >= 0);
ssize_t oldCount = m_count.fetch_add(count, std::memory_order_release);
ssize_t toRelease = -oldCount < count ? -oldCount : count;
if (toRelease > 0)
{
m_sema.signal((int)toRelease);
}
}
std::size_t availableApprox() const
{
ssize_t count = m_count.load(std::memory_order_relaxed);
return count > 0 ? static_cast<std::size_t>(count) : 0;
}
};
} // end namespace moodycamel
-105
View File
@@ -1,105 +0,0 @@
AccessModifierOffset: -4
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: Empty
BinPackArguments: false
BinPackParameters: false
ColumnLimit: 120
IndentCaseLabels: false
IndentWidth: 4
---
Language: Cpp
# BasedOnStyle: Google
#AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: true
AlignTrailingComments: true
#AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
#AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
#BinPackArguments: true
#BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
#ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
#IndentCaseLabels: true
#IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 8
UseTab: Never
...
-30
View File
@@ -1,30 +0,0 @@
name: Coverage
on: [push, pull_request]
jobs:
coverage:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: dependencies
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y -qq make cmake gcc g++ lcov bc
- name: build
shell: bash
run: |
export LD_LIBRARY_PATH=.:$(cat /etc/ld.so.conf.d/* | grep -vF "#" | tr "\\n" ":" | sed -e "s/:$//g")
cmake . -DCMAKE_BUILD_TYPE=Debug -DENABLE_COVERAGE=On
make all -j$(nproc)
- name: coverage
shell: bash
run: |
make coverage
lines=$(lcov --summary coverage.info | grep -F lines | awk '{print $2}' | sed -e "s/%//g")
if (( $(echo "${lines} < ${COVERAGE_THRESHOLD}" | bc -l) )); then
echo "Line coverage dropped below ${COVERAGE_THRESHOLD}% to ${lines}%"
exit 1
fi
env:
COVERAGE_THRESHOLD: 85.0
-13
View File
@@ -1,13 +0,0 @@
name: Lint
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: lint
uses: DoozyX/clang-format-lint-action@v0.12
with:
clangFormatVersion: 12
source: './include/cpp-statsd-client ./tests'
-23
View File
@@ -1,23 +0,0 @@
name: Linux
on: [push, pull_request]
jobs:
linux:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: dependencies
shell: bash
run: |
sudo apt-get update
sudo apt-get install -y -qq make cmake gcc g++
- name: build
shell: bash
run: |
export LD_LIBRARY_PATH=.:$(cat /etc/ld.so.conf.d/* | grep -vF "#" | tr "\\n" ":" | sed -e "s/:$//g")
cmake . -DCMAKE_BUILD_TYPE=RelWithDebInfo -DENABLE_SANITIZERS=On
make all -j$(nproc)
- name: test
shell: bash
run: |
make test
-18
View File
@@ -1,18 +0,0 @@
name: Windows
on: [push, pull_request]
jobs:
windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: dependencies
run: |
choco install cmake
- name: build
run: |
cmake -S . -B build -G "Visual Studio 16 2019" -A x64
cmake --build build --target ALL_BUILD --config Release
- name: test
run: |
cmake --build build --target RUN_TESTS --config Release
-1
View File
@@ -1 +0,0 @@
bin
-85
View File
@@ -1,85 +0,0 @@
# Basic project setup
cmake_minimum_required(VERSION 3.5)
project(cpp-statsd-client
VERSION 1.0.2
LANGUAGES CXX
DESCRIPTION "A header-only StatsD client implemented in C++"
HOMEPAGE_URL "https://github.com/vthiery/cpp-statsd-client")
option(CPP_STATSD_STANDALONE "Allows configuration of targets for verifying library functionality" ON)
option(ENABLE_TESTS "Build tests" ON)
option(ENABLE_COVERAGE "Build with coverage instrumentalisation" OFF)
if(NOT CPP_STATSD_STANDALONE)
set(ENABLE_TESTS OFF)
set(ENABLE_COVERAGE OFF)
endif()
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
find_package(Threads)
# Optional code coverage targets
if(ENABLE_COVERAGE)
set(COVERAGE_EXCLUDES /usr/*)
include(${PROJECT_SOURCE_DIR}/cmake/CodeCoverage.cmake)
APPEND_COVERAGE_COMPILER_FLAGS()
SETUP_TARGET_FOR_COVERAGE_LCOV(NAME coverage
EXECUTABLE testStatsdClient
DEPENDENCIES ${PROJECT_NAME}
)
endif()
# The library target
add_library(${PROJECT_NAME} INTERFACE)
target_include_directories(
${PROJECT_NAME}
INTERFACE $<BUILD_INTERFACE:${${PROJECT_NAME}_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
target_link_libraries(${PROJECT_NAME} INTERFACE Threads::Threads)
if(WIN32)
target_link_libraries(${PROJECT_NAME} INTERFACE ws2_32)
endif()
# The installation and pkg-config-like cmake config
install(TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}_Targets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
write_basic_package_version_file("${PROJECT_NAME}ConfigVersion.cmake"
VERSION ${PROJECT_VERSION}
COMPATIBILITY SameMajorVersion)
configure_package_config_file(
"${PROJECT_SOURCE_DIR}/cmake/${PROJECT_NAME}Config.cmake.in"
"${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
INSTALL_DESTINATION
${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake)
install(EXPORT ${PROJECT_NAME}_Targets
FILE ${PROJECT_NAME}Targets.cmake
NAMESPACE ${PROJECT_NAME}::
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake)
install(FILES "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
"${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}/cmake)
install(DIRECTORY ${PROJECT_SOURCE_DIR}/include DESTINATION include)
if(ENABLE_TESTS)
# The test targets
add_executable(testStatsdClient ${CMAKE_CURRENT_SOURCE_DIR}/tests/testStatsdClient.cpp)
if(WIN32)
target_compile_options(testStatsdClient PRIVATE -W4 -WX /external:W0)
else()
target_compile_options(testStatsdClient PRIVATE -Wall -Wextra -pedantic -Werror)
endif()
target_include_directories(testStatsdClient PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/tests)
target_link_libraries(testStatsdClient ${PROJECT_NAME})
set_property(TARGET testStatsdClient PROPERTY CXX_STANDARD 11)
set_property(TARGET testStatsdClient PROPERTY CXX_EXTENSIONS OFF)
# The test suite
enable_testing()
add_test(ctestTestStatsdClient testStatsdClient)
add_custom_target(check COMMAND ${CMAKE_CTEST_COMMAND} DEPENDS testStatsdClient)
endif()
-9
View File
@@ -1,9 +0,0 @@
MIT License
Copyright (c) 2017 Vincent Thiery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-22
View File
@@ -1,22 +0,0 @@
# simple makefile to build, test and clean
BUILD_MODE ?= Release
ENABLE_COVERAGE ?= On
build: clean
@echo "Build in ${BUILD_MODE} mode"
mkdir -p bin/${BUILD_MODE}
@cd bin/${BUILD_MODE}; cmake ../../ -DCMAKE_BUILD_TYPE=${BUILD_MODE} -DENABLE_COVERAGE=${ENABLE_COVERAGE}
@cd bin/${BUILD_MODE}; make
test: build
@cd bin/${BUILD_MODE}; make test
coverage: build
@cd bin/${BUILD_MODE}; make coverage
install: build
@cd bin/${BUILD_MODE}; make install
clean:
@rm -rf bin
-150
View File
@@ -1,150 +0,0 @@
# C++ StatsD Client
![logo](https://raw.githubusercontent.com/vthiery/cpp-statsd-client/master/images/logo.svg?sanitize=true)
[![Release](https://img.shields.io/github/release/vthiery/cpp-statsd-client.svg?style=for-the-badge)](https://github.com/vthiery/cpp-statsd-client/releases/latest)
![License](https://img.shields.io/github/license/vthiery/cpp-statsd-client?style=for-the-badge)
[![Linux status](https://img.shields.io/github/workflow/status/vthiery/cpp-statsd-client/Linux?label=Linux&style=for-the-badge)](https://github.com/vthiery/cpp-statsd-client/actions/workflows/linux.yml?query=branch%3Amaster++)
[![Windows status](https://img.shields.io/github/workflow/status/vthiery/cpp-statsd-client/Windows?label=Windows&style=for-the-badge)](https://github.com/vthiery/cpp-statsd-client/actions/workflows/windows.yml?query=branch%3Amaster++)
A header-only StatsD client implemented in C++.
The client allows:
- batching,
- change of configuration at runtime,
- user-defined frequency rate.
## Install and Test
### Makefile
In order to install the header files and/or run the tests, simply use the Makefile and execute
```sh
make install
```
and
```sh
make test
```
### Conan
If you are using [Conan](https://www.conan.io/) to manage your dependencies, merely add statsdclient/x.y.z@vthiery/stable to your conanfile.py's requires, where x.y.z is the release version you want to use. Please file issues here if you experience problems with the packages. You can also directly download the latest version [here](https://bintray.com/vthiery/conan-packages/statsdclient%3Avthiery/_latestVersion).
## Usage
### Example
A simple example of how to use the client:
```cpp
#include "StatsdClient.hpp"
using namespace Statsd;
int main() {
// Define the client on localhost, with port 8080,
// using a prefix,
// a batching size of 20 bytes,
// and three points of precision for floating point gauge values
StatsdClient client{ "127.0.0.1", 8080, "myPrefix", 20, 3 };
// Increment the metric "coco"
client.increment("coco");
// Decrement the metric "kiki"
client.decrement("kiki");
// Adjusts "toto" by +3
client.count("toto", 2, 0.1f);
// Record a gauge "titi" to 3
client.gauge("titi", 3);
// Record a timing of 2ms for "myTiming"
client.timing("myTiming", 2, 0.1f);
// Send a metric explicitly
client.send("tutu", 4, "c", 2.0f);
exit(0);
}
```
### Advanced Testing
A simple mock StatsD server can be found at `tests/StatsdServer.hpp`. This can be used to do simple validation of your application's metrics, typically in the form of unit tests. In fact this is the primary means by which this library is tested. The mock server itself is not distributed with the library so to use it you'd need to vendor this project into your project. Once you have though, you can test your application's use of the client like so:
```cpp
#include "StatsdClient.hpp"
#include "StatsdServer.hpp"
#include <cassert>
using namespace Statsd;
struct MyApp {
void doWork() const {
m_client.count("bar", 3);
}
private:
StatsdClient m_client{"localhost", 8125, "foo"};
};
int main() {
StatsdServer mockServer;
MyApp app;
app.doWork();
assert(mockServer.receive() == "foo.bar:3|c");
exit(0);
}
```
### Configuration
The configuration of the client must be input when one instantiates it. Nevertheless, the API allows the configuration ot change afterwards. For example, one can do the following:
```cpp
#include "StatsdClient.hpp"
using namespace Statsd;
int main()
{
// Define the client on localhost, with port 8080,
// using a prefix,
// a batching size of 20 bytes,
// and three points of precision for floating point gauge values
StatsdClient client{ "127.0.0.1", 8080, "myPrefix", 20, 3 };
client.increment("coco");
// Set a new configuration, using a different port, a different prefix, and more gauge precision
client.setConfig("127.0.0.1", 8000, "anotherPrefix", 6);
client.decrement("kiki");
}
```
The batchsize is the only parameter that cannot be changed for the time being.
### Batching
The client supports batching of the metrics. The batch size parameter is the number of bytes to allow in each batch (UDP datagram payload) to be sent to the statsd process. This number is not a hard limit. If appending the current stat to the current batch (separated by the `'\n'` character) pushes the current batch over the batch size, that batch is enqueued (not sent) and a new batch is started. If batch size is 0, the default, then each stat is sent individually to the statsd process and no batches are enqueued.
### Sending
As previously mentioned, if batching is disabled (by setting the batch size to 0) then every stat is sent immediately in a blocking fashion. If batching is enabled (ie non-zero) then you may also set the send interval. The send interval controls the time, in milliseconds, to wait before flushing/sending the queued stats batches to the statsd process. When the send interval is non-zero a background thread is spawned which will do the flushing/sending at the configured send interval, in other words asynchronously. The queuing mechanism in this case is *not* lock-free. If batching is enabled but the send interval is set to zero then the queued batchs of stats will not be sent automatically by a background thread but must be sent manually via the `flush` method. The `flush` method is a blocking call.
### Frequency rate
When sending a metric, a frequency rate can be set in order to limit the metrics' sampling. By default, the frequency rate is set to one and won't affect the sampling. If set to a value `epsilon` (0.0001 for the time being) close to one, the sampling is not affected either.
If the frequency rate is set and `epsilon` different from one, the sending will be rejected randomly (the higher the frequency rate, the lower the probability of rejection).
## License
This library is under MIT license.
-708
View File
@@ -1,708 +0,0 @@
# Copyright (c) 2012 - 2017, Lars Bilke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# CHANGES:
#
# 2012-01-31, Lars Bilke
# - Enable Code Coverage
#
# 2013-09-17, Joakim Söderberg
# - Added support for Clang.
# - Some additional usage instructions.
#
# 2016-02-03, Lars Bilke
# - Refactored functions to use named parameters
#
# 2017-06-02, Lars Bilke
# - Merged with modified version from github.com/ufz/ogs
#
# 2019-05-06, Anatolii Kurotych
# - Remove unnecessary --coverage flag
#
# 2019-12-13, FeRD (Frank Dana)
# - Deprecate COVERAGE_LCOVR_EXCLUDES and COVERAGE_GCOVR_EXCLUDES lists in favor
# of tool-agnostic COVERAGE_EXCLUDES variable, or EXCLUDE setup arguments.
# - CMake 3.4+: All excludes can be specified relative to BASE_DIRECTORY
# - All setup functions: accept BASE_DIRECTORY, EXCLUDE list
# - Set lcov basedir with -b argument
# - Add automatic --demangle-cpp in lcovr, if 'c++filt' is available (can be
# overridden with NO_DEMANGLE option in setup_target_for_coverage_lcovr().)
# - Delete output dir, .info file on 'make clean'
# - Remove Python detection, since version mismatches will break gcovr
# - Minor cleanup (lowercase function names, update examples...)
#
# 2019-12-19, FeRD (Frank Dana)
# - Rename Lcov outputs, make filtered file canonical, fix cleanup for targets
#
# 2020-01-19, Bob Apthorpe
# - Added gfortran support
#
# 2020-02-17, FeRD (Frank Dana)
# - Make all add_custom_target()s VERBATIM to auto-escape wildcard characters
# in EXCLUDEs, and remove manual escaping from gcovr targets
#
# 2021-01-19, Robin Mueller
# - Add CODE_COVERAGE_VERBOSE option which will allow to print out commands which are run
# - Added the option for users to set the GCOVR_ADDITIONAL_ARGS variable to supply additional
# flags to the gcovr command
#
# 2020-05-04, Mihchael Davis
# - Add -fprofile-abs-path to make gcno files contain absolute paths
# - Fix BASE_DIRECTORY not working when defined
# - Change BYPRODUCT from folder to index.html to stop ninja from complaining about double defines
#
# 2021-05-10, Martin Stump
# - Check if the generator is multi-config before warning about non-Debug builds
#
# USAGE:
#
# 1. Copy this file into your cmake modules path.
#
# 2. Add the following line to your CMakeLists.txt (best inside an if-condition
# using a CMake option() to enable it just optionally):
# include(CodeCoverage)
#
# 3. Append necessary compiler flags:
# append_coverage_compiler_flags()
#
# 3.a (OPTIONAL) Set appropriate optimization flags, e.g. -O0, -O1 or -Og
#
# 4. If you need to exclude additional directories from the report, specify them
# using full paths in the COVERAGE_EXCLUDES variable before calling
# setup_target_for_coverage_*().
# Example:
# set(COVERAGE_EXCLUDES
# '${PROJECT_SOURCE_DIR}/src/dir1/*'
# '/path/to/my/src/dir2/*')
# Or, use the EXCLUDE argument to setup_target_for_coverage_*().
# Example:
# setup_target_for_coverage_lcov(
# NAME coverage
# EXECUTABLE testrunner
# EXCLUDE "${PROJECT_SOURCE_DIR}/src/dir1/*" "/path/to/my/src/dir2/*")
#
# 4.a NOTE: With CMake 3.4+, COVERAGE_EXCLUDES or EXCLUDE can also be set
# relative to the BASE_DIRECTORY (default: PROJECT_SOURCE_DIR)
# Example:
# set(COVERAGE_EXCLUDES "dir1/*")
# setup_target_for_coverage_gcovr_html(
# NAME coverage
# EXECUTABLE testrunner
# BASE_DIRECTORY "${PROJECT_SOURCE_DIR}/src"
# EXCLUDE "dir2/*")
#
# 5. Use the functions described below to create a custom make target which
# runs your test executable and produces a code coverage report.
#
# 6. Build a Debug build:
# cmake -DCMAKE_BUILD_TYPE=Debug ..
# make
# make my_coverage_target
#
include(CMakeParseArguments)
option(CODE_COVERAGE_VERBOSE "Verbose information" FALSE)
# Check prereqs
find_program( GCOV_PATH gcov )
find_program( LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl)
find_program( FASTCOV_PATH NAMES fastcov fastcov.py )
find_program( GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat )
find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test)
find_program( CPPFILT_PATH NAMES c++filt )
if(NOT GCOV_PATH)
message(FATAL_ERROR "gcov not found! Aborting...")
endif() # NOT GCOV_PATH
get_property(LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
list(GET LANGUAGES 0 LANG)
if("${CMAKE_${LANG}_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
if("${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS 3)
message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...")
endif()
elseif(NOT CMAKE_COMPILER_IS_GNUCXX)
if("${CMAKE_Fortran_COMPILER_ID}" MATCHES "[Ff]lang")
# Do nothing; exit conditional without error if true
elseif("${CMAKE_Fortran_COMPILER_ID}" MATCHES "GNU")
# Do nothing; exit conditional without error if true
else()
message(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
endif()
endif()
set(COVERAGE_COMPILER_FLAGS "-g -fprofile-arcs -ftest-coverage"
CACHE INTERNAL "")
if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)")
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-fprofile-abs-path HAVE_fprofile_abs_path)
if(HAVE_fprofile_abs_path)
set(COVERAGE_COMPILER_FLAGS "${COVERAGE_COMPILER_FLAGS} -fprofile-abs-path")
endif()
endif()
set(CMAKE_Fortran_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the Fortran compiler during coverage builds."
FORCE )
set(CMAKE_CXX_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C++ compiler during coverage builds."
FORCE )
set(CMAKE_C_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C compiler during coverage builds."
FORCE )
set(CMAKE_EXE_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used for linking binaries during coverage builds."
FORCE )
set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used by the shared libraries linker during coverage builds."
FORCE )
mark_as_advanced(
CMAKE_Fortran_FLAGS_COVERAGE
CMAKE_CXX_FLAGS_COVERAGE
CMAKE_C_FLAGS_COVERAGE
CMAKE_EXE_LINKER_FLAGS_COVERAGE
CMAKE_SHARED_LINKER_FLAGS_COVERAGE )
get_property(GENERATOR_IS_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG))
message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading")
endif() # NOT (CMAKE_BUILD_TYPE STREQUAL "Debug" OR GENERATOR_IS_MULTI_CONFIG)
if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
link_libraries(gcov)
endif()
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_lcov(
# NAME testrunner_coverage # New target name
# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES testrunner # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# NO_DEMANGLE # Don't demangle C++ symbols
# # even if c++filt is found
# )
function(setup_target_for_coverage_lcov)
set(options NO_DEMANGLE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES LCOV_ARGS GENHTML_ARGS)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT LCOV_PATH)
message(FATAL_ERROR "lcov not found! Aborting...")
endif() # NOT LCOV_PATH
if(NOT GENHTML_PATH)
message(FATAL_ERROR "genhtml not found! Aborting...")
endif() # NOT GENHTML_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(DEFINED Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(LCOV_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_LCOV_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND LCOV_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES LCOV_EXCLUDES)
# Conditional arguments
if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
set(GENHTML_EXTRA_ARGS "--demangle-cpp")
endif()
# Setting up commands which will be run to generate coverage data.
# Cleanup lcov
set(LCOV_CLEAN_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -directory .
-b ${BASEDIR} --zerocounters
)
# Create baseline to make sure untouched files show up in the report
set(LCOV_BASELINE_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -c -i -d . -b
${BASEDIR} -o ${Coverage_NAME}.base
)
# Run tests
set(LCOV_EXEC_TESTS_CMD
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
)
# Capturing lcov counters and generating report
set(LCOV_CAPTURE_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --directory . -b
${BASEDIR} --capture --output-file ${Coverage_NAME}.capture
)
# add baseline counters
set(LCOV_BASELINE_COUNT_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -a ${Coverage_NAME}.base
-a ${Coverage_NAME}.capture --output-file ${Coverage_NAME}.total
)
# filter collected data to final coverage report
set(LCOV_FILTER_CMD
${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --remove
${Coverage_NAME}.total ${LCOV_EXCLUDES} --output-file ${Coverage_NAME}.info
)
# Generate HTML output
set(LCOV_GEN_HTML_CMD
${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS} -o
${Coverage_NAME} ${Coverage_NAME}.info
)
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Executed command report")
message(STATUS "Command to clean up lcov: ")
string(REPLACE ";" " " LCOV_CLEAN_CMD_SPACED "${LCOV_CLEAN_CMD}")
message(STATUS "${LCOV_CLEAN_CMD_SPACED}")
message(STATUS "Command to create baseline: ")
string(REPLACE ";" " " LCOV_BASELINE_CMD_SPACED "${LCOV_BASELINE_CMD}")
message(STATUS "${LCOV_BASELINE_CMD_SPACED}")
message(STATUS "Command to run the tests: ")
string(REPLACE ";" " " LCOV_EXEC_TESTS_CMD_SPACED "${LCOV_EXEC_TESTS_CMD}")
message(STATUS "${LCOV_EXEC_TESTS_CMD_SPACED}")
message(STATUS "Command to capture counters and generate report: ")
string(REPLACE ";" " " LCOV_CAPTURE_CMD_SPACED "${LCOV_CAPTURE_CMD}")
message(STATUS "${LCOV_CAPTURE_CMD_SPACED}")
message(STATUS "Command to add baseline counters: ")
string(REPLACE ";" " " LCOV_BASELINE_COUNT_CMD_SPACED "${LCOV_BASELINE_COUNT_CMD}")
message(STATUS "${LCOV_BASELINE_COUNT_CMD_SPACED}")
message(STATUS "Command to filter collected data: ")
string(REPLACE ";" " " LCOV_FILTER_CMD_SPACED "${LCOV_FILTER_CMD}")
message(STATUS "${LCOV_FILTER_CMD_SPACED}")
message(STATUS "Command to generate lcov HTML output: ")
string(REPLACE ";" " " LCOV_GEN_HTML_CMD_SPACED "${LCOV_GEN_HTML_CMD}")
message(STATUS "${LCOV_GEN_HTML_CMD_SPACED}")
endif()
# Setup target
add_custom_target(${Coverage_NAME}
COMMAND ${LCOV_CLEAN_CMD}
COMMAND ${LCOV_BASELINE_CMD}
COMMAND ${LCOV_EXEC_TESTS_CMD}
COMMAND ${LCOV_CAPTURE_CMD}
COMMAND ${LCOV_BASELINE_COUNT_CMD}
COMMAND ${LCOV_FILTER_CMD}
COMMAND ${LCOV_GEN_HTML_CMD}
# Set output files as GENERATED (will be removed on 'make clean')
BYPRODUCTS
${Coverage_NAME}.base
${Coverage_NAME}.capture
${Coverage_NAME}.total
${Coverage_NAME}.info
${Coverage_NAME}/index.html
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
)
# Show where to find the lcov info report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Lcov code coverage info report saved in ${Coverage_NAME}.info."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
)
endfunction() # setup_target_for_coverage_lcov
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_gcovr_xml(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# )
# The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the
# GCVOR command.
function(setup_target_for_coverage_gcovr_xml)
set(options NONE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(DEFINED Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(GCOVR_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
# Combine excludes to several -e arguments
set(GCOVR_EXCLUDE_ARGS "")
foreach(EXCLUDE ${GCOVR_EXCLUDES})
list(APPEND GCOVR_EXCLUDE_ARGS "-e")
list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
endforeach()
# Set up commands which will be run to generate coverage data
# Run tests
set(GCOVR_XML_EXEC_TESTS_CMD
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
)
# Running gcovr
set(GCOVR_XML_CMD
${GCOVR_PATH} --xml -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS} ${GCOVR_EXCLUDE_ARGS}
--object-directory=${PROJECT_BINARY_DIR} -o ${Coverage_NAME}.xml
)
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Executed command report")
message(STATUS "Command to run tests: ")
string(REPLACE ";" " " GCOVR_XML_EXEC_TESTS_CMD_SPACED "${GCOVR_XML_EXEC_TESTS_CMD}")
message(STATUS "${GCOVR_XML_EXEC_TESTS_CMD_SPACED}")
message(STATUS "Command to generate gcovr XML coverage data: ")
string(REPLACE ";" " " GCOVR_XML_CMD_SPACED "${GCOVR_XML_CMD}")
message(STATUS "${GCOVR_XML_CMD_SPACED}")
endif()
add_custom_target(${Coverage_NAME}
COMMAND ${GCOVR_XML_EXEC_TESTS_CMD}
COMMAND ${GCOVR_XML_CMD}
BYPRODUCTS ${Coverage_NAME}.xml
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Running gcovr to produce Cobertura code coverage report."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Cobertura code coverage report saved in ${Coverage_NAME}.xml."
)
endfunction() # setup_target_for_coverage_gcovr_xml
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_gcovr_html(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# )
# The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the
# GCVOR command.
function(setup_target_for_coverage_gcovr_html)
set(options NONE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(DEFINED Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(GCOVR_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
# Combine excludes to several -e arguments
set(GCOVR_EXCLUDE_ARGS "")
foreach(EXCLUDE ${GCOVR_EXCLUDES})
list(APPEND GCOVR_EXCLUDE_ARGS "-e")
list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
endforeach()
# Set up commands which will be run to generate coverage data
# Run tests
set(GCOVR_HTML_EXEC_TESTS_CMD
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
)
# Create folder
set(GCOVR_HTML_FOLDER_CMD
${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/${Coverage_NAME}
)
# Running gcovr
set(GCOVR_HTML_CMD
${GCOVR_PATH} --html --html-details -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS}
${GCOVR_EXCLUDE_ARGS} --object-directory=${PROJECT_BINARY_DIR}
-o ${Coverage_NAME}/index.html
)
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Executed command report")
message(STATUS "Command to run tests: ")
string(REPLACE ";" " " GCOVR_HTML_EXEC_TESTS_CMD_SPACED "${GCOVR_HTML_EXEC_TESTS_CMD}")
message(STATUS "${GCOVR_HTML_EXEC_TESTS_CMD_SPACED}")
message(STATUS "Command to create a folder: ")
string(REPLACE ";" " " GCOVR_HTML_FOLDER_CMD_SPACED "${GCOVR_HTML_FOLDER_CMD}")
message(STATUS "${GCOVR_HTML_FOLDER_CMD_SPACED}")
message(STATUS "Command to generate gcovr HTML coverage data: ")
string(REPLACE ";" " " GCOVR_HTML_CMD_SPACED "${GCOVR_HTML_CMD}")
message(STATUS "${GCOVR_HTML_CMD_SPACED}")
endif()
add_custom_target(${Coverage_NAME}
COMMAND ${GCOVR_HTML_EXEC_TESTS_CMD}
COMMAND ${GCOVR_HTML_FOLDER_CMD}
COMMAND ${GCOVR_HTML_CMD}
BYPRODUCTS ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html # report directory
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Running gcovr to produce HTML code coverage report."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
)
endfunction() # setup_target_for_coverage_gcovr_html
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_fastcov(
# NAME testrunner_coverage # New target name
# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES testrunner # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/" "src/dir2/" # Patterns to exclude.
# NO_DEMANGLE # Don't demangle C++ symbols
# # even if c++filt is found
# SKIP_HTML # Don't create html report
# POST_CMD perl -i -pe s!${PROJECT_SOURCE_DIR}/!!g ctest_coverage.json # E.g. for stripping source dir from file paths
# )
function(setup_target_for_coverage_fastcov)
set(options NO_DEMANGLE SKIP_HTML)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES FASTCOV_ARGS GENHTML_ARGS POST_CMD)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT FASTCOV_PATH)
message(FATAL_ERROR "fastcov not found! Aborting...")
endif()
if(NOT Coverage_SKIP_HTML AND NOT GENHTML_PATH)
message(FATAL_ERROR "genhtml not found! Aborting...")
endif()
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(Coverage_BASE_DIRECTORY)
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (Patterns, not paths, for fastcov)
set(FASTCOV_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_FASTCOV_EXCLUDES})
list(APPEND FASTCOV_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES FASTCOV_EXCLUDES)
# Conditional arguments
if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
set(GENHTML_EXTRA_ARGS "--demangle-cpp")
endif()
# Set up commands which will be run to generate coverage data
set(FASTCOV_EXEC_TESTS_CMD ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS})
set(FASTCOV_CAPTURE_CMD ${FASTCOV_PATH} ${Coverage_FASTCOV_ARGS} --gcov ${GCOV_PATH}
--search-directory ${BASEDIR}
--process-gcno
--output ${Coverage_NAME}.json
--exclude ${FASTCOV_EXCLUDES}
--exclude ${FASTCOV_EXCLUDES}
)
set(FASTCOV_CONVERT_CMD ${FASTCOV_PATH}
-C ${Coverage_NAME}.json --lcov --output ${Coverage_NAME}.info
)
if(Coverage_SKIP_HTML)
set(FASTCOV_HTML_CMD ";")
else()
set(FASTCOV_HTML_CMD ${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS}
-o ${Coverage_NAME} ${Coverage_NAME}.info
)
endif()
set(FASTCOV_POST_CMD ";")
if(Coverage_POST_CMD)
set(FASTCOV_POST_CMD ${Coverage_POST_CMD})
endif()
if(CODE_COVERAGE_VERBOSE)
message(STATUS "Code coverage commands for target ${Coverage_NAME} (fastcov):")
message(" Running tests:")
string(REPLACE ";" " " FASTCOV_EXEC_TESTS_CMD_SPACED "${FASTCOV_EXEC_TESTS_CMD}")
message(" ${FASTCOV_EXEC_TESTS_CMD_SPACED}")
message(" Capturing fastcov counters and generating report:")
string(REPLACE ";" " " FASTCOV_CAPTURE_CMD_SPACED "${FASTCOV_CAPTURE_CMD}")
message(" ${FASTCOV_CAPTURE_CMD_SPACED}")
message(" Converting fastcov .json to lcov .info:")
string(REPLACE ";" " " FASTCOV_CONVERT_CMD_SPACED "${FASTCOV_CONVERT_CMD}")
message(" ${FASTCOV_CONVERT_CMD_SPACED}")
if(NOT Coverage_SKIP_HTML)
message(" Generating HTML report: ")
string(REPLACE ";" " " FASTCOV_HTML_CMD_SPACED "${FASTCOV_HTML_CMD}")
message(" ${FASTCOV_HTML_CMD_SPACED}")
endif()
if(Coverage_POST_CMD)
message(" Running post command: ")
string(REPLACE ";" " " FASTCOV_POST_CMD_SPACED "${FASTCOV_POST_CMD}")
message(" ${FASTCOV_POST_CMD_SPACED}")
endif()
endif()
# Setup target
add_custom_target(${Coverage_NAME}
# Cleanup fastcov
COMMAND ${FASTCOV_PATH} ${Coverage_FASTCOV_ARGS} --gcov ${GCOV_PATH}
--search-directory ${BASEDIR}
--zerocounters
COMMAND ${FASTCOV_EXEC_TESTS_CMD}
COMMAND ${FASTCOV_CAPTURE_CMD}
COMMAND ${FASTCOV_CONVERT_CMD}
COMMAND ${FASTCOV_HTML_CMD}
COMMAND ${FASTCOV_POST_CMD}
# Set output files as GENERATED (will be removed on 'make clean')
BYPRODUCTS
${Coverage_NAME}.info
${Coverage_NAME}.json
${Coverage_NAME}/index.html # report directory
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Resetting code coverage counters to zero. Processing code coverage counters and generating report."
)
set(INFO_MSG "fastcov code coverage info report saved in ${Coverage_NAME}.info and ${Coverage_NAME}.json.")
if(NOT Coverage_SKIP_HTML)
string(APPEND INFO_MSG " Open ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html in your browser to view the coverage report.")
endif()
# Show where to find the fastcov info report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E echo ${INFO_MSG}
)
endfunction() # setup_target_for_coverage_fastcov
function(append_coverage_compiler_flags)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
message(STATUS "Appending code coverage compiler flags: ${COVERAGE_COMPILER_FLAGS}")
endfunction() # append_coverage_compiler_flags
-18
View File
@@ -1,18 +0,0 @@
# Copyright (c) 2016, Ruslan Baratov
#
# Licensed under the MIT License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://opensource.org/licenses/MIT
#
# 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.
@PACKAGE_INIT@
find_package(Threads REQUIRED)
include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake")
check_required_components("@PROJECT_NAME@")
@@ -1,4 +0,0 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake")
check_required_components("@PROJECT_NAME@")
-16
View File
@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="515px" height="315px" viewBox="0 0 515 315" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 47.1 (45422) - http://www.bohemiancoding.com/sketch -->
<title>Artboard Copy</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round">
<g id="Artboard-Copy" stroke-width="3">
<g id="Group" transform="translate(55.000000, 70.000000)">
<polyline id="Path-4" stroke="#F3A530" points="7.5 118.5 48.5 44.5 191.5 170 355 87"></polyline>
<polyline id="Path-5" stroke="#30499B" points="0.5 62 113 160.5 355 0"></polyline>
<polyline id="Path-6" stroke="#4CB2D4" points="42 146.5 194 39 406 175.5"></polyline>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 968 B

@@ -1,318 +0,0 @@
#ifndef STATSD_CLIENT_HPP
#define STATSD_CLIENT_HPP
#include <cpp-statsd-client/UDPSender.hpp>
#include <cstdint>
#include <cstdio>
#include <iomanip>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <vector>
namespace Statsd {
/*!
*
* Statsd client
*
* This is the Statsd client, exposing the classic methods
* and relying on a UDP sender for the actual sending.
*
* The prefix for a stat is provided once at construction or
* on reconfiguring the client. The separator character '.'
* is automatically inserted between the prefix and the stats
* key, therefore you should neither append one to the prefix
* nor prepend one to the key
*
* The sampling frequency is specified per call and uses a
* random number generator to determine whether or not the stat
* will be recorded this time or not.
*
* The top level configuration includes 2 optional parameters
* that determine how the stats are delivered to statsd. These
* parameters are the batching size and the send interval.
*
* The batching size controls the number of bytes to send
* in each UDP datagram to statsd. This is not a hard limit as
* we continue appending to a batch of stats until the limit
* has been reached or surpassed. When this occurs we add the
* batch to a queue and create a new batch to appended to. A
* value of 0 for the batching size will disable batching such
* that each stat will be sent to the daemon individually.
*
* The send interval controls the rate at which queued batches
* of stats will be sent to statsd. If batching is disabled,
* this value is ignored and each individual stat is sent to
* statsd immediately in a blocking fashion. If batching is
* enabled (ie. non-zero) then the send interval is the number
* of milliseconds to wait before flushing the queue of
* batched stats messages to the daemon. This is done in a non-
* blocking fashion via a background thread. If the send
* interval is 0 then the stats messages are appended to a
* queue until the caller manually flushes the queue via the
* flush method.
*
*/
class StatsdClient {
public:
//!@name Constructor and destructor, non-copyable
//!@{
//! Constructor
StatsdClient(const std::string& host,
const uint16_t port,
const std::string& prefix,
const uint64_t batchsize = 0,
const uint64_t sendInterval = 1000,
const unsigned int gaugePrecision = 4) noexcept;
StatsdClient(const StatsdClient&) = delete;
StatsdClient& operator=(const StatsdClient&) = delete;
//!@}
//!@name Methods
//!@{
//! Sets a configuration { host, port, prefix, batchsize }
void setConfig(const std::string& host,
const uint16_t port,
const std::string& prefix,
const uint64_t batchsize = 0,
const uint64_t sendInterval = 1000,
const unsigned int gaugePrecision = 4) noexcept;
//! Returns the error message as an std::string
const std::string& errorMessage() const noexcept;
//! Increments the key, at a given frequency rate
void increment(const std::string& key,
float frequency = 1.0f,
const std::vector<std::string>& tags = {}) const noexcept;
//! Increments the key, at a given frequency rate
void decrement(const std::string& key,
float frequency = 1.0f,
const std::vector<std::string>& tags = {}) const noexcept;
//! Adjusts the specified key by a given delta, at a given frequency rate
void count(const std::string& key,
const int delta,
float frequency = 1.0f,
const std::vector<std::string>& tags = {}) const noexcept;
//! Records a gauge for the key, with a given value, at a given frequency rate
template <typename T>
void gauge(const std::string& key,
const T value,
float frequency = 1.0f,
const std::vector<std::string>& tags = {}) const noexcept;
//! Records a timing for a key, at a given frequency
void timing(const std::string& key,
const unsigned int ms,
float frequency = 1.0f,
const std::vector<std::string>& tags = {}) const noexcept;
//! Records a count of unique occurrences for a key, at a given frequency
void set(const std::string& key,
const unsigned int sum,
float frequency = 1.0f,
const std::vector<std::string>& tags = {}) const noexcept;
//! Seed the RNG that controls sampling
void seed(unsigned int seed = std::random_device()()) noexcept;
//! Flush any queued stats to the daemon
void flush() noexcept;
//!@}
private:
// @name Private methods
// @{
//! Send a value for a key, according to its type, at a given frequency
template <typename T>
void send(const std::string& key,
const T value,
const char* type,
float frequency,
const std::vector<std::string>& tags) const noexcept;
//!@}
private:
//! The prefix to be used for metrics
std::string m_prefix;
//! The UDP sender to be used for actual sending
std::unique_ptr<UDPSender> m_sender;
//! The random number generator for handling sampling
mutable std::mt19937 m_randomEngine;
//! The buffer string format our stats before sending them
mutable std::string m_buffer;
//! Fixed floating point precision of gauges
unsigned int m_gaugePrecision;
};
namespace detail {
inline std::string sanitizePrefix(std::string prefix) {
// For convenience we provide the dot when generating the stat message
if (!prefix.empty() && prefix.back() == '.') {
prefix.pop_back();
}
return prefix;
}
// All supported metric types
constexpr char METRIC_TYPE_COUNT[] = "c";
constexpr char METRIC_TYPE_GAUGE[] = "g";
constexpr char METRIC_TYPE_TIMING[] = "ms";
constexpr char METRIC_TYPE_SET[] = "s";
} // namespace detail
inline StatsdClient::StatsdClient(const std::string& host,
const uint16_t port,
const std::string& prefix,
const uint64_t batchsize,
const uint64_t sendInterval,
const unsigned int gaugePrecision) noexcept
: m_prefix(detail::sanitizePrefix(prefix)),
m_sender(new UDPSender{host, port, batchsize, sendInterval}),
m_gaugePrecision(gaugePrecision) {
// Initialize the random generator to be used for sampling
seed();
// Avoid re-allocations by reserving a generous buffer
m_buffer.reserve(256);
}
inline void StatsdClient::setConfig(const std::string& host,
const uint16_t port,
const std::string& prefix,
const uint64_t batchsize,
const uint64_t sendInterval,
const unsigned int gaugePrecision) noexcept {
m_prefix = detail::sanitizePrefix(prefix);
m_sender.reset(new UDPSender(host, port, batchsize, sendInterval));
m_gaugePrecision = gaugePrecision;
}
inline const std::string& StatsdClient::errorMessage() const noexcept {
return m_sender->errorMessage();
}
inline void StatsdClient::decrement(const std::string& key,
float frequency,
const std::vector<std::string>& tags) const noexcept {
count(key, -1, frequency, tags);
}
inline void StatsdClient::increment(const std::string& key,
float frequency,
const std::vector<std::string>& tags) const noexcept {
count(key, 1, frequency, tags);
}
inline void StatsdClient::count(const std::string& key,
const int delta,
float frequency,
const std::vector<std::string>& tags) const noexcept {
send(key, delta, detail::METRIC_TYPE_COUNT, frequency, tags);
}
template <typename T>
inline void StatsdClient::gauge(const std::string& key,
const T value,
const float frequency,
const std::vector<std::string>& tags) const noexcept {
send(key, value, detail::METRIC_TYPE_GAUGE, frequency, tags);
}
inline void StatsdClient::timing(const std::string& key,
const unsigned int ms,
float frequency,
const std::vector<std::string>& tags) const noexcept {
send(key, ms, detail::METRIC_TYPE_TIMING, frequency, tags);
}
inline void StatsdClient::set(const std::string& key,
const unsigned int sum,
float frequency,
const std::vector<std::string>& tags) const noexcept {
send(key, sum, detail::METRIC_TYPE_SET, frequency, tags);
}
template <typename T>
inline void StatsdClient::send(const std::string& key,
const T value,
const char* type,
float frequency,
const std::vector<std::string>& tags) const noexcept {
// Bail if we can't send anything anyway
if (!m_sender->initialized()) {
return;
}
// A valid frequency is: 0 <= f <= 1
// At 0 you never emit the stat, at 1 you always emit the stat and with anything else you roll the dice
frequency = std::max(std::min(frequency, 1.f), 0.f);
constexpr float epsilon{0.0001f};
const bool isFrequencyOne = std::fabs(frequency - 1.0f) < epsilon;
const bool isFrequencyZero = std::fabs(frequency) < epsilon;
if (isFrequencyZero ||
(!isFrequencyOne && (frequency < std::uniform_real_distribution<float>(0.f, 1.f)(m_randomEngine)))) {
return;
}
// Format the stat message
std::stringstream valueStream;
valueStream << std::fixed << std::setprecision(m_gaugePrecision) << value;
m_buffer.clear();
m_buffer.append(m_prefix);
if (!m_prefix.empty() && !key.empty()) {
m_buffer.push_back('.');
}
m_buffer.append(key);
m_buffer.push_back(':');
m_buffer.append(valueStream.str());
m_buffer.push_back('|');
m_buffer.append(type);
if (frequency < 1.f) {
m_buffer.append("|@0.");
m_buffer.append(std::to_string(static_cast<int>(frequency * 100)));
}
if (!tags.empty()) {
m_buffer.append("|#");
for (const auto& tag : tags) {
m_buffer.append(tag);
m_buffer.push_back(',');
}
m_buffer.pop_back();
}
// Send the message via the UDP sender
m_sender->send(m_buffer);
}
inline void StatsdClient::seed(unsigned int seed) noexcept {
m_randomEngine.seed(seed);
}
inline void StatsdClient::flush() noexcept {
m_sender->flush();
}
} // namespace Statsd
#endif
@@ -1,345 +0,0 @@
#ifndef UDP_SENDER_HPP
#define UDP_SENDER_HPP
#ifdef _WIN32
#define NOMINMAX
#include <io.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <atomic>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
namespace Statsd {
#ifdef _WIN32
using SOCKET_TYPE = SOCKET;
constexpr SOCKET_TYPE k_invalidSocket{INVALID_SOCKET};
#define SOCKET_ERRNO WSAGetLastError()
#define SOCKET_CLOSE closesocket
#else
using SOCKET_TYPE = int;
constexpr SOCKET_TYPE k_invalidSocket{-1};
#define SOCKET_ERRNO errno
#define SOCKET_CLOSE close
#endif
/*!
*
* UDP sender
*
* A simple UDP sender handling batching.
*
*/
class UDPSender final {
public:
//!@name Constructor and destructor, non-copyable
//!@{
//! Constructor
UDPSender(const std::string& host,
const uint16_t port,
const uint64_t batchsize,
const uint64_t sendInterval) noexcept;
//! Destructor
~UDPSender();
UDPSender(const UDPSender&) = delete;
UDPSender& operator=(const UDPSender&) = delete;
UDPSender(UDPSender&&) = delete;
//!@}
//!@name Methods
//!@{
//! Send or enqueue a message
void send(const std::string& message) noexcept;
//! Returns the error message as a string
const std::string& errorMessage() const noexcept;
//! Returns true if the sender is initialized
bool initialized() const noexcept;
//! Flushes any queued messages
void flush() noexcept;
//!@}
private:
// @name Private methods
// @{
//! Initialize the sender and returns true when it is initialized
bool initialize() noexcept;
//! Queue a message to be sent to the daemon later
inline void queueMessage(const std::string& message) noexcept;
//! Send a message to the daemon
void sendToDaemon(const std::string& message) noexcept;
//!@}
private:
// @name State variables
// @{
//! Shall we exit?
std::atomic<bool> m_mustExit{false};
//!@}
// @name Network info
// @{
//! The hostname
std::string m_host;
//! The port
uint16_t m_port;
//! The structure holding the server
struct sockaddr_in m_server;
//! The socket to be used
SOCKET_TYPE m_socket = k_invalidSocket;
//!@}
// @name Batching info
// @{
//! The batching size
uint64_t m_batchsize;
//! The sending frequency in milliseconds
uint64_t m_sendInterval;
//! The queue batching the messages
std::deque<std::string> m_batchingMessageQueue;
//! The mutex used for batching
std::mutex m_batchingMutex;
//! The thread dedicated to the batching
std::thread m_batchingThread;
//!@}
//! Error message (optional string)
std::string m_errorMessage;
};
namespace detail {
inline bool isValidSocket(const SOCKET_TYPE socket) {
return socket != k_invalidSocket;
}
#ifdef _WIN32
struct WinSockSingleton {
inline static const WinSockSingleton& getInstance() {
static const WinSockSingleton instance;
return instance;
}
inline bool ok() const {
return m_ok;
}
~WinSockSingleton() {
WSACleanup();
}
private:
WinSockSingleton() {
WSADATA wsa;
m_ok = WSAStartup(MAKEWORD(2, 2), &wsa) == 0;
}
bool m_ok;
};
#endif
} // namespace detail
inline UDPSender::UDPSender(const std::string& host,
const uint16_t port,
const uint64_t batchsize,
const uint64_t sendInterval) noexcept
: m_host(host), m_port(port), m_batchsize(batchsize), m_sendInterval(sendInterval) {
// Initialize the socket
if (!initialize()) {
return;
}
// If batching is on, use a dedicated thread to send after the wait time is reached
if (m_batchsize != 0 && m_sendInterval > 0) {
// Define the batching thread
m_batchingThread = std::thread([this] {
// TODO: this will drop unsent stats, should we send all the unsent stats before we exit?
while (!m_mustExit.load(std::memory_order_acquire)) {
std::deque<std::string> stagedMessageQueue;
std::unique_lock<std::mutex> batchingLock(m_batchingMutex);
m_batchingMessageQueue.swap(stagedMessageQueue);
batchingLock.unlock();
// Flush the queue
while (!stagedMessageQueue.empty()) {
sendToDaemon(stagedMessageQueue.front());
stagedMessageQueue.pop_front();
}
// Wait before sending the next batch
std::this_thread::sleep_for(std::chrono::milliseconds(m_sendInterval));
}
});
}
}
inline UDPSender::~UDPSender() {
if (!initialized()) {
return;
}
// If we're running a background thread tell it to stop
if (m_batchingThread.joinable()) {
m_mustExit.store(true, std::memory_order_release);
m_batchingThread.join();
}
// Cleanup the socket
SOCKET_CLOSE(m_socket);
}
inline void UDPSender::send(const std::string& message) noexcept {
m_errorMessage.clear();
// If batching is on, accumulate messages in the queue
if (m_batchsize > 0) {
queueMessage(message);
return;
}
// Or send it right now
sendToDaemon(message);
}
inline void UDPSender::queueMessage(const std::string& message) noexcept {
// We aquire a lock but only if we actually need to (i.e. there is a thread also accessing the queue)
auto batchingLock =
m_batchingThread.joinable() ? std::unique_lock<std::mutex>(m_batchingMutex) : std::unique_lock<std::mutex>();
// Either we don't have a place to batch our message or we exceeded the batch size, so make a new batch
if (m_batchingMessageQueue.empty() || m_batchingMessageQueue.back().length() > m_batchsize) {
m_batchingMessageQueue.emplace_back();
m_batchingMessageQueue.back().reserve(m_batchsize + 256);
} // When there is already a batch open we need a separator when its not empty
else if (!m_batchingMessageQueue.back().empty()) {
m_batchingMessageQueue.back().push_back('\n');
}
// Add the new message to the batch
m_batchingMessageQueue.back().append(message);
}
inline const std::string& UDPSender::errorMessage() const noexcept {
return m_errorMessage;
}
inline bool UDPSender::initialize() noexcept {
#ifdef _WIN32
if (!detail::WinSockSingleton::getInstance().ok()) {
m_errorMessage = "WSAStartup failed: errno=" + std::to_string(SOCKET_ERRNO);
}
#endif
// Connect the socket
m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (!detail::isValidSocket(m_socket)) {
m_errorMessage = "socket creation failed: errno=" + std::to_string(SOCKET_ERRNO);
return false;
}
std::memset(&m_server, 0, sizeof(m_server));
m_server.sin_family = AF_INET;
m_server.sin_port = htons(m_port);
if (inet_pton(AF_INET, m_host.c_str(), &m_server.sin_addr) == 0) {
// An error code has been returned by inet_aton
// Specify the criteria for selecting the socket address structure
struct addrinfo hints;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM;
// Get the address info using the hints
struct addrinfo* results = nullptr;
const int ret{getaddrinfo(m_host.c_str(), nullptr, &hints, &results)};
if (ret != 0) {
// An error code has been returned by getaddrinfo
SOCKET_CLOSE(m_socket);
m_socket = k_invalidSocket;
m_errorMessage = "getaddrinfo failed: err=" + std::to_string(ret) + ", msg=" + gai_strerror(ret);
return false;
}
// Copy the results in m_server
struct sockaddr_in* host_addr = (struct sockaddr_in*)results->ai_addr;
std::memcpy(&m_server.sin_addr, &host_addr->sin_addr, sizeof(struct in_addr));
// Free the memory allocated
freeaddrinfo(results);
}
return true;
}
inline void UDPSender::sendToDaemon(const std::string& message) noexcept {
// Try sending the message
const auto ret = sendto(m_socket,
message.data(),
#ifdef _WIN32
static_cast<int>(message.size()),
#else
message.size(),
#endif
0,
(struct sockaddr*)&m_server,
sizeof(m_server));
if (ret == -1) {
m_errorMessage = "sendto server failed: host=" + m_host + ":" + std::to_string(m_port) +
", err=" + std::to_string(SOCKET_ERRNO);
}
}
inline bool UDPSender::initialized() const noexcept {
return m_socket != k_invalidSocket;
}
inline void UDPSender::flush() noexcept {
// We aquire a lock but only if we actually need to (ie there is a thread also accessing the queue)
auto batchingLock =
m_batchingThread.joinable() ? std::unique_lock<std::mutex>(m_batchingMutex) : std::unique_lock<std::mutex>();
// Flush the queue
while (!m_batchingMessageQueue.empty()) {
sendToDaemon(m_batchingMessageQueue.front());
m_batchingMessageQueue.pop_front();
}
}
} // namespace Statsd
#endif
-80
View File
@@ -1,80 +0,0 @@
#ifndef STATSD_SERVER_HPP
#define STATSD_SERVER_HPP
// It might make sense to include this test class in the UDPSender header
// it includes most of the cross platform defines etc that we need for socket io
#include "cpp-statsd-client/UDPSender.hpp"
#include <algorithm>
#include <string>
namespace Statsd {
class StatsdServer {
public:
StatsdServer(unsigned short port = 8125) noexcept {
#ifdef _WIN32
if (!detail::WinSockSingleton::getInstance().ok()) {
m_errorMessage = "WSAStartup failed: errno=" + std::to_string(SOCKET_ERRNO);
}
#endif
// Create the socket
m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (!detail::isValidSocket(m_socket)) {
m_errorMessage = "socket creation failed: errno=" + std::to_string(SOCKET_ERRNO);
return;
}
// Binding should be with ipv4 to all interfaces
struct sockaddr_in address {};
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;
// Try to bind
if (bind(m_socket, reinterpret_cast<const struct sockaddr*>(&address), sizeof(address)) != 0) {
SOCKET_CLOSE(m_socket);
m_socket = k_invalidSocket;
m_errorMessage = "bind failed: errno=" + std::to_string(SOCKET_ERRNO);
}
}
~StatsdServer() {
if (detail::isValidSocket(m_socket)) {
SOCKET_CLOSE(m_socket);
}
}
const std::string& errorMessage() const noexcept {
return m_errorMessage;
}
std::string receive() noexcept {
// If uninitialized then bail
if (!detail::isValidSocket(m_socket)) {
return "";
}
// Try to receive (this is blocking)
std::string buffer(256, '\0');
int string_len;
if ((string_len = recv(m_socket, &buffer[0], static_cast<int>(buffer.size()), 0)) < 1) {
m_errorMessage = "Could not recv on the socket file descriptor";
return "";
}
// No error return the trimmed result
m_errorMessage.clear();
buffer.resize(std::min(static_cast<size_t>(string_len), buffer.size()));
return buffer;
}
private:
SOCKET_TYPE m_socket;
std::string m_errorMessage;
};
} // namespace Statsd
#endif
-184
View File
@@ -1,184 +0,0 @@
#include <iostream>
#include "StatsdServer.hpp"
#include "cpp-statsd-client/StatsdClient.hpp"
using namespace Statsd;
// Each test suite below spawns a thread to recv the client messages over UDP as if it were a real statsd server
// Note that we could just synchronously recv metrics and not use a thread but doing the test async has the
// advantage that we can test the threaded batching mode in a straightforward way. The server thread basically
// just keeps storing metrics in an vector until it hears a special one signaling the test is over and bails
void mock(StatsdServer& server, std::vector<std::string>& messages) {
do {
// Grab the messages that are waiting
auto recvd = server.receive();
// Split the messages on '\n'
auto start = std::string::npos;
do {
// Keep this message
auto end = recvd.find('\n', ++start);
messages.emplace_back(recvd.substr(start, end));
start = end;
// Bail if we found the special quit message
if (messages.back().find("DONE") != std::string::npos) {
messages.pop_back();
return;
}
} while (start != std::string::npos);
} while (server.errorMessage().empty() && !messages.back().empty());
}
template <typename SocketWrapper>
void throwOnError(const SocketWrapper& wrapped, bool expectEmpty = true, const std::string& extraMessage = "") {
if (wrapped.errorMessage().empty() != expectEmpty) {
std::cerr << (expectEmpty ? wrapped.errorMessage() : extraMessage) << std::endl;
throw std::runtime_error(expectEmpty ? wrapped.errorMessage() : extraMessage);
}
}
void throwOnWrongMessage(StatsdServer& server, const std::string& expected) {
auto actual = server.receive();
if (actual != expected) {
std::cerr << "Expected: " << expected << " but got: " << actual << std::endl;
throw std::runtime_error("Incorrect stat received");
}
}
void testErrorConditions() {
// Resolve a rubbish ip and make sure initialization failed
StatsdClient client{"256.256.256.256", 8125, "myPrefix", 20};
throwOnError(client, false, "Should not be able to resolve a ridiculous ip");
}
void testReconfigure() {
StatsdServer server;
throwOnError(server);
StatsdClient client("localhost", 8125, "first.");
client.increment("foo");
throwOnWrongMessage(server, "first.foo:1|c");
client.setConfig("localhost", 8125, "second");
client.increment("bar");
throwOnWrongMessage(server, "second.bar:1|c");
client.setConfig("localhost", 8125, "");
client.increment("third.baz");
throwOnWrongMessage(server, "third.baz:1|c");
client.increment("");
throwOnWrongMessage(server, ":1|c");
// TODO: test what happens with the batching after resolving the question about incomplete
// batches being dropped vs sent on reconfiguring
}
void testSendRecv(uint64_t batchSize, uint64_t sendInterval) {
StatsdServer mock_server;
std::vector<std::string> messages, expected;
std::thread server(mock, std::ref(mock_server), std::ref(messages));
// Set a new config that has the client send messages to a proper address that can be resolved
StatsdClient client("localhost", 8125, "sendRecv.", batchSize, sendInterval, 3);
throwOnError(client);
// TODO: I forget if we need to wait for the server to be ready here before sending the first stats
// is there a race condition where the client sending before the server binds would drop that clients message
for (int i = 0; i < 3; ++i) {
// Increment "coco"
client.increment("coco");
throwOnError(client);
expected.emplace_back("sendRecv.coco:1|c");
// Decrement "kiki"
client.decrement("kiki");
throwOnError(client);
expected.emplace_back("sendRecv.kiki:-1|c");
// Adjusts "toto" by +2
client.seed(19); // this seed gets a hit on the first call
client.count("toto", 2, 0.1f);
throwOnError(client);
expected.emplace_back("sendRecv.toto:2|c|@0.10");
// Gets "sampled out" by the random number generator
client.count("popo", 9, 0.1f);
throwOnError(client);
// Record a gauge "titi" to 3
client.gauge("titi", 3);
throwOnError(client);
expected.emplace_back("sendRecv.titi:3|g");
// Record a gauge "titifloat" to -123.456789 with precision 3
client.gauge("titifloat", -123.456789);
throwOnError(client);
expected.emplace_back("sendRecv.titifloat:-123.457|g");
// Record a timing of 2ms for "myTiming"
client.seed(19);
client.timing("myTiming", 2, 0.1f);
throwOnError(client);
expected.emplace_back("sendRecv.myTiming:2|ms|@0.10");
// Send a set with 1227 total uniques
client.set("tutu", 1227, 2.0f);
throwOnError(client);
expected.emplace_back("sendRecv.tutu:1227|s");
// Gauge but with tags
client.gauge("dr.röstigrabe", 333, 1.f, {"liegt", "im", "weste"});
throwOnError(client);
expected.emplace_back("sendRecv.dr.röstigrabe:333|g|#liegt,im,weste");
// All the things
client.count("foo", -42, .9f, {"bar", "baz"});
throwOnError(client);
expected.emplace_back("sendRecv.foo:-42|c|@0.90|#bar,baz");
}
// Signal the mock server we are done
client.timing("DONE", 0);
// If manual flushing do it now
if (sendInterval == 0) {
client.flush();
}
// Wait for the server to stop
server.join();
// Make sure we get the exactly correct output
if (messages != expected) {
std::cerr << "Unexpected stats received by server, got:" << std::endl;
for (const auto& message : messages) {
std::cerr << message << std::endl;
}
std::cerr << std::endl << "But we expected:" << std::endl;
for (const auto& message : expected) {
std::cerr << message << std::endl;
}
throw std::runtime_error("Unexpected stats");
}
}
int main() {
// If any of these tests fail they throw an exception, not catching makes for a nonzero return code
// general things that should be errors
testErrorConditions();
// reconfiguring how you are sending
testReconfigure();
// no batching
testSendRecv(0, 0);
// background batching
testSendRecv(32, 1000);
// manual flushing of batches
testSendRecv(16, 0);
return EXIT_SUCCESS;
}
BIN
View File
Binary file not shown.
-3
View File
@@ -1,3 +0,0 @@
#pragma once
bool FValidKey(const char *key, size_t cch);
BIN
View File
Binary file not shown.
-1
Submodule deps/rocksdb deleted from 444b3f4845.
+5 -70
View File
@@ -184,9 +184,7 @@ tcp-keepalive 300
#
# tls-client-key-file-pass secret
# Configure a DH parameters file to enable Diffie-Hellman (DH) key exchange,
# required by older versions of OpenSSL (<3.0). Newer versions do not require
# this configuration and recommend against it.
# Configure a DH parameters file to enable Diffie-Hellman (DH) key exchange:
#
# tls-dh-params-file keydb.dh
@@ -259,24 +257,6 @@ tcp-keepalive 300
#
# tls-session-cache-timeout 60
# Allow the server to monitor the filesystem and rotate out TLS certificates if
# they change on disk, defaults to no.
#
# tls-rotation no
# Setup a allowlist of allowed Common Names (CNs)/Subject Alternative Names (SANs)
# that are allowed to connect to this server. This includes both normal clients as
# well as other servers connected for replication/clustering purposes. If nothing is
# specified, then no allowlist is used and all certificates are accepted.
# Supports IPv4, DNS, RFC822, and URI SAN types.
# You can put multiple names on one line as follows:
#
# tls-allowlist <dns1> <dns2> <dns3> ...
#
#
# This configuration also allows for wildcard characters with glob style formatting
# i.e. "*.com" would allow all clients to connect with a CN/SAN that ends with ".com"
################################# GENERAL #####################################
# By default KeyDB does not run as a daemon. Use 'yes' if you need it.
@@ -1145,11 +1125,6 @@ acllog-max-len 128
#
# active-expire-effort 1
# Force evictions when used system memory reaches X% of total system memory.
# This is useful as a safeguard to prevent OOM kills (0 to disable).
#
# force-eviction-percent 0
############################# LAZY FREEING ####################################
# KeyDB has two primitives to delete keys. One is called DEL and is a blocking
@@ -2060,49 +2035,9 @@ server-threads 2
# bringing up replicas can result in data loss (the first master will win).
# active-replica yes
# KeyDB will attempt to balance clients across threads evenly; However, replica clients
# are usually much more expensive than a normal client, and so KeyDB will try to assign
# fewer clients to threads with a replica. The weighting factor below is intented to help tune
# this behavior. A replica weighting factor of 2 means we treat a replica as the equivalent
# of two normal clients. Adjusting this value may improve performance when replication is
# used. The best weighting is workload specific - e.g. read heavy workloads should set
# this to 1. Very write heavy workloads may benefit from higher numbers.
#
# By default KeyDB sets this to 2.
replica-weighting-factor 2
# Enable Pro? KeyDB pro provides support for pro only features
# note: you may omit the license key to demo pro features for a limited time
# enable-pro [License Key]
# Should KeyDB make active attempts at balancing clients across threads? This can impact
# performance accepting new clients. By default this is enabled. If disabled there is still
# a best effort from the kernel to distribute across threads with SO_REUSEPORT but it will not
# be as fair.
#
# By default this is enabled
#
active-client-balancing yes
# Enable FLASH support (Experimental Feature)
# Enable FLASH support? (Pro Only)
# storage-provider flash /path/to/flash/db
# Blob support is a way to store very large objects (>200MB) on disk
# The files are automatically cleaned up when KeyDB exits and are only
# for temporary use. This helps reduce memory pressure for very large
# data items at the cost of some performance.
#
# By default this config is disable. When enabled the disk associated
# with KeyDB's working directory will be used. If there is insufficient
# disk space or any other I/O error KeyDB will instead use memory.
#
# blob-support false
# Begin load shedding if we use more than X% CPU relative to the number of server threads
# E.g. if overload-protect-percent is set to 80 and there are 8 server-threads, then the
# actual CPU protection will be 8 * 100 * 0.80 = 640% CPU usage.
#
# Set to 0 to disable
# overload-protect-percent 0
# Inform KeyDB of the availability zone if running in a cloud environment. Currently
# this is only exposed via the info command for clients to use, but in the future we
# we may also use this when making decisions for replication.
#
# availability-zone "us-east-1a"
-114
View File
@@ -1,114 +0,0 @@
FROM ubuntu:20.04
SHELL ["/bin/bash","-c"]
RUN groupadd -r keydb && useradd -r -g keydb keydb
# use gosu for easy step-down from root: https://github.com/tianon/gosu/releases
ENV GOSU_VERSION 1.14
RUN set -eux; \
savedAptMark="$(apt-mark showmanual)"; \
apt-get update; \
apt-get -o Dpkg::Options::="--force-confnew" install -y --no-install-recommends ca-certificates dirmngr gnupg wget; \
rm -rf /var/lib/apt/lists/*; \
dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \
wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \
wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \
export GNUPGHOME="$(mktemp -d)"; \
gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4; \
gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \
gpgconf --kill all; \
rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \
apt-mark auto '.*' > /dev/null; \
[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
chmod +x /usr/local/bin/gosu; \
gosu --version; \
gosu nobody true
# build KeyDB
ARG MAKE_JOBS=""
ARG ENABLE_FLASH=""
COPY . /tmp/keydb-internal
RUN set -eux; \
cd /tmp/keydb-internal; \
savedAptMark="$(apt-mark showmanual)"; \
apt-get update; \
DEBIAN_FRONTEND=noninteractive apt-get -o Dpkg::Options::="--force-confnew" install -qqy --no-install-recommends \
dpkg-dev \
pkg-config \
ca-certificates \
build-essential \
nasm \
autotools-dev \
autoconf \
libjemalloc-dev \
tcl \
tcl-dev \
uuid-dev \
libcurl4-openssl-dev \
libbz2-dev \
libzstd-dev \
liblz4-dev \
libsnappy-dev \
libssl-dev \
git; \
# disable protected mode as it relates to docker
grep -E '^ *createBoolConfig[(]"protected-mode",.*, *1 *,.*[)],$' ./src/config.cpp; \
sed -ri 's!^( *createBoolConfig[(]"protected-mode",.*, *)1( *,.*[)],)$!\10\2!' ./src/config.cpp; \
grep -E '^ *createBoolConfig[(]"protected-mode",.*, *0 *,.*[)],$' ./src/config.cpp; \
make distclean; \
make -j$([ -z "$MAKE_JOBS" ] && nproc || echo "$MAKE_JOBS") BUILD_TLS=yes NO_LICENSE_CHECK=yes $([ -z "$ENABLE_FLASH" ] && echo "" || echo "ENABLE_FLASH=$ENABLE_FLASH"); \
cd src; \
mv modules/keydb_modstatsd/modstatsd.so /usr/local/lib/; \
strip keydb-cli keydb-benchmark keydb-check-rdb keydb-check-aof keydb-diagnostic-tool keydb-sentinel; \
mv keydb-server keydb-cli keydb-benchmark keydb-check-rdb keydb-check-aof keydb-diagnostic-tool keydb-sentinel /usr/local/bin/; \
# clean up unused dependencies
echo $savedAptMark; \
apt-mark auto '.*' > /dev/null; \
[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
find /usr/local -type f -executable -exec ldd '{}' ';' \
| awk '/=>/ { print $(NF-1) }' \
| sed 's:.*/::' \
| sort -u \
| xargs -r dpkg-query --search \
| cut -d: -f1 \
| sort -u \
| xargs -r apt-mark manual \
; \
apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
rm -rf /var/lib/apt/lists/*; \
# create working directories and organize files
RUN \
mkdir /data && chown keydb:keydb /data; \
mkdir /flash && chown keydb:keydb /flash; \
mkdir -p /etc/keydb; \
cp /tmp/keydb-internal/keydb.conf /etc/keydb/; \
sed -i 's/^\(daemonize .*\)$/# \1/' /etc/keydb/keydb.conf; \
sed -i 's/^\(dir .*\)$/# \1\ndir \/data/' /etc/keydb/keydb.conf; \
sed -i 's/^\(logfile .*\)$/# \1/' /etc/keydb/keydb.conf; \
sed -i 's/protected-mode yes/protected-mode no/g' /etc/keydb/keydb.conf; \
sed -i 's/^\(bind .*\)$/# \1/' /etc/keydb/keydb.conf; \
echo -e "\nloadmodule /usr/local/lib/modstatsd.so" >> /etc/keydb/keydb.conf; \
ln -s keydb-cli redis-cli; \
cd /etc/keydb; \
ln -s keydb.conf redis.conf; \
rm -rf /tmp/*
# generate entrypoint script
RUN set -eux; \
echo '#!/bin/sh' > /usr/local/bin/docker-entrypoint.sh; \
echo 'set -e' >> /usr/local/bin/docker-entrypoint.sh; \
echo "# perpend 'keydb-server' if not provided as first argument" >> /usr/local/bin/docker-entrypoint.sh; \
echo 'if [ "${1}" != "keydb-server" ]; then' >> /usr/local/bin/docker-entrypoint.sh; \
echo ' set -- keydb-server "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'fi' >> /usr/local/bin/docker-entrypoint.sh; \
echo "# allow the container to be started with `--user`" >> /usr/local/bin/docker-entrypoint.sh; \
echo 'if [ "$1" = "keydb-server" -a "$(id -u)" = "0" ]; then' >> /usr/local/bin/docker-entrypoint.sh; \
echo " find . \! -user keydb -exec chown keydb '{}' +" >> /usr/local/bin/docker-entrypoint.sh; \
echo ' exec gosu keydb "$0" "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'fi' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'exec "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
chmod +x /usr/local/bin/docker-entrypoint.sh
# set remaining image properties
VOLUME /data
WORKDIR /data
ENV KEYDB_PRO_DIRECTORY=/usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
EXPOSE 6379
CMD ["keydb-server","/etc/keydb/keydb.conf"]
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash
# make the build
git submodule init && git submodule update
make BUILD_TLS=yes ENABLE_FLASH=yes -j$(nproc) KEYDB_CFLAGS='-Werror' KEYDB_CXXFLAGS='-Werror'
# gen-cert
./utils/gen-test-certs.sh
-283
View File
@@ -1,283 +0,0 @@
import random
import time
import socket
import asyncore
import threading
import argparse
from pprint import pprint
# Globals
ops = {}
numclients = 0
numkeys = 0
runtime = 0
clients = []
def _buildResp(*args):
result = "*" + str(len(args)) + "\r\n"
for v in args:
result = result + "$" + str(len(v)) + "\r\n"
result = result + v + "\r\n"
return result.encode('utf-8')
class Client(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
self.buf = b''
self.inbuf = b''
self.callbacks = list()
self.client_id = 0
self.get_client_id()
def handle_connect(self):
pass
def handle_read(self):
self.inbuf += self.recv(8192)
self.parse_response()
def handle_write(self):
sent = self.send(self.buf)
self.buf = self.buf[sent:]
def handle_close(self):
self.close()
def writable(self):
return len(self.buf) > 0
def parse_array(self, startpos):
assert(self.inbuf[startpos] == ord('*'))
endrange = self.inbuf[startpos+1:].find(ord('\r')) + 1 + startpos
assert(endrange > 0)
numargs = int(self.inbuf[startpos+1:endrange])
if numargs == -1: # Nil array, used in some returns
startpos = endrange + 2
return startpos, []
assert(numargs > 0)
args = list()
startpos = endrange + 2 # plus 1 gets us to the '\n' and the next gets us to the start char
while len(args) < numargs:
# We're parsing entries of the form "$N\r\nnnnnnn\r\n"
if startpos >= len(self.inbuf):
return # Not the full response
if self.inbuf[startpos] == ord('*'):
startpos, arr = self.parse_array(startpos)
args.append(arr)
else:
assert(self.inbuf[startpos] == ord('$'))
startpos = startpos + 1
endrange = self.inbuf[startpos:].find(b'\r')
if endrange < 0:
return
endrange += startpos
assert(endrange <= len(self.inbuf))
length = int(self.inbuf[startpos:endrange])
if length < 0:
return
startpos = endrange + 2
assert((startpos + length) <= len(self.inbuf))
assert(self.inbuf[startpos+length] == ord('\r'))
assert(self.inbuf[startpos+length+1] == ord('\n'))
args.append(self.inbuf[startpos:(startpos+length)])
startpos += length + 2
assert(len(args) == numargs)
return startpos, args
def parse_response(self):
if len(self.inbuf) == 0:
return
while len(self.inbuf) > 0:
if self.inbuf[0] == ord('+') or self.inbuf[0] == ord('-') or self.inbuf[0] == ord(':'):
# This is a single line response
endpos = self.inbuf.find(b'\n')
if endpos < 0:
return # incomplete response
self.callbacks[0](self, self.inbuf[0:endpos-1])
self.callbacks.pop(0)
self.inbuf = self.inbuf[endpos+1:]
elif self.inbuf[0] == ord('*'):
#RESP response
try:
startpos, args = self.parse_array(0)
except:
return # Not all data here yet
self.callbacks[0](self, args)
self.callbacks.pop(0)
self.inbuf = self.inbuf[startpos:]
else:
print("ERROR: Unknown response:")
pprint(self.inbuf)
assert(False)
def default_result_handler(self, result):
pprint(result)
# Public Methods
def set(self, key, val, callback = default_result_handler):
self.buf += _buildResp("set", key, val)
self.callbacks.append(callback)
def lpush(self, key, val, callback = default_result_handler):
self.buf += _buildResp("lpush", key, val)
self.callbacks.append(callback)
def blpop(self, *keys, timeout=0, callback=default_result_handler):
self.buf += _buildResp("blpop", *keys, str(timeout))
self.callbacks.append(callback)
def delete(self, key, callback = default_result_handler):
self.buf += _buildResp("del", key)
self.callbacks.append(callback)
def unblock(self, client_id, callback=default_result_handler):
self.buf += _buildResp("client", "unblock", str(client_id))
self.callbacks.append(callback)
def scan(self, iter, match=None, count=None, callback = default_result_handler):
args = ["scan", str(iter)]
if match != None:
args.append("MATCH")
args.append(match)
if count != None:
args.append("COUNT")
args.append(str(count))
self.buf += _buildResp(*args)
self.callbacks.append(callback)
def get_client_id(self):
self.buf += _buildResp("client", "id")
self.callbacks.append(self.store_client_id)
def store_client_id(self, c, resp):
assert(resp[0] == ord(':'))
self.client_id = int(resp[1:])
assert(self.client_id == c.client_id)
def get(self, key, callback = None):
return
def getrandomkey():
return str(random.randrange(0, numkeys))
def handle_lpush_response(c, resp=None):
global ops
if resp != None:
ops['lpush'] += 1
assert(resp[0] == ord(':'))
c.lpush("list_" + getrandomkey(), 'bardsklfjkldsjfdlsjflksdfjklsdjflksd kldsjflksd jlkdsjf lksdjklds jrfklsdjfklsdjfkl', handle_lpush_response)
def handle_blpop_response(c, resp=None):
global ops
if resp != None:
ops['blpop'] += 1
c.blpop("list_" + getrandomkey(), callback=handle_blpop_response)
def handle_set_response(c, resp=None):
global ops
if resp != None:
ops['set'] += 1
assert(resp[0] == ord('+'))
c.set("str_" + getrandomkey(), 'bardsklfjkldsjfdlsjflksdfjklsdjflksd kldsjflksd jlkdsjf lksdjklds jrfklsdjfklsdjfkl', handle_set_response)
def handle_del_response(c, resp=None):
global ops
if resp != None:
ops['del'] += 1
c.delete("list_" + getrandomkey(), handle_del_response)
def scan_callback(c, resp=None):
global ops
nextstart = int(resp[0])
c.scan(nextstart, count=500, callback=scan_callback)
ops['scan'] += 1
def clear_ops():
global ops
ops = {'lpush': 0, 'blpop': 0, 'del': 0, 'scan': 0, 'set': 0, 'get': 0}
def stats_thread():
global ops
global runtime
i = 0
while i < runtime or not runtime:
time.sleep(1)
print("Ops per second: " + str({k:v for (k,v) in ops.items() if v}))
clear_ops()
i += 1
asyncore.close_all()
def flush_db_sync():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect(('127.0.0.1', 6379))
server.send(_buildResp("flushdb"))
resp = server.recv(8192)
assert(resp[:3] == "+OK".encode('utf-8'))
def init_blocking():
global clients
if numkeys > 100 * numclients:
print("WARNING: High ratio of keys to clients. Most lpushes will not be popped and unblocking will take a long time!")
for i in range(numclients):
clients.append(Client('127.0.0.1', 6379))
if i % 2:
handle_blpop_response(clients[-1])
else:
handle_lpush_response(clients[-1])
def init_lpush():
global clients
for i in range(numclients):
clients.append(Client('127.0.0.1', 6379))
for i in range (10):
handle_lpush_response(clients[-1])
#handle_set_response(clients[-1], None)
scan_client = Client('127.0.0.1', 6379)
scan_client.scan(0, count=500, callback=scan_callback)
del_client = Client('127.0.0.1', 6379)
handle_del_response(del_client)
def main(test, flush):
clear_ops()
if flush:
flush_db_sync()
try:
globals()[f"init_{test}"]()
except KeyError:
print(f"Test \"{test}\" not found. Exiting...")
exit()
except ConnectionRefusedError:
print("Could not connect to server. Is it running?")
print("Exiting...")
exit()
threading.Thread(target=stats_thread).start()
asyncore.loop()
print("Done.")
parser = argparse.ArgumentParser(description="Test use cases for KeyDB.")
parser.add_argument('test', choices=[x[5:] for x in filter(lambda name: name.startswith("init_"), globals().keys())], help="which test to run")
parser.add_argument('-c', '--clients', type=int, default=50, help="number of running clients to use")
parser.add_argument('-k', '--keys', type=int, default=100000, help="number of keys to choose from for random tests")
parser.add_argument('-t', '--runtime', type=int, default=0, help="how long to run the test for (default: 0 for infinite)")
parser.add_argument('-f', '--flush', action="store_true", help="flush the db before running the test")
if __name__ == "__main__":
try:
args = parser.parse_args()
except:
exit()
numclients = args.clients
numkeys = args.keys
runtime = args.runtime
main(args.test, args.flush)
+2 -20
View File
@@ -1,21 +1,3 @@
### KeyDB DEB Package Source Builds
### KeyDB Packaging
This directory contains scripts and components needed to generate debian packages on different distributions/architectures from source
The 'debian' directory contains debian source code for bionic, buster and later distributions as it uses functions only available with debhelper11+. 'debian_dh9' is used for xenial, stretch and earlier distributions using debhelper9.
You will need to install pbuilder `sudo apt install pbuilder` along with other distribution specific dependencies
Generate deb packages with the following script command run from this directory:
```
$ ./deb-buildsource.sh
```
This generates a directory structure, .dsc file, original.tar.gz, and new changelog for the distribution and architecture installed.
When complete the produced debian packages will be located in deb_files_generated directory.
Arguments for the deb-buildsource.sh script that can be passed are either 'None' or '"your custom comments"'. 'None' assumes a permanent changelog entry has been made listing the correct build for the version. If you quote and enter your own comment string, it will be appended to the changelog for that deb package. If no argument is passed a default comment is generated saying that this deb package was generated by this script.
This script has been tested on xenial/bionic/focal/stretch/buster/bullseye
The following directories contain packaging code used to create rpm and deb packages as well as docker images.
+8 -4
View File
@@ -1,17 +1,21 @@
### KeyDB DEB Package Source Builds
This directory contains scripts and components needed to generate debian packages on different distributions/architectures using source
This directory contains scripts and components needed to generate debian packages on different distributions/architectures from source
You will need to install pbuilder `sudo apt install pbuilder`
The 'debian' directory contains debian source code for bionic, buster and later distributions as it uses functions only available with debhelper11+. 'debian_dh9' is used for xenial, stretch and earlier distributions using debhelper9.
You will need to install pbuilder `sudo apt install pbuilder` along with other distribution specific dependancies
Generate deb packages with the following script command run from this directory:
```
$ ./deb-buildsource.sh
```
This generates a directory structure, .dsc file, original.tar.gz, .changes files and new changelog for the distribution and architecture installed.
This generates a directory structure, .dsc file, original.tar.gz, and new changelog for the distribution and architecture installed.
When complete the produced debian packages will be located in deb_files_generated directory.
Arguments for the deb-buildsource.sh script that can be passed are either 'None' or '"your custom comments"'. 'None' assumes a permanent changelog entry has been made listing the correct build for the version. If you quote and enter your own comment string, it will be appended to the changelog for that deb package. If no argument is passed a default comment is generated saying that this deb package was generated by this script.
This script has been tested on xenial/bionic/focal/stretch/buster/bullseye
This script has been tested on xenial/bionic/stretch/buster
+4 -40
View File
@@ -257,24 +257,6 @@ tcp-keepalive 300
#
# tls-session-cache-timeout 60
# Allow the server to monitor the filesystem and rotate out TLS certificates if
# they change on disk, defaults to no.
#
# tls-rotation no
# Setup a allowlist of allowed Common Names (CNs)/Subject Alternative Names (SANs)
# that are allowed to connect to this server. This includes both normal clients as
# well as other servers connected for replication/clustering purposes. If nothing is
# specified, then no allowlist is used and all certificates are accepted.
# Supports IPv4, DNS, RFC822, and URI SAN types.
# You can put multiple names on one line as follows:
#
# tls-allowlist <dns1> <dns2> <dns3> ...
#
#
# This configuration also allows for wildcard characters with glob style formatting
# i.e. "*.com" would allow all clients to connect with a CN/SAN that ends with ".com"
################################# GENERAL #####################################
# By default KeyDB does not run as a daemon. Use 'yes' if you need it.
@@ -2053,27 +2035,9 @@ server-threads 2
# bringing up replicas can result in data loss (the first master will win).
# active-replica yes
# KeyDB will attempt to balance clients across threads evenly; However, replica clients
# are usually much more expensive than a normal client, and so KeyDB will try to assign
# fewer clients to threads with a replica. The weighting factor below is intented to help tune
# this behavior. A replica weighting factor of 2 means we treat a replica as the equivalent
# of two normal clients. Adjusting this value may improve performance when replication is
# used. The best weighting is workload specific - e.g. read heavy workloads should set
# this to 1. Very write heavy workloads may benefit from higher numbers.
#
# By default KeyDB sets this to 2.
replica-weighting-factor 2
# Enable Pro? KeyDB pro provides support for pro only features
# note: you may omit the license key to demo pro features for a limited time
# enable-pro [License Key]
# Enable FLASH support (Experimental Feature)
# Enable FLASH support? (Pro Only)
# storage-provider flash /path/to/flash/db
# Blob support is a way to store very large objects (>200MB) on disk
# The files are automatically cleaned up when KeyDB exits and are only
# for temporary use. This helps reduce memory pressure for very large
# data items at the cost of some performance.
#
# By default this config is disable. When enabled the disk associated
# with KeyDB's working directory will be used. If there is insufficient
# disk space or any other I/O error KeyDB will instead use memory.
#
# blob-support false
+1 -7
View File
@@ -19,11 +19,6 @@ elif [ "$distributor" == "Ubuntu" ]; then
fi
codename=$(lsb_release --codename --short)
date=$(date +%a," "%d" "%b" "%Y" "%T)
# overwrite debian bookworm version until updated
if [ $codename == "bookworm" ]; then
distname=+deb12u1
fi
pkg_name=keydb-$majorv:$version$distname
# create build tree
@@ -58,9 +53,8 @@ if [ "$codename" == "xenial" ]; then
else
sudo pbuilder create --distribution $codename
fi
sudo pbuilder --update
sudo pbuilder --build *.dsc --logfile /mnt/pbuilderlog.log
sudo pbuilder --build *.dsc
# move new packages to deb_files_generated and clean up
cp /var/cache/pbuilder/result/*$version*.deb ../deb_files_generated
+3 -9
View File
@@ -8,7 +8,6 @@ Build-Depends:
systemd,
libsystemd-dev <!nocheck>,
procps <!nocheck>,
pkg-config <!nocheck>,
build-essential <!nocheck>,
tcl <!nocheck>,
tcl-dev <!nocheck>,
@@ -18,16 +17,11 @@ Build-Depends:
autotools-dev <!nocheck>,
autoconf <!nocheck>,
libjemalloc-dev <!nocheck>,
libssl-dev <!nocheck>,
libsnappy-dev <!nocheck>,
zlib1g-dev <!nocheck>,
libbz2-dev <!nocheck>,
liblz4-dev <!nocheck>,
libzstd-dev <!nocheck>
libssl-dev <!nocheck>
Standards-Version: 4.2.1
Homepage: https://docs.keydb.dev/
Vcs-Git: https://github.com/Snapchat/KeyDB.git
Vcs-Browser: https://github.com/Snapchat/KeyDB
Vcs-Git: https://github.com/JohnSully/KeyDB.git
Vcs-Browser: https://github.com/JohnSully/KeyDB
Package: keydb
Architecture: all
+1 -3
View File
@@ -6,9 +6,8 @@ Source: https://github.com/EQ-Alpha/KeyDB
Files: *
Copyright:
© 2006-2014 Salvatore Sanfilippo <antirez@gmail.com>
© 2019 John Sully
© 2019-2021 John Sully
© 2019-2021 EQ Alpha Technology Ltd.
© 2021 Snap Inc.
License: BSD-3-clause
@@ -90,7 +89,6 @@ Files: pkg/deb/debian/*
Copyright:
© 2009 Chris Lamb <lamby@debian.org>
© 2020-2021 EQ Alpha Technology Ltd. <support@eqalpha.com>
© 2021 Snap Inc.
License: BSD-3-clause
License: BSD-2-clause
-1
View File
@@ -4,7 +4,6 @@ include /usr/share/dpkg/buildflags.mk
export BUILD_TLS=yes
export USE_SYSTEMD=yes
export ENABLE_FLASH=yes
export CFLAGS CPPFLAGS LDFLAGS
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_APPEND = -ldl -latomic $(LUA_LDFLAGS)
+1 -1
View File
@@ -1,3 +1,3 @@
version=6
opts=uversionmangle=s/-?(alpha|beta|rc)/~$1/ \
https://github.com/EQ-Alpha/KeyDB/releases .*/archive/(.*).tar.gz
https://github.com/JohnSully/KeyDB-Pro/releases .*/archive/(.*).tar.gz
+3 -8
View File
@@ -17,16 +17,11 @@ Build-Depends:
autotools-dev <!nocheck>,
autoconf <!nocheck>,
libjemalloc-dev <!nocheck>,
libssl-dev <!nocheck>,
libsnappy-dev <!nocheck>,
zlib1g-dev <!nocheck>,
libbz2-dev <!nocheck>,
liblz4-dev <!nocheck>,
libzstd-dev <!nocheck>
libssl-dev <!nocheck>
Standards-Version: 4.2.1
Homepage: https://docs.keydb.dev/
Vcs-Git: https://github.com/Snapchat/KeyDB.git
Vcs-Browser: https://github.com/Snapchat/KeyDB
Vcs-Git: https://github.com/JohnSully/KeyDB.git
Vcs-Browser: https://github.com/JohnSully/KeyDB
Package: keydb
Architecture: all
+1 -1
View File
@@ -6,7 +6,7 @@ Source: https://github.com/EQ-Alpha/KeyDB
Files: *
Copyright:
© 2006-2014 Salvatore Sanfilippo <antirez@gmail.com>
© 2019 John Sully
© 2019-2021 John Sully
© 2019-2021 EQ Alpha Technology Ltd.
License: BSD-3-clause
-1
View File
@@ -10,7 +10,6 @@ include /usr/share/dpkg/buildflags.mk
export BUILD_TLS=yes
export USE_SYSTEMD=yes
export ENABLE_FLASH=yes
export CFLAGS CPPFLAGS LDFLAGS
export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_APPEND = -ldl -latomic $(LUA_LDFLAGS)
+1 -1
View File
@@ -1,3 +1,3 @@
version=4
opts=uversionmangle=s/-?(alpha|beta|rc)/~$1/ \
https://github.com/EQ-Alpha/KeyDB/releases .*/archive/(.*).tar.gz
https://github.com/JohnSully/KeyDB/releases .*/archive/(.*).tar.gz
+1 -92
View File
@@ -1,94 +1,3 @@
keydb (6:6.3.1-1distribution_placeholder) codename_placeholder; urgency=medium
* This point release contains fixes to bugs related to expires, active-rep, and rdb saving
* Issues fixed: #419, #422, #428
* PRs: #426, #429, #431, #433
-- Ben Schermel <ben@eqalpha.com> Mon, 23 May 2022 20:00:37 +0000
keydb (6:6.3.0-1distribution_placeholder) codename_placeholder; urgency=medium
* This release open sources KeyDB Enterprise features into the open source project along with PSYNC for active replication
* Partial synchronization for active replication is introduced
* MVCC introduced into codebase from KeyDB Enterprise
* Async commands added: GET, MGET. These will see perf improvements
* KEYS and SCAN commands will no longer be blocking calls
* Async Rehash implemented for additional stability to perf
* IStorage interface added
* In-process background saving (forkless) to comply with maxmemory setting
* See v6.3.0 tagged release notes on github for a detailed explanation of these changes
-- Ben Schermel <ben@eqalpha.com> Wed, 11 May 2022 20:00:37 +0000
keydb (6:6.2.2-1distribution_placeholder) codename_placeholder; urgency=medium
* Acquire lock in module.cpp to fix module test break
* Fix usage of nanosleep() on Apple hardware
* Fix networking deadlock (#183)
* Remove redundant zfree() in keydb-benchmark
* Issues resolved: #378, #384
-- Ben Schermel <ben@eqalpha.com> Sat, 15 Jan 2022 20:00:37 +0000
keydb (6:6.2.1-1distribution_placeholder) codename_placeholder; urgency=medium
* This release of KeyDB is at parity with Redis 6.2.6. In addition, the following changes were included:
* Systemd support for release packages
* Fixes to buffer overflows in the `BITOP SHIFT` and `CRON` commands
* Server times are now computed on a seperate thread to improve performance
* Now enforces syslog identity and facility as soon as possible
* Removed erroneous use of LOG_... flags when using syslog
* Fixed erroneous `#endif` leading to build errors on some platforms
* Fixed the incorrect counting of client connections
* Issues resolved: #355, #370
-- Ben Schermel <ben@eqalpha.com> Wed, 17 Nov 2021 20:00:37 +0000
keydb (6:6.2.0-1distribution_placeholder) codename_placeholder; urgency=medium
* Removed unused command line options(-a, -d, -P, -r, -q, --csv, -l, -I, -e, --precision, --cluster, --enable-tracking)
* --ms option changed to --time, added --clients, --host, --port, and --threads options
* Added keydb-diagnostic-tool
* Improved test reliability
* Fixed memory leak in keydb-benchmark
* Fixed a number of race conditions
* Fixed OSX build issues
* Feature parity with Redis 6.2.3
* Fixed Issues: #323 #325 #276
-- Ben Schermel <ben@eqalpha.com> Thu, 12 Aug 2021 20:00:37 +0000
keydb (6:6.0.18-1distribution_placeholder) codename_placeholder; urgency=medium
* 6.0.18 - This release contains a number of improvements to stability and performance.
* Additional tests were added with improvements to existing test reliability
* Merged Redis 6.0.10 into KeyDB
* Issues resolved in this release: #214, #222, #238, #257, #273, #276, #285
-- Ben Schermel <ben@eqalpha.com> Fri, 26 Mar 2021 16:00:00 +0000
keydb (6:6.0.16-1distribution_placeholder) codename_placeholder; urgency=medium
* 6.0.16 - This release contains significant performance improvements as well as fixes to the following issues: #234, #236, #233, #207, #229, #231
* Reduced memory consumption when Active Replication is not used
* Reduced CPU consumption
* Improved TLS performance
* replica-quorum config for multi-master.Intended to be used with "replica-serve-stale-data no", if at least N replicas are connected we will consider our master link up and serve data.
* Subkey expires performance improvement for big sets
-- Ben Schermel <ben@eqalpha.com> Mon, 28 Sep 2020 16:00:00 +0000
keydb (6:6.0.13-1distribution_placeholder) codename_placeholder; urgency=medium
* 6.0.13 New features added: KEYDB.MEXISTS, REPLICAOF REMOVE, multi-master-no-forward configuration option
* KEYDB.MEXISTS - return exactly which keys exist in the database not just the count
* REPLICAOF REMOVE - Remove specific masters in a multi master setup
* multi-master-no-forward configuration option - Reduce network traffic in mesh topology multimaster setups
* Redis 6.0.5 feature parity
* Fixed Issues: 194 Bad directive or wrong number of arguments error on 'lazyfree-lazy-user-del no'; 209 Timeout using modules; 210 Databases are not merged on multi-master sync; 211 rpm packages now signed; 212 rpm file permissions updated
-- Ben Schermel <ben@eqalpha.com> Mon, 13 Jul 2020 8:00:00 +0000
keydb (6:6.0.9-1distribution_placeholder) codename_placeholder; urgency=medium
* 6.0.9 Addressing issues 187 - cpu lockup with subkey expire, 190 - missing sentinel binary in keydb-tools.
@@ -99,7 +8,7 @@ keydb (6:6.0.8-1distribution_placeholder) codename_placeholder; urgency=medium
* This is our first release to fully support all Redis 6.0.4 features, including but not limited to: TLS Support (fully supports multithreading!), Client side caching, RESP 3 Support
* KeyDB Has also added the following new features: Improved memory efficiency for short strings, Fastlock autotuning, KeyDB.HRENAME (rename a member of a hash)In addition we've spent a lot of time focussing on stability.
* The following bug fixes are resolved: 150 - Deadlock in ReplicationFeedMonitors, 170 - KeyDB dying via SIGABORT, 180 - crash after setting maxclients via cmd line, 169 - Write performance of a master dropped sharply when a replica is added
* The following bug fixes are resolved: 150 - Deadlock in ReplicationFeedMonitors, 170 - KeyDB dying via SIGABORT, 180 - crash after setting maxclients via cmd line, 169 - Write performance of a master dropped sharply when a slave is added
* In addition untracked issues were resolved: Potential deadlock when entering futex sleep, Pub/Sub Async messages may not be sent in a timely manner when load is low, Excessive logging during failed RREPLAY, KeyDB unresponsive handling clients on different threads during RDB load
* Updated deb package builds to build from source and phasing out init.d. dh_installsystemd from deb helper 11 used where applicable
* Naming conventions are now updated [ keydbpackage_version-build~distribution_architecture] and master changelog included and maintained
+82 -104
View File
@@ -1,113 +1,91 @@
FROM ubuntu:20.04
SHELL ["/bin/bash","-c"]
FROM ubuntu:18.04
# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
RUN groupadd -r keydb && useradd -r -g keydb keydb
# use gosu for easy step-down from root: https://github.com/tianon/gosu/releases
ENV GOSU_VERSION 1.14
# grab gosu for easy step-down from root
# https://github.com/tianon/gosu/releases
ENV GOSU_VERSION 1.11
RUN set -eux; \
savedAptMark="$(apt-mark showmanual)"; \
apt-get update; \
apt-get install -y --no-install-recommends ca-certificates dirmngr gnupg wget; \
rm -rf /var/lib/apt/lists/*; \
dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \
wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \
wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \
export GNUPGHOME="$(mktemp -d)"; \
gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4; \
gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \
gpgconf --kill all; \
rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \
apt-mark auto '.*' > /dev/null; \
[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
chmod +x /usr/local/bin/gosu; \
gosu --version; \
gosu nobody true
# build KeyDB
ARG BRANCH
RUN set -eux; \
\
savedAptMark="$(apt-mark showmanual)"; \
apt-get update; \
DEBIAN_FRONTEND=noninteractive apt-get install -qqy --no-install-recommends \
dpkg-dev \
pkg-config \
ca-certificates \
build-essential \
nasm \
autotools-dev \
autoconf \
libjemalloc-dev \
tcl \
tcl-dev \
uuid-dev \
libcurl4-openssl-dev \
libbz2-dev \
libzstd-dev \
liblz4-dev \
libsnappy-dev \
libssl-dev \
git; \
cd /tmp && git clone --branch $BRANCH https://github.com/Snapchat/KeyDB.git --recursive; \
cd /tmp/KeyDB; \
# disable protected mode as it relates to docker
grep -E '^ *createBoolConfig[(]"protected-mode",.*, *1 *,.*[)],$' ./src/config.cpp; \
sed -ri 's!^( *createBoolConfig[(]"protected-mode",.*, *)1( *,.*[)],)$!\10\2!' ./src/config.cpp; \
grep -E '^ *createBoolConfig[(]"protected-mode",.*, *0 *,.*[)],$' ./src/config.cpp; \
make -j$(nproc) BUILD_TLS=yes ENABLE_FLASH=yes; \
cd src; \
strip keydb-cli keydb-benchmark keydb-check-rdb keydb-check-aof keydb-diagnostic-tool keydb-sentinel keydb-server; \
mv keydb-server keydb-cli keydb-benchmark keydb-check-rdb keydb-check-aof keydb-diagnostic-tool keydb-sentinel /usr/local/bin/; \
# clean up unused dependencies
echo $savedAptMark; \
apt-mark auto '.*' > /dev/null; \
[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
find /usr/local -type f -executable -exec ldd '{}' ';' \
| awk '/=>/ { print $(NF-1) }' \
| sed 's:.*/::' \
| sort -u \
| xargs -r dpkg-query --search \
| cut -d: -f1 \
| sort -u \
| xargs -r apt-mark manual \
; \
apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
rm -rf /var/lib/apt/lists/*; \
# create working directories and organize files
# save list of currently installed packages for later so we can clean up
savedAptMark="$(apt-mark showmanual)"; \
apt-get update; \
apt-get install -y --no-install-recommends \
ca-certificates \
dirmngr \
gnupg \
wget \
; \
\
dpkgArch="$(dpkg --print-architecture | awk -F- '{ print $NF }')"; \
wget -O /usr/local/bin/gosu "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch"; \
wget -O /usr/local/bin/gosu.asc "https://github.com/tianon/gosu/releases/download/$GOSU_VERSION/gosu-$dpkgArch.asc"; \
\
# verify the signature
export GNUPGHOME="$(mktemp -d)"; \
gpg --batch --keyserver hkps://keys.openpgp.org --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4; \
gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \
gpgconf --kill all; \
rm -rf "$GNUPGHOME" /usr/local/bin/gosu.asc; \
\
# clean up fetch dependencies
apt-mark auto '.*' > /dev/null; \
[ -z "$savedAptMark" ] || apt-mark manual $savedAptMark > /dev/null; \
apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false; \
\
chmod +x /usr/local/bin/gosu; \
# verify that the binary works
gosu --version; \
gosu nobody true
# Load pre-generated equivalent binaries to image (reduces deployment build times)
RUN \
mkdir /data && chown keydb:keydb /data; \
mkdir /flash && chown keydb:keydb /flash; \
mkdir -p /etc/keydb; \
cp /tmp/KeyDB/keydb.conf /etc/keydb/; \
sed -i 's/^\(daemonize .*\)$/# \1/' /etc/keydb/keydb.conf; \
sed -i 's/^\(dir .*\)$/# \1\ndir \/data/' /etc/keydb/keydb.conf; \
sed -i 's/^\(logfile .*\)$/# \1/' /etc/keydb/keydb.conf; \
sed -i 's/protected-mode yes/protected-mode no/g' /etc/keydb/keydb.conf; \
sed -i 's/^\(bind .*\)$/# \1/' /etc/keydb/keydb.conf; \
cd /usr/local/bin; \
ln -s keydb-cli redis-cli; \
cd /etc/keydb; \
ln -s keydb.conf redis.conf; \
rm -rf /tmp/*
# generate entrypoint script
mkdir -p /etc/keydb
ADD ./app/keydb-* /usr/local/bin/
ADD ./app/docker-entrypoint.sh /usr/local/bin/
ADD ./app/*.conf /etc/keydb/
# Set up config and binaries
RUN \
cd /usr/local/bin && \
sed -i 's/^\(bind .*\)$/# \1/' /etc/keydb/keydb.conf && \
sed -i 's/^\(daemonize .*\)$/# \1/' /etc/keydb/keydb.conf && \
sed -i 's/^\(dir .*\)$/# \1\ndir \/data/' /etc/keydb/keydb.conf && \
sed -i 's/^\(logfile .*\)$/# \1/' /etc/keydb/keydb.conf && \
sed -i 's/protected-mode yes/protected-mode no/g' /etc/keydb/keydb.conf && \
ln -s keydb-cli redis-cli && \
cd /etc/keydb && \
ln -s keydb.conf redis.conf
# Ensure deps installed for binaries
RUN set -eux; \
echo '#!/bin/sh' > /usr/local/bin/docker-entrypoint.sh; \
echo 'set -e' >> /usr/local/bin/docker-entrypoint.sh; \
echo "# first arg is '-f' or '--some-option'" >> /usr/local/bin/docker-entrypoint.sh; \
echo "# or first arg is `something.conf`" >> /usr/local/bin/docker-entrypoint.sh; \
echo 'if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then' >> /usr/local/bin/docker-entrypoint.sh; \
echo ' set -- keydb-server "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'fi' >> /usr/local/bin/docker-entrypoint.sh; \
echo "# allow the container to be started with `--user`" >> /usr/local/bin/docker-entrypoint.sh; \
echo 'if [ "$1" = "keydb-server" -a "$(id -u)" = "0" ]; then' >> /usr/local/bin/docker-entrypoint.sh; \
echo " find . \! -user keydb -exec chown keydb '{}' +" >> /usr/local/bin/docker-entrypoint.sh; \
echo ' exec gosu keydb "$0" "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'fi' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'exec "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
chmod +x /usr/local/bin/docker-entrypoint.sh
# set remaining image properties
\
savedAptMark="$(apt-mark showmanual)"; \
apt-get install -y --no-install-recommends \
libcurl4 \
libc6 \
libssl1.1 \
libuuid1 \
libstdc++6 \
libgcc1 \
zlib1g \
libbz2-1.0 \
liblz4-1 \
libsnappy1v5 \
libzstd1 \
; \
rm -rf /var/lib/apt/lists/*
# create working directories
RUN \
mkdir /data && chown keydb:keydb /data && \
mkdir /flash && chown keydb:keydb /flash
VOLUME /data
WORKDIR /data
ENV KEYDB_PRO_DIRECTORY=/usr/local/bin/
#COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]
# Expose container port and start KeyDB by default on running container
EXPOSE 6379
CMD ["keydb-server","/etc/keydb/keydb.conf"]
CMD ["keydb-server", "/etc/keydb/keydb.conf"]
-82
View File
@@ -1,82 +0,0 @@
FROM alpine:3.12
# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
RUN addgroup -S -g 1000 keydb && adduser -S -G keydb -u 999 keydb
RUN mkdir -p /etc/keydb
ARG BRANCH
RUN set -eux; \
\
apk add --no-cache su-exec tini; \
apk add --no-cache --virtual .build-deps \
coreutils \
gcc \
linux-headers \
make \
musl-dev \
openssl-dev \
git \
util-linux-dev \
curl-dev \
g++ \
libunwind-dev \
bash \
perl \
git \
bzip2-dev \
zstd-dev \
lz4-dev \
snappy-dev \
; \
cd /tmp && git clone --branch $BRANCH https://github.com/Snapchat/KeyDB.git --recursive; \
cd /tmp/KeyDB; \
# disable protected mode as it relates to docker
grep -E '^ *createBoolConfig[(]"protected-mode",.*, *1 *,.*[)],$' ./src/config.cpp; \
sed -ri 's!^( *createBoolConfig[(]"protected-mode",.*, *)1( *,.*[)],)$!\10\2!' ./src/config.cpp; \
grep -E '^ *createBoolConfig[(]"protected-mode",.*, *0 *,.*[)],$' ./src/config.cpp; \
make -j$(nproc) BUILD_TLS=yes ENABLE_FLASH=yes; \
cd src; \
strip keydb-cli keydb-benchmark keydb-check-rdb keydb-check-aof keydb-diagnostic-tool keydb-sentinel keydb-server; \
mv keydb-server keydb-cli keydb-benchmark keydb-check-rdb keydb-check-aof keydb-diagnostic-tool keydb-sentinel /usr/local/bin/; \
runDeps="$( \
scanelf --needed --nobanner --format '%n#p' --recursive /usr/local \
| tr ',' '\n' \
| sort -u \
| awk 'system("[ -e /usr/local/lib/" $1 " ]") == 0 { next } { print "so:" $1 }' \
)"; \
apk add --no-network --virtual .keydb-rundeps $runDeps; \
apk del --no-network .build-deps; \
# create working directories and organize files
mkdir /data && chown keydb:keydb /data; \
mkdir /flash && chown keydb:keydb /flash; \
mkdir -p /etc/keydb; \
cp /tmp/KeyDB/keydb.conf /etc/keydb/; \
sed -i 's/^\(daemonize .*\)$/# \1/' /etc/keydb/keydb.conf; \
sed -i 's/^\(dir .*\)$/# \1\ndir \/data/' /etc/keydb/keydb.conf; \
sed -i 's/^\(logfile .*\)$/# \1/' /etc/keydb/keydb.conf; \
sed -i 's/protected-mode yes/protected-mode no/g' /etc/keydb/keydb.conf; \
sed -i 's/^\(bind .*\)$/# \1/' /etc/keydb/keydb.conf; \
cd /usr/local/bin; \
ln -s keydb-cli redis-cli; \
cd /etc/keydb; \
ln -s keydb.conf redis.conf; \
rm -rf /tmp/*
# generate entrypoint script
RUN set -eux; \
echo '#!/bin/sh' > /usr/local/bin/docker-entrypoint.sh; \
echo 'set -e' >> /usr/local/bin/docker-entrypoint.sh; \
echo "# first arg is '-f' or '--some-option'" >> /usr/local/bin/docker-entrypoint.sh; \
echo "# or first arg is `something.conf`" >> /usr/local/bin/docker-entrypoint.sh; \
echo 'if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then' >> /usr/local/bin/docker-entrypoint.sh; \
echo ' set -- keydb-server "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'fi' >> /usr/local/bin/docker-entrypoint.sh; \
echo "# allow the container to be started with `--user`" >> /usr/local/bin/docker-entrypoint.sh; \
echo 'if [ "$1" = "keydb-server" -a "$(id -u)" = "0" ]; then' >> /usr/local/bin/docker-entrypoint.sh; \
echo " find . \! -user keydb -exec chown keydb '{}' +" >> /usr/local/bin/docker-entrypoint.sh; \
echo ' exec su-exec keydb "$0" "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'fi' >> /usr/local/bin/docker-entrypoint.sh; \
echo 'exec "$@"' >> /usr/local/bin/docker-entrypoint.sh; \
chmod +x /usr/local/bin/docker-entrypoint.sh
VOLUME /data
WORKDIR /data
ENTRYPOINT ["tini", "--", "docker-entrypoint.sh"]
EXPOSE 6379
CMD ["keydb-server", "/etc/keydb/keydb.conf"]
+2 -4
View File
@@ -1,7 +1,5 @@
This Dockerfile will clone the KeyDB repo, build, and generate a Docker image you can use
To build, use experimental mode to enable use of build args. Tag the build and specify branch name. The command below will generate your docker image:
In order to create a docker image, generate the keydb binaries, copy them to the app directory, copy keydb.conf and sentinel.conf to the app directory as well, then run the following command:
```
DOCKER_CLI_EXPERIMENTAL=enabled docker build --build-arg BRANCH=<keydbBranch> -t <yourImageName>
$ sudo docker build . -t <yourimagename>
```
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
set -e
# first arg is `-f` or `--some-option`
# or first arg is `something.conf`
if [ "${1#-}" != "$1" ] || [ "${1%.conf}" != "$1" ]; then
set -- keydb-server "$@"
fi
# allow the container to be started with `--user`
if [ "$1" = 'keydb-server' -a "$(id -u)" = '0' ]; then
find . \! -user keydb -exec chown keydb '{}' +
exec gosu keydb "$0" "$@"
fi
exec "$@"
+1 -1
View File
@@ -1,6 +1,6 @@
### Generate RPM files for the generated binaries
After making the binaries you can run the following script
After running make to produce keydb binaries you can run the following script to create rpm package
Usage:
```
+3 -2
View File
@@ -1,13 +1,14 @@
Name : keydb
Version : 6.0.5
Version : 5.3.3
Release : 1%{?dist}
Group : Unspecified
License : BSD
Packager : Snap Inc.
Packager : EQ Alpha Technology
URL : https://keydb.dev
Summary : A persistent key-value database
Requires: /bin/awk
Requires: logrotate
Requires(pre): shadow-utils
@@ -257,24 +257,6 @@ tcp-keepalive 300
#
# tls-session-cache-timeout 60
# Allow the server to monitor the filesystem and rotate out TLS certificates if
# they change on disk, defaults to no.
#
# tls-rotation no
# Setup a allowlist of allowed Common Names (CNs)/Subject Alternative Names (SANs)
# that are allowed to connect to this server. This includes both normal clients as
# well as other servers connected for replication/clustering purposes. If nothing is
# specified, then no allowlist is used and all certificates are accepted.
# Supports IPv4, DNS, RFC822, and URI SAN types.
# You can put multiple names on one line as follows:
#
# tls-allowlist <dns1> <dns2> <dns3> ...
#
#
# This configuration also allows for wildcard characters with glob style formatting
# i.e. "*.com" would allow all clients to connect with a CN/SAN that ends with ".com"
################################# GENERAL #####################################
# By default KeyDB does not run as a daemon. Use 'yes' if you need it.
@@ -2053,27 +2035,9 @@ server-threads 2
# bringing up replicas can result in data loss (the first master will win).
# active-replica yes
# KeyDB will attempt to balance clients across threads evenly; However, replica clients
# are usually much more expensive than a normal client, and so KeyDB will try to assign
# fewer clients to threads with a replica. The weighting factor below is intented to help tune
# this behavior. A replica weighting factor of 2 means we treat a replica as the equivalent
# of two normal clients. Adjusting this value may improve performance when replication is
# used. The best weighting is workload specific - e.g. read heavy workloads should set
# this to 1. Very write heavy workloads may benefit from higher numbers.
#
# By default KeyDB sets this to 2.
replica-weighting-factor 2
# Enable Pro? KeyDB pro provides support for pro only features
# note: you may omit the license key to demo pro features for a limited time
# enable-pro [License Key]
# Enable FLASH support (Experimental Feature)
# Enable FLASH support? (Pro Only)
# storage-provider flash /path/to/flash/db
# Blob support is a way to store very large objects (>200MB) on disk
# The files are automatically cleaned up when KeyDB exits and are only
# for temporary use. This helps reduce memory pressure for very large
# data items at the cost of some performance.
#
# By default this config is disable. When enabled the disk associated
# with KeyDB's working directory will be used. If there is insufficient
# disk space or any other I/O error KeyDB will instead use memory.
#
# blob-support false
@@ -1,7 +1,7 @@
[Unit]
Description=Advanced key-value store
After=network.target
Documentation=http://keydb.io/documentation, man:keydb-sentinel(1)
Documentation=https://docs.keydb.dev, man:keydb-sentinel(1)
[Service]
Type=forking
+1 -4
View File
@@ -1,8 +1,5 @@
Copyright (c) 2006-2020, Salvatore Sanfilippo
Copyright (c) 2006-2015, Salvatore Sanfilippo
Copyright (C) 2019, John Sully
Copyright (C) 2020-2021, EQ Alpha Technology Ltd.
Copyright (C) 2021, Snap Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
View File
File mode changed.
File mode changed.
View File
File mode changed.
-1
View File
@@ -37,6 +37,5 @@ $TCLSH tests/test_helper.tcl \
--single unit/moduleapi/hash \
--single unit/moduleapi/zset \
--single unit/moduleapi/stream \
--single unit/moduleapi/load \
--config server-threads 3 \
"${@}"
-31
View File
@@ -1,31 +0,0 @@
#!/bin/sh
TCL_VERSIONS="8.5 8.6"
TCLSH=""
export ASAN_OPTIONS=allocator_may_return_null=1 $ASAN_OPTIONS
for VERSION in $TCL_VERSIONS; do
TCL=`which tclsh$VERSION 2>/dev/null` && TCLSH=$TCL
done
if [ -z $TCLSH ]
then
echo "You need tcl 8.5 or newer in order to run the KeyDB test"
exit 1
fi
if [ ! -r tests/tls ] || [ ! -r tests/tls_1 ] || [ ! -r tests/tls_2 ];
then
echo "Generating neccessary certificates for TLS rotation testing."
rm -rf tests/tls tests/tls_1 tests/tls_2
utils/gen-test-certs.sh
mv tests/tls tests/tls_1
utils/gen-test-certs.sh
mv tests/tls tests/tls_2
utils/gen-test-certs.sh
fi
$TCLSH tests/test_helper.tcl \
--single unit/tls-rotation \
--tls \
--config server-threads 3 \
"${@}"
-131
View File
@@ -1,131 +0,0 @@
#include "AsyncWorkQueue.h"
#include "server.h"
AsyncWorkQueue::AsyncWorkQueue(int nthreads)
{
for (int i = 0; i < nthreads; ++i)
{
m_vecthreads.emplace_back([&]{
WorkerThreadMain();
});
}
}
void AsyncWorkQueue::WorkerThreadMain()
{
redisServerThreadVars vars;
serverTL = &vars;
vars.clients_pending_asyncwrite = listCreate();
m_mutex.lock();
m_vecpthreadVars.push_back(&vars);
m_mutex.unlock();
while (!m_fQuitting)
{
std::unique_lock<std::mutex> lock(m_mutex);
if (m_workqueue.empty())
m_cvWakeup.wait(lock);
aeThreadOnline();
while (!m_workqueue.empty())
{
WorkItem task = std::move(m_workqueue.front());
m_workqueue.pop_front();
lock.unlock();
serverTL->gcEpoch = g_pserver->garbageCollector.startEpoch();
task.fnAsync();
g_pserver->garbageCollector.endEpoch(serverTL->gcEpoch);
lock.lock();
}
lock.unlock();
serverTL->gcEpoch = g_pserver->garbageCollector.startEpoch();
if (listLength(serverTL->clients_pending_asyncwrite)) {
aeAcquireLock();
ProcessPendingAsyncWrites();
aeReleaseLock();
}
g_pserver->garbageCollector.endEpoch(serverTL->gcEpoch);
serverTL->gcEpoch.reset();
aeThreadOffline();
}
listRelease(vars.clients_pending_asyncwrite);
std::unique_lock<fastlock> lockf(serverTL->lockPendingWrite);
serverTL->vecclientsProcess.clear();
serverTL->clients_pending_write.clear();
std::atomic_thread_fence(std::memory_order_seq_cst);
}
bool AsyncWorkQueue::removeClientAsyncWrites(client *c)
{
bool fFound = false;
aeAcquireLock();
m_mutex.lock();
for (auto pvars : m_vecpthreadVars)
{
listIter li;
listNode *ln;
listRewind(pvars->clients_pending_asyncwrite, &li);
while ((ln = listNext(&li)) != nullptr)
{
if (c == listNodeValue(ln))
{
listDelNode(pvars->clients_pending_asyncwrite, ln);
fFound = true;
}
}
}
m_mutex.unlock();
aeReleaseLock();
return fFound;
}
void AsyncWorkQueue::shutdown()
{
std::unique_lock<std::mutex> lock(m_mutex);
serverAssert(!GlobalLocksAcquired());
m_fQuitting = true;
m_cvWakeup.notify_all();
lock.unlock();
for (auto &thread : m_vecthreads)
thread.join();
}
void AsyncWorkQueue::abandonThreads()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_fQuitting = true;
m_cvWakeup.notify_all();
for (auto &thread : m_vecthreads)
{
thread.detach();
}
m_vecthreads.clear();
}
AsyncWorkQueue::~AsyncWorkQueue()
{
serverAssert(!GlobalLocksAcquired() || m_vecthreads.empty());
std::unique_lock<std::mutex> lock(m_mutex);
m_fQuitting = true;
m_cvWakeup.notify_all();
lock.unlock();
abandonThreads();
}
void AsyncWorkQueue::AddWorkFunction(std::function<void()> &&fnAsync, bool fHiPri)
{
std::unique_lock<std::mutex> lock(m_mutex);
if (fHiPri)
m_workqueue.emplace_front(std::move(fnAsync));
else
m_workqueue.emplace_back(std::move(fnAsync));
m_cvWakeup.notify_one();
}
-40
View File
@@ -1,40 +0,0 @@
#pragma once
#include "fastlock.h"
#include <vector>
#include <deque>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <functional>
class AsyncWorkQueue
{
struct WorkItem
{
WorkItem(std::function<void()> &&fnAsync)
: fnAsync(std::move(fnAsync))
{}
WorkItem(WorkItem&&) = default;
std::function<void()> fnAsync;
};
std::vector<std::thread> m_vecthreads;
std::vector<struct redisServerThreadVars*> m_vecpthreadVars;
std::deque<WorkItem> m_workqueue;
std::mutex m_mutex;
std::condition_variable m_cvWakeup;
std::atomic<bool> m_fQuitting { false };
void WorkerThreadMain();
public:
AsyncWorkQueue(int nthreads);
~AsyncWorkQueue();
void AddWorkFunction(std::function<void()> &&fnAsync, bool fHiPri = false);
bool removeClientAsyncWrites(struct client *c);
void shutdown();
void abandonThreads();
};
-62
View File
@@ -1,62 +0,0 @@
#pragma once
#include <functional>
#include "sds.h"
#include <string>
#define METADATA_DB_IDENTIFIER "c299fde0-6d42-4ec4-b939-34f680ffe39f"
class IStorageFactory
{
public:
typedef void (*key_load_iterator)(const char *rgchKey, size_t cchKey, void *privdata);
virtual ~IStorageFactory() {}
virtual class IStorage *create(int db, key_load_iterator itr, void *privdata) = 0;
virtual class IStorage *createMetadataDb() = 0;
virtual const char *name() const = 0;
virtual size_t totalDiskspaceUsed() const = 0;
virtual sdsstring getInfo() const = 0;
virtual bool FSlow() const = 0;
virtual size_t filedsRequired() const { return 0; }
};
class IStorage
{
public:
typedef std::function<bool(const char *, size_t, const void *, size_t)> callback;
typedef std::function<void(const char *, size_t, const void *, size_t)> callbackSingle;
virtual ~IStorage();
virtual void insert(const char *key, size_t cchKey, void *data, size_t cb, bool fOverwire) = 0;
virtual bool erase(const char *key, size_t cchKey) = 0;
virtual void retrieve(const char *key, size_t cchKey, callbackSingle fn) const = 0;
virtual size_t clear() = 0;
virtual bool enumerate(callback fn) const = 0;
virtual bool enumerate_hashslot(callback fn, unsigned int hashslot) const = 0;
virtual size_t count() const = 0;
virtual void bulkInsert(char **rgkeys, size_t *rgcbkeys, char **rgvals, size_t *rgcbvals, size_t celem) {
beginWriteBatch();
for (size_t ielem = 0; ielem < celem; ++ielem) {
insert(rgkeys[ielem], rgcbkeys[ielem], rgvals[ielem], rgcbvals[ielem], false);
}
endWriteBatch();
}
virtual std::vector<std::string> getExpirationCandidates(unsigned int count) = 0;
virtual std::vector<std::string> getEvictionCandidates(unsigned int count) = 0;
virtual void setExpire(const char *key, size_t cchKey, long long expire) = 0;
virtual void removeExpire(const char *key, size_t cchKey, long long expire) = 0;
virtual void beginWriteBatch() {} // NOP
virtual void endWriteBatch() {} // NOP
virtual void batch_lock() {} // NOP
virtual void batch_unlock() {} // NOP
virtual void flush() = 0;
/* This is permitted to be a shallow clone */
virtual const IStorage *clone() const = 0;
};
+11 -52
View File
@@ -12,20 +12,16 @@
# Dependencies are stored in the Makefile.dep file. To rebuild this file
# Just use 'make dep', but this is only needed by developers.
# we ship KeyDB with TLS by default
# export it here as both this file and deps/Makefile uses it
export BUILD_TLS ?= yes
release_hdr := $(shell sh -c './mkreleasehdr.sh')
uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')
uname_M := $(shell sh -c 'uname -m 2>/dev/null || echo not')
OPTIMIZATION?=-O2 -flto
OPTIMIZATION?=-O2
DEPENDENCY_TARGETS=hiredis linenoise lua hdr_histogram
NODEPS:=clean distclean
# Default settings
STD=-pedantic -DREDIS_STATIC=''
CXX_STD=-std=c++17 -pedantic -fno-rtti -D__STDC_FORMAT_MACROS
CXX_STD=-std=c++14 -pedantic -fno-rtti -D__STDC_FORMAT_MACROS
ifneq (,$(findstring clang,$(CC)))
STD+=-Wno-c11-extensions
else
@@ -62,7 +58,6 @@ endif
endif
USEASM?=true
ENABLE_FLASH?=no
ifneq ($(strip $(SANITIZE)),)
CFLAGS+= -fsanitize=$(SANITIZE) -DSANITIZE -fno-omit-frame-pointer
@@ -72,19 +67,6 @@ ifneq ($(strip $(SANITIZE)),)
USEASM=false
endif
ifeq ($(ENABLE_FLASH),yes)
FINAL_LIBS+= -lz -lcrypto -lbz2 -lzstd -llz4 -lsnappy
CXXFLAGS+= -I../deps/rocksdb/include/ -DENABLE_ROCKSDB
STORAGE_OBJ+= storage/rocksdb.o storage/rocksdbfactory.o
FINAL_LIBS+= ../deps/rocksdb/librocksdb.a
DEPENDENCY_TARGETS+= rocksdb
endif
ifeq ($(CHECKED),true)
CXXFLAGS+= -DCHECKED_BUILD
endif
# Do we use our assembly spinlock? X64 only
ifeq ($(uname_S),Linux)
ifeq ($(uname_M),x86_64)
@@ -100,6 +82,7 @@ endif
ifeq ($(COMPILER_NAME),clang)
CXXFLAGS+= -stdlib=libc++
LDFLAGS+= -latomic
endif
# To get ARM stack traces if KeyDB crashes we need a special C flag.
@@ -130,24 +113,17 @@ ifeq ($(USE_JEMALLOC),no)
MALLOC=libc
endif
ifeq ($(NO_LICENSE_CHECK),yes)
CXXFLAGS+=-DNO_LICENSE_CHECK=1
endif
# Override default settings if possible
-include .make-settings
DEBUG=-g -ggdb
FINAL_CFLAGS=$(STD) $(WARN) $(OPT) $(DEBUG) $(CFLAGS) $(KEYDB_CFLAGS) $(REDIS_CFLAGS)
FINAL_CXXFLAGS=$(CXX_STD) $(WARN) $(OPT) $(DEBUG) $(CXXFLAGS) $(KEYDB_CFLAGS) $(REDIS_CFLAGS)
FINAL_LDFLAGS=$(LDFLAGS) $(KEYDB_LDFLAGS) $(DEBUG)
FINAL_LIBS+=-lm -lz -lcrypto
FINAL_LIBS+=-lm
DEBUG=-g -ggdb
ifneq ($(uname_S),Darwin)
ifneq ($(uname_S),FreeBSD)
FINAL_LIBS+=-latomic
endif
endif
# Linux ARM32 needs -latomic at linking time
ifneq (,$(findstring armv,$(uname_M)))
@@ -213,13 +189,7 @@ ifeq ($(uname_S),NetBSD)
else
ifeq ($(uname_S),FreeBSD)
# FreeBSD
FINAL_LIBS+= -lpthread -luuid -lexecinfo
FINAL_CFLAGS+= -I/usr/local/include
FINAL_CXXFLAGS+= -I/usr/local/include
FINAL_LDFLAGS+= -L/usr/local/lib
ifeq ($(USE_BACKTRACE),yes)
FINAL_CFLAGS+= -DUSE_BACKTRACE
endif
FINAL_LIBS+= -lpthread -lexecinfo
else
ifeq ($(uname_S),DragonFly)
# DragonFly
@@ -260,7 +230,6 @@ endif
ifdef OPENSSL_PREFIX
OPENSSL_CFLAGS=-I$(OPENSSL_PREFIX)/include
OPENSSL_CXXFLAGS=-I$(OPENSSL_PREFIX)/include
OPENSSL_LDFLAGS=-L$(OPENSSL_PREFIX)/lib
# Also export OPENSSL_PREFIX so it ends up in deps sub-Makefiles
export OPENSSL_PREFIX
@@ -268,7 +237,7 @@ endif
# Include paths to dependencies
FINAL_CFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src -I../deps/hdr_histogram
FINAL_CXXFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src -I../deps/hdr_histogram -I../deps/rocksdb/include/ -I../deps/concurrentqueue
FINAL_CXXFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src -I../deps/hdr_histogram
# Determine systemd support and/or build preference (defaulting to auto-detection)
BUILD_WITH_SYSTEMD=no
@@ -377,17 +346,15 @@ ENDCOLOR="\033[0m"
ifndef V
QUIET_CC = @printf ' %b %b\n' $(CCCOLOR)CC$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR);
QUIET_CP = @printf ' %b %b\n' $(CCCOLOR)COPY$(ENDCOLOR) $(SRCCOLOR)$@$(ENDCOLOR);
QUIET_LINK = @printf ' %b %b\n' $(LINKCOLOR)LINK$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR);
QUIET_INSTALL = @printf ' %b %b\n' $(LINKCOLOR)INSTALL$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR);
endif
REDIS_SERVER_NAME=keydb-server$(PROG_SUFFIX)
REDIS_SENTINEL_NAME=keydb-sentinel$(PROG_SUFFIX)
REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o t_nhash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crcspeed.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o t_stream.o listpack.o localtime.o acl.o storage.o rdb-s3.o fastlock.o new.o tracking.o cron.o connection.o tls.o sha256.o motd_server.o timeout.o setcpuaffinity.o AsyncWorkQueue.o snapshot.o storage/teststorageprovider.o keydbutils.o StorageCache.o monotonic.o cli_common.o mt19937-64.o meminfo.o $(ASM_OBJ) $(STORAGE_OBJ)
KEYDB_SERVER_OBJ=SnapshotPayloadParseState.o
REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o t_nhash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crcspeed.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o t_stream.o listpack.o localtime.o acl.o storage.o rdb-s3.o fastlock.o new.o tracking.o cron.o connection.o tls.o sha256.o motd.o timeout.o setcpuaffinity.o monotonic.o mt19937-64.o $(ASM_OBJ)
REDIS_CLI_NAME=keydb-cli$(PROG_SUFFIX)
REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o redis-cli-cpphelper.o zmalloc.o release.o anet.o ae.o crcspeed.o crc64.o siphash.o crc16.o storage-lite.o fastlock.o motd_client.o monotonic.o cli_common.o mt19937-64.o $(ASM_OBJ)
REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o redis-cli-cpphelper.o zmalloc.o release.o anet.o ae.o crcspeed.o crc64.o siphash.o crc16.o storage-lite.o fastlock.o new.o motd.o monotonic.o cli_common.o mt19937-64.o $(ASM_OBJ)
REDIS_BENCHMARK_NAME=keydb-benchmark$(PROG_SUFFIX)
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o dict.o zmalloc.o release.o crcspeed.o crc64.o siphash.o redis-benchmark.o storage-lite.o fastlock.o new.o monotonic.o cli_common.o mt19937-64.o $(ASM_OBJ)
REDIS_CHECK_RDB_NAME=keydb-check-rdb$(PROG_SUFFIX)
@@ -444,7 +411,7 @@ endif
@touch $@
# keydb-server
$(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ) $(KEYDB_SERVER_OBJ)
$(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ)
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/lua/src/liblua.a $(FINAL_LIBS)
# keydb-sentinel
@@ -471,18 +438,12 @@ $(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ)
$(KEYDB_DIAGNOSTIC_NAME): $(KEYDB_DIAGNOSTIC_OBJ)
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS)
DEP = $(REDIS_SERVER_OBJ:%.o=%.d) $(KEYDB_SERVER_OBJ:%.o=%.d) $(REDIS_CLI_OBJ:%.o=%.d) $(REDIS_BENCHMARK_OBJ:%.o=%.d)
DEP = $(REDIS_SERVER_OBJ:%.o=%.d) $(REDIS_CLI_OBJ:%.o=%.d) $(REDIS_BENCHMARK_OBJ:%.o=%.d)
-include $(DEP)
# Because the jemalloc.h header is generated as a part of the jemalloc build,
# building it should complete before building any other object. Instead of
# depending on a single artifact, build all dependencies first.
motd_client.o: motd.cpp .make-prerequisites
$(REDIS_CXX) -MMD -o motd_client.o -c $< -DCLIENT -fno-lto
motd_server.o: motd.cpp .make-prerequisites
$(REDIS_CXX) -MMD -o motd_server.o -c $< -DSERVER
%.o: %.c .make-prerequisites
$(REDIS_CC) -MMD -o $@ -c $<
@@ -494,8 +455,6 @@ motd_server.o: motd.cpp .make-prerequisites
clean:
rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) $(KEYDB_DIAGNOSTIC_NAME) *.o *.gcda *.gcno *.gcov KeyDB.info lcov-html Makefile.dep
rm -rf storage/*.o
rm -rf keydb-server
rm -f $(DEP)
.PHONY: clean
-344
View File
@@ -1,344 +0,0 @@
#include "server.h"
#include "SnapshotPayloadParseState.h"
#include <sys/mman.h>
static const size_t SLAB_SIZE = 2*1024*1024; // Note 64 MB because we try to give 64MB to a block
class SlabAllocator
{
class Slab {
char *m_pv = nullptr;
size_t m_cb = 0;
size_t m_cbAllocated = 0;
public:
Slab(size_t cbAllocate) {
m_pv = (char*)zmalloc(cbAllocate);
m_cb = cbAllocate;
}
~Slab() {
zfree(m_pv);
}
Slab(Slab &&other) {
m_pv = other.m_pv;
m_cb = other.m_cb;
m_cbAllocated = other.m_cbAllocated;
other.m_pv = nullptr;
other.m_cb = 0;
other.m_cbAllocated = 0;
}
bool canAllocate(size_t cb) const {
return (m_cbAllocated + cb) <= m_cb;
}
void *allocate(size_t cb) {
if ((m_cbAllocated + cb) > m_cb)
return nullptr;
void *pvret = m_pv + m_cbAllocated;
m_cbAllocated += cb;
return pvret;
}
};
std::vector<Slab> m_vecslabs;
public:
void *allocate(size_t cb) {
if (m_vecslabs.empty() || !m_vecslabs.back().canAllocate(cb)) {
m_vecslabs.emplace_back(std::max(cb, SLAB_SIZE));
}
return m_vecslabs.back().allocate(cb);
}
};
static uint64_t dictCStringHash(const void *key) {
return dictGenHashFunction((unsigned char*)key, strlen((char*)key));
}
static void dictKeyDestructor(void *privdata, void *key)
{
DICT_NOTUSED(privdata);
sdsfree((sds)key);
}
static int dictCStringCompare(void *, const void *key1, const void *key2)
{
int l1,l2;
l1 = strlen((sds)key1);
l2 = strlen((sds)key2);
if (l1 != l2) return 0;
return memcmp(key1, key2, l1) == 0;
}
dictType metadataLongLongDictType = {
dictCStringHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictCStringCompare, /* key compare */
dictKeyDestructor, /* key destructor */
nullptr, /* val destructor */
nullptr, /* allow to expand */
nullptr /* async free destructor */
};
dictType metadataDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictSdsDestructor, /* val destructor */
nullptr, /* allow to expand */
nullptr /* async free destructor */
};
SnapshotPayloadParseState::ParseStageName SnapshotPayloadParseState::getNextStage() {
if (stackParse.empty())
return ParseStageName::Global;
switch (stackParse.back().name)
{
case ParseStageName::None:
return ParseStageName::Global;
case ParseStageName::Global:
if (stackParse.back().arraycur == 0)
return ParseStageName::MetaData;
else if (stackParse.back().arraycur == 1)
return ParseStageName::Databases;
break;
case ParseStageName::MetaData:
return ParseStageName::KeyValuePair;
case ParseStageName::Databases:
return ParseStageName::Dataset;
case ParseStageName::Dataset:
return ParseStageName::KeyValuePair;
default:
break;
}
throw "Bad protocol: corrupt state";
}
void SnapshotPayloadParseState::flushQueuedKeys() {
if (vecqueuedKeys.empty())
return;
serverAssert(current_database >= 0);
// TODO: We can't finish parse until all the work functions finish
int idb = current_database;
serverAssert(vecqueuedKeys.size() == vecqueuedVals.size());
auto sizePrev = vecqueuedKeys.size();
(*insertsInFlight)++;
std::weak_ptr<std::atomic<int>> insertsInFlightTmp = insertsInFlight; // C++ GRRRRRRRRRRRRRRRR, we don't want to capute "this" because that's dangerous
if (current_database < cserver.dbnum) {
g_pserver->asyncworkqueue->AddWorkFunction([idb, vecqueuedKeys = std::move(this->vecqueuedKeys), vecqueuedKeysCb = std::move(this->vecqueuedKeysCb), vecqueuedVals = std::move(this->vecqueuedVals), vecqueuedValsCb = std::move(this->vecqueuedValsCb), insertsInFlightTmp, pallocator = m_spallocator.release()]() mutable {
g_pserver->db[idb]->bulkDirectStorageInsert(vecqueuedKeys.data(), vecqueuedKeysCb.data(), vecqueuedVals.data(), vecqueuedValsCb.data(), vecqueuedKeys.size());
(*(insertsInFlightTmp.lock()))--;
delete pallocator;
});
} else {
// else drop the data
vecqueuedKeys.clear();
vecqueuedKeysCb.clear();
vecqueuedVals.clear();
vecqueuedValsCb.clear();
// Note: m_spallocator will get free'd when overwritten below
}
m_spallocator = std::make_unique<SlabAllocator>();
cbQueued = 0;
vecqueuedKeys.reserve(sizePrev);
vecqueuedKeysCb.reserve(sizePrev);
vecqueuedVals.reserve(sizePrev);
vecqueuedValsCb.reserve(sizePrev);
serverAssert(vecqueuedKeys.empty());
serverAssert(vecqueuedVals.empty());
}
SnapshotPayloadParseState::SnapshotPayloadParseState() {
// This is to represent the first array the client is intended to send us
ParseStage stage;
stage.name = ParseStageName::None;
stage.arraylen = 1;
stackParse.push_back(stage);
dictLongLongMetaData = dictCreate(&metadataLongLongDictType, nullptr);
dictMetaData = dictCreate(&metadataDictType, nullptr);
insertsInFlight = std::make_shared<std::atomic<int>>();
m_spallocator = std::make_unique<SlabAllocator>();
}
SnapshotPayloadParseState::~SnapshotPayloadParseState() {
dictRelease(dictLongLongMetaData);
dictRelease(dictMetaData);
}
const char *SnapshotPayloadParseState::getStateDebugName(ParseStage stage) {
switch (stage.name) {
case ParseStageName::None:
return "None";
case ParseStageName::Global:
return "Global";
case ParseStageName::MetaData:
return "MetaData";
case ParseStageName::Databases:
return "Databases";
case ParseStageName::KeyValuePair:
return "KeyValuePair";
case ParseStageName::Dataset:
return "Dataset";
default:
return "Unknown";
}
}
size_t SnapshotPayloadParseState::depth() const { return stackParse.size(); }
void SnapshotPayloadParseState::trimState() {
while (!stackParse.empty() && (stackParse.back().arraycur == stackParse.back().arraylen))
stackParse.pop_back();
if (stackParse.empty()) {
flushQueuedKeys();
while (*insertsInFlight > 0) {
// TODO: ProcessEventsWhileBlocked
aeReleaseLock();
aeAcquireLock();
}
}
}
void SnapshotPayloadParseState::pushArray(long long size) {
if (stackParse.empty())
throw "Bad Protocol: unexpected trailing data";
if (size == 0) {
stackParse.back().arraycur++;
return;
}
if (stackParse.back().name == ParseStageName::Databases) {
flushQueuedKeys();
current_database = stackParse.back().arraycur;
}
ParseStage stage;
stage.name = getNextStage();
stage.arraylen = size;
if (stage.name == ParseStageName::Dataset) {
g_pserver->db[current_database]->expand(stage.arraylen);
}
// Note: This affects getNextStage so ensure its after
stackParse.back().arraycur++;
stackParse.push_back(stage);
}
void SnapshotPayloadParseState::pushValue(const char *rgch, long long cch) {
if (stackParse.empty())
throw "Bad Protocol: unexpected trailing bulk string";
if (stackParse.back().arraycur >= static_cast<int>(stackParse.back().arrvalues.size()))
throw "Bad protocol: Unexpected value";
auto &stage = stackParse.back();
stage.arrvalues[stackParse.back().arraycur].first = (char*)m_spallocator->allocate(cch);
stage.arrvalues[stackParse.back().arraycur].second = cch;
memcpy(stage.arrvalues[stackParse.back().arraycur].first, rgch, cch);
stage.arraycur++;
switch (stage.name) {
case ParseStageName::KeyValuePair:
if (stackParse.size() < 2)
throw "Bad Protocol: unexpected bulk string";
if (stackParse[stackParse.size()-2].name == ParseStageName::MetaData) {
if (stage.arraycur == 2) {
// We loaded both pairs
if (stage.arrvalues[0].first == nullptr || stage.arrvalues[1].first == nullptr)
throw "Bad Protocol: Got array when expecing a string"; // A baddy could make us derefence the vector when its too small
if (!strcasecmp(stage.arrvalues[0].first, "lua")) {
/* Load the script back in memory. */
robj *auxval = createStringObject(stage.arrvalues[1].first, stage.arrvalues[1].second);
if (luaCreateFunction(NULL,g_pserver->lua,auxval) == NULL) {
throw "Can't load Lua script";
}
} else {
dictAdd(dictMetaData, sdsnewlen(stage.arrvalues[0].first, stage.arrvalues[0].second), sdsnewlen(stage.arrvalues[1].first, stage.arrvalues[1].second));
}
}
} else if (stackParse[stackParse.size()-2].name == ParseStageName::Dataset) {
if (stage.arraycur == 2) {
// We loaded both pairs
if (stage.arrvalues[0].first == nullptr || stage.arrvalues[1].first == nullptr)
throw "Bad Protocol: Got array when expecing a string"; // A baddy could make us derefence the vector when its too small
vecqueuedKeys.push_back(stage.arrvalues[0].first);
vecqueuedKeysCb.push_back(stage.arrvalues[0].second);
vecqueuedVals.push_back(stage.arrvalues[1].first);
vecqueuedValsCb.push_back(stage.arrvalues[1].second);
stage.arrvalues[0].first = nullptr;
stage.arrvalues[1].first = nullptr;
cbQueued += vecqueuedKeysCb.back();
cbQueued += vecqueuedValsCb.back();
if (cbQueued >= queuedBatchLimit)
flushQueuedKeys();
}
} else {
throw "Bad Protocol: unexpected bulk string";
}
break;
default:
throw "Bad Protocol: unexpected bulk string out of KV pair";
}
}
void SnapshotPayloadParseState::pushValue(long long value) {
if (stackParse.empty())
throw "Bad Protocol: unexpected integer value";
stackParse.back().arraycur++;
if (stackParse.back().arraycur != 2 || stackParse.back().arrvalues[0].first == nullptr)
throw "Bad Protocol: unexpected integer value";
dictEntry *de = dictAddRaw(dictLongLongMetaData, sdsnewlen(stackParse.back().arrvalues[0].first, stackParse.back().arrvalues[0].second), nullptr);
if (de == nullptr)
throw "Bad Protocol: metadata field sent twice";
de->v.s64 = value;
}
long long SnapshotPayloadParseState::getMetaDataLongLong(const char *szField) const {
dictEntry *de = dictFind(dictLongLongMetaData, szField);
if (de == nullptr) {
serverLog(LL_WARNING, "Master did not send field: %s", szField);
throw false;
}
return de->v.s64;
}
sds SnapshotPayloadParseState::getMetaDataStr(const char *szField) const {
sdsstring str(szField, strlen(szField));
dictEntry *de = dictFind(dictMetaData, str.get());
if (de == nullptr) {
serverLog(LL_WARNING, "Master did not send field: %s", szField);
throw false;
}
return (sds)de->v.val;
}
-66
View File
@@ -1,66 +0,0 @@
#pragma once
#include <stack>
#include <vector>
class SlabAllocator;
class SnapshotPayloadParseState {
enum class ParseStageName {
None,
Global,
MetaData,
Databases,
Dataset,
KeyValuePair,
};
struct ParseStage {
ParseStageName name;
long long arraylen = 0;
long long arraycur = 0;
std::array<std::pair<char*, size_t>, 2> arrvalues;
ParseStage() {
for (auto &pair : arrvalues) {
pair.first = nullptr;
pair.second = 0;
}
}
};
std::vector<ParseStage> stackParse;
std::vector<char*> vecqueuedKeys;
std::vector<size_t> vecqueuedKeysCb;
std::vector<char*> vecqueuedVals;
std::vector<size_t> vecqueuedValsCb;
std::shared_ptr<std::atomic<int>> insertsInFlight;
std::unique_ptr<SlabAllocator> m_spallocator;
dict *dictLongLongMetaData = nullptr;
dict *dictMetaData = nullptr;
size_t cbQueued = 0;
static const size_t queuedBatchLimit = 64*1024*1024; // 64 MB
int current_database = -1;
ParseStageName getNextStage();
void flushQueuedKeys();
public:
SnapshotPayloadParseState();
~SnapshotPayloadParseState();
long long getMetaDataLongLong(const char *field) const;
sds getMetaDataStr(const char *szField) const;
static const char *getStateDebugName(ParseStage stage);
size_t depth() const;
void trimState();
void pushArray(long long size);
void pushValue(const char *rgch, long long cch);
void pushValue(long long value);
bool shouldThrottle() const { return *insertsInFlight > (cserver.cthreads*4); }
};
-236
View File
@@ -1,236 +0,0 @@
#include "server.h"
uint64_t hashPassthrough(const void *hash) {
return static_cast<uint64_t>(reinterpret_cast<uintptr_t>(hash));
}
int hashCompare(void *, const void *key1, const void *key2) {
auto diff = (reinterpret_cast<uintptr_t>(key1) - reinterpret_cast<uintptr_t>(key2));
return !diff;
}
dictType dbStorageCacheType = {
hashPassthrough, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
hashCompare, /* key compare */
NULL, /* key destructor */
NULL /* val destructor */
};
StorageCache::StorageCache(IStorage *storage, bool fCache)
: m_spstorage(storage)
{
if (!g_pserver->flash_disable_key_cache && fCache)
m_pdict = dictCreate(&dbStorageCacheType, nullptr);
}
StorageCache::~StorageCache()
{
if (m_pdict != nullptr)
dictRelease(m_pdict);
}
void StorageCache::clear(void(callback)(void*))
{
std::unique_lock<fastlock> ul(m_lock);
if (m_pdict != nullptr)
dictEmpty(m_pdict, callback);
m_spstorage->clear();
m_collisionCount = 0;
}
void StorageCache::clearAsync()
{
std::unique_lock<fastlock> ul(m_lock);
if (count() == 0)
return;
if (m_pdict != nullptr) {
dict *dSav = m_pdict;
m_pdict = dictCreate(&dbStorageCacheType, nullptr);
g_pserver->asyncworkqueue->AddWorkFunction([dSav]{
dictEmpty(dSav, nullptr);
});
}
m_spstorage->clear();
m_collisionCount = 0;
}
void StorageCache::cacheKey(sds key)
{
if (m_pdict == nullptr)
return;
uintptr_t hash = dictSdsHash(key);
if (dictAdd(m_pdict, reinterpret_cast<void*>(hash), (void*)1) != DICT_OK) {
dictEntry *de = dictFind(m_pdict, reinterpret_cast<void*>(hash));
serverAssert(de != nullptr);
de->v.s64++;
m_collisionCount++;
}
}
void StorageCache::cacheKey(const char *rgch, size_t cch)
{
if (m_pdict == nullptr)
return;
uintptr_t hash = dictGenHashFunction(rgch, (int)cch);
if (dictAdd(m_pdict, reinterpret_cast<void*>(hash), (void*)1) != DICT_OK) {
dictEntry *de = dictFind(m_pdict, reinterpret_cast<void*>(hash));
serverAssert(de != nullptr);
de->v.s64++;
m_collisionCount++;
}
}
bool StorageCache::erase(sds key)
{
unsigned long long when = 0;
m_spstorage->retrieve(key, sdslen(key), [&when](const char *, size_t, const void * data, size_t cbdata) {
auto e = deserializeExpire((const char *)data, cbdata, nullptr);
if (e != nullptr)
when = e->when();
});
bool result = m_spstorage->erase(key, sdslen(key));
std::unique_lock<fastlock> ul(m_lock);
if (result)
{
if (m_pdict != nullptr)
{
uint64_t hash = dictSdsHash(key);
dictEntry *de = dictFind(m_pdict, reinterpret_cast<void*>(hash));
serverAssert(de != nullptr);
de->v.s64--;
serverAssert(de->v.s64 >= 0);
if (de->v.s64 == 0) {
dictDelete(m_pdict, reinterpret_cast<void*>(hash));
} else {
m_collisionCount--;
}
}
if (when != 0) {
m_spstorage->removeExpire(key, sdslen(key), when);
}
}
return result;
}
void StorageCache::insert(sds key, const void *data, size_t cbdata, bool fOverwrite)
{
std::unique_lock<fastlock> ul(m_lock);
if (!fOverwrite && m_pdict != nullptr)
{
cacheKey(key);
}
ul.unlock();
m_spstorage->insert(key, sdslen(key), (void*)data, cbdata, fOverwrite);
auto e = deserializeExpire((const char *)data, cbdata, nullptr);
if (e != nullptr)
m_spstorage->setExpire(key, sdslen(key), e->when());
}
long _dictKeyIndex(dict *d, const void *key, uint64_t hash, dictEntry **existing);
void StorageCache::bulkInsert(char **rgkeys, size_t *rgcbkeys, char **rgvals, size_t *rgcbvals, size_t celem)
{
std::vector<dictEntry*> vechashes;
if (m_pdict != nullptr) {
vechashes.reserve(celem);
}
for (size_t ielem = 0; ielem < celem; ++ielem) {
if (m_pdict != nullptr) {
dictEntry *de = (dictEntry*)zmalloc(sizeof(dictEntry));
de->key = (void*)dictGenHashFunction(rgkeys[ielem], (int)rgcbkeys[ielem]);
de->v.u64 = 1;
vechashes.push_back(de);
}
auto e = deserializeExpire(rgvals[ielem], rgcbvals[ielem], nullptr);
if (e != nullptr)
m_spstorage->setExpire(rgkeys[ielem], rgcbkeys[ielem], e->when());
}
std::unique_lock<fastlock> ul(m_lock);
bulkInsertsInProgress++;
if (m_pdict != nullptr) {
for (dictEntry *de : vechashes) {
if (dictIsRehashing(m_pdict)) dictRehash(m_pdict,1);
/* Get the index of the new element, or -1 if
* the element already exists. */
long index;
if ((index = _dictKeyIndex(m_pdict, de->key, (uint64_t)de->key, nullptr)) == -1) {
dictEntry *deLocal = dictFind(m_pdict, de->key);
serverAssert(deLocal != nullptr);
deLocal->v.s64++;
m_collisionCount++;
zfree(de);
} else {
int iht = dictIsRehashing(m_pdict) ? 1 : 0;
de->next = m_pdict->ht[iht].table[index];
m_pdict->ht[iht].table[index] = de;
m_pdict->ht[iht].used++;
}
}
}
ul.unlock();
m_spstorage->bulkInsert(rgkeys, rgcbkeys, rgvals, rgcbvals, celem);
bulkInsertsInProgress--;
}
const StorageCache *StorageCache::clone()
{
std::unique_lock<fastlock> ul(m_lock);
// Clones never clone the cache
StorageCache *cacheNew = new StorageCache(const_cast<IStorage*>(m_spstorage->clone()), false /*fCache*/);
return cacheNew;
}
void StorageCache::expand(uint64_t slots)
{
std::unique_lock<fastlock> ul(m_lock);
if (m_pdict) {
dictExpand(m_pdict, slots);
}
}
void StorageCache::retrieve(sds key, IStorage::callbackSingle fn) const
{
std::unique_lock<fastlock> ul(m_lock);
if (m_pdict != nullptr)
{
uint64_t hash = dictSdsHash(key);
dictEntry *de = dictFind(m_pdict, reinterpret_cast<void*>(hash));
if (de == nullptr)
return; // Not found
}
ul.unlock();
m_spstorage->retrieve(key, sdslen(key), fn);
}
size_t StorageCache::count() const
{
std::unique_lock<fastlock> ul(m_lock, std::defer_lock);
bool fLocked = ul.try_lock();
size_t count = m_spstorage->count();
if (m_pdict != nullptr && fLocked) {
serverAssert(bulkInsertsInProgress.load(std::memory_order_seq_cst) || count == (dictSize(m_pdict) + m_collisionCount));
}
return count;
}
void StorageCache::beginWriteBatch() {
serverAssert(GlobalLocksAcquired()); // Otherwise we deadlock
m_spstorage->beginWriteBatch();
}
void StorageCache::emergencyFreeCache() {
std::unique_lock<fastlock> ul(m_lock);
dict *d = m_pdict;
m_pdict = nullptr;
if (d != nullptr) {
g_pserver->asyncworkqueue->AddWorkFunction([d]{
dictRelease(d);
});
}
}
-69
View File
@@ -1,69 +0,0 @@
#pragma once
#include "sds.h"
class StorageCache
{
std::shared_ptr<IStorage> m_spstorage;
dict *m_pdict = nullptr;
int m_collisionCount = 0;
mutable fastlock m_lock {"StorageCache"};
std::atomic<int> bulkInsertsInProgress;
StorageCache(IStorage *storage, bool fNoCache);
void cacheKey(sds key);
void cacheKey(const char *rgchKey, size_t cchKey);
struct load_iter_data
{
StorageCache *cache;
IStorageFactory::key_load_iterator itrParent;
void *privdataParent;
};
static void key_load_itr(const char *rgchKey, size_t cchKey, void *privdata)
{
load_iter_data *data = (load_iter_data*)privdata;
data->cache->cacheKey(rgchKey, cchKey);
if (data->itrParent)
data->itrParent(rgchKey, cchKey, data->privdataParent);
}
public:
~StorageCache();
static StorageCache *create(IStorageFactory *pfactory, int db, IStorageFactory::key_load_iterator fn, void *privdata) {
StorageCache *cache = new StorageCache(nullptr, pfactory->FSlow() /*fCache*/);
load_iter_data data = {cache, fn, privdata};
cache->m_spstorage = std::shared_ptr<IStorage>(pfactory->create(db, key_load_itr, (void*)&data));
return cache;
}
void clear(void(callback)(void*));
void clearAsync();
void insert(sds key, const void *data, size_t cbdata, bool fOverwrite);
void bulkInsert(char **rgkeys, size_t *rgcbkeys, char **rgvals, size_t *rgcbvals, size_t celem);
void retrieve(sds key, IStorage::callbackSingle fn) const;
bool erase(sds key);
void emergencyFreeCache();
bool keycacheIsEnabled() const { return m_pdict != nullptr; }
void expand(uint64_t slots);
bool enumerate(IStorage::callback fn) const { return m_spstorage->enumerate(fn); }
bool enumerate_hashslot(IStorage::callback fn, unsigned int hashslot) const { return m_spstorage->enumerate_hashslot(fn, hashslot); }
std::vector<std::string> getExpirationCandidates(unsigned int count) { return m_spstorage->getExpirationCandidates(count); }
std::vector<std::string> getEvictionCandidates(unsigned int count) { return m_spstorage->getEvictionCandidates(count); }
void setExpire(const char *key, size_t cchKey, long long expire) { m_spstorage->setExpire(key, cchKey, expire); }
void removeExpire(const char *key, size_t cchKey, long long expire) { m_spstorage->removeExpire(key, cchKey, expire); }
void beginWriteBatch();
void endWriteBatch() { m_spstorage->endWriteBatch(); }
void batch_lock() { return m_spstorage->batch_lock(); }
void batch_unlock() { return m_spstorage->batch_unlock(); }
void flush() { m_spstorage->flush(); }
size_t count() const;
const StorageCache *clone();
};
+12 -72
View File
@@ -113,8 +113,6 @@ enum class AE_ASYNC_OP
PostCppFunction,
DeleteFileEvent,
CreateFileEvent,
PostAsynDBFunction,
};
struct aeCommand
@@ -127,18 +125,12 @@ struct aeCommand
aePostFunctionProc *proc;
aeFileProc *fproc;
std::function<void()> *pfn;
aePostFunctionTokenProc* tproc;
};
void *clientData;
};
#ifdef PIPE_BUF
static_assert(sizeof(aeCommand) <= PIPE_BUF, "aeCommand must be small enough to send atomically through a pipe");
#endif
void aeProcessCmd(aeEventLoop *eventLoop, int fd, void *, int )
{
std::unique_lock<decltype(g_lock)> ulock(g_lock, std::defer_lock);
aeCommand cmd;
for (;;)
{
@@ -160,7 +152,8 @@ void aeProcessCmd(aeEventLoop *eventLoop, int fd, void *, int )
case AE_ASYNC_OP::PostFunction:
{
if (cmd.fLock && !ulock.owns_lock()) {
std::unique_lock<decltype(g_lock)> ulock(g_lock, std::defer_lock);
if (cmd.fLock) {
g_forkLock.releaseRead();
ulock.lock();
g_forkLock.acquireRead();
@@ -171,7 +164,8 @@ void aeProcessCmd(aeEventLoop *eventLoop, int fd, void *, int )
case AE_ASYNC_OP::PostCppFunction:
{
if (cmd.fLock && !ulock.owns_lock()) {
std::unique_lock<decltype(g_lock)> ulock(g_lock, std::defer_lock);
if (cmd.fLock) {
g_forkLock.releaseRead();
ulock.lock();
g_forkLock.acquireRead();
@@ -179,17 +173,6 @@ void aeProcessCmd(aeEventLoop *eventLoop, int fd, void *, int )
(*cmd.pfn)();
delete cmd.pfn;
break;
}
case AE_ASYNC_OP::PostAsynDBFunction:
{ //added to support async api IStorage
if (cmd.fLock && !ulock.owns_lock()) {
g_forkLock.releaseRead();
ulock.lock();
g_forkLock.acquireRead();
}
((aePostFunctionTokenProc*)cmd.tproc)(eventLoop,(StorageToken*)cmd.clientData);
break;
}
break;
}
@@ -271,20 +254,6 @@ int aePostFunction(aeEventLoop *eventLoop, aePostFunctionProc *proc, void *arg)
return AE_OK;
}
int aePostFunction(aeEventLoop *eventLoop, aePostFunctionTokenProc *proc, StorageToken *token)
{
//added to support async api IStorage
aeCommand cmd = {};
cmd.op = AE_ASYNC_OP::PostAsynDBFunction;
cmd.tproc = proc;
cmd.clientData = (void*)token;
cmd.fLock = true;
auto size = write(eventLoop->fdCmdWrite, &cmd, sizeof(cmd));
if (size != sizeof(cmd))
return AE_ERR;
return AE_OK;
}
int aePostFunction(aeEventLoop *eventLoop, std::function<void()> fn, bool fLock, bool fForceQueue)
{
if (eventLoop == g_eventLoopThisThread && !fForceQueue)
@@ -295,7 +264,7 @@ int aePostFunction(aeEventLoop *eventLoop, std::function<void()> fn, bool fLock,
aeCommand cmd = {};
cmd.op = AE_ASYNC_OP::PostCppFunction;
cmd.pfn = new std::function<void()>(fn);
cmd.pfn = new (MALLOC_LOCAL) std::function<void()>(fn);
cmd.fLock = fLock;
auto size = write(eventLoop->fdCmdWrite, &cmd, sizeof(cmd));
@@ -745,6 +714,11 @@ int aeProcessEvents(aeEventLoop *eventLoop, int flags)
}
}
if (eventLoop->flags & AE_DONT_WAIT) {
tv.tv_sec = tv.tv_usec = 0;
tvp = &tv;
}
if (eventLoop->beforesleep != NULL && flags & AE_CALL_BEFORE_SLEEP) {
std::unique_lock<decltype(g_lock)> ulock(g_lock, std::defer_lock);
if (!(eventLoop->beforesleepFlags & AE_SLEEP_THREADSAFE)) {
@@ -755,11 +729,6 @@ int aeProcessEvents(aeEventLoop *eventLoop, int flags)
eventLoop->beforesleep(eventLoop);
}
if (eventLoop->flags & AE_DONT_WAIT) {
tv.tv_sec = tv.tv_usec = 0;
tvp = &tv;
}
/* Call the multiplexing API, will return only on timeout or when
* some event fires. */
numevents = aeApiPoll(eventLoop, tvp);
@@ -840,7 +809,6 @@ void aeSetAfterSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *aftersleep,
}
thread_local spin_worker tl_worker = nullptr;
thread_local bool fOwnLockOverride = false;
void setAeLockSetThreadSpinWorker(spin_worker worker)
{
tl_worker = worker;
@@ -878,42 +846,14 @@ void aeReleaseLock()
g_lock.unlock();
}
void aeSetThreadOwnsLockOverride(int fOverride)
{
fOwnLockOverride = fOverride;
}
void aeReleaseForkLock()
{
g_forkLock.downgradeWrite();
}
void aeForkLockInChild()
{
g_forkLock.setMulti(false);
}
int aeThreadOwnsLock()
{
return fOwnLockOverride || g_lock.fOwnLock();
}
int aeLockContested(int threshold)
{
ticket ticketT;
__atomic_load(&g_lock.m_ticket.u, &ticketT.u, __ATOMIC_RELAXED);
return ticketT.m_active < static_cast<uint16_t>(ticketT.m_avail - threshold);
}
int aeLockContention()
{
ticket ticketT;
__atomic_load(&g_lock.m_ticket.u, &ticketT.u, __ATOMIC_RELAXED);
int32_t avail = ticketT.m_avail;
int32_t active = ticketT.m_active;
if (avail < active)
avail += 0x10000;
return avail - active;
return g_lock.fOwnLock();
}
void aeClosePipesForForkChild(aeEventLoop *el)
@@ -922,4 +862,4 @@ void aeClosePipesForForkChild(aeEventLoop *el)
el->fdCmdRead = -1;
close(el->fdCmdWrite);
el->fdCmdWrite = -1;
}
}
+1 -9
View File
@@ -72,15 +72,13 @@ extern "C" {
#define AE_NOTUSED(V) ((void) V)
struct aeEventLoop;
/* Types and data structures */
typedef void aeFileProc(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask);
typedef int aeTimeProc(struct aeEventLoop *eventLoop, long long id, void *clientData);
typedef void aeEventFinalizerProc(struct aeEventLoop *eventLoop, void *clientData);
typedef void aeBeforeSleepProc(struct aeEventLoop *eventLoop);
typedef void aePostFunctionProc(void *pvArgs);
//added to support async api IStorage
struct StorageToken;
typedef void aePostFunctionTokenProc(struct aeEventLoop *el, struct StorageToken *token);
/* File event structure */
typedef struct aeFileEvent {
@@ -136,8 +134,6 @@ int aePostFunction(aeEventLoop *eventLoop, aePostFunctionProc *proc, void *arg);
#ifdef __cplusplus
} // EXTERN C
int aePostFunction(aeEventLoop *eventLoop, std::function<void()> fn, bool fLock = true, bool fForceQueue = false);
//added to support async api IStorage
int aePostFunction(aeEventLoop *eventLoop, aePostFunctionTokenProc *proc, StorageToken *token);
extern "C" {
#endif
void aeDeleteEventLoop(aeEventLoop *eventLoop);
@@ -175,11 +171,7 @@ int aeTryAcquireLock(int fWeak);
void aeThreadOffline();
void aeReleaseLock();
void aeReleaseForkLock();
void aeForkLockInChild();
int aeThreadOwnsLock();
void aeSetThreadOwnsLockOverride(int fOverride);
int aeLockContested(int threshold);
int aeLockContention(); // returns the number of instantaneous threads waiting on the lock
#ifdef __cplusplus
}
+1
View File
@@ -21,6 +21,7 @@ public:
if (c != nullptr)
{
serverAssert(!m_fArmed);
serverAssert(c->lock.fOwnLock());
if (!aeTryAcquireLock(true /*fWeak*/)) // avoid locking the client if we can
+1 -1
View File
@@ -441,7 +441,7 @@ static int _anetTcpServer(char *err, int port, const char *bindaddr, int af, int
char _port[6]; /* strlen("65535") */
struct addrinfo hints, *servinfo, *p;
snprintf(_port,sizeof(_port),"%d",port);
snprintf(_port,6,"%d",port);
memset(&hints,0,sizeof(hints));
hints.ai_family = af;
hints.ai_socktype = SOCK_STREAM;
+51 -58
View File
@@ -285,7 +285,7 @@ int startAppendOnly(void) {
strerror(errno));
return C_ERR;
}
if (hasActiveChildProcessOrBGSave() && g_pserver->child_type != CHILD_TYPE_AOF) {
if (hasActiveChildProcess() && g_pserver->child_type != CHILD_TYPE_AOF) {
g_pserver->aof_rewrite_scheduled = 1;
serverLog(LL_WARNING,"AOF was enabled but there is already another background operation. An AOF background was scheduled to start when possible.");
} else {
@@ -438,7 +438,7 @@ void flushAppendOnlyFile(int force) {
* useful for graphing / monitoring purposes. */
if (sync_in_progress) {
latencyAddSampleIfNeeded("aof-write-pending-fsync",latency);
} else if (hasActiveChildProcessOrBGSave()) {
} else if (hasActiveChildProcess()) {
latencyAddSampleIfNeeded("aof-write-active-child",latency);
} else {
latencyAddSampleIfNeeded("aof-write-alone",latency);
@@ -535,7 +535,7 @@ void flushAppendOnlyFile(int force) {
try_fsync:
/* Don't fsync if no-appendfsync-on-rewrite is set to yes and there are
* children doing I/O in the background. */
if (g_pserver->aof_no_fsync_on_rewrite && hasActiveChildProcessOrBGSave())
if (g_pserver->aof_no_fsync_on_rewrite && hasActiveChildProcess())
return;
/* Perform the fsync if needed. */
@@ -752,7 +752,7 @@ void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int a
* accumulate the differences between the child DB and the current one
* in a buffer, so that when the child process will do its work we
* can append the differences to the new append only file. */
if (hasActiveChildProcess() && g_pserver->child_type == CHILD_TYPE_AOF)
if (g_pserver->child_type == CHILD_TYPE_AOF)
aofRewriteBufferAppend((unsigned char*)buf,sdslen(buf));
sdsfree(buf);
@@ -765,7 +765,7 @@ void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int a
/* In Redis commands are always executed in the context of a client, so in
* order to load the append only file we need to create a fake client. */
struct client *createAOFClient(void) {
struct client *c = new client();
struct client *c =(client*) zmalloc(sizeof(*c), MALLOC_LOCAL);
selectDb(c,0);
c->id = CLIENT_ID_AOF; /* So modules can identify it's the AOF client. */
@@ -778,6 +778,7 @@ struct client *createAOFClient(void) {
c->argv = NULL;
c->original_argc = 0;
c->original_argv = NULL;
c->argv_len_sum = 0;
c->bufpos = 0;
c->fPendingAsyncWrite = FALSE;
c->fPendingAsyncWriteHandler = FALSE;
@@ -805,7 +806,6 @@ struct client *createAOFClient(void) {
c->sockname = NULL;
c->resp = 2;
c->user = NULL;
c->mvccCheckpoint = 0;
listSetFreeMethod(c->reply,freeClientReplyValue);
listSetDupMethod(c->reply,dupClientReplyValue);
fastlock_init(&c->lock, "fake client");
@@ -820,7 +820,7 @@ void freeFakeClientArgv(struct client *c) {
for (j = 0; j < c->argc; j++)
decrRefCount(c->argv[j]);
zfree(c->argv);
c->argv_len_sumActive = 0;
c->argv_len_sum = 0;
}
void freeFakeClient(struct client *c) {
@@ -831,7 +831,7 @@ void freeFakeClient(struct client *c) {
freeClientOriginalArgv(c);
fastlock_unlock(&c->lock);
fastlock_free(&c->lock);
delete c;
zfree(c);
}
/* Replay the append log file. On success C_OK is returned. On non fatal
@@ -870,11 +870,6 @@ int loadAppendOnlyFile(char *filename) {
fakeClient = createAOFClient();
startLoadingFile(fp, filename, RDBFLAGS_AOF_PREAMBLE);
for (int idb = 0; idb < cserver.dbnum; ++idb)
{
g_pserver->db[idb]->trackChanges(true);
}
/* Check if this AOF file has an RDB preamble. In that case we need to
* load the RDB file and later continue loading the AOF tail. */
char sig[5]; /* "REDIS" */
@@ -1010,11 +1005,6 @@ int loadAppendOnlyFile(char *filename) {
}
loaded_ok: /* DB loaded, cleanup and return C_OK to the caller. */
for (int idb = 0; idb < cserver.dbnum; ++idb)
{
if (g_pserver->db[idb]->processChanges(false))
g_pserver->db[idb]->commitChanges();
}
fclose(fp);
freeFakeClient(fakeClient);
g_pserver->aof_state = old_aof_state;
@@ -1548,6 +1538,8 @@ ssize_t aofReadDiffFromParent(void) {
}
int rewriteAppendOnlyFileRio(rio *aof) {
dictIterator *di = NULL;
dictEntry *de;
size_t processed = 0;
int j;
long key_count = 0;
@@ -1555,62 +1547,69 @@ int rewriteAppendOnlyFileRio(rio *aof) {
for (j = 0; j < cserver.dbnum; j++) {
char selectcmd[] = "*2\r\n$6\r\nSELECT\r\n";
redisDb *db = g_pserver->db[j];
if (db->size() == 0) continue;
redisDb *db = g_pserver->db+j;
dict *d = db->dict;
if (dictSize(d) == 0) continue;
di = dictGetSafeIterator(d);
/* SELECT the new DB */
if (rioWrite(aof,selectcmd,sizeof(selectcmd)-1) == 0) goto werr;
if (rioWriteBulkLongLong(aof,j) == 0) goto werr;
/* Iterate this DB writing every entry */
bool fComplete = db->iterate([&](const char *keystr, robj *o)->bool{
while((de = dictNext(di)) != NULL) {
sds keystr;
redisObjectStack key;
initStaticStringObject(key,(sds)keystr);
robj *o = nullptr;
keystr = (sds)dictGetKey(de);
o = (robj*)dictGetVal(de);
initStaticStringObject(key,keystr);
expireEntry *pexpire = getExpire(db,&key);
/* Save the key and associated value */
if (o->type == OBJ_STRING) {
/* Emit a SET command */
char cmd[]="*3\r\n$3\r\nSET\r\n";
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) return false;
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) goto werr;
/* Key and value */
if (rioWriteBulkObject(aof,&key) == 0) return false;
if (rioWriteBulkObject(aof,o) == 0) return false;
if (rioWriteBulkObject(aof,&key) == 0) goto werr;
if (rioWriteBulkObject(aof,o) == 0) goto werr;
} else if (o->type == OBJ_LIST) {
if (rewriteListObject(aof,&key,o) == 0) return false;
if (rewriteListObject(aof,&key,o) == 0) goto werr;
} else if (o->type == OBJ_SET) {
if (rewriteSetObject(aof,&key,o) == 0) return false;
if (rewriteSetObject(aof,&key,o) == 0) goto werr;
} else if (o->type == OBJ_ZSET) {
if (rewriteSortedSetObject(aof,&key,o) == 0) return false;
if (rewriteSortedSetObject(aof,&key,o) == 0) goto werr;
} else if (o->type == OBJ_HASH) {
if (rewriteHashObject(aof,&key,o) == 0) return false;
if (rewriteHashObject(aof,&key,o) == 0) goto werr;
} else if (o->type == OBJ_STREAM) {
if (rewriteStreamObject(aof,&key,o) == 0) return false;
if (rewriteStreamObject(aof,&key,o) == 0) goto werr;
} else if (o->type == OBJ_MODULE) {
if (rewriteModuleObject(aof,&key,o) == 0) return false;
if (rewriteModuleObject(aof,&key,o) == 0) goto werr;
} else {
serverPanic("Unknown object type");
}
/* Save the expire time */
if (o->FExpires()) {
expireEntry *pexpire = &o->expire;
if (pexpire != nullptr) {
for (auto &subExpire : *pexpire) {
if (subExpire.subkey() == nullptr)
{
char cmd[]="*3\r\n$9\r\nPEXPIREAT\r\n";
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) return false;
if (rioWriteBulkObject(aof,&key) == 0) return false;
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) goto werr;
if (rioWriteBulkObject(aof,&key) == 0) goto werr;
}
else
{
char cmd[]="*4\r\n$12\r\nPEXPIREMEMBERAT\r\n";
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) return false;
if (rioWriteBulkObject(aof,&key) == 0) return false;
if (rioWrite(aof,subExpire.subkey(),sdslen(subExpire.subkey())) == 0) return false;
if (rioWrite(aof,cmd,sizeof(cmd)-1) == 0) goto werr;
if (rioWriteBulkObject(aof,&key) == 0) goto werr;
if (rioWrite(aof,subExpire.subkey(),sdslen(subExpire.subkey())) == 0) goto werr;
}
if (rioWriteBulkLongLong(aof,subExpire.when()) == 0) return false; // common
if (rioWriteBulkLongLong(aof,subExpire.when()) == 0) goto werr; // common
}
}
/* Read some diff from the parent process from time to time. */
if (aof->processed_bytes > processed+AOF_READ_DIFF_INTERVAL_BYTES) {
processed = aof->processed_bytes;
@@ -1627,15 +1626,14 @@ int rewriteAppendOnlyFileRio(rio *aof) {
updated_time = now;
}
}
return true;
});
if (!fComplete)
goto werr;
}
dictReleaseIterator(di);
di = NULL;
}
return C_OK;
werr:
if (di) dictReleaseIterator(di);
return C_ERR;
}
@@ -1657,7 +1655,7 @@ int rewriteAppendOnlyFile(char *filename) {
{ // BEGIN GOTO SCOPED VARIABLES
/* Note that we have to use a different temp name here compared to the
* one used by rewriteAppendOnlyFileBackground() function. */
snprintf(tmpfile,sizeof(tmpfile),"temp-rewriteaof-%d.aof", (int) getpid());
snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) getpid());
fp = fopen(tmpfile,"w");
if (!fp) {
serverLog(LL_WARNING, "Opening the temp file for AOF rewrite in rewriteAppendOnlyFile(): %s", strerror(errno));
@@ -1674,12 +1672,7 @@ int rewriteAppendOnlyFile(char *filename) {
if (g_pserver->aof_use_rdb_preamble) {
int error;
std::vector<const redisDbPersistentDataSnapshot*> vecpdb;
for (int idb = 0; idb < cserver.dbnum; ++idb)
{
vecpdb.push_back(g_pserver->db[idb]);
}
if (rdbSaveRio(&aof,vecpdb.data(),&error,RDBFLAGS_AOF_PREAMBLE,NULL) == C_ERR) {
if (rdbSaveRio(&aof,&error,RDBFLAGS_AOF_PREAMBLE,NULL) == C_ERR) {
errno = error;
goto werr;
}
@@ -1886,7 +1879,7 @@ void aofClosePipes(void) {
int rewriteAppendOnlyFileBackground(void) {
pid_t childpid;
if (hasActiveChildProcessOrBGSave()) return C_ERR;
if (hasActiveChildProcess()) return C_ERR;
if (aofCreatePipes() != C_OK) return C_ERR;
if ((childpid = redisFork(CHILD_TYPE_AOF)) == 0) {
char tmpfile[256];
@@ -1894,7 +1887,7 @@ int rewriteAppendOnlyFileBackground(void) {
/* Child */
redisSetProcTitle("keydb-aof-rewrite");
redisSetCpuAffinity(g_pserver->aof_rewrite_cpulist);
snprintf(tmpfile,sizeof(tmpfile),"temp-rewriteaof-bg-%d.aof", (int) getpid());
snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) getpid());
if (rewriteAppendOnlyFile(tmpfile) == C_OK) {
sendChildCowInfo(CHILD_INFO_TYPE_AOF_COW_SIZE, "AOF rewrite");
exitFromChild(0);
@@ -1929,7 +1922,7 @@ int rewriteAppendOnlyFileBackground(void) {
void bgrewriteaofCommand(client *c) {
if (g_pserver->child_type == CHILD_TYPE_AOF) {
addReplyError(c,"Background append only file rewriting already in progress");
} else if (hasActiveChildProcessOrBGSave()) {
} else if (hasActiveChildProcess()) {
g_pserver->aof_rewrite_scheduled = 1;
addReplyStatus(c,"Background append only file rewriting scheduled");
} else if (rewriteAppendOnlyFileBackground() == C_OK) {
@@ -1943,10 +1936,10 @@ void bgrewriteaofCommand(client *c) {
void aofRemoveTempFile(pid_t childpid) {
char tmpfile[256];
snprintf(tmpfile,sizeof(tmpfile),"temp-rewriteaof-bg-%d.aof", (int) childpid);
snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof", (int) childpid);
bg_unlink(tmpfile);
snprintf(tmpfile,sizeof(tmpfile),"temp-rewriteaof-%d.aof", (int) childpid);
snprintf(tmpfile,256,"temp-rewriteaof-%d.aof", (int) childpid);
bg_unlink(tmpfile);
}
@@ -1984,7 +1977,7 @@ void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
/* Flush the differences accumulated by the parent to the
* rewritten AOF. */
latencyStartMonitor(latency);
snprintf(tmpfile,sizeof(tmpfile),"temp-rewriteaof-bg-%d.aof",
snprintf(tmpfile,256,"temp-rewriteaof-bg-%d.aof",
(int)g_pserver->child_pid);
newfd = open(tmpfile,O_WRONLY|O_APPEND);
if (newfd == -1) {
+1 -1
View File
@@ -32,7 +32,7 @@ const char *ascii_logo =
" _ \n"
" _-(+)-_ \n"
" _-- / \\ --_ \n"
" _-- / \\ --_ KeyDB %s (%s/%d) %s bit \n"
" _-- / \\ --_ KeyDB %s (%s/%d) %s bit \n"
" __-- / \\ --__ \n"
" (+) _ / \\ _ (+) Running in %s mode\n"
" | -- / \\ -- | Port: %d\n"
+1 -1
View File
@@ -322,7 +322,7 @@ handle_wrap:
return 1;
}
int checkSignedBitfieldOverflow(int64_t value, int64_t incr, int bits, int owtype, int64_t *limit) {
int checkSignedBitfieldOverflow(int64_t value, int64_t incr, uint64_t bits, int owtype, int64_t *limit) {
int64_t max = (bits == 64) ? INT64_MAX : (((int64_t)1<<(bits-1))-1);
int64_t min = (-max)-1;
+1 -7
View File
@@ -96,8 +96,6 @@ void blockClient(client *c, int btype) {
c->flags |= CLIENT_BLOCKED;
c->btype = btype;
if (btype == BLOCKED_ASYNC)
c->casyncOpsPending++;
g_pserver->blocked_clients++;
g_pserver->blocked_clients_by_type[btype]++;
addClientToTimeoutTable(c);
@@ -154,7 +152,7 @@ void processUnblockedClients(int iel) {
}
/* Then process client if it has more data in it's buffer. */
if (c->querybuf && sdslen(c->querybuf) > 0) {
processInputBuffer(c, true /*fParse*/, CMD_CALL_FULL);
processInputBuffer(c, CMD_CALL_FULL);
}
}
}
@@ -201,9 +199,6 @@ void unblockClient(client *c) {
} else if (c->btype == BLOCKED_MODULE) {
if (moduleClientIsBlockedOnKeys(c)) unblockClientWaitingData(c);
unblockClientFromModule(c);
} else if (c->btype == BLOCKED_ASYNC) {
serverAssert(c->casyncOpsPending > 0);
c->casyncOpsPending--;
} else if (c->btype == BLOCKED_PAUSE) {
listDelNode(g_pserver->paused_clients,c->paused_list_node);
c->paused_list_node = NULL;
@@ -732,7 +727,6 @@ void unblockClientWaitingData(client *c) {
c->bpop.xread_group = NULL;
c->bpop.xread_consumer = NULL;
}
c->bpop.timeout = 0;
}
static int getBlockedTypeByType(int type) {
-2
View File
@@ -42,7 +42,6 @@ typedef struct {
* RDB / AOF saving process from the child to the parent (for instance
* the amount of copy on write memory used) */
void openChildInfoPipe(void) {
serverAssert(g_pserver->child_info_pipe[0] == -1);
if (pipe(g_pserver->child_info_pipe) == -1) {
/* On error our two file descriptors should be still set to -1,
* but we call anyway closeChildInfoPipe() since can't hurt. */
@@ -70,7 +69,6 @@ void closeChildInfoPipe(void) {
/* Send save data to parent. */
void sendChildInfoGeneric(childInfoType info_type, size_t keys, double progress, const char *pname) {
if (g_pserver->child_info_pipe[1] == -1) return;
if (g_pserver->rdbThreadVars.fRdbThreadActive && g_pserver->rdbThreadVars.fRdbThreadCancel) return;
static monotime cow_updated = 0;
static uint64_t cow_update_cost = 0;
+24 -74
View File
@@ -771,7 +771,7 @@ unsigned long getClusterConnectionsCount(void) {
/* We decrement the number of nodes by one, since there is the
* "myself" node too in the list. Each node uses two file descriptors,
* one incoming and one outgoing, thus the multiplication by 2. */
return g_pserver->cluster_enabled && g_pserver->cluster != nullptr ?
return g_pserver->cluster_enabled ?
((dictSize(g_pserver->cluster->nodes)-1)*2) : 0;
}
@@ -785,7 +785,7 @@ unsigned long getClusterConnectionsCount(void) {
* However if the key contains the {...} pattern, only the part between
* { and } is hashed. This may be useful in the future to force certain
* keys to be in the same node (assuming no resharding is in progress). */
unsigned int keyHashSlot(const char *key, int keylen) {
unsigned int keyHashSlot(char *key, int keylen) {
int s, e; /* start-end indexes of { and } */
for (s = 0; s < keylen; s++)
@@ -1525,9 +1525,7 @@ void clusterProcessGossipSection(clusterMsg *hdr, clusterLink *link) {
* it's greater than our view but is not in the future
* (with 500 milliseconds tolerance) from the POV of our
* clock. */
mstime_t mstime;
__atomic_load(&g_pserver->mstime, &mstime, __ATOMIC_RELAXED);
if (pongtime <= (mstime+500) &&
if (pongtime <= (g_pserver->mstime+500) &&
pongtime > node->pong_received)
{
node->pong_received = pongtime;
@@ -4129,7 +4127,7 @@ int verifyClusterConfigWithData(void) {
/* Make sure we only have keys in DB0. */
for (j = 1; j < cserver.dbnum; j++) {
if (g_pserver->db[j]->size()) return C_ERR;
if (dictSize(g_pserver->db[j].dict)) return C_ERR;
}
/* Check that all the slots we see populated memory have a corresponding
@@ -4516,8 +4514,8 @@ void clusterCommand(client *c) {
"NODES",
" Return cluster configuration seen by node. Output format:",
" <id> <ip:port> <flags> <master> <pings> <pongs> <epoch> <link> <slot> ...",
"REPLICATE (<node-id>|NO ONE)",
" Configure current node as replica to <node-id> or turn it into empty primary.",
"REPLICATE <node-id>",
" Configure current node as replica to <node-id>.",
"RESET [HARD|SOFT]",
" Reset current node (default: soft).",
"SET-CONFIG-EPOCH <epoch>",
@@ -4579,7 +4577,7 @@ NULL
clusterReplyMultiBulkSlots(c);
} else if (!strcasecmp(szFromObj(c->argv[1]),"flushslots") && c->argc == 2) {
/* CLUSTER FLUSHSLOTS */
if (g_pserver->db[0]->size() != 0) {
if (dictSize(g_pserver->db[0].dict) != 0) {
addReplyError(c,"DB must be empty to perform CLUSTER FLUSHSLOTS.");
return;
}
@@ -4890,22 +4888,14 @@ NULL
clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|
CLUSTER_TODO_SAVE_CONFIG);
addReply(c,shared.ok);
} else if (!strcasecmp(szFromObj(c->argv[1]),"replicate") && (c->argc == 3 || c->argc == 4)) {
/* CLUSTER REPLICATE (<NODE ID>|NO ONE) */
clusterNode *n;
if (c->argc == 4) {
if (0 != strcasecmp(szFromObj(c->argv[2]),"NO") || 0 != strcasecmp(szFromObj(c->argv[3]),"ONE")) {
addReplySubcommandSyntaxError(c);
return;
}
n = nullptr;
} else {
/* Lookup the specified node in our table. */
n = clusterLookupNode(szFromObj(c->argv[2]));
if (n == nullptr) {
addReplyErrorFormat(c,"Unknown node %s", (char*)ptrFromObj(c->argv[2]));
return;
}
} else if (!strcasecmp(szFromObj(c->argv[1]),"replicate") && c->argc == 3) {
/* CLUSTER REPLICATE <NODE ID> */
clusterNode *n = clusterLookupNode(szFromObj(c->argv[2]));
/* Lookup the specified node in our table. */
if (!n) {
addReplyErrorFormat(c,"Unknown node %s", (char*)ptrFromObj(c->argv[2]));
return;
}
/* I can't replicate myself. */
@@ -4915,7 +4905,7 @@ NULL
}
/* Can't replicate a slave. */
if (n != nullptr && nodeIsSlave(n)) {
if (nodeIsSlave(n)) {
addReplyError(c,"I can only replicate a master, not a replica.");
return;
}
@@ -4924,33 +4914,15 @@ NULL
* slots nor keys to accept to replicate some other node.
* Slaves can switch to another master without issues. */
if (nodeIsMaster(myself) &&
(myself->numslots != 0 || g_pserver->db[0]->size() != 0)) {
(myself->numslots != 0 || dictSize(g_pserver->db[0].dict) != 0)) {
addReplyError(c,
"To set a master the node must be empty and "
"without assigned slots.");
return;
}
if (n == nullptr) {
if (nodeIsMaster(myself)) {
addReply(c,shared.ok);
return;
}
serverLog(LL_NOTICE,"Stop replication and turning myself into empty primary.");
clusterSetNodeAsMaster(myself);
if (listLength(g_pserver->masters) > 0)
{
serverAssert(listLength(g_pserver->masters) == 1);
replicationUnsetMaster((redisMaster*)listFirst(g_pserver->masters)->value);
}
int empty_db_flags = g_pserver->repl_slave_lazy_flush ? EMPTYDB_ASYNC : EMPTYDB_NO_FLAGS;
emptyDb(-1,empty_db_flags, nullptr);
/* Reset manual failover state. */
resetManualFailover();
} else {
/* Set the master. */
clusterSetMaster(n);
}
/* Set the master. */
clusterSetMaster(n);
clusterDoBeforeSleep(CLUSTER_TODO_UPDATE_STATE|CLUSTER_TODO_SAVE_CONFIG);
addReply(c,shared.ok);
} else if ((!strcasecmp(szFromObj(c->argv[1]),"slaves") ||
@@ -5102,7 +5074,7 @@ NULL
/* Slaves can be reset while containing data, but not master nodes
* that must be empty. */
if (nodeIsMaster(myself) && c->db->size() != 0) {
if (nodeIsMaster(myself) && dictSize(c->db->dict) != 0) {
addReplyError(c,"CLUSTER RESET can't be called with "
"master nodes containing keys");
return;
@@ -5118,7 +5090,6 @@ NULL
/* -----------------------------------------------------------------------------
* DUMP, RESTORE and MIGRATE commands
* -------------------------------------------------------------------------- */
ssize_t rdbSaveAuxFieldStrStr(rio *rdb, const char *key, const char *val);
/* Generates a DUMP-format representation of the object 'o', adding it to the
* io stream pointed by 'rio'. This function can't fail. */
@@ -5131,10 +5102,6 @@ void createDumpPayload(rio *payload, robj_roptr o, robj *key) {
rioInitWithBuffer(payload,sdsempty());
serverAssert(rdbSaveObjectType(payload,o));
serverAssert(rdbSaveObject(payload,o,key));
char szT[32];
uint64_t mvcc = mvccFromObj(o);
snprintf(szT, sizeof(szT), "%" PRIu64, mvcc);
serverAssert(rdbSaveAuxFieldStrStr(payload,"mvcc-tstamp", szT) != -1);
/* Write the footer, this is how it looks like:
* ----------------+---------------------+---------------+
@@ -5318,21 +5285,6 @@ void restoreCommand(client *c) {
addReplyError(c,"Bad data format");
return;
}
if (rdbLoadType(&payload) == RDB_OPCODE_AUX)
{
robj *auxkey, *auxval;
if ((auxkey = rdbLoadStringObject(&payload)) == NULL) goto eoferr;
if ((auxval = rdbLoadStringObject(&payload)) == NULL) {
decrRefCount(auxkey);
goto eoferr;
}
if (strcasecmp(szFromObj(auxkey), "mvcc-tstamp") == 0) {
setMvccTstamp(obj, strtoull(szFromObj(auxval), nullptr, 10));
}
decrRefCount(auxkey);
decrRefCount(auxval);
}
eoferr:
/* Remove the old key if needed. */
int deleted = 0;
@@ -5610,7 +5562,7 @@ try_again:
/* Create RESTORE payload and generate the protocol to call the command. */
for (j = 0; j < num_keys; j++) {
long long ttl = 0;
expireEntry *pexpire = c->db->getExpire(kv[j]);
expireEntry *pexpire = getExpire(c->db,kv[j]);
long long expireat = INVALID_EXPIRE;
if (pexpire != nullptr)
pexpire->FGetPrimaryExpire(&expireat);
@@ -5901,7 +5853,7 @@ clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, in
multiState *ms, _ms;
multiCmd mc;
int i, slot = 0, migrating_slot = 0, importing_slot = 0, missing_keys = 0;
serverAssert((c->cmd->flags & CMD_ASYNC_OK) || GlobalLocksAcquired());
serverAssert(GlobalLocksAcquired());
/* Allow any key to be set if a module disabled cluster redirections. */
if (g_pserver->cluster_module_flags & CLUSTER_MODULE_FLAG_NO_REDIRECTION)
@@ -5991,9 +5943,7 @@ clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, in
/* If it is not the first key, make sure it is exactly
* the same key as the first we saw. */
if (!equalStringObjects(firstkey,thiskey)) {
clusterNode* nThisKey = g_pserver->cluster->slots[thisslot];
if ((slot != thisslot) && (nThisKey != n || migrating_slot || importing_slot || g_pserver->cluster->migrating_slots_to[slot] != nullptr || g_pserver->cluster->importing_slots_from[slot] != nullptr)) {
if (slot != thisslot) {
/* Error: multiple keys from different slots. */
getKeysFreeResult(&result);
if (error_code)
@@ -6009,7 +5959,7 @@ clusterNode *getNodeByQuery(client *c, struct redisCommand *cmd, robj **argv, in
/* Migrating / Importing slot? Count keys we don't have. */
if ((migrating_slot || importing_slot) &&
lookupKeyRead(g_pserver->db[0],thiskey) == nullptr)
lookupKeyRead(&g_pserver->db[0],thiskey) == nullptr)
{
missing_keys++;
}
+3 -11
View File
@@ -30,16 +30,7 @@ public:
zfree(m_data);
}
compactvector(const compactvector &src)
{
m_celem = src.m_celem;
m_max = src.m_max;
m_data = (T*)zmalloc(sizeof(T) * m_max, MALLOC_LOCAL);
for (size_t ielem = 0; ielem < m_celem; ++ielem)
{
new (m_data+ielem) T(src[ielem]);
}
}
compactvector(compactvector &) noexcept = delete;
compactvector(compactvector &&src) noexcept
{
@@ -51,6 +42,7 @@ public:
src.m_max = 0;
}
compactvector &operator=(const compactvector&) noexcept = delete;
compactvector &operator=(compactvector &&src) noexcept
{
zfree(m_data);
@@ -69,7 +61,7 @@ public:
inline T* end() { return m_data + m_celem; }
inline const T* end() const { return m_data + m_celem; }
T* insert(T* where, const T &val)
T* insert(T* where, T &val)
{
assert(where >= m_data);
size_t idx = where - m_data;
+15 -240
View File
@@ -29,19 +29,12 @@
*/
#include "server.h"
#include "storage/rocksdbfactory.h"
#include "storage/teststorageprovider.h"
#include "cluster.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#ifdef __linux__
#include <sys/sysinfo.h>
#endif
const char *KEYDB_SET_VERSION = KEYDB_REAL_VERSION;
size_t g_semiOrderedSetTargetBucketSize = 0; // Its a header only class so nowhere else for this to go
/*-----------------------------------------------------------------------------
* Config file name-value maps.
@@ -107,11 +100,6 @@ configEnum repl_diskless_load_enum[] = {
{NULL, 0}
};
configEnum storage_memory_model_enum[] = {
{"writeback", STORAGE_WRITEBACK},
{"writethrough", STORAGE_WRITETHROUGH},
};
configEnum tls_auth_clients_enum[] = {
{"no", TLS_CLIENT_AUTH_NO},
{"yes", TLS_CLIENT_AUTH_YES},
@@ -345,72 +333,6 @@ void queueLoadModule(sds path, sds *argv, int argc) {
listAddNodeTail(g_pserver->loadmodule_queue,loadmod);
}
sds g_sdsProvider = nullptr;
sds g_sdsArgs = nullptr;
bool initializeStorageProvider(const char **err)
{
try
{
bool fTest = false;
if (g_sdsProvider == nullptr)
return true;
if (!strcasecmp(g_sdsProvider, "flash") && g_sdsArgs != nullptr)
{
#ifdef ENABLE_ROCKSDB
// Create The Storage Factory (if necessary)
serverLog(LL_NOTICE, "Initializing FLASH storage provider (this may take a long time)");
adjustOpenFilesLimit();
g_pserver->m_pstorageFactory = CreateRocksDBStorageFactory(g_sdsArgs, cserver.dbnum, cserver.storage_conf, cserver.storage_conf ? strlen(cserver.storage_conf) : 0);
#else
serverLog(LL_WARNING, "To use the flash storage provider please compile KeyDB with ENABLE_FLASH=yes");
serverLog(LL_WARNING, "Exiting due to the use of an unsupported storage provider");
exit(EXIT_FAILURE);
#endif
}
else if (!strcasecmp(g_sdsProvider, "test") && g_sdsArgs == nullptr)
{
g_pserver->m_pstorageFactory = new (MALLOC_LOCAL) TestStorageFactory();
fTest = true;
}
if (g_pserver->m_pstorageFactory != nullptr && !fTest)
{
// We need to set max memory to a sane default so keys are actually evicted properly
if (g_pserver->maxmemory == 0 && g_pserver->maxmemory_policy == MAXMEMORY_NO_EVICTION)
{
#ifdef __linux__
struct sysinfo sys;
if (sysinfo(&sys) == 0)
{
// By default it's a little under half the memory. This gives sufficient room for background saving
g_pserver->maxmemory = static_cast<unsigned long long>(sys.totalram / 2.2);
g_pserver->maxmemory_policy = MAXMEMORY_ALLKEYS_LRU;
}
#else
serverLog(LL_WARNING, "Unable to dynamically set maxmemory, please set maxmemory and maxmemory-policy if you are using a storage provier");
#endif
}
else if (g_pserver->maxmemory_policy == MAXMEMORY_NO_EVICTION)
{
g_pserver->maxmemory_policy = MAXMEMORY_ALLKEYS_LRU;
}
}
else
{
*err = "Unknown storage provider";
}
return g_pserver->m_pstorageFactory != nullptr;
}
catch(std::string str)
{
serverLog(LL_WARNING, "ERROR: Failed to initialize %s storage provider. Details to follow below.", g_sdsProvider);
serverLog(LL_WARNING, "\t%s", str.c_str());
serverLog(LL_WARNING, "KeyDB cannot start. Exiting.");
exit(EXIT_FAILURE);
}
}
/* Parse an array of CONFIG_OOM_COUNT sds strings, validate and populate
* g_pserver->oom_score_adj_values if valid.
*/
@@ -749,36 +671,6 @@ void loadServerConfigFromString(char *config) {
g_pserver->fActiveReplica = CONFIG_DEFAULT_ACTIVE_REPLICA;
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
if (listLength(g_pserver->masters) && g_pserver->fActiveReplica) {
err = "must not set replica-of config before active-replica config"; goto loaderr;
}
} else if (!strcasecmp(argv[0], "multi-master") && argc == 2) {
g_pserver->enable_multimaster = yesnotoi(argv[1]);
if (g_pserver->enable_multimaster == -1) {
g_pserver->enable_multimaster = CONFIG_DEFAULT_ENABLE_MULTIMASTER;
err = "argument must be 'yes' or 'no'"; goto loaderr;
}
if (listLength(g_pserver->masters) && g_pserver->enable_multimaster) {
err = "must not set replica-of config before multi-master config"; goto loaderr;
}
} else if (!strcasecmp(argv[0], "tls-allowlist")) {
if (argc < 2) {
err = "must supply at least one element in the allow list"; goto loaderr;
}
if (!g_pserver->tls_allowlist.empty()) {
err = "tls-allowlist may only be set once"; goto loaderr;
}
for (int i = 1; i < argc; i++)
g_pserver->tls_allowlist.emplace(argv[i], strlen(argv[i]));
} else if (!strcasecmp(argv[0], "tls-auditlog-blocklist")) {
if (argc < 2) {
err = "must supply at least one element in the block list"; goto loaderr;
}
if (!g_pserver->tls_auditlog_blocklist.empty()) {
err = "tls-auditlog-blocklist may only be set once"; goto loaderr;
}
for (int i = 1; i < argc; i++)
g_pserver->tls_auditlog_blocklist.emplace(argv[i], strlen(argv[i]));
} else if (!strcasecmp(argv[0], "version-override") && argc == 2) {
KEYDB_SET_VERSION = zstrdup(argv[1]);
serverLog(LL_WARNING, "Warning version is overriden to: %s\n", KEYDB_SET_VERSION);
@@ -786,16 +678,9 @@ void loadServerConfigFromString(char *config) {
g_fTestMode = yesnotoi(argv[1]);
} else if (!strcasecmp(argv[0],"rdbfuzz-mode")) {
// NOP, handled in main
} else if (!strcasecmp(argv[0],"storage-provider") && argc >= 2) {
g_sdsProvider = sdsdup(argv[1]);
if (argc > 2)
g_sdsArgs = sdsdup(argv[2]);
} else if (!strcasecmp(argv[0],"is-flash-enabled") && argc == 1) {
#ifdef ENABLE_ROCKSDB
exit(EXIT_SUCCESS);
#else
exit(EXIT_FAILURE);
#endif
} else if (!strcasecmp(argv[0],"enable-pro")) {
cserver.fUsePro = true;
break;
} else {
err = "Bad directive or wrong number of arguments"; goto loaderr;
}
@@ -905,18 +790,8 @@ void configSetCommand(client *c) {
int err;
const char *errstr = NULL;
serverAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2]));
if (c->argc < 4 || c->argc > 4) {
o = nullptr;
// Variadic set is only supported for tls-allowlist
if (strcasecmp(szFromObj(c->argv[2]), "tls-allowlist")) {
addReplySubcommandSyntaxError(c);
return;
}
} else {
o = c->argv[3];
serverAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3]));
}
serverAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3]));
o = c->argv[3];
/* Iterate the configs that are standard */
for (standardConfig *config = configs; config->name != NULL; config++) {
@@ -1078,12 +953,6 @@ void configSetCommand(client *c) {
enableWatchdog(ll);
else
disableWatchdog();
} config_set_special_field("tls-allowlist") {
g_pserver->tls_allowlist.clear();
for (int i = 3; i < c->argc; ++i) {
robj *val = c->argv[i];
g_pserver->tls_allowlist.emplace(szFromObj(val), sdslen(szFromObj(val)));
}
/* Everything else is an error... */
} config_set_else {
addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s",
@@ -1287,14 +1156,6 @@ void configGetCommand(client *c) {
addReplyBulkCString(c, g_pserver->fActiveReplica ? "yes" : "no");
matches++;
}
if (stringmatch(pattern, "tls-allowlist", 1)) {
addReplyBulkCString(c,"tls-allowlist");
addReplyArrayLen(c, (long)g_pserver->tls_allowlist.size());
for (auto &elem : g_pserver->tls_allowlist) {
addReplyBulkCBuffer(c, elem.get(), elem.size()); // addReplyBulkSds will free which we absolutely don't want
}
matches++;
}
setDeferredMapLen(c,replylen,matches);
}
@@ -1964,20 +1825,6 @@ int rewriteConfig(char *path, int force_all) {
rewriteConfigStringOption(state, "version-override",KEYDB_SET_VERSION,KEYDB_REAL_VERSION);
rewriteConfigOOMScoreAdjValuesOption(state);
if (!g_pserver->tls_allowlist.empty()) {
sds conf = sdsnew("tls-allowlist ");
for (auto &elem : g_pserver->tls_allowlist) {
conf = sdscatsds(conf, (sds)elem.get());
conf = sdscat(conf, " ");
}
// trim the trailing space
sdsrange(conf, 0, -1);
rewriteConfigRewriteLine(state,"tls-allowlist",conf,1 /*force*/);
// note: conf is owned by rewriteConfigRewriteLine - no need to free
} else {
rewriteConfigMarkAsProcessed(state, "tls-allowlist"); // ensure the line is removed if it existed
}
/* Rewrite Sentinel config if in Sentinel mode. */
if (g_pserver->sentinel_mode) rewriteConfigSentinelOption(state);
@@ -2121,10 +1968,7 @@ static void sdsConfigGet(client *c, typeData data) {
}
static void sdsConfigRewrite(typeData data, const char *name, struct rewriteConfigState *state) {
sds sdsDefault = data.sds.default_value ? sdsnew(data.sds.default_value) : NULL;
rewriteConfigSdsOption(state, name, *(data.sds.config), sdsDefault);
if (sdsDefault)
sdsfree(sdsDefault);
rewriteConfigSdsOption(state, name, *(data.sds.config), data.sds.default_value ? sdsnew(data.sds.default_value) : NULL);
}
@@ -2481,32 +2325,6 @@ static int isValidAOFfilename(char *val, const char **err) {
return 1;
}
static int isValidS3Bucket(char *s3bucket, const char **err) {
int status = EXIT_FAILURE;
pid_t pid = fork();
if (pid < 0)
{
*err = "couldn't fork to call aws cli";
return 0;
}
if (pid == 0)
{
execlp("aws", "aws", "s3", "ls", s3bucket, nullptr);
exit(EXIT_FAILURE);
}
else
{
waitpid(pid, &status, 0);
}
if (status != EXIT_SUCCESS) {
*err = "could not access s3 bucket";
return 0;
}
return 1;
}
/* Validate specified string is a valid proc-title-template */
static int isValidProcTitleTemplate(char *val, const char **err) {
if (!validateProcTitleTemplate(val)) {
@@ -2574,12 +2392,8 @@ static int updateJemallocBgThread(int val, int prev, const char **err) {
static int updateReplBacklogSize(long long val, long long prev, const char **err) {
/* resizeReplicationBacklog sets g_pserver->repl_backlog_size, and relies on
* being able to tell when the size changes, so restore prev before calling it. */
if (cserver.repl_backlog_disk_size) {
*err = "Unable to dynamically resize the backlog because disk backlog is enabled";
return 0;
}
UNUSED(err);
g_pserver->repl_backlog_size = prev;
g_pserver->repl_backlog_config_size = val;
resizeReplicationBacklog(val);
return 1;
}
@@ -2592,20 +2406,7 @@ static int updateMaxmemory(long long val, long long prev, const char **err) {
if ((unsigned long long)val < used) {
serverLog(LL_WARNING,"WARNING: the new maxmemory value set via CONFIG SET (%llu) is smaller than the current memory usage (%zu). This will result in key eviction and/or the inability to accept new write commands depending on the maxmemory-policy.", g_pserver->maxmemory, used);
}
performEvictions(false /*fPreSnapshot*/);
}
return 1;
}
static int updateFlashMaxmemory(long long val, long long prev, const char **err) {
UNUSED(prev);
UNUSED(err);
if (val && g_pserver->m_pstorageFactory) {
size_t used = g_pserver->m_pstorageFactory->totalDiskspaceUsed();
if ((unsigned long long)val < used) {
serverLog(LL_WARNING,"WARNING: the new maxstorage value set via CONFIG SET (%llu) is smaller than the current storage usage (%zu). This will result in key eviction and/or the inability to accept new write commands depending on the maxmemory-policy.", g_pserver->maxstorage, used);
}
performEvictions(false /*fPreSnapshot*/);
performEvictions();
}
return 1;
}
@@ -2652,7 +2453,7 @@ static int updateMaxclients(long long val, long long prev, const char **err) {
adjustOpenFilesLimit();
if (g_pserver->maxclients != val) {
static char msg[128];
snprintf(msg, sizeof(msg), "The operating system is not able to handle the specified number of clients, try with %d", g_pserver->maxclients);
sprintf(msg, "The operating system is not able to handle the specified number of clients, try with %d", g_pserver->maxclients);
*err = msg;
if (g_pserver->maxclients > prev) {
g_pserver->maxclients = prev;
@@ -2691,7 +2492,7 @@ static int updateMaxclients(long long val, long long prev, const char **err) {
if (res != AE_OK){
static char msg[128];
snprintf(msg, sizeof(msg),"Failed to post the request to change setsize for Thread %d", iel);
sprintf(msg, "Failed to post the request to change setsize for Thread %d", iel);
*err = msg;
return 0;
}
@@ -2835,27 +2636,20 @@ standardConfig configs[] = {
createBoolConfig("replica-serve-stale-data", "slave-serve-stale-data", MODIFIABLE_CONFIG, g_pserver->repl_serve_stale_data, 1, NULL, NULL),
createBoolConfig("replica-read-only", "slave-read-only", MODIFIABLE_CONFIG, g_pserver->repl_slave_ro, 1, NULL, NULL),
createBoolConfig("replica-ignore-maxmemory", "slave-ignore-maxmemory", MODIFIABLE_CONFIG, g_pserver->repl_slave_ignore_maxmemory, 1, NULL, NULL),
createBoolConfig("multi-master", NULL, IMMUTABLE_CONFIG, g_pserver->enable_multimaster,CONFIG_DEFAULT_ENABLE_MULTIMASTER, NULL, NULL),
createBoolConfig("jemalloc-bg-thread", NULL, MODIFIABLE_CONFIG, cserver.jemalloc_bg_thread, 1, NULL, updateJemallocBgThread),
createBoolConfig("activedefrag", NULL, MODIFIABLE_CONFIG, cserver.active_defrag_enabled, 0, isValidActiveDefrag, NULL),
createBoolConfig("syslog-enabled", NULL, IMMUTABLE_CONFIG, g_pserver->syslog_enabled, 0, NULL, NULL),
createBoolConfig("cluster-enabled", NULL, IMMUTABLE_CONFIG, g_pserver->cluster_enabled, 0, NULL, NULL),
createBoolConfig("appendonly", NULL, MODIFIABLE_CONFIG, g_pserver->aof_enabled, 0, NULL, updateAppendonly),
createBoolConfig("cluster-allow-reads-when-down", NULL, MODIFIABLE_CONFIG, g_pserver->cluster_allow_reads_when_down, 0, NULL, NULL),
createBoolConfig("delete-on-evict", NULL, MODIFIABLE_CONFIG, cserver.delete_on_evict, 0, NULL, NULL),
createBoolConfig("use-fork", NULL, IMMUTABLE_CONFIG, cserver.fForkBgSave, 1, NULL, NULL),
createBoolConfig("io-threads-do-reads", NULL, IMMUTABLE_CONFIG, fDummy, 0, NULL, NULL),
createBoolConfig("time-thread-priority", NULL, IMMUTABLE_CONFIG, cserver.time_thread_priority, 0, NULL, NULL),
createBoolConfig("prefetch-enabled", NULL, MODIFIABLE_CONFIG, g_pserver->prefetch_enabled, 1, NULL, NULL),
createBoolConfig("allow-rdb-resize-op", NULL, MODIFIABLE_CONFIG, g_pserver->allowRdbResizeOp, 1, NULL, NULL),
createBoolConfig("crash-log-enabled", NULL, MODIFIABLE_CONFIG, g_pserver->crashlog_enabled, 1, NULL, updateSighandlerEnabled),
createBoolConfig("crash-memcheck-enabled", NULL, MODIFIABLE_CONFIG, g_pserver->memcheck_enabled, 1, NULL, NULL),
createBoolConfig("use-exit-on-panic", NULL, MODIFIABLE_CONFIG, g_pserver->use_exit_on_panic, 0, NULL, NULL),
createBoolConfig("disable-thp", NULL, MODIFIABLE_CONFIG, g_pserver->disable_thp, 1, NULL, NULL),
createBoolConfig("cluster-allow-replica-migration", NULL, MODIFIABLE_CONFIG, g_pserver->cluster_allow_replica_migration, 1, NULL, NULL),
createBoolConfig("replica-announced", NULL, MODIFIABLE_CONFIG, g_pserver->replica_announced, 1, NULL, NULL),
createBoolConfig("enable-async-commands", NULL, MODIFIABLE_CONFIG, g_pserver->enable_async_commands, 0, NULL, NULL),
createBoolConfig("multithread-load-enabled", NULL, MODIFIABLE_CONFIG, g_pserver->multithread_load_enabled, 0, NULL, NULL),
createBoolConfig("active-client-balancing", NULL, MODIFIABLE_CONFIG, g_pserver->active_client_balancing, 1, NULL, NULL),
/* String Configs */
createStringConfig("aclfile", NULL, IMMUTABLE_CONFIG, ALLOW_EMPTY_STRING, g_pserver->acl_filename, "", NULL, NULL),
@@ -2866,13 +2660,11 @@ standardConfig configs[] = {
createStringConfig("cluster-announce-ip", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->cluster_announce_ip, NULL, NULL, NULL),
createStringConfig("syslog-ident", NULL, IMMUTABLE_CONFIG, ALLOW_EMPTY_STRING, g_pserver->syslog_ident, "redis", NULL, NULL),
createStringConfig("dbfilename", NULL, MODIFIABLE_CONFIG, ALLOW_EMPTY_STRING, g_pserver->rdb_filename, CONFIG_DEFAULT_RDB_FILENAME, isValidDBfilename, NULL),
createStringConfig("db-s3-object", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->rdb_s3bucketpath, NULL, isValidS3Bucket, NULL),
createStringConfig("appendfilename", NULL, IMMUTABLE_CONFIG, ALLOW_EMPTY_STRING, g_pserver->aof_filename, "appendonly.aof", isValidAOFfilename, NULL),
createStringConfig("server_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->server_cpulist, NULL, NULL, NULL),
createStringConfig("bio_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->bio_cpulist, NULL, NULL, NULL),
createStringConfig("aof_rewrite_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->aof_rewrite_cpulist, NULL, NULL, NULL),
createStringConfig("bgsave_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->bgsave_cpulist, NULL, NULL, NULL),
createStringConfig("storage-provider-options", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, cserver.storage_conf, NULL, NULL, NULL),
createStringConfig("ignore-warnings", NULL, MODIFIABLE_CONFIG, ALLOW_EMPTY_STRING, g_pserver->ignore_warnings, "", NULL, NULL),
createStringConfig("proc-title-template", NULL, MODIFIABLE_CONFIG, ALLOW_EMPTY_STRING, cserver.proc_title_template, CONFIG_DEFAULT_PROC_TITLE_TEMPLATE, isValidProcTitleTemplate, updateProcTitleTemplate),
@@ -2887,7 +2679,6 @@ standardConfig configs[] = {
createEnumConfig("loglevel", NULL, MODIFIABLE_CONFIG, loglevel_enum, cserver.verbosity, LL_NOTICE, NULL, NULL),
createEnumConfig("maxmemory-policy", NULL, MODIFIABLE_CONFIG, maxmemory_policy_enum, g_pserver->maxmemory_policy, MAXMEMORY_NO_EVICTION, NULL, NULL),
createEnumConfig("appendfsync", NULL, MODIFIABLE_CONFIG, aof_fsync_enum, g_pserver->aof_fsync, AOF_FSYNC_EVERYSEC, NULL, NULL),
createEnumConfig("storage-cache-mode", NULL, IMMUTABLE_CONFIG, storage_memory_model_enum, cserver.storage_memory_model, STORAGE_WRITETHROUGH, NULL, NULL),
createEnumConfig("oom-score-adj", NULL, MODIFIABLE_CONFIG, oom_score_adj_enum, g_pserver->oom_score_adj, OOM_SCORE_ADJ_NO, NULL, updateOOMScoreAdj),
createEnumConfig("acl-pubsub-default", NULL, MODIFIABLE_CONFIG, acl_pubsub_default_enum, g_pserver->acl_pubsub_default, USER_FLAG_ALLCHANNELS, NULL, NULL),
createEnumConfig("sanitize-dump-payload", NULL, MODIFIABLE_CONFIG, sanitize_dump_payload_enum, cserver.sanitize_dump_payload, SANITIZE_DUMP_NO, NULL, NULL),
@@ -2908,7 +2699,7 @@ standardConfig configs[] = {
createIntConfig("lfu-decay-time", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->lfu_decay_time, 1, INTEGER_CONFIG, NULL, NULL),
createIntConfig("replica-priority", "slave-priority", MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->slave_priority, 100, INTEGER_CONFIG, NULL, NULL),
createIntConfig("repl-diskless-sync-delay", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->repl_diskless_sync_delay, 5, INTEGER_CONFIG, NULL, NULL),
createIntConfig("maxmemory-samples", NULL, MODIFIABLE_CONFIG, 1, INT_MAX, g_pserver->maxmemory_samples, 16, INTEGER_CONFIG, NULL, NULL),
createIntConfig("maxmemory-samples", NULL, MODIFIABLE_CONFIG, 1, INT_MAX, g_pserver->maxmemory_samples, 5, INTEGER_CONFIG, NULL, NULL),
createIntConfig("maxmemory-eviction-tenacity", NULL, MODIFIABLE_CONFIG, 0, 100, g_pserver->maxmemory_eviction_tenacity, 10, INTEGER_CONFIG, NULL, NULL),
createIntConfig("timeout", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, cserver.maxidletime, 0, INTEGER_CONFIG, NULL, NULL), /* Default client timeout: infinite */
createIntConfig("replica-announce-port", "slave-announce-port", MODIFIABLE_CONFIG, 0, 65535, g_pserver->slave_announce_port, 0, INTEGER_CONFIG, NULL, NULL),
@@ -2921,18 +2712,15 @@ standardConfig configs[] = {
createIntConfig("list-compress-depth", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->list_compress_depth, 0, INTEGER_CONFIG, NULL, NULL),
createIntConfig("rdb-key-save-delay", NULL, MODIFIABLE_CONFIG, INT_MIN, INT_MAX, g_pserver->rdb_key_save_delay, 0, INTEGER_CONFIG, NULL, NULL),
createIntConfig("key-load-delay", NULL, MODIFIABLE_CONFIG, INT_MIN, INT_MAX, g_pserver->key_load_delay, 0, INTEGER_CONFIG, NULL, NULL),
createIntConfig("active-expire-effort", NULL, MODIFIABLE_CONFIG, 1, 10, g_pserver->active_expire_effort, 1, INTEGER_CONFIG, NULL, NULL), /* From 1 to 10. */
createIntConfig("active-expire-effort", NULL, MODIFIABLE_CONFIG, 1, 10, cserver.active_expire_effort, 1, INTEGER_CONFIG, NULL, NULL), /* From 1 to 10. */
createIntConfig("hz", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->config_hz, CONFIG_DEFAULT_HZ, INTEGER_CONFIG, NULL, updateHZ),
createIntConfig("min-replicas-to-write", "min-slaves-to-write", MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->repl_min_slaves_to_write, 0, INTEGER_CONFIG, NULL, updateGoodSlaves),
createIntConfig("min-replicas-max-lag", "min-slaves-max-lag", MODIFIABLE_CONFIG, 0, INT_MAX, g_pserver->repl_min_slaves_max_lag, 10, INTEGER_CONFIG, NULL, updateGoodSlaves),
createIntConfig("min-clients-per-thread", NULL, MODIFIABLE_CONFIG, 0, 400, cserver.thread_min_client_threshold, 20, INTEGER_CONFIG, NULL, NULL),
createIntConfig("storage-flush-period", NULL, MODIFIABLE_CONFIG, 1, 10000, g_pserver->storage_flush_period, 500, INTEGER_CONFIG, NULL, NULL),
createIntConfig("replica-quorum", NULL, MODIFIABLE_CONFIG, -1, INT_MAX, g_pserver->repl_quorum, -1, INTEGER_CONFIG, NULL, NULL),
createIntConfig("replica-weighting-factor", NULL, MODIFIABLE_CONFIG, 1, INT_MAX, g_pserver->replicaIsolationFactor, 2, INTEGER_CONFIG, NULL, NULL),
/* Unsigned int configs */
createUIntConfig("maxclients", NULL, MODIFIABLE_CONFIG, 1, UINT_MAX, g_pserver->maxclients, 10000, INTEGER_CONFIG, NULL, updateMaxclients),
createUIntConfig("loading-process-events-interval-keys", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, g_pserver->loading_process_events_interval_keys, 8192, MEMORY_CONFIG, NULL, NULL),
createUIntConfig("maxclients-reserved", NULL, MODIFIABLE_CONFIG, 0, 100, g_pserver->maxclientsReserved, 0, INTEGER_CONFIG, NULL, NULL),
/* Unsigned Long configs */
createULongConfig("active-defrag-max-scan-fields", NULL, MODIFIABLE_CONFIG, 1, LONG_MAX, cserver.active_defrag_max_scan_fields, 1000, INTEGER_CONFIG, NULL, NULL), /* Default: keys with more than 1000 fields will be processed separately */
@@ -2946,14 +2734,10 @@ standardConfig configs[] = {
createLongLongConfig("latency-monitor-threshold", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, g_pserver->latency_monitor_threshold, 0, INTEGER_CONFIG, NULL, NULL),
createLongLongConfig("proto-max-bulk-len", NULL, MODIFIABLE_CONFIG, 1024*1024, LLONG_MAX, g_pserver->proto_max_bulk_len, 512ll*1024*1024, MEMORY_CONFIG, NULL, NULL), /* Bulk request max size */
createLongLongConfig("stream-node-max-entries", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, g_pserver->stream_node_max_entries, 100, INTEGER_CONFIG, NULL, NULL),
createLongLongConfig("repl-backlog-size", NULL, MODIFIABLE_CONFIG, 1, LLONG_MAX, g_pserver->repl_backlog_config_size, 1024*1024, MEMORY_CONFIG, NULL, updateReplBacklogSize), /* Default: 1mb */
createLongLongConfig("repl-backlog-disk-reserve", NULL, IMMUTABLE_CONFIG, 0, LLONG_MAX, cserver.repl_backlog_disk_size, 0, MEMORY_CONFIG, NULL, NULL),
createLongLongConfig("max-snapshot-slip", NULL, MODIFIABLE_CONFIG, 0, 5000, g_pserver->snapshot_slip, 400, 0, NULL, NULL),
createLongLongConfig("max-rand-count", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX/2, g_pserver->rand_total_threshold, LONG_MAX/2, 0, NULL, NULL),
createLongLongConfig("repl-backlog-size", NULL, MODIFIABLE_CONFIG, 1, LLONG_MAX, g_pserver->repl_backlog_size, 1024*1024, MEMORY_CONFIG, NULL, updateReplBacklogSize), /* Default: 1mb */
/* Unsigned Long Long configs */
createULongLongConfig("maxmemory", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, g_pserver->maxmemory, 0, MEMORY_CONFIG, NULL, updateMaxmemory),
createULongLongConfig("maxstorage", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, g_pserver->maxstorage, 0, MEMORY_CONFIG, NULL, updateFlashMaxmemory),
/* Size_t configs */
createSizeTConfig("hash-max-ziplist-entries", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, g_pserver->hash_max_ziplist_entries, 512, INTEGER_CONFIG, NULL, NULL),
@@ -2975,14 +2759,6 @@ standardConfig configs[] = {
createULongConfig("loading-process-events-interval-bytes", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, g_pserver->loading_process_events_interval_bytes, 2*1024*1024, MEMORY_CONFIG, NULL, NULL),
createBoolConfig("multi-master-no-forward", NULL, MODIFIABLE_CONFIG, cserver.multimaster_no_forward, 0, validateMultiMasterNoForward, NULL),
createBoolConfig("allow-write-during-load", NULL, MODIFIABLE_CONFIG, g_pserver->fWriteDuringActiveLoad, 0, NULL, NULL),
createBoolConfig("force-backlog-disk-reserve", NULL, MODIFIABLE_CONFIG, cserver.force_backlog_disk, 0, NULL, NULL),
createBoolConfig("soft-shutdown", NULL, MODIFIABLE_CONFIG, g_pserver->config_soft_shutdown, 0, NULL, NULL),
createBoolConfig("flash-disable-key-cache", NULL, MODIFIABLE_CONFIG, g_pserver->flash_disable_key_cache, 0, NULL, NULL),
createSizeTConfig("semi-ordered-set-bucket-size", NULL, MODIFIABLE_CONFIG, 0, 1024, g_semiOrderedSetTargetBucketSize, 0, INTEGER_CONFIG, NULL, NULL),
createSDSConfig("availability-zone", NULL, MODIFIABLE_CONFIG, 0, g_pserver->sdsAvailabilityZone, "", NULL, NULL),
createIntConfig("overload-protect-percent", NULL, MODIFIABLE_CONFIG, 0, 200, g_pserver->overload_protect_threshold, 0, INTEGER_CONFIG, NULL, NULL),
createIntConfig("force-eviction-percent", NULL, MODIFIABLE_CONFIG, 0, 100, g_pserver->force_eviction_percent, 0, INTEGER_CONFIG, NULL, NULL),
createBoolConfig("enable-async-rehash", NULL, MODIFIABLE_CONFIG, g_pserver->enable_async_rehash, 1, NULL, NULL),
#ifdef USE_OPENSSL
createIntConfig("tls-port", NULL, MODIFIABLE_CONFIG, 0, 65535, g_pserver->tls_port, 0, INTEGER_CONFIG, NULL, updateTLSPort), /* TCP port. */
@@ -2993,7 +2769,6 @@ standardConfig configs[] = {
createEnumConfig("tls-auth-clients", NULL, MODIFIABLE_CONFIG, tls_auth_clients_enum, g_pserver->tls_auth_clients, TLS_CLIENT_AUTH_YES, NULL, NULL),
createBoolConfig("tls-prefer-server-ciphers", NULL, MODIFIABLE_CONFIG, g_pserver->tls_ctx_config.prefer_server_ciphers, 0, NULL, updateTlsCfgBool),
createBoolConfig("tls-session-caching", NULL, MODIFIABLE_CONFIG, g_pserver->tls_ctx_config.session_caching, 1, NULL, updateTlsCfgBool),
createBoolConfig("tls-rotation", NULL, MODIFIABLE_CONFIG, g_pserver->tls_rotation, 0, NULL, updateTlsCfgBool),
createStringConfig("tls-cert-file", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->tls_ctx_config.cert_file, NULL, NULL, updateTlsCfg),
createStringConfig("tls-key-file", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->tls_ctx_config.key_file, NULL, NULL, updateTlsCfg),
createStringConfig("tls-key-file-pass", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, g_pserver->tls_ctx_config.key_file_pass, NULL, NULL, updateTlsCfg),
@@ -3037,7 +2812,7 @@ NULL
};
addReplyHelp(c, help);
} else if (!strcasecmp(szFromObj(c->argv[1]),"set") && c->argc >= 3) {
} else if (!strcasecmp(szFromObj(c->argv[1]),"set") && c->argc == 4) {
configSetCommand(c);
} else if (!strcasecmp(szFromObj(c->argv[1]),"get") && c->argc == 3) {
configGetCommand(c);
+10 -33
View File
@@ -29,7 +29,6 @@
#include "server.h"
#include "connhelpers.h"
#include "aelocker.h"
/* The connections module provides a lean abstraction of network connections
* to avoid direct socket and async event management across the Redis code base.
@@ -113,7 +112,7 @@ static int connSocketConnect(connection *conn, const char *addr, int port, const
conn->state = CONN_STATE_CONNECTING;
conn->conn_handler = connect_handler;
aeCreateFileEvent(serverTL->el, conn->fd, AE_WRITABLE|AE_WRITE_THREADSAFE,
aeCreateFileEvent(serverTL->el, conn->fd, AE_WRITABLE,
conn->type->ae_handler, conn);
return C_OK;
@@ -161,11 +160,6 @@ static void connSocketClose(connection *conn) {
return;
}
if (conn->fprint) {
zfree(conn->fprint);
conn->fprint = NULL;
}
zfree(conn);
}
@@ -231,15 +225,14 @@ static int connSocketSetWriteHandler(connection *conn, ConnectionCallbackFunc fu
else
conn->flags &= ~CONN_FLAG_WRITE_BARRIER;
int flags = AE_WRITABLE;
if (fThreadSafe)
conn->flags |= CONN_FLAG_WRITE_THREADSAFE;
else
conn->flags &= ~CONN_FLAG_WRITE_THREADSAFE;
flags |= AE_WRITE_THREADSAFE;
if (!conn->write_handler)
aeDeleteFileEvent(serverTL->el,conn->fd,AE_WRITABLE);
else
if (aeCreateFileEvent(serverTL->el,conn->fd,AE_WRITABLE|AE_WRITE_THREADSAFE,
if (aeCreateFileEvent(serverTL->el,conn->fd,flags,
conn->type->ae_handler,conn) == AE_ERR) return C_ERR;
return C_OK;
}
@@ -249,18 +242,17 @@ static int connSocketSetWriteHandler(connection *conn, ConnectionCallbackFunc fu
*/
static int connSocketSetReadHandler(connection *conn, ConnectionCallbackFunc func, bool fThreadSafe) {
if (func == conn->read_handler) return C_OK;
int flags = AE_READABLE;
if (fThreadSafe)
conn->flags |= CONN_FLAG_READ_THREADSAFE;
else
conn->flags &= ~CONN_FLAG_READ_THREADSAFE;
flags |= AE_READ_THREADSAFE;
conn->read_handler = func;
if (!conn->read_handler)
aeDeleteFileEvent(serverTL->el,conn->fd,AE_READABLE);
else
if (aeCreateFileEvent(serverTL->el,conn->fd,
AE_READABLE|AE_READ_THREADSAFE,conn->type->ae_handler,conn) == AE_ERR) return C_ERR;
flags,conn->type->ae_handler,conn) == AE_ERR) return C_ERR;
return C_OK;
}
@@ -268,7 +260,7 @@ static const char *connSocketGetLastError(connection *conn) {
return strerror(conn->last_errno);
}
void connSocketEventHandler(struct aeEventLoop *el, int fd, void *clientData, int mask)
static void connSocketEventHandler(struct aeEventLoop *el, int fd, void *clientData, int mask)
{
UNUSED(el);
UNUSED(fd);
@@ -287,11 +279,7 @@ void connSocketEventHandler(struct aeEventLoop *el, int fd, void *clientData, in
if (!conn->write_handler) aeDeleteFileEvent(serverTL->el,conn->fd,AE_WRITABLE);
{
AeLocker locker;
locker.arm(nullptr);
if (!callHandler(conn, conn->conn_handler)) return;
}
conn->conn_handler = NULL;
}
@@ -313,27 +301,15 @@ void connSocketEventHandler(struct aeEventLoop *el, int fd, void *clientData, in
/* Handle normal I/O flows */
if (!invert && call_read) {
AeLocker lock;
if (!(conn->flags & CONN_FLAG_READ_THREADSAFE))
lock.arm(nullptr);
if (!callHandler(conn, conn->read_handler)) return;
}
/* Fire the writable event. */
if (call_write) {
AeLocker lock;
if (!(conn->flags & CONN_FLAG_WRITE_THREADSAFE))
lock.arm(nullptr);
if (!callHandler(conn, conn->write_handler)) return;
}
/* If we have to invert the call, fire the readable event now
* after the writable one. */
if (invert && call_read) {
AeLocker lock;
if (!(conn->flags & CONN_FLAG_READ_THREADSAFE))
lock.arm(nullptr);
if (!callHandler(conn, conn->read_handler)) return;
}
}
@@ -476,3 +452,4 @@ const char *connGetInfo(connection *conn, char *buf, size_t buf_len) {
snprintf(buf, buf_len-1, "fd=%i", conn == NULL ? -1 : conn->fd);
return buf;
}
-2
View File
@@ -51,7 +51,6 @@ typedef enum {
#define CONN_FLAG_WRITE_BARRIER (1<<1) /* Write barrier requested */
#define CONN_FLAG_READ_THREADSAFE (1<<2)
#define CONN_FLAG_WRITE_THREADSAFE (1<<3)
#define CONN_FLAG_AUDIT_LOGGING_REQUIRED (1<<4)
#define CONN_TYPE_SOCKET 1
#define CONN_TYPE_TLS 2
@@ -87,7 +86,6 @@ struct connection {
ConnectionCallbackFunc write_handler;
ConnectionCallbackFunc read_handler;
int fd;
char* fprint;
};
/* The connection module does not deal with listening and accepting sockets,
-55
View File
@@ -1,55 +0,0 @@
#pragma once
template <class T>
class CowPtr
{
public:
typedef std::shared_ptr<T> RefPtr;
private:
mutable RefPtr m_sp;
void detach()
{
if( !( m_sp == nullptr || m_sp.unique() ) ) {
m_sp = std::make_shared<T>(*m_sp);
}
}
public:
CowPtr() = default;
CowPtr(const RefPtr& refptr)
: m_sp(refptr)
{
}
bool operator==(std::nullptr_t) const
{
return m_sp == nullptr;
}
bool operator!=(std::nullptr_t) const
{
return m_sp != nullptr;
}
const T& operator*() const
{
return *m_sp;
}
T& operator*()
{
detach();
return *m_sp;
}
const T* operator->() const
{
return m_sp.operator->();
}
T* operator->()
{
detach();
return m_sp.operator->();
}
};
+6 -9
View File
@@ -31,8 +31,7 @@ void cronCommand(client *c)
if (getLongLongFromObjectOrReply(c, c->argv[ARG_EXPIRE], &interval, "missing expire time") != C_OK)
return;
long long base;
__atomic_load(&g_pserver->mstime, &base, __ATOMIC_ACQUIRE);
long long base = g_pserver->mstime;
if (getLongLongFromObject(c->argv[ARG_EXPIRE+1], &base) == C_OK) {
arg_offset++;
std::swap(base, interval);
@@ -61,7 +60,7 @@ void cronCommand(client *c)
spjob->interval = (uint64_t)interval;
spjob->startTime = (uint64_t)base;
spjob->fSingleShot = fSingleShot;
spjob->dbNum = dbnumFromDb(c->db);
spjob->dbNum = c->db - g_pserver->db;
for (long i = 0; i < numkeys; ++i)
spjob->veckeys.emplace_back(sdsdup(szFromObj(c->argv[ARG_KEYSTART+i])));
for (long i = ARG_KEYSTART + numkeys; i < c->argc; ++i)
@@ -117,25 +116,23 @@ void executeCronJobExpireHook(const char *key, robj *o)
int dbId = job->dbNum;
if (job->fSingleShot)
{
serverAssert(dbSyncDelete(cFake->db, keyobj));
dbSyncDelete(cFake->db, keyobj);
}
else
{
job->startTime += job->interval;
mstime_t mstime;
__atomic_load(&g_pserver->mstime, &mstime, __ATOMIC_ACQUIRE);
if (job->startTime < (uint64_t)mstime)
if (job->startTime < (uint64_t)g_pserver->mstime)
{
// If we are more than one interval in the past then fast forward to
// the first interval still in the future. If startTime wasn't zero align
// this to the original startTime, if it was zero align to now
if (job->startTime == job->interval)
{ // startTime was 0
job->startTime = mstime + job->interval;
job->startTime = g_pserver->mstime + job->interval;
}
else
{
auto delta = mstime - job->startTime;
auto delta = g_pserver->mstime - job->startTime;
auto multiple = (delta / job->interval)+1;
job->startTime += job->interval * multiple;
}
+330 -1430
View File
File diff suppressed because it is too large. Load diff
+64 -115
View File
@@ -78,8 +78,6 @@ void bugReportStart(void);
void printCrashReport(void);
void bugReportEnd(int killViaSignal, int sig);
void logStackTrace(void *eip, int uplevel);
void getTempFileName(char tmpfile[], int tmpfileNum);
bool initializeStorageProvider(const char **err);
/* ================================= Debugging ============================== */
@@ -147,10 +145,10 @@ void mixStringObjectDigest(unsigned char *digest, robj_roptr o) {
* Note that this function does not reset the initial 'digest' passed, it
* will continue mixing this object digest to anything that was already
* present. */
void xorObjectDigest(unsigned char *digest, robj_roptr o) {
void xorObjectDigest(redisDb *db, robj_roptr keyobj, unsigned char *digest, robj_roptr o) {
uint32_t aux = htonl(o->type);
mixDigest(digest,&aux,sizeof(aux));
const expireEntry *pexpire = o->FExpires() ? &o->expire : nullptr;
expireEntry *pexpire = getExpire(db,keyobj);
long long expiretime = INVALID_EXPIRE;
char buf[128];
@@ -293,15 +291,19 @@ void xorObjectDigest(unsigned char *digest, robj_roptr o) {
* as input in order to ensure that a different ordered list will result in
* a different digest. */
void computeDatasetDigest(unsigned char *final) {
unsigned char digest[20];
dictIterator *di = NULL;
dictEntry *de;
int j;
uint32_t aux;
memset(final,0,20); /* Start with a clean result */
for (j = 0; j < cserver.dbnum; j++) {
redisDb *db = g_pserver->db[j];
redisDb *db = g_pserver->db+j;
if (db->size() == 0) continue;
if (dictSize(db->dict) == 0) continue;
di = dictGetSafeIterator(db->dict);
/* hash the DB id, so the same dataset moved in a different
* DB will lead to a different digest */
@@ -309,22 +311,24 @@ void computeDatasetDigest(unsigned char *final) {
mixDigest(final,&aux,sizeof(aux));
/* Iterate this DB writing every entry */
db->iterate_threadsafe([final](const char *key, robj_roptr o)->bool {
unsigned char digest[20];
robj *keyobj;
while((de = dictNext(di)) != NULL) {
sds key;
robj *keyobj, *o;
memset(digest,0,20); /* This key-val digest */
key = (sds)dictGetKey(de);
keyobj = createStringObject(key,sdslen(key));
mixDigest(digest,key,sdslen(key));
xorObjectDigest(digest,o);
o = (robj*)dictGetVal(de);
xorObjectDigest(db,keyobj,digest,o);
/* We can finally xor the key-val digest to the final digest */
xorDigest(final,digest,20);
decrRefCount(keyobj);
return true;
});
}
dictReleaseIterator(di);
}
}
@@ -341,10 +345,10 @@ void mallctl_int(client *c, robj **argv, int argc) {
}
size_t sz = sizeof(old);
while (sz > 0) {
if ((ret=mallctl(szFromObj(argv[0]), &old, &sz, argc > 1? &val: NULL, argc > 1?sz: 0))) {
if ((ret=je_mallctl(szFromObj(argv[0]), &old, &sz, argc > 1? &val: NULL, argc > 1?sz: 0))) {
if (ret == EPERM && argc > 1) {
/* if this option is write only, try just writing to it. */
if (!(ret=mallctl(szFromObj(argv[0]), NULL, 0, &val, sz))) {
if (!(ret=je_mallctl(szFromObj(argv[0]), NULL, 0, &val, sz))) {
addReply(c, shared.ok);
return;
}
@@ -375,7 +379,7 @@ void mallctl_string(client *c, robj **argv, int argc) {
char *old;
size_t sz = sizeof(old);
/* for strings, it seems we need to first get the old value, before overriding it. */
if ((rret=mallctl(szFromObj(argv[0]), &old, &sz, NULL, 0))) {
if ((rret=je_mallctl(szFromObj(argv[0]), &old, &sz, NULL, 0))) {
/* return error unless this option is write only. */
if (!(rret == EPERM && argc > 1)) {
addReplyErrorFormat(c,"%s", strerror(rret));
@@ -387,7 +391,7 @@ void mallctl_string(client *c, robj **argv, int argc) {
char **valref = &val;
if ((!strcmp(val,"VOID")))
valref = NULL, sz = 0;
wret = mallctl(szFromObj(argv[0]), NULL, 0, valref, sz);
wret = je_mallctl(szFromObj(argv[0]), NULL, 0, valref, sz);
}
if (!rret)
addReplyBulkCString(c, old);
@@ -536,75 +540,30 @@ NULL
return;
}
}
if (g_pserver->m_pstorageFactory) {
protectClient(c);
for (int idb = 0; idb < cserver.dbnum; ++idb) {
if (g_pserver->db[idb]->processChanges(false))
g_pserver->db[idb]->commitChanges();
g_pserver->db[idb]->storageProviderDelete();
}
delete g_pserver->metadataDb;
if (flush) emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
delete g_pserver->m_pstorageFactory;
const char *err;
if (!initializeStorageProvider(&err))
{
serverLog(LL_WARNING, "Failed to initialize storage provider: %s",err);
exit(EXIT_FAILURE);
}
g_pserver->metadataDb = g_pserver->m_pstorageFactory->createMetadataDb();
for (int idb = 0; idb < cserver.dbnum; ++idb)
{
int dbid = idb;
std::string dbid_key = "db-" + std::to_string(idb);
g_pserver->metadataDb->retrieve(dbid_key.c_str(), dbid_key.length(), [&](const char *, size_t, const void *data, size_t){
dbid = *(int*)data;
});
delete g_pserver->db[idb];
g_pserver->db[idb] = new (MALLOC_LOCAL) redisDb();
g_pserver->db[idb]->initialize(dbid);
}
moduleFireServerEvent(REDISMODULE_EVENT_LOADING, REDISMODULE_SUBEVENT_LOADING_FLASH_START, NULL);
for (int idb = 0; idb < cserver.dbnum; ++idb)
{
g_pserver->db[idb]->storageProviderInitialize();
g_pserver->db[idb]->trackChanges(false);
}
moduleFireServerEvent(REDISMODULE_EVENT_LOADING, REDISMODULE_SUBEVENT_LOADING_ENDED, NULL);
unprotectClient(c);
} else {
/* The default behavior is to save the RDB file before loading
* it back. */
if (save) {
rdbSaveInfo rsi, *rsiptr;
rsiptr = rdbPopulateSaveInfo(&rsi);
if (rdbSave(nullptr, rsiptr) != C_OK) {
addReply(c,shared.err);
return;
}
}
/* The default behavior is to remove the current dataset from
* memory before loading the RDB file, however when MERGE is
* used together with NOFLUSH, we are able to merge two datasets. */
if (flush) emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
protectClient(c);
int ret = rdbLoadFile(g_pserver->rdb_filename,NULL,flags);
unprotectClient(c);
if (ret != C_OK) {
addReplyError(c,"Error trying to load the RDB dump");
/* The default behavior is to save the RDB file before loading
* it back. */
if (save) {
rdbSaveInfo rsi, *rsiptr;
rsiptr = rdbPopulateSaveInfo(&rsi);
if (rdbSaveFile(g_pserver->rdb_filename,rsiptr) != C_OK) {
addReply(c,shared.err);
return;
}
}
/* The default behavior is to remove the current dataset from
* memory before loading the RDB file, however when MERGE is
* used together with NOFLUSH, we are able to merge two datasets. */
if (flush) emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
protectClient(c);
int ret = rdbLoadFile(g_pserver->rdb_filename,NULL,flags);
unprotectClient(c);
if (ret != C_OK) {
addReplyError(c,"Error trying to load the RDB dump");
return;
}
serverLog(LL_WARNING,"DB reloaded by DEBUG RELOAD");
addReply(c,shared.ok);
} else if (!strcasecmp(szFromObj(c->argv[1]),"loadaof")) {
@@ -621,14 +580,15 @@ NULL
serverLog(LL_WARNING,"Append Only File loaded by DEBUG LOADAOF");
addReply(c,shared.ok);
} else if (!strcasecmp(szFromObj(c->argv[1]),"object") && c->argc == 3) {
dictEntry *de;
robj *val;
const char *strenc;
val = c->db->find(c->argv[2]);
if (val == NULL) {
if ((de = dictFind(c->db->dict,ptrFromObj(c->argv[2]))) == NULL) {
addReplyErrorObject(c,shared.nokeyerr);
return;
}
val = (robj*)dictGetVal(de);
strenc = strEncoding(val->encoding);
char extra[138] = {0};
@@ -672,14 +632,16 @@ NULL
strenc, rdbSavedObjectLen(val, c->argv[2]),
val->lru, estimateObjectIdleTime(val)/1000, extra);
} else if (!strcasecmp(szFromObj(c->argv[1]),"sdslen") && c->argc == 3) {
auto itr = c->db->find(c->argv[2]);
robj *val = itr.val();
const char *key = itr.key();
dictEntry *de;
robj *val;
sds key;
if (val == NULL) {
if ((de = dictFind(c->db->dict,ptrFromObj(c->argv[2]))) == NULL) {
addReplyErrorObject(c,shared.nokeyerr);
return;
}
val = (robj*)dictGetVal(de);
key = (sds)dictGetKey(de);
if (val->type != OBJ_STRING || !sdsEncodedObject(val)) {
addReplyError(c,"Not an sds encoded string.");
@@ -689,7 +651,7 @@ NULL
"val_sds_len:%lld, val_sds_avail:%lld, val_zmalloc: %lld",
(long long) sdslen(key),
(long long) sdsavail(key),
(long long) sdsZmallocSize((sds)key),
(long long) sdsZmallocSize(key),
(long long) sdslen(szFromObj(val)),
(long long) sdsavail(szFromObj(val)),
(long long) getStringObjectSdsUsedMemory(val));
@@ -714,8 +676,8 @@ NULL
if (getPositiveLongFromObjectOrReply(c, c->argv[2], &keys, NULL) != C_OK)
return;
c->db->expand(keys);
dictExpand(c->db->dict,keys);
long valsize = 0;
if ( c->argc == 5 && getPositiveLongFromObjectOrReply(c, c->argv[4], &valsize, NULL) != C_OK )
return;
@@ -759,9 +721,9 @@ NULL
/* We don't use lookupKey because a debug command should
* work on logically expired keys */
auto itr = c->db->find(c->argv[j]);
robj* o = (robj*)(itr == NULL ? NULL : itr.val());
if (o) xorObjectDigest(digest,o);
dictEntry *de;
robj *o = (robj*)((de = dictFind(c->db->dict,ptrFromObj(c->argv[j]))) == NULL) ? NULL : (robj*)dictGetVal(de);
if (o) xorObjectDigest(c->db,c->argv[j],digest,o);
sds d = sdsempty();
for (int i = 0; i < 20; i++) d = sdscatprintf(d, "%02x",digest[i]);
@@ -885,9 +847,13 @@ NULL
}
stats = sdscatprintf(stats,"[Dictionary HT]\n");
g_pserver->db[dbid]->getStats(buf,sizeof(buf));
dictGetStats(buf,sizeof(buf),g_pserver->db[dbid].dict);
stats = sdscat(stats,buf);
stats = sdscatprintf(stats,"[Expires set]\n");
g_pserver->db[dbid].setexpire->getstats(buf, sizeof(buf));
stats = sdscat(stats, buf);
addReplyVerbatim(c,stats,sdslen(stats),"txt");
sdsfree(stats);
} else if (!strcasecmp(szFromObj(c->argv[1]),"htstats-key") && c->argc == 3) {
@@ -947,10 +913,6 @@ NULL
c->flags &= ~(CLIENT_MASTER | CLIENT_MASTER_FORCE_REPLY);
}
addReply(c, shared.ok);
} else if (!strcasecmp(szFromObj(c->argv[1]), "get-temp-file") && c->argc == 2) {
char tmpfile[256];
getTempFileName(tmpfile, g_pserver->rdbThreadVars.tmpfileNum);
addReplyBulkCString(c, tmpfile);
} else if (!strcasecmp(szFromObj(c->argv[1]),"truncate-repl-backlog") && c->argc == 2) {
g_pserver->repl_backlog_idx = 0;
g_pserver->repl_backlog_off = g_pserver->master_repl_offset+1;
@@ -978,21 +940,6 @@ NULL
mallctl_string(c, c->argv+2, c->argc-2);
return;
#endif
} else if(!strcasecmp(szFromObj(c->argv[1]),"flush-storage") && c->argc == 2) {
if (g_pserver->m_pstorageFactory != nullptr) {
for (int i = 0; i < cserver.dbnum; i++) {
g_pserver->db[i]->getStorageCache()->flush();
}
addReply(c,shared.ok);
} else {
addReplyError(c, "Can't flush storage if no storage provider is set");
}
} else if (!strcasecmp(szFromObj(c->argv[1]),"get-storage-usage") && c->argc == 2) {
if (g_pserver->m_pstorageFactory != nullptr) {
addReplyLongLong(c, g_pserver->m_pstorageFactory->totalDiskspaceUsed());
} else {
addReplyLongLong(c, 0);
}
} else {
addReplySubcommandSyntaxError(c);
return;
@@ -1846,10 +1793,12 @@ void logCurrentClient(void) {
* selected DB, and if so print info about the associated object. */
if (cc->argc > 1) {
robj *val, *key;
dictEntry *de;
key = getDecodedObject(cc->argv[1]);
val = cc->db->find(key);
if (val) {
de = dictFind(cc->db->dict, ptrFromObj(key));
if (de) {
val = (robj*)dictGetVal(de);
serverLog(LL_WARNING,"key '%s' found in DB containing the following object:", (char*)ptrFromObj(key));
serverLogObjectDebugInfo(val);
}
+32 -11
View File
@@ -47,6 +47,7 @@ extern "C" int je_get_defrag_hint(void* ptr);
/* forward declarations*/
void defragDictBucketCallback(void *privdata, dictEntry **bucketref);
dictEntry* replaceSatelliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, sds newkey, uint64_t hash, long *defragged);
bool replaceSatelliteOSetKeyPtr(expireset &set, sds oldkey, sds newkey);
/* Defrag helper for generic allocations.
*
@@ -424,6 +425,20 @@ dictEntry* replaceSatelliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, s
return NULL;
}
bool replaceSatelliteOSetKeyPtr(expireset &set, sds oldkey, sds newkey) {
auto itr = set.find(oldkey);
if (itr != set.end())
{
expireEntry eNew(std::move(*itr));
eNew.setKeyUnsafe(newkey);
set.erase(itr);
set.insert(eNew);
serverAssert(set.find(newkey) != set.end());
return true;
}
return false;
}
long activeDefragQuickListNode(quicklist *ql, quicklistNode **node_ref) {
quicklistNode *newnode, *node = *node_ref;
long defragged = 0;
@@ -846,10 +861,18 @@ long defragKey(redisDb *db, dictEntry *de) {
/* Try to defrag the key name. */
newsds = activeDefragSds(keysds);
if (newsds) {
if (newsds)
{
defragged++, de->key = newsds;
if (!db->setexpire->empty()) {
bool fReplaced = replaceSatelliteOSetKeyPtr(*db->setexpire, keysds, newsds);
serverAssert(fReplaced == ob->FExpires());
} else {
serverAssert(!ob->FExpires());
}
}
/* Try to defrag robj and / or string value. */
if ((newob = activeDefragStringOb(ob, &defragged))) {
de->v.val = newob;
ob = newob;
@@ -966,8 +989,9 @@ long defragOtherGlobals() {
/* returns 0 more work may or may not be needed (see non-zero cursor),
* and 1 if time is up and more work is needed. */
int defragLaterItem(sds key, robj *ob, unsigned long *cursor, long long endtime) {
if (ob) {
int defragLaterItem(dictEntry *de, unsigned long *cursor, long long endtime) {
if (de) {
robj *ob = (robj*)dictGetVal(de);
if (ob->type == OBJ_LIST) {
return scanLaterList(ob, cursor, endtime, &g_pserver->stat_active_defrag_hits);
} else if (ob->type == OBJ_SET) {
@@ -979,9 +1003,7 @@ int defragLaterItem(sds key, robj *ob, unsigned long *cursor, long long endtime)
} else if (ob->type == OBJ_STREAM) {
return scanLaterStreamListpacks(ob, cursor, endtime, &g_pserver->stat_active_defrag_hits);
} else if (ob->type == OBJ_MODULE) {
redisObjectStack oT;
initStaticStringObject(oT, key);
return moduleLateDefrag(&oT, ob, cursor, endtime, &g_pserver->stat_active_defrag_hits);
return moduleLateDefrag((robj*)dictGetKey(de), ob, cursor, endtime, &g_pserver->stat_active_defrag_hits);
} else {
*cursor = 0; /* object type may have changed since we schedule it for later */
}
@@ -1026,11 +1048,11 @@ int defragLaterStep(redisDb *db, long long endtime) {
}
/* each time we enter this function we need to fetch the key from the dict again (if it still exists) */
robj *o = db->find(defrag_later_current_key);
dictEntry *de = dictFind(db->dict, defrag_later_current_key);
key_defragged = g_pserver->stat_active_defrag_hits;
do {
int quit = 0;
if (defragLaterItem(defrag_later_current_key, o, &defrag_later_cursor, endtime))
if (defragLaterItem(de, &defrag_later_cursor, endtime))
quit = 1; /* time is up, we didn't finish all the work */
/* Once in 16 scan iterations, 512 pointer reallocations, or 64 fields
@@ -1178,7 +1200,7 @@ void activeDefragCycle(void) {
start_stat = g_pserver->stat_active_defrag_hits;
}
db = g_pserver->db[current_db];
db = &g_pserver->db[current_db];
cursor = 0;
}
@@ -1189,8 +1211,7 @@ void activeDefragCycle(void) {
break; /* this will exit the function and we'll continue on the next cycle */
}
// we actually look at the objects too but defragScanCallback can handle missing values
cursor = dictScan(db->dictUnsafeKeyOnly(), cursor, defragScanCallback, defragDictBucketCallback, db);
cursor = dictScan(db->dict, cursor, defragScanCallback, defragDictBucketCallback, db);
/* Once in 16 scan iterations, 512 pointer reallocations. or 64 keys
* (if we have a lot of pointers in one hash bucket or rehasing),
+48 -422
View File
@@ -42,7 +42,6 @@
#include <stdarg.h>
#include <limits.h>
#include <sys/time.h>
#include <algorithm>
#include "dict.h"
#include "zmalloc.h"
@@ -63,15 +62,13 @@ static unsigned int dict_force_resize_ratio = 5;
static int _dictExpandIfNeeded(dict *ht);
static unsigned long _dictNextPower(unsigned long size);
long _dictKeyIndex(dict *ht, const void *key, uint64_t hash, dictEntry **existing);
static long _dictKeyIndex(dict *ht, const void *key, uint64_t hash, dictEntry **existing);
static int _dictInit(dict *ht, dictType *type, void *privDataPtr);
/* -------------------------- hash functions -------------------------------- */
static uint8_t dict_hash_function_seed[16];
extern "C" void asyncFreeDictTable(dictEntry **de);
void dictSetHashFunctionSeed(uint8_t *seed) {
memcpy(dict_hash_function_seed,seed,sizeof(dict_hash_function_seed));
}
@@ -126,22 +123,32 @@ int _dictInit(dict *d, dictType *type,
d->privdata = privDataPtr;
d->rehashidx = -1;
d->pauserehash = 0;
d->asyncdata = nullptr;
d->refcount = 1;
d->noshrink = false;
return DICT_OK;
}
/* Resize the table to the minimal size that contains all the elements,
* but with the invariant of a USED/BUCKETS ratio near to <= 1 */
int dictResize(dict *d)
{
unsigned long minimal;
if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
minimal = d->ht[0].used;
if (minimal < DICT_HT_INITIAL_SIZE)
minimal = DICT_HT_INITIAL_SIZE;
return dictExpand(d, minimal);
}
/* Expand or create the hash table,
* when malloc_failed is non-NULL, it'll avoid panic if malloc fails (in which case it'll be set to 1).
* Returns DICT_OK if expand was performed, and DICT_ERR if skipped. */
int _dictExpand(dict *d, unsigned long size, bool fShrink, int* malloc_failed)
int _dictExpand(dict *d, unsigned long size, int* malloc_failed)
{
if (malloc_failed) *malloc_failed = 0;
/* the size is invalid if it is smaller than the number of
* elements already inside the hash table */
if (dictIsRehashing(d) || (d->ht[0].used > size && !fShrink) || size == 0)
if (dictIsRehashing(d) || d->ht[0].used > size)
return DICT_ERR;
dictht n; /* the new hash table */
@@ -181,169 +188,15 @@ int _dictExpand(dict *d, unsigned long size, bool fShrink, int* malloc_failed)
return DICT_OK;
}
/* Resize the table to the minimal size that contains all the elements,
* but with the invariant of a USED/BUCKETS ratio near to <= 1 */
int dictResize(dict *d)
{
unsigned long minimal;
if (!dict_can_resize || dictIsRehashing(d)) return DICT_ERR;
minimal = d->ht[0].used;
if (minimal < DICT_HT_INITIAL_SIZE)
minimal = DICT_HT_INITIAL_SIZE;
return _dictExpand(d, minimal, false /*fShirnk*/, nullptr);
}
int dictMerge(dict *dst, dict *src)
{
#define MERGE_BLOCK_SIZE 4
dictEntry *rgdeT[MERGE_BLOCK_SIZE];
assert(dst != src);
if (dictSize(src) == 0)
return DICT_OK;
if (dictSize(dst) == 0)
{
dict::swap(*dst, *src);
std::swap(dst->pauserehash, src->pauserehash);
return DICT_OK;
}
size_t expectedSize = dictSize(src) + dictSize(dst);
if (dictSize(src) > dictSize(dst) && src->asyncdata == nullptr && dst->asyncdata == nullptr)
{
dict::swap(*dst, *src);
std::swap(dst->pauserehash, src->pauserehash);
}
if (!dictIsRehashing(dst) && !dictIsRehashing(src))
{
if (dst->ht[0].size >= src->ht[0].size)
{
dst->ht[1] = dst->ht[0];
dst->ht[0] = src->ht[0];
}
else
{
dst->ht[1] = src->ht[0];
}
_dictReset(&src->ht[0]);
dst->rehashidx = 0;
assert(dictIsRehashing(dst));
assert((dictSize(src)+dictSize(dst)) == expectedSize);
return DICT_OK;
}
if (!dictIsRehashing(src) && dictSize(src) > 0 &&
(src->ht[0].size == dst->ht[0].size || src->ht[0].size == dst->ht[1].size))
{
auto &htDst = (src->ht[0].size == dst->ht[0].size) ? dst->ht[0] : dst->ht[1];
assert(src->ht[0].size == htDst.size);
for (size_t ide = 0; ide < src->ht[0].size; ide += MERGE_BLOCK_SIZE)
{
if (src->ht[0].used == 0)
break;
for (int dde = 0; dde < MERGE_BLOCK_SIZE; ++dde) {
rgdeT[dde] = src->ht[0].table[ide + dde];
src->ht[0].table[ide + dde] = nullptr;
}
for (;;) {
bool fAnyFound = false;
for (int dde = 0; dde < MERGE_BLOCK_SIZE; ++dde) {
if (rgdeT[dde] == nullptr)
continue;
dictEntry *deNext = rgdeT[dde]->next;
rgdeT[dde]->next = htDst.table[ide+dde];
htDst.table[ide+dde] = rgdeT[dde];
rgdeT[dde] = deNext;
htDst.used++;
src->ht[0].used--;
fAnyFound = fAnyFound || (deNext != nullptr);
}
if (!fAnyFound)
break;
}
}
// If we copied to the base hash table of a rehashing dst, reset the rehash
if (dictIsRehashing(dst) && src->ht[0].size == dst->ht[0].size)
dst->rehashidx = 0;
assert(dictSize(src) == 0);
assert((dictSize(src)+dictSize(dst)) == expectedSize);
return DICT_OK;
}
_dictExpand(dst, dictSize(dst)+dictSize(src), false /* fShrink */, nullptr); // start dst rehashing if necessary
auto &htDst = dictIsRehashing(dst) ? dst->ht[1] : dst->ht[0];
for (int iht = 0; iht < 2; ++iht)
{
for (size_t ide = 0; ide < src->ht[iht].size; ide += MERGE_BLOCK_SIZE)
{
if (src->ht[iht].used == 0)
break;
for (int dde = 0; dde < MERGE_BLOCK_SIZE; ++dde) {
rgdeT[dde] = src->ht[iht].table[ide + dde];
src->ht[iht].table[ide + dde] = nullptr;
}
for (;;) {
bool fAnyFound = false;
for (int dde = 0; dde < MERGE_BLOCK_SIZE; ++dde) {
if (rgdeT[dde] == nullptr)
continue;
uint64_t h = dictHashKey(dst, rgdeT[dde]->key) & htDst.sizemask;
dictEntry *deNext = rgdeT[dde]->next;
rgdeT[dde]->next = htDst.table[h];
htDst.table[h] = rgdeT[dde];
rgdeT[dde] = deNext;
htDst.used++;
src->ht[iht].used--;
fAnyFound = fAnyFound || (deNext != nullptr);
}
if (!fAnyFound)
break;
}
#if 0
dictEntry *de = src->ht[iht].table[ide];
src->ht[iht].table[ide] = nullptr;
while (de != nullptr)
{
dictEntry *deNext = de->next;
uint64_t h = dictHashKey(dst, de->key) & htDst.sizemask;
de->next = htDst.table[h];
htDst.table[h] = de;
htDst.used++;
de = deNext;
src->ht[iht].used--;
}
#endif
}
}
assert((dictSize(src)+dictSize(dst)) == expectedSize);
return DICT_OK;
}
/* return DICT_ERR if expand was not performed */
int dictExpand(dict *d, unsigned long size, bool fShrink) {
// External expand likely means mass insertion, and we don't want to shrink during that
d->noshrink = true;
return _dictExpand(d, size, fShrink, NULL);
int dictExpand(dict *d, unsigned long size) {
return _dictExpand(d, size, NULL);
}
/* return DICT_ERR if expand failed due to memory allocation failure */
int dictTryExpand(dict *d, unsigned long size, bool fShrink) {
int dictTryExpand(dict *d, unsigned long size) {
int malloc_failed;
// External expand likely means mass insertion, and we don't want to shrink during that
d->noshrink = true;
_dictExpand(d, size, fShrink, &malloc_failed);
_dictExpand(d, size, &malloc_failed);
return malloc_failed? DICT_ERR : DICT_OK;
}
@@ -359,7 +212,6 @@ int dictTryExpand(dict *d, unsigned long size, bool fShrink) {
int dictRehash(dict *d, int n) {
int empty_visits = n*10; /* Max number of empty buckets to visit. */
if (!dictIsRehashing(d)) return 0;
if (d->asyncdata) return 0;
while(n-- && d->ht[0].used != 0) {
dictEntry *de, *nextde;
@@ -390,7 +242,7 @@ int dictRehash(dict *d, int n) {
/* Check if we already rehashed the whole table... */
if (d->ht[0].used == 0) {
asyncFreeDictTable(d->ht[0].table);
zfree(d->ht[0].table);
d->ht[0] = d->ht[1];
_dictReset(&d->ht[1]);
d->rehashidx = -1;
@@ -401,158 +253,6 @@ int dictRehash(dict *d, int n) {
return 1;
}
dictAsyncRehashCtl::dictAsyncRehashCtl(struct dict *d, dictAsyncRehashCtl *next) : dict(d), next(next) {
queue.reserve(c_targetQueueSize);
__atomic_fetch_add(&d->refcount, 1, __ATOMIC_ACQ_REL);
this->rehashIdxBase = d->rehashidx;
}
dictAsyncRehashCtl *dictRehashAsyncStart(dict *d, int buckets) {
assert(d->type->asyncfree != nullptr);
if (!dictIsRehashing(d) || d->pauserehash != 0) return nullptr;
d->asyncdata = new dictAsyncRehashCtl(d, d->asyncdata);
int empty_visits = buckets*10;
while (d->asyncdata->queue.size() < (size_t)buckets && (size_t)d->rehashidx < d->ht[0].size) {
dictEntry *de;
/* Note that rehashidx can't overflow as we are sure there are more
* elements because ht[0].used != 0 */
while(d->ht[0].table[d->rehashidx] == NULL) {
d->rehashidx++;
if (--empty_visits == 0) goto LDone;
if ((size_t)d->rehashidx >= d->ht[0].size) goto LDone;
}
de = d->ht[0].table[d->rehashidx];
// We have to queue every node in the bucket, even if we go over our target size
while (de != nullptr) {
d->asyncdata->queue.emplace_back(de);
de = de->next;
}
d->rehashidx++;
}
LDone:
if (d->asyncdata->queue.empty()) {
// We didn't find any work to do (can happen if there is a large gap in the hash table)
auto asyncT = d->asyncdata;
d->asyncdata = d->asyncdata->next;
delete asyncT;
return nullptr;
}
return d->asyncdata;
}
void dictRehashAsync(dictAsyncRehashCtl *ctl) {
if (ctl->abondon.load(std::memory_order_acquire)) {
ctl->hashIdx = ctl->queue.size();
}
for (size_t idx = ctl->hashIdx; idx < ctl->queue.size(); ++idx) {
auto &wi = ctl->queue[idx];
wi.hash = dictHashKey(ctl->dict, dictGetKey(wi.de));
}
ctl->hashIdx = ctl->queue.size();
ctl->done = true;
}
bool dictRehashSomeAsync(dictAsyncRehashCtl *ctl, size_t hashes) {
if (ctl->abondon.load(std::memory_order_acquire)) {
ctl->hashIdx = ctl->queue.size();
}
size_t max = std::min(ctl->hashIdx + hashes, ctl->queue.size());
for (; ctl->hashIdx < max; ++ctl->hashIdx) {
auto &wi = ctl->queue[ctl->hashIdx];
wi.hash = dictHashKey(ctl->dict, dictGetKey(wi.de));
}
if (ctl->hashIdx == ctl->queue.size()) ctl->done = true;
return ctl->hashIdx < ctl->queue.size();
}
void discontinueAsyncRehash(dict *d) {
// We inform our async rehashers and the completion function the results are to be
// abandoned. We keep the asyncdata linked in so that dictEntry's are still added
// to the GC list. This is because we can't gurantee when the other threads will
// stop looking at them.
if (d->asyncdata != nullptr) {
auto adata = d->asyncdata;
while (adata != nullptr && !adata->abondon.load(std::memory_order_relaxed)) {
adata->abondon = true;
adata = adata->next;
}
if (dictIsRehashing(d))
d->rehashidx = 0;
}
}
void dictCompleteRehashAsync(dictAsyncRehashCtl *ctl, bool fFree) {
dict *d = ctl->dict;
assert(ctl->done);
// Unlink ourselves
bool fUnlinked = false;
dictAsyncRehashCtl **pprev = &d->asyncdata;
while (*pprev != nullptr) {
if (*pprev == ctl) {
*pprev = ctl->next;
fUnlinked = true;
break;
}
pprev = &((*pprev)->next);
}
if (fUnlinked) {
if (ctl->next != nullptr && ctl->deGCList != nullptr) {
// An older work item may depend on our free list, so pass our free list to them
dictEntry **deGC = &ctl->next->deGCList;
while (*deGC != nullptr) deGC = &((*deGC)->next);
*deGC = ctl->deGCList;
ctl->deGCList = nullptr;
}
}
if (fUnlinked && !ctl->abondon) {
if (d->ht[0].table != nullptr) { // can be null if we're cleared during the rehash
for (auto &wi : ctl->queue) {
// We need to remove it from the source hash table, and store it in the dest.
// Note that it may have been deleted in the meantime and therefore not exist.
// In this case it will be in the garbage collection list
dictEntry **pdePrev = &d->ht[0].table[wi.hash & d->ht[0].sizemask];
while (*pdePrev != nullptr && *pdePrev != wi.de) {
pdePrev = &((*pdePrev)->next);
}
if (*pdePrev != nullptr) { // The element may be NULL if its in the GC list
assert(*pdePrev == wi.de);
*pdePrev = wi.de->next;
// Now link it to the dest hash table
wi.de->next = d->ht[1].table[wi.hash & d->ht[1].sizemask];
d->ht[1].table[wi.hash & d->ht[1].sizemask] = wi.de;
d->ht[0].used--;
d->ht[1].used++;
}
}
}
/* Check if we already rehashed the whole table... */
if (d->ht[0].used == 0 && d->asyncdata == nullptr) {
asyncFreeDictTable(d->ht[0].table);
d->ht[0] = d->ht[1];
_dictReset(&d->ht[1]);
d->rehashidx = -1;
}
}
if (fFree) {
d->type->asyncfree(ctl);
}
}
long long timeInMilliseconds(void) {
struct timeval tv;
@@ -560,18 +260,6 @@ long long timeInMilliseconds(void) {
return (((long long)tv.tv_sec)*1000)+(tv.tv_usec/1000);
}
dictAsyncRehashCtl::~dictAsyncRehashCtl() {
while (deGCList != nullptr) {
auto next = deGCList->next;
dictFreeKey(dict, deGCList);
if (deGCList->v.val != nullptr)
dictFreeVal(dict, deGCList);
zfree(deGCList);
deGCList = next;
}
dictRelease(this->dict);
}
/* Rehash in ms+"delta" milliseconds. The value of "delta" is larger
* than 0, and is smaller than 1 in most cases. The exact upper bound
* depends on the running time of dictRehash(d,100).*/
@@ -581,8 +269,8 @@ int dictRehashMilliseconds(dict *d, int ms) {
long long start = timeInMilliseconds();
int rehashes = 0;
while(dictRehash(d,1000)) {
rehashes += 1000;
while(dictRehash(d,100)) {
rehashes += 100;
if (timeInMilliseconds()-start > ms) break;
}
return rehashes;
@@ -597,15 +285,13 @@ int dictRehashMilliseconds(dict *d, int ms) {
* dictionary so that the hash table automatically migrates from H1 to H2
* while it is actively used. */
static void _dictRehashStep(dict *d) {
int16_t pauserehash;
__atomic_load(&d->pauserehash, &pauserehash, __ATOMIC_RELAXED);
if (pauserehash == 0) dictRehash(d,1);
if (d->pauserehash == 0) dictRehash(d,1);
}
/* Add an element to the target hash table */
int dictAdd(dict *d, void *key, void *val, dictEntry **existing)
int dictAdd(dict *d, void *key, void *val)
{
dictEntry *entry = dictAddRaw(d,key,existing);
dictEntry *entry = dictAddRaw(d,key,NULL);
if (!entry) return DICT_ERR;
dictSetVal(d, entry, val);
@@ -707,9 +393,6 @@ static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
dictEntry *he, *prevHe;
int table;
// if we are deleting elements we probably aren't mass inserting anymore and it is safe to shrink
d->noshrink = false;
if (d->ht[0].used == 0 && d->ht[1].used == 0) return NULL;
if (dictIsRehashing(d)) _dictRehashStep(d);
@@ -727,19 +410,11 @@ static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
else
d->ht[table].table[idx] = he->next;
if (!nofree) {
if (table == 0 && d->asyncdata != nullptr && (ssize_t)idx < d->rehashidx) {
dictFreeVal(d, he);
he->v.val = nullptr;
he->next = d->asyncdata->deGCList;
d->asyncdata->deGCList = he;
} else {
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
d->ht[table].used--;
_dictExpandIfNeeded(d);
return he;
}
prevHe = he;
@@ -747,7 +422,6 @@ static dictEntry *dictGenericDelete(dict *d, const void *key, int nofree) {
}
if (!dictIsRehashing(d)) break;
}
_dictExpandIfNeeded(d);
return NULL; /* not found */
}
@@ -787,16 +461,9 @@ dictEntry *dictUnlink(dict *ht, const void *key) {
void dictFreeUnlinkedEntry(dict *d, dictEntry *he) {
if (he == NULL) return;
if (d->asyncdata) {
dictFreeVal(d, he);
he->v.val = nullptr;
he->next = d->asyncdata->deGCList;
d->asyncdata->deGCList = he;
} else {
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
/* Destroy an entire dictionary */
@@ -810,26 +477,17 @@ int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
if (callback && (i & 65535) == 0) callback(d->privdata);
if ((he = ht->table[i]) == NULL) continue;
dictEntry *deNull = nullptr;
__atomic_store(&ht->table[i], &deNull, __ATOMIC_RELEASE);
while(he) {
nextHe = he->next;
if (d->asyncdata && (ssize_t)i < d->rehashidx) {
dictFreeVal(d, he);
he->v.val = nullptr;
he->next = d->asyncdata->deGCList;
d->asyncdata->deGCList = he;
} else {
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
}
dictFreeKey(d, he);
dictFreeVal(d, he);
zfree(he);
ht->used--;
he = nextHe;
}
}
/* Free the table and the allocated cache structure */
asyncFreeDictTable(ht->table);
zfree(ht->table);
/* Re-initialize the table */
_dictReset(ht);
return DICT_OK; /* never fails */
@@ -838,30 +496,25 @@ int _dictClear(dict *d, dictht *ht, void(callback)(void *)) {
/* Clear & Release the hash table */
void dictRelease(dict *d)
{
if (__atomic_sub_fetch(&d->refcount, 1, __ATOMIC_ACQ_REL) == 0) {
_dictClear(d,&d->ht[0],NULL);
_dictClear(d,&d->ht[1],NULL);
zfree(d);
}
_dictClear(d,&d->ht[0],NULL);
_dictClear(d,&d->ht[1],NULL);
zfree(d);
}
dictEntry *dictFindWithPrev(dict *d, const void *key, uint64_t h, dictEntry ***dePrevPtr, dictht **pht, bool fShallowCompare)
dictEntry *dictFind(dict *d, const void *key)
{
dictEntry *he;
uint64_t idx, table;
uint64_t h, idx, table;
if (dictSize(d) == 0) return NULL; /* dict is empty */
if (dictIsRehashing(d)) _dictRehashStep(d);
h = dictHashKey(d, key);
for (table = 0; table <= 1; table++) {
*pht = d->ht + table;
idx = h & d->ht[table].sizemask;
he = d->ht[table].table[idx];
*dePrevPtr = &d->ht[table].table[idx];
while(he) {
if (key==he->key || (!fShallowCompare && dictCompareKeys(d, key, he->key))) {
if (key==he->key || dictCompareKeys(d, key, he->key))
return he;
}
*dePrevPtr = &he->next;
he = he->next;
}
if (!dictIsRehashing(d)) return NULL;
@@ -869,14 +522,6 @@ dictEntry *dictFindWithPrev(dict *d, const void *key, uint64_t h, dictEntry ***d
return NULL;
}
dictEntry *dictFind(dict *d, const void *key)
{
dictEntry **deT;
dictht *ht;
uint64_t h = dictHashKey(d, key);
return dictFindWithPrev(d, key, h, &deT, &ht);
}
void *dictFetchValue(dict *d, const void *key) {
dictEntry *he;
@@ -999,16 +644,10 @@ dictEntry *dictGetRandomKey(dict *d)
if (dictSize(d) == 0) return NULL;
if (dictIsRehashing(d)) _dictRehashStep(d);
if (dictIsRehashing(d)) {
long rehashidx = d->rehashidx;
auto async = d->asyncdata;
while (async != nullptr) {
rehashidx = std::min((long)async->rehashIdxBase, rehashidx);
async = async->next;
}
do {
/* We are sure there are no elements in indexes from 0
* to rehashidx-1 */
h = rehashidx + (randomULong() % (dictSlots(d) - rehashidx));
h = d->rehashidx + (randomULong() % (dictSlots(d) - d->rehashidx));
he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
d->ht[0].table[h];
} while(he == NULL);
@@ -1347,12 +986,11 @@ static int dictTypeExpandAllowed(dict *d) {
/* Expand the hash table if needed */
static int _dictExpandIfNeeded(dict *d)
{
static const size_t SHRINK_FACTOR = 4;
/* Incremental rehashing already in progress. Return. */
if (dictIsRehashing(d)) return DICT_OK;
/* If the hash table is empty expand it to the initial size. */
if (d->ht[0].size == 0) return _dictExpand(d, DICT_HT_INITIAL_SIZE, false /*fShrink*/, nullptr);
if (d->ht[0].size == 0) return dictExpand(d, DICT_HT_INITIAL_SIZE);
/* If we reached the 1:1 ratio, and we are allowed to resize the hash
* table (global setting) or we should avoid it but the ratio between
@@ -1363,12 +1001,7 @@ static int _dictExpandIfNeeded(dict *d)
d->ht[0].used/d->ht[0].size > dict_force_resize_ratio) &&
dictTypeExpandAllowed(d))
{
return _dictExpand(d, d->ht[0].used + 1, false /*fShrink*/, nullptr);
}
else if (d->ht[0].used > 0 && d->ht[0].size >= (1024*SHRINK_FACTOR) && (d->ht[0].used * 16) < d->ht[0].size && dict_can_resize && !d->noshrink)
{
// If the dictionary has shurnk a lot we'll need to shrink the hash table instead
return _dictExpand(d, d->ht[0].size/SHRINK_FACTOR, true /*fShrink*/, nullptr);
return dictExpand(d, d->ht[0].used + 1);
}
return DICT_OK;
}
@@ -1393,7 +1026,7 @@ static unsigned long _dictNextPower(unsigned long size)
*
* Note that if we are in the process of rehashing the hash table, the
* index is always returned in the context of the second (new) hash table. */
long _dictKeyIndex(dict *d, const void *key, uint64_t hash, dictEntry **existing)
static long _dictKeyIndex(dict *d, const void *key, uint64_t hash, dictEntry **existing)
{
unsigned long idx, table;
dictEntry *he;
@@ -1541,13 +1174,6 @@ void dictGetStats(char *buf, size_t bufsize, dict *d) {
if (orig_bufsize) orig_buf[orig_bufsize-1] = '\0';
}
void dictForceRehash(dict *d)
{
int16_t pauserehash;
__atomic_load(&d->pauserehash, &pauserehash, __ATOMIC_RELAXED);
while (pauserehash == 0 && dictIsRehashing(d)) _dictRehashStep(d);
}
/* ------------------------------- Benchmark ---------------------------------*/
#ifdef REDIS_TEST
@@ -1577,7 +1203,7 @@ char *stringFromLongLong(long long value) {
int len;
char *s;
len = snprintf(buf,sizeof(buf),"%lld",value);
len = sprintf(buf,"%lld",value);
s = zmalloc(len+1);
memcpy(s, buf, len);
s[len] = '\0';
+9 -45
View File
@@ -56,7 +56,6 @@ extern "C" {
/* Unused arguments generate annoying warnings... */
#define DICT_NOTUSED(V) ((void) V)
struct dictAsyncRehashCtl;
typedef struct dictEntry {
void *key;
@@ -77,7 +76,6 @@ typedef struct dictType {
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
int (*expandAllowed)(size_t moreMem, double usedRatio);
void (*asyncfree)(dictAsyncRehashCtl *);
} dictType;
/* This is our hash table structure. Every dictionary has two of this as we
@@ -104,49 +102,24 @@ struct dictAsyncRehashCtl {
struct dict *dict = nullptr;
std::vector<workItem> queue;
size_t hashIdx = 0;
long rehashIdxBase;
bool release = false;
dictAsyncRehashCtl *next = nullptr;
std::atomic<bool> done { false };
std::atomic<bool> abondon { false };
dictAsyncRehashCtl(struct dict *d, dictAsyncRehashCtl *next);
dictAsyncRehashCtl(const dictAsyncRehashCtl&) = delete;
dictAsyncRehashCtl(dictAsyncRehashCtl&&) = delete;
~dictAsyncRehashCtl();
dictAsyncRehashCtl(struct dict *d, dictAsyncRehashCtl *next) : dict(d), next(next) {
queue.reserve(c_targetQueueSize);
}
};
#else
struct dictAsyncRehashCtl;
#endif
void discontinueAsyncRehash(dict *d);
typedef struct dict {
dictType *type;
void *privdata;
dictht ht[2];
long rehashidx; /* rehashing not in progress if rehashidx == -1 */
unsigned refcount;
dictAsyncRehashCtl *asyncdata;
int16_t pauserehash; /* If >0 rehashing is paused (<0 indicates coding error) */
uint8_t noshrink = false;
#ifdef __cplusplus
dict() = default;
dict(dict &) = delete; // No Copy Ctor
static void swap(dict& a, dict& b) {
discontinueAsyncRehash(&a);
discontinueAsyncRehash(&b);
std::swap(a.type, b.type);
std::swap(a.privdata, b.privdata);
std::swap(a.ht[0], b.ht[0]);
std::swap(a.ht[1], b.ht[1]);
std::swap(a.rehashidx, b.rehashidx);
// Never swap refcount - they are attached to the specific dict obj
std::swap(a.pauserehash, b.pauserehash);
std::swap(a.noshrink, b.noshrink);
}
#endif
} dict;
/* If safe is set to 1 this is a safe iterator, that means, you can call
@@ -214,8 +187,8 @@ typedef void (dictScanBucketFunction)(void *privdata, dictEntry **bucketref);
#define dictSlots(d) ((d)->ht[0].size+(d)->ht[1].size)
#define dictSize(d) ((d)->ht[0].used+(d)->ht[1].used)
#define dictIsRehashing(d) ((d)->rehashidx != -1)
#define dictPauseRehashing(d) __atomic_fetch_add(&(d)->pauserehash, 1, __ATOMIC_SEQ_CST)
#define dictResumeRehashing(d) __atomic_fetch_sub(&(d)->pauserehash, 1, __ATOMIC_SEQ_CST)
#define dictPauseRehashing(d) (d)->pauserehash++
#define dictResumeRehashing(d) (d)->pauserehash--
/* If our unsigned long type can store a 64 bit number, use a 64 bit PRNG. */
#if ULONG_MAX >= 0xffffffffffffffff
@@ -226,9 +199,9 @@ typedef void (dictScanBucketFunction)(void *privdata, dictEntry **bucketref);
/* API */
dict *dictCreate(dictType *type, void *privDataPtr);
int dictExpand(dict *d, unsigned long size, bool fShrink = false);
int dictTryExpand(dict *d, unsigned long size, bool fShrink);
int dictAdd(dict *d, void *key, void *val, dictEntry **existing = nullptr);
int dictExpand(dict *d, unsigned long size);
int dictTryExpand(dict *d, unsigned long size);
int dictAdd(dict *d, void *key, void *val);
dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing);
dictEntry *dictAddOrFind(dict *d, void *key);
int dictReplace(dict *d, void *key, void *val);
@@ -237,7 +210,6 @@ dictEntry *dictUnlink(dict *ht, const void *key);
void dictFreeUnlinkedEntry(dict *d, dictEntry *he);
void dictRelease(dict *d);
dictEntry * dictFind(dict *d, const void *key);
dictEntry * dictFindWithPrev(dict *d, const void *key, uint64_t h, dictEntry ***dePrevPtr, dictht **ht, bool fShallowCompare = false);
void *dictFetchValue(dict *d, const void *key);
int dictResize(dict *d);
dictIterator *dictGetIterator(dict *d);
@@ -260,14 +232,6 @@ uint8_t *dictGetHashFunctionSeed(void);
unsigned long dictScan(dict *d, unsigned long v, dictScanFunction *fn, dictScanBucketFunction *bucketfn, void *privdata);
uint64_t dictGetHash(dict *d, const void *key);
dictEntry **dictFindEntryRefByPtrAndHash(dict *d, const void *oldptr, uint64_t hash);
void dictForceRehash(dict *d);
int dictMerge(dict *dst, dict *src);
/* Async API */
dictAsyncRehashCtl *dictRehashAsyncStart(dict *d, int buckets);
bool dictRehashSomeAsync(dictAsyncRehashCtl *ctl, size_t hashes);
void dictCompleteRehashAsync(dictAsyncRehashCtl *ctl, bool fFree);
void dictRehashAsync(dictAsyncRehashCtl *ctl);
/* Hash table types */
extern dictType dictTypeHeapStringCopyKey;
+3 -3
View File
@@ -112,15 +112,15 @@ int endianconvTest(int argc, char *argv[], int accurate) {
UNUSED(argv);
UNUSED(accurate);
snprintf(buf,sizeof(buf),"ciaoroma");
sprintf(buf,"ciaoroma");
memrev16(buf);
printf("%s\n", buf);
snprintf(buf,sizeof(buf),"ciaoroma");
sprintf(buf,"ciaoroma");
memrev32(buf);
printf("%s\n", buf);
snprintf(buf,sizeof(buf),"ciaoroma");
sprintf(buf,"ciaoroma");
memrev64(buf);
printf("%s\n", buf);
+115 -340
View File
@@ -34,7 +34,6 @@
#include "bio.h"
#include "atomicvar.h"
#include <mutex>
#include <map>
#include <math.h>
/* ----------------------------------------------------------------------------
@@ -100,36 +99,6 @@ unsigned long long estimateObjectIdleTime(robj_roptr o) {
}
}
unsigned long long getIdle(robj *obj, const expireEntry *e) {
unsigned long long idle;
/* Calculate the idle time according to the policy. This is called
* idle just because the code initially handled LRU, but is in fact
* just a score where an higher score means better candidate. */
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LRU) {
idle = (obj != nullptr) ? estimateObjectIdleTime(obj) : 0;
} else if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU) {
/* When we use an LRU policy, we sort the keys by idle time
* so that we expire keys starting from greater idle time.
* However when the policy is an LFU one, we have a frequency
* estimation, and we want to evict keys with lower frequency
* first. So inside the pool we put objects using the inverted
* frequency subtracting the actual frequency to the maximum
* frequency of 255. */
idle = 255-LFUDecrAndReturn(obj);
} else if (g_pserver->maxmemory_policy == MAXMEMORY_VOLATILE_TTL) {
/* In this case the sooner the expire the better. */
if (e != nullptr)
idle = ULLONG_MAX - e->when();
else
idle = 0;
} else if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) {
idle = ULLONG_MAX;
} else {
serverPanic("Unknown eviction policy in storage eviction");
}
return idle;
}
/* LRU approximation algorithm
*
* Redis uses an approximation of the LRU algorithm that runs in constant
@@ -167,7 +136,28 @@ void evictionPoolAlloc(void) {
void processEvictionCandidate(int dbid, sds key, robj *o, const expireEntry *e, struct evictionPoolEntry *pool)
{
unsigned long long idle = getIdle(o,e);
unsigned long long idle;
/* Calculate the idle time according to the policy. This is called
* idle just because the code initially handled LRU, but is in fact
* just a score where an higher score means better candidate. */
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LRU) {
idle = (o != nullptr) ? estimateObjectIdleTime(o) : 0;
} else if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU) {
/* When we use an LRU policy, we sort the keys by idle time
* so that we expire keys starting from greater idle time.
* However when the policy is an LFU one, we have a frequency
* estimation, and we want to evict keys with lower frequency
* first. So inside the pool we put objects using the inverted
* frequency subtracting the actual frequency to the maximum
* frequency of 255. */
idle = 255-LFUDecrAndReturn(o);
} else if (g_pserver->maxmemory_policy == MAXMEMORY_VOLATILE_TTL) {
/* In this case the sooner the expire the better. */
idle = ULLONG_MAX - e->when();
} else {
serverPanic("Unknown eviction policy in evictionPoolPopulate()");
}
/* Insert the element inside the pool.
* First, find the first empty bucket or the first populated
@@ -231,23 +221,37 @@ void processEvictionCandidate(int dbid, sds key, robj *o, const expireEntry *e,
* idle time are on the left, and keys with the higher idle time on the
* right. */
int evictionPoolPopulate(int dbid, redisDb *db, bool fVolatile, struct evictionPoolEntry *pool)
struct visitFunctor
{
int returnCount = 0;
dictEntry **samples = (dictEntry**)alloca(g_pserver->maxmemory_samples * sizeof(dictEntry*));
int count = dictGetSomeKeys(db->dictUnsafeKeyOnly(),samples,g_pserver->maxmemory_samples);
for (int j = 0; j < count; j++) {
robj *o = (robj*)dictGetVal(samples[j]);
// If the object is in second tier storage we don't need to evict it (since it already is)
if (o != nullptr)
{
if (!fVolatile || o->FExpires()) {
processEvictionCandidate(dbid, (sds)dictGetKey(samples[j]), o, &o->expire, pool);
++returnCount;
}
int dbid;
dict *dbdict;
struct evictionPoolEntry *pool;
int count;
bool operator()(const expireEntry &e)
{
dictEntry *de = dictFind(dbdict, e.key());
processEvictionCandidate(dbid, (sds)dictGetKey(de), (robj*)dictGetVal(de), &e, pool);
++count;
return count < g_pserver->maxmemory_samples;
}
};
void evictionPoolPopulate(int dbid, dict *dbdict, expireset *setexpire, struct evictionPoolEntry *pool)
{
if (setexpire != nullptr)
{
visitFunctor visitor { dbid, dbdict, pool, 0 };
setexpire->random_visit(visitor);
}
else
{
dictEntry **samples = (dictEntry**)alloca(g_pserver->maxmemory_samples * sizeof(dictEntry*));
int count = dictGetSomeKeys(dbdict,samples,g_pserver->maxmemory_samples);
for (int j = 0; j < count; j++) {
robj *o = (robj*)dictGetVal(samples[j]);
processEvictionCandidate(dbid, (sds)dictGetKey(samples[j]), o, nullptr, pool);
}
}
return returnCount;
}
/* ----------------------------------------------------------------------------
@@ -326,7 +330,7 @@ uint8_t LFULogIncr(uint8_t counter) {
* This function is used in order to scan the dataset for the best object
* to fit: as we check for the candidate, we incrementally decrement the
* counter of the scanned objects if needed. */
unsigned long LFUDecrAndReturn(robj_roptr o) {
unsigned long LFUDecrAndReturn(robj *o) {
unsigned long ldt = o->lru >> 8;
unsigned long counter = o->lru & 255;
unsigned long num_periods = g_pserver->lfu_decay_time ? LFUTimeElapsed(ldt) / g_pserver->lfu_decay_time : 0;
@@ -335,8 +339,6 @@ unsigned long LFUDecrAndReturn(robj_roptr o) {
return counter;
}
unsigned long getClientReplicationBacklogSharedUsage(client *c);
/* We don't want to count AOF buffers and slaves output buffers as
* used memory: the eviction should use mostly data size. This function
* returns the sum of AOF and slaves buffer. */
@@ -353,15 +355,9 @@ size_t freeMemoryGetNotCountedMemory(void) {
while((ln = listNext(&li))) {
client *replica = (client*)listNodeValue(ln);
std::unique_lock<fastlock>(replica->lock);
/* we don't wish to multiple count the replication backlog shared usage */
overhead += (getClientOutputBufferMemoryUsage(replica) - getClientReplicationBacklogSharedUsage(replica));
overhead += getClientOutputBufferMemoryUsage(replica);
}
}
/* also don't count the replication backlog memory
* that's where the replication clients get their memory from */
overhead += g_pserver->repl_backlog_size - g_pserver->repl_backlog_config_size;
if (g_pserver->aof_state != AOF_OFF) {
overhead += sdsalloc(g_pserver->aof_buf)+aofRewriteBufferSize();
}
@@ -391,39 +387,17 @@ size_t freeMemoryGetNotCountedMemory(void) {
* memory currently used. May be > 1 if we are over the memory
* limit.
* (Populated both for C_ERR and C_OK)
*
* 'reason' the reason why the memory limit was exceeded
* EVICT_REASON_USER: reported user memory exceeded maxmemory
* EVICT_REASON_SYS: available system memory under configurable threshold
* (Populated when C_ERR is returned)
*/
int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *level, EvictReason *reason, bool fQuickCycle, bool fPreSnapshot) {
int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *level) {
size_t mem_reported, mem_used, mem_tofree;
/* Check if we are over the memory usage limit. If we are not, no need
* to subtract the slaves output buffers. We can just return ASAP. */
mem_reported = zmalloc_used_memory();
if (total) *total = mem_reported;
size_t maxmemory = g_pserver->maxmemory;
if (fPreSnapshot)
maxmemory = static_cast<size_t>(maxmemory*0.9); // derate memory by 10% since we won't be able to free during snapshot
if (g_pserver->FRdbSaveInProgress() && !cserver.fForkBgSave)
maxmemory = static_cast<size_t>(maxmemory*1.2);
/* If available system memory is below a certain threshold, force eviction */
long long sys_available_mem_buffer = 0;
if (g_pserver->force_eviction_percent && g_pserver->cron_malloc_stats.sys_total) {
float available_mem_ratio = (float)(100 - g_pserver->force_eviction_percent)/100;
size_t min_available_mem = static_cast<size_t>(g_pserver->cron_malloc_stats.sys_total * available_mem_ratio);
sys_available_mem_buffer = static_cast<long>(g_pserver->cron_malloc_stats.sys_available - min_available_mem);
if (sys_available_mem_buffer < 0) {
long long mem_threshold = mem_reported + sys_available_mem_buffer;
maxmemory = ((long long)maxmemory < mem_threshold) ? maxmemory : static_cast<size_t>(mem_threshold);
}
}
/* We may return ASAP if there is no need to compute the level. */
int return_ok_asap = !maxmemory || mem_reported <= maxmemory;
int return_ok_asap = !g_pserver->maxmemory || mem_reported <= g_pserver->maxmemory;
if (return_ok_asap && !level) return C_OK;
/* Remove the size of slaves output buffers and AOF buffer from the
@@ -432,106 +406,29 @@ int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *lev
size_t overhead = freeMemoryGetNotCountedMemory();
mem_used = (mem_used > overhead) ? mem_used-overhead : 0;
/* If system available memory is too low, we want to force evictions no matter
* what so we also offset the overhead from maxmemory. */
if (sys_available_mem_buffer < 0) {
maxmemory = (maxmemory > overhead) ? maxmemory-overhead : 0;
}
/* Compute the ratio of memory usage. */
if (level) {
if (!maxmemory) {
if (!g_pserver->maxmemory) {
*level = 0;
} else {
*level = (float)mem_used / (float)maxmemory;
*level = (float)mem_used / (float)g_pserver->maxmemory;
}
}
if (return_ok_asap) return C_OK;
/* Check if we are still over the memory limit. */
if (mem_used <= maxmemory) return C_OK;
if (mem_used <= g_pserver->maxmemory) return C_OK;
/* Compute how much memory we need to free. */
mem_tofree = mem_used - maxmemory;
if (g_pserver->m_pstorageFactory && !fQuickCycle)
{
mem_tofree += static_cast<size_t>(maxmemory * 0.05); // if we have a storage provider be much more aggressive
}
mem_tofree = mem_used - g_pserver->maxmemory;
if (logical) *logical = mem_used;
if (tofree) *tofree = mem_tofree;
if (reason) *reason = sys_available_mem_buffer < 0 ? EvictReason::System : EvictReason::User;
return C_ERR;
}
class FreeMemoryLazyFree : public ICollectable
{
ssize_t m_cb = 0;
std::vector<std::pair<dict*, std::vector<dictEntry*>>> vecdictvecde;
public:
static std::atomic<int> s_clazyFreesInProgress;
FreeMemoryLazyFree() {
s_clazyFreesInProgress++;
}
FreeMemoryLazyFree(const FreeMemoryLazyFree&) = delete;
FreeMemoryLazyFree(FreeMemoryLazyFree&&) = default;
~FreeMemoryLazyFree() {
aeAcquireLock();
for (auto &pair : vecdictvecde) {
for (auto de : pair.second) {
dictFreeUnlinkedEntry(pair.first, de);
}
dictRelease(pair.first);
}
aeReleaseLock();
--s_clazyFreesInProgress;
}
ssize_t addEntry(dict *d, dictEntry *de) {
ssize_t cbFreedNow = 0;
ssize_t cb = sizeof(dictEntry);
cb += sdsAllocSize((sds)dictGetKey(de));
robj *o = (robj*)dictGetVal(de);
switch (o->type) {
case OBJ_STRING:
cb += getStringObjectSdsUsedMemory(o)+sizeof(robj);
break;
default:
// If we don't know about it we can't accurately track the memory so free now
cbFreedNow = zmalloc_used_memory();
decrRefCount(o);
cbFreedNow -= zmalloc_used_memory();
de->v.val = nullptr;
}
auto itr = std::lower_bound(vecdictvecde.begin(), vecdictvecde.end(), d,
[](const std::pair<dict*, std::vector<dictEntry*>> &a, dict *d) -> bool {
return a.first < d;
}
);
if (itr == vecdictvecde.end() || itr->first != d) {
itr = vecdictvecde.insert(itr, std::make_pair(d, std::vector<dictEntry*>()));
__atomic_fetch_add(&d->refcount, 1, __ATOMIC_ACQ_REL);
}
serverAssert(itr->first == d);
itr->second.push_back(de);
m_cb += cb;
return cb + cbFreedNow;
}
size_t memory_queued() { return m_cb; }
};
std::atomic<int> FreeMemoryLazyFree::s_clazyFreesInProgress {0};
/* Return 1 if used memory is more than maxmemory after allocating more memory,
* return 0 if not. Redis may reject user's requests or evict some keys if used
* memory exceeds maxmemory, especially, when we allocate huge memory at once. */
@@ -557,9 +454,8 @@ static int evictionTimeProc(
UNUSED(eventLoop);
UNUSED(id);
UNUSED(clientData);
serverAssert(GlobalLocksAcquired());
if (performEvictions((bool)clientData) == EVICT_RUNNING) return 0; /* keep evicting */
if (performEvictions() == EVICT_RUNNING) return 0; /* keep evicting */
/* For EVICT_OK - things are good, no need to keep evicting.
* For EVICT_FAIL - there is nothing left to evict. */
@@ -574,14 +470,11 @@ static int evictionTimeProc(
static int isSafeToPerformEvictions(void) {
/* - There must be no script in timeout condition.
* - Nor we are loading data right now. */
if (g_pserver->shutdown_asap || g_pserver->lua_timedout || g_pserver->loading) return 0;
if (g_pserver->lua_timedout || g_pserver->loading) return 0;
/* By default replicas should ignore maxmemory
* and just be masters exact copies. */
if (g_pserver->m_pstorageFactory == nullptr && listLength(g_pserver->masters) && g_pserver->repl_slave_ignore_maxmemory && !g_pserver->fActiveReplica) return 0;
/* If we have a lazy free obj pending, our amounts will be off, wait for it to go away */
if (FreeMemoryLazyFree::s_clazyFreesInProgress > 0) return 0;
if (listLength(g_pserver->masters) && g_pserver->repl_slave_ignore_maxmemory && !g_pserver->fActiveReplica) return 0;
/* When clients are paused the dataset should be static not just from the
* POV of clients not being able to write, but also from the POV of
@@ -609,37 +502,6 @@ static unsigned long evictionTimeLimitUs() {
return ULONG_MAX; /* No limit to eviction time */
}
void evict(redisDb *db, robj *keyobj) {
mstime_t eviction_latency;
propagateExpire(db,keyobj,g_pserver->lazyfree_lazy_eviction);
/* We compute the amount of memory freed by db*Delete() alone.
* It is possible that actually the memory needed to propagate
* the DEL in AOF and replication link is greater than the one
* we are freeing removing the key, but we can't account for
* that otherwise we would never exit the loop.
*
* AOF and Output buffer memory will be freed eventually so
* we only care about memory used by the key space. */
latencyStartMonitor(eviction_latency);
if (g_pserver->lazyfree_lazy_eviction)
dbAsyncDelete(db,keyobj);
else
dbSyncDelete(db,keyobj);
latencyEndMonitor(eviction_latency);
latencyAddSampleIfNeeded("eviction-del",eviction_latency);
signalModifiedKey(NULL,db,keyobj);
notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted",
keyobj, db->id);
decrRefCount(keyobj);
}
static void updateSysAvailableMemory() {
if (g_pserver->force_eviction_percent) {
g_pserver->cron_malloc_stats.sys_available = getMemAvailable();
}
}
/* Check that memory usage is within the current "maxmemory" limit. If over
* "maxmemory", attempt to free memory by evicting data (if it's safe to do so).
*
@@ -664,24 +526,19 @@ static void updateSysAvailableMemory() {
* EVICT_RUNNING - memory is over the limit, but eviction is still processing
* EVICT_FAIL - memory is over the limit, and there's nothing to evict
* */
int performEvictions(bool fPreSnapshot) {
int performEvictions(void) {
if (!isSafeToPerformEvictions()) return EVICT_OK;
serverAssert(GlobalLocksAcquired());
int keys_freed = 0;
size_t mem_reported, mem_tofree;
long long mem_freed; /* May be negative */
mstime_t latency;
mstime_t latency, eviction_latency;
long long delta;
int slaves = listLength(g_pserver->slaves);
const bool fEvictToStorage = !cserver.delete_on_evict && g_pserver->db[0]->FStorageProvider();
int result = EVICT_FAIL;
int ckeysFailed = 0;
EvictReason evictReason;
std::unique_ptr<FreeMemoryLazyFree> splazy = std::make_unique<FreeMemoryLazyFree>();
if (getMaxmemoryState(&mem_reported,NULL,&mem_tofree,NULL,&evictReason,false,fPreSnapshot) == C_OK)
if (getMaxmemoryState(&mem_reported,NULL,&mem_tofree,NULL) == C_OK)
return EVICT_OK;
if (g_pserver->maxmemory_policy == MAXMEMORY_NO_EVICTION)
@@ -696,54 +553,13 @@ int performEvictions(bool fPreSnapshot) {
monotime evictionTimer;
elapsedStart(&evictionTimer);
if (g_pserver->maxstorage && g_pserver->m_pstorageFactory != nullptr) {
while (g_pserver->m_pstorageFactory->totalDiskspaceUsed() >= g_pserver->maxstorage && elapsedUs(evictionTimer) < eviction_time_limit_us) {
redisDb *db;
std::vector<std::string> evictionPool;
robj *bestkey = nullptr;
redisDb *bestdb = nullptr;
unsigned long long bestidle = 0;
for (int i = 0; i < cserver.dbnum; i++) {
db = g_pserver->db[i];
evictionPool = db->getStorageCache()->getEvictionCandidates(g_pserver->maxmemory_samples);
for (std::string key : evictionPool) {
robj *keyobj = createStringObject(key.c_str(), key.size());
robj *obj = db->find(szFromObj(keyobj));
if (obj != nullptr) {
expireEntry *e = db->getExpire(keyobj);
unsigned long long idle = getIdle(obj, e);
if (bestkey == nullptr || bestidle < idle) {
if (bestkey != nullptr)
decrRefCount(bestkey);
incrRefCount(keyobj);
bestkey = keyobj;
bestidle = idle;
bestdb = db;
}
}
decrRefCount(keyobj);
}
}
if (bestkey) {
evict(bestdb, bestkey);
} else {
break; //could not find a key to evict so stop now
}
}
}
if (g_pserver->maxstorage && g_pserver->m_pstorageFactory != nullptr && g_pserver->m_pstorageFactory->totalDiskspaceUsed() >= g_pserver->maxstorage)
goto cant_free_storage;
while (mem_freed < (long long)mem_tofree) {
int j, k, i;
static unsigned int next_db = 0;
sds bestkey = NULL;
int bestdbid;
redisDb *db;
bool fFallback = false;
if (g_pserver->maxmemory_policy & (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
g_pserver->maxmemory_policy == MAXMEMORY_VOLATILE_TTL)
{
@@ -756,33 +572,33 @@ int performEvictions(bool fPreSnapshot) {
* so to start populate the eviction pool sampling keys from
* every DB. */
for (i = 0; i < cserver.dbnum; i++) {
db = g_pserver->db[i];
db = g_pserver->db+i;
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS)
{
if ((keys = db->size()) != 0) {
total_keys += evictionPoolPopulate(i, db, false, pool);
if ((keys = dictSize(db->dict)) != 0) {
evictionPoolPopulate(i, db->dict, nullptr, pool);
total_keys += keys;
}
}
else
{
keys = db->expireSize();
keys = db->setexpire->size();
if (keys != 0)
total_keys += evictionPoolPopulate(i, db, true, pool);
evictionPoolPopulate(i, db->dict, db->setexpire, pool);
total_keys += keys;
}
}
if (!total_keys) break; /* No keys to evict. */
/* Go backward from best to worst element to evict. */
for (k = EVPOOL_SIZE-1; k >= 0; k--) {
if (pool[k].key == NULL) {
continue;
}
if (pool[k].key == NULL) continue;
bestdbid = pool[k].dbid;
sds key = nullptr;
auto itr = g_pserver->db[pool[k].dbid]->find(pool[k].key);
if (itr != nullptr && (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS || itr.val()->FExpires()))
key = itr.key();
dictEntry *de = dictFind(g_pserver->db[pool[k].dbid].dict,pool[k].key);
if (de != nullptr && (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS || ((robj*)dictGetVal(de))->FExpires()))
key = (sds)dictGetKey(de);
/* Remove the entry from the pool. */
if (pool[k].key != pool[k].cached)
@@ -800,35 +616,32 @@ int performEvictions(bool fPreSnapshot) {
}
}
}
if (bestkey == nullptr && fEvictToStorage)
fFallback = true;
}
/* volatile-random and allkeys-random policy */
if (g_pserver->maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM ||
g_pserver->maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM
|| fFallback)
else if (g_pserver->maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM ||
g_pserver->maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM)
{
/* When evicting a random key, we try to evict a key for
* each DB, so we use the static 'next_db' variable to
* incrementally visit all DBs. */
for (i = 0; i < cserver.dbnum; i++) {
j = (++next_db) % cserver.dbnum;
db = g_pserver->db[j];
if (g_pserver->maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM || fFallback)
db = g_pserver->db+j;
if (g_pserver->maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM)
{
if (db->size() != 0) {
auto itr = db->random_cache_threadsafe(true /*fPrimaryOnly*/); // primary only because we can't evict a snapshot key
bestkey = itr.key();
if (dictSize(db->dict) != 0) {
dictEntry *de = dictGetRandomKey(db->dict);
bestkey = (sds)dictGetKey(de);
bestdbid = j;
break;
}
}
else
{
if (db->expireSize())
if (!db->setexpire->empty())
{
db->random_expire(&bestkey);
bestkey = (sds)db->setexpire->random_value().key();
bestdbid = j;
break;
}
@@ -838,33 +651,34 @@ int performEvictions(bool fPreSnapshot) {
/* Finally remove the selected key. */
if (bestkey) {
db = g_pserver->db[bestdbid];
if (fEvictToStorage)
{
// This key is in the storage so we only need to free the object
dictEntry *deT;
if (db->removeCachedValue(bestkey, &deT)) {
mem_freed += splazy->addEntry(db->dictUnsafeKeyOnly(), deT);
ckeysFailed = 0;
g_pserver->stat_evictedkeys++;
}
else {
delta = 0;
ckeysFailed++;
if (ckeysFailed > 1024)
goto cant_free;
}
}
db = g_pserver->db+bestdbid;
robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
propagateExpire(db,keyobj,g_pserver->lazyfree_lazy_eviction);
/* We compute the amount of memory freed by db*Delete() alone.
* It is possible that actually the memory needed to propagate
* the DEL in AOF and replication link is greater than the one
* we are freeing removing the key, but we can't account for
* that otherwise we would never exit the loop.
*
* Same for CSC invalidation messages generated by signalModifiedKey.
*
* AOF and Output buffer memory will be freed eventually so
* we only care about memory used by the key space. */
delta = (long long) zmalloc_used_memory();
latencyStartMonitor(eviction_latency);
if (g_pserver->lazyfree_lazy_eviction)
dbAsyncDelete(db,keyobj);
else
{
robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
delta = (long long) zmalloc_used_memory();
evict(db, keyobj);
delta -= (long long) zmalloc_used_memory();
mem_freed += delta;
g_pserver->stat_evictedkeys++;
}
dbSyncDelete(db,keyobj);
latencyEndMonitor(eviction_latency);
latencyAddSampleIfNeeded("eviction-del",eviction_latency);
delta -= (long long) zmalloc_used_memory();
mem_freed += delta;
g_pserver->stat_evictedkeys++;
signalModifiedKey(NULL,db,keyobj);
notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted",
keyobj, db->id);
decrRefCount(keyobj);
keys_freed++;
if (keys_freed % 16 == 0) {
@@ -882,9 +696,6 @@ int performEvictions(bool fPreSnapshot) {
* across the dbAsyncDelete() call, while the thread can
* release the memory all the time. */
if (g_pserver->lazyfree_lazy_eviction) {
if (evictReason == EvictReason::System) {
updateSysAvailableMemory();
}
if (getMaxmemoryState(NULL,NULL,NULL,NULL) == C_OK) {
break;
}
@@ -893,12 +704,12 @@ int performEvictions(bool fPreSnapshot) {
/* After some time, exit the loop early - even if memory limit
* hasn't been reached. If we suddenly need to free a lot of
* memory, don't want to spend too much time here. */
if (g_pserver->m_pstorageFactory == nullptr && elapsedUs(evictionTimer) > eviction_time_limit_us) {
if (elapsedUs(evictionTimer) > eviction_time_limit_us) {
// We still need to free memory - start eviction timer proc
if (!isEvictionProcRunning && serverTL->el != nullptr) {
if (!isEvictionProcRunning) {
isEvictionProcRunning = 1;
aeCreateTimeEvent(serverTL->el, 0,
evictionTimeProc, (void*)fPreSnapshot, NULL);
evictionTimeProc, NULL, NULL);
}
break;
}
@@ -910,42 +721,7 @@ int performEvictions(bool fPreSnapshot) {
/* at this point, the memory is OK, or we have reached the time limit */
result = (isEvictionProcRunning) ? EVICT_RUNNING : EVICT_OK;
if (splazy != nullptr && splazy->memory_queued() > 0 && !serverTL->gcEpoch.isReset()) {
g_pserver->garbageCollector.enqueue(serverTL->gcEpoch, std::move(splazy));
}
cant_free:
if (mem_freed > 0 && evictReason == EvictReason::System) {
updateSysAvailableMemory();
}
if (g_pserver->m_pstorageFactory)
{
if (mem_reported < g_pserver->maxmemory*1.2) {
return EVICT_OK; // Allow us to temporarily go over without OOMing
}
}
if (!cserver.delete_on_evict && result == EVICT_FAIL)
{
for (int idb = 0; idb < cserver.dbnum; ++idb)
{
redisDb *db = g_pserver->db[idb];
if (db->FStorageProvider())
{
if (db->size() != 0 && db->size(true /*fcachedOnly*/) == 0 && db->keycacheIsEnabled()) {
serverLog(LL_WARNING, "Key cache exceeds maxmemory, freeing - performance may be affected increase maxmemory if possible");
db->disableKeyCache();
} else if (db->size(true /*fCachedOnly*/)) {
serverLog(LL_WARNING, "Failed to evict keys, falling back to flushing entire cache. Consider increasing maxmemory-samples.");
db->removeAllCachedValues();
if (((mem_reported - zmalloc_used_memory()) + mem_freed) >= mem_tofree)
result = EVICT_OK;
}
}
}
}
if (result == EVICT_FAIL) {
/* At this point, we have run out of evictable items. It's possible
* that some items are being freed in the lazyfree thread. Perform a
@@ -960,7 +736,6 @@ cant_free:
latencyEndMonitor(latency);
latencyAddSampleIfNeeded("eviction-cycle",latency);
cant_free_storage:
return result;
}
+86 -205
View File
@@ -72,20 +72,22 @@ void activeExpireCycleExpireFullKey(redisDb *db, const char *key) {
*----------------------------------------------------------------------------*/
int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long long now, size_t &tried) {
int activeExpireCycleExpire(redisDb *db, expireEntry &e, long long now, size_t &tried) {
if (!e.FFat())
{
activeExpireCycleExpireFullKey(db, key);
activeExpireCycleExpireFullKey(db, e.key());
++tried;
return 1;
}
expireEntryFat *pfat = e.pfatentry();
robj *val = db->find(key);
dictEntry *de = dictFind(db->dict, e.key());
robj *val = (robj*)dictGetVal(de);
int deleted = 0;
redisObjectStack objKey;
initStaticStringObject(objKey, (char*)key);
initStaticStringObject(objKey, (char*)e.key());
bool fTtlChanged = false;
while (!pfat->FEmpty())
{
@@ -96,7 +98,7 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
// Is it the full key expiration?
if (pfat->nextExpireEntry().spsubkey == nullptr)
{
activeExpireCycleExpireFullKey(db, key);
activeExpireCycleExpireFullKey(db, e.key());
return ++deleted;
}
@@ -106,7 +108,7 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
if (setTypeRemove(val,pfat->nextExpireEntry().spsubkey.get())) {
deleted++;
if (setTypeSize(val) == 0) {
activeExpireCycleExpireFullKey(db, key);
activeExpireCycleExpireFullKey(db, e.key());
return deleted;
}
}
@@ -116,7 +118,7 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
if (hashTypeDelete(val,(sds)pfat->nextExpireEntry().spsubkey.get())) {
deleted++;
if (hashTypeLength(val) == 0) {
activeExpireCycleExpireFullKey(db, key);
activeExpireCycleExpireFullKey(db, e.key());
return deleted;
}
}
@@ -126,7 +128,7 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
if (zsetDel(val,(sds)pfat->nextExpireEntry().spsubkey.get())) {
deleted++;
if (zsetLength(val) == 0) {
activeExpireCycleExpireFullKey(db, key);
activeExpireCycleExpireFullKey(db, e.key());
return deleted;
}
}
@@ -134,15 +136,15 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
case OBJ_CRON:
{
sds keyCopy = sdsdup(key);
sds keyCopy = sdsdup(e.key());
incrRefCount(val);
aePostFunction(g_pserver->rgthreadvar[IDX_EVENT_LOOP_MAIN].el, [keyCopy, val]{
executeCronJobExpireHook(keyCopy, val);
sdsfree(keyCopy);
decrRefCount(val);
}, true /*fLock*/, true /*fForceQueue*/);
break;
}
return deleted;
case OBJ_LIST:
default:
@@ -154,14 +156,19 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
propagateSubkeyExpire(db, val->type, &objKey, &objSubkey);
pfat->popfrontExpireEntry();
fTtlChanged = true;
if ((tried % ACTIVE_EXPIRE_CYCLE_SUBKEY_LOOKUPS_PER_LOOP) == 0) {
break;
}
}
if (pfat->FEmpty())
if (!pfat->FEmpty() && fTtlChanged)
{
removeExpire(db, &objKey);
// We need to resort the expire entry since it may no longer be in the correct position
auto itr = db->setexpire->find(e.key());
expireEntry eT = std::move(e);
db->setexpire->erase(itr);
db->setexpire->insert(eT);
}
if (deleted)
@@ -175,6 +182,10 @@ int activeExpireCycleExpire(redisDb *db, const char *key, expireEntry &e, long l
}
}
if (pfat->FEmpty())
{
removeExpire(db, &objKey);
}
return deleted;
}
@@ -205,7 +216,7 @@ void expireMemberCore(client *c, robj *key, robj *subkey, long long basetime, lo
/* No key, return zero. */
robj *val = lookupKeyWriteOrReply(c, key, shared.czero);
if (val == nullptr) {
if (val == NULL) {
return;
}
@@ -308,26 +319,8 @@ void pexpireMemberAtCommand(client *c)
* If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is
* executed, where the time limit is a percentage of the REDIS_HZ period
* as specified by the ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC define. */
#define ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP 20 /* Keys for each DB loop. */
#define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds. */
#define ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC 25 /* Max % of CPU to use. */
#define ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE 10 /* % of stale keys after which
we do extra efforts. */
/*static*/ void redisDbPersistentData::activeExpireCycleCore(int type) {
/* Adjust the running parameters according to the configured expire
* effort. The default effort is 1, and the maximum configurable effort
* is 10. */
unsigned long
effort = g_pserver->active_expire_effort-1, /* Rescale from 0 to 9. */
config_keys_per_loop = ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP +
ACTIVE_EXPIRE_CYCLE_KEYS_PER_LOOP/4*effort,
config_cycle_fast_duration = ACTIVE_EXPIRE_CYCLE_FAST_DURATION +
ACTIVE_EXPIRE_CYCLE_FAST_DURATION/4*effort,
config_cycle_slow_time_perc = ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC +
2*effort,
config_cycle_acceptable_stale = ACTIVE_EXPIRE_CYCLE_ACCEPTABLE_STALE-
effort;
void activeExpireCycleCore(int type) {
/* This function has some global state in order to continue the work
* incrementally across calls. */
static unsigned int current_db = 0; /* Next DB to test. */
@@ -345,16 +338,10 @@ void pexpireMemberAtCommand(client *c)
if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
/* Don't start a fast cycle if the previous cycle did not exit
* for time limit, unless the percentage of estimated stale keys is
* too high. Also never repeat a fast cycle for the same period
* for time limit. Also don't repeat a fast cycle for the same period
* as the fast cycle total duration itself. */
if (!timelimit_exit &&
g_pserver->stat_expired_stale_perc < config_cycle_acceptable_stale)
return;
if (start < last_fast_cycle + (long long)config_cycle_fast_duration*2)
return;
if (!timelimit_exit) return;
if (start < last_fast_cycle + ACTIVE_EXPIRE_CYCLE_FAST_DURATION*2) return;
last_fast_cycle = start;
}
@@ -368,16 +355,16 @@ void pexpireMemberAtCommand(client *c)
if (dbs_per_call > cserver.dbnum || timelimit_exit)
dbs_per_call = cserver.dbnum;
/* We can use at max 'config_cycle_slow_time_perc' percentage of CPU
* time per iteration. Since this function gets called with a frequency of
* server.hz times per second, the following is the max amount of
/* We can use at max ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC percentage of CPU time
* per iteration. Since this function gets called with a frequency of
* g_pserver->hz times per second, the following is the max amount of
* microseconds we can spend in this function. */
timelimit = config_cycle_slow_time_perc*1000000/g_pserver->hz/100;
timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/g_pserver->hz/100;
timelimit_exit = 0;
if (timelimit <= 0) timelimit = 1;
if (type == ACTIVE_EXPIRE_CYCLE_FAST)
timelimit = config_cycle_fast_duration; /* in microseconds. */
timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* in microseconds. */
/* Accumulate some global stats as we expire keys, to have some idea
* about the number of keys that are already logically expired, but still
@@ -386,166 +373,54 @@ void pexpireMemberAtCommand(client *c)
long total_expired = 0;
for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) {
/* Expired and checked in a single loop. */
unsigned long expired, sampled;
redisDb *db = g_pserver->db[(current_db % cserver.dbnum)];
redisDb *db = g_pserver->db+(current_db % cserver.dbnum);
/* Increment the DB now so we are sure if we run out of time
* in the current DB we'll restart from the next. This allows to
* distribute the time evenly across DBs. */
current_db++;
if (g_pserver->m_pstorageFactory == nullptr) {
/* Continue to expire if at the end of the cycle there are still
* a big percentage of keys to expire, compared to the number of keys
* we scanned. The percentage, stored in config_cycle_acceptable_stale
* is not fixed, but depends on the Redis configured "expire effort". */
do {
unsigned long num, slots;
long long now, ttl_sum;
int ttl_samples;
iteration++;
long long now;
iteration++;
now = mstime();
/* If there is nothing to expire try next DB ASAP. */
if (db->expireSize() == 0) {
db->avg_ttl = 0;
break;
}
num = dictSize(db->m_pdict);
slots = dictSlots(db->m_pdict);
now = mstime();
/* When there are less than 1% filled slots, sampling the key
* space is expensive, so stop here waiting for better times...
* The dictionary will be resized asap. */
if (slots > DICT_HT_INITIAL_SIZE &&
(num*100/slots < 1)) break;
/* The main collection cycle. Sample random keys among keys
* with an expire set, checking for expired ones. */
expired = 0;
sampled = 0;
ttl_sum = 0;
ttl_samples = 0;
if (num > config_keys_per_loop)
num = config_keys_per_loop;
/* Here we access the low level representation of the hash table
* for speed concerns: this makes this code coupled with dict.c,
* but it hardly changed in ten years.
*
* Note that certain places of the hash table may be empty,
* so we want also a stop condition about the number of
* buckets that we scanned. However scanning for free buckets
* is very fast: we are in the cache line scanning a sequential
* array of NULL pointers, so we can scan a lot more buckets
* than keys in the same time. */
long max_buckets = num*20;
long checked_buckets = 0;
while (sampled < num && checked_buckets < max_buckets) {
for (int table = 0; table < 2; table++) {
if (table == 1 && !dictIsRehashing(db->m_pdict)) break;
unsigned long idx = db->expires_cursor;
idx &= db->m_pdict->ht[table].sizemask;
dictEntry *de = db->m_pdict->ht[table].table[idx];
long long ttl;
/* Scan the current bucket of the current table. */
checked_buckets++;
while(de) {
/* Get the next entry now since this entry may get
* deleted. */
dictEntry *e = de;
robj *o = (robj*)dictGetVal(de);
de = de->next;
if (!o->FExpires())
continue;
expireEntry *exp = &o->expire;
serverAssert(exp->when() > 0);
ttl = exp->when()-now;
size_t tried = 0;
if (exp->when() <= now) {
if (activeExpireCycleExpire(db,(const char*)dictGetKey(e),*exp,now,tried)) expired++;
serverAssert(ttl <= 0);
} else {
serverAssert(ttl > 0);
}
if (ttl > 0) {
/* We want the average TTL of keys yet
* not expired. */
ttl_sum += ttl;
ttl_samples++;
}
sampled++;
}
}
db->expires_cursor++;
}
total_expired += expired;
total_sampled += sampled;
/* Update the average TTL stats for this database. */
if (ttl_samples) {
long long avg_ttl = ttl_sum/ttl_samples;
/* Do a simple running average with a few samples.
* We just use the current estimate with a weight of 2%
* and the previous estimate with a weight of 98%. */
if (db->avg_ttl == 0) db->avg_ttl = avg_ttl;
db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50);
}
/* If there is nothing to expire try next DB ASAP. */
if (db->setexpire->empty())
{
db->avg_ttl = 0;
db->last_expire_set = now;
continue;
}
size_t expired = 0;
size_t tried = 0;
long long check = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; // assume a check is roughly 1us. It isn't but good enough
db->expireitr = db->setexpire->enumerate(db->expireitr, now, [&](expireEntry &e) __attribute__((always_inline)) {
if (e.when() < now)
{
expired += activeExpireCycleExpire(db, e, now, tried);
}
if ((tried % ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP) == 0)
{
/* We can't block forever here even if there are many keys to
* expire. So after a given amount of milliseconds return to the
* caller waiting for the other active expire cycle. */
if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */
elapsed = ustime()-start;
if (elapsed > timelimit) {
timelimit_exit = 1;
g_pserver->stat_expired_time_cap_reached_count++;
break;
}
}
/* We don't repeat the cycle for the current database if there are
* an acceptable amount of stale keys (logically expired but yet
* not reclaimed). */
} while (sampled == 0 ||
(expired*100/sampled) > config_cycle_acceptable_stale);
} else {
long prev_expired;
long long now = mstime();
size_t tried = 0;
std::vector<std::string> keys;
do {
prev_expired = total_expired;
keys = db->getStorageCache()->getExpirationCandidates(ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP);
for (std::string key : keys) {
robj* keyobj = createStringObject(key.c_str(), key.size());
db->find(szFromObj(keyobj));
expireEntry *e = db->getExpire(keyobj);
if (e != nullptr && e->when() < now)
total_expired += activeExpireCycleExpire(db, szFromObj(keyobj), *e, now, tried);
decrRefCount(keyobj);
}
total_sampled += keys.size();
elapsed = ustime()-start;
} while (keys.size() > 0 && (elapsed < timelimit) && (total_expired - prev_expired) > 0);
if (ustime()-start > timelimit) {
timelimit_exit = 1;
g_pserver->stat_expired_time_cap_reached_count++;
if (elapsed > timelimit) {
timelimit_exit = 1;
g_pserver->stat_expired_time_cap_reached_count++;
return false;
}
check = ACTIVE_EXPIRE_CYCLE_FAST_DURATION;
}
}
return true;
}, &check);
total_expired += expired;
}
elapsed = ustime()-start;
g_pserver->stat_expire_cycle_time_used += elapsed;
latencyAddSampleIfNeeded("expire-cycle",elapsed/1000);
/* Update our estimate of keys existing but yet to be expired.
@@ -561,7 +436,7 @@ void pexpireMemberAtCommand(client *c)
void activeExpireCycle(int type)
{
runAndPropogateToReplicas(redisDbPersistentData::activeExpireCycleCore, type);
runAndPropogateToReplicas(activeExpireCycleCore, type);
}
/*-----------------------------------------------------------------------------
@@ -620,15 +495,20 @@ void expireSlaveKeys(void) {
int dbid = 0;
while(dbids && dbid < cserver.dbnum) {
if ((dbids & 1) != 0) {
redisDb *db = g_pserver->db[dbid];
auto itrDB = db->find(keyname);
redisDb *db = g_pserver->db+dbid;
// the expire is hashed based on the key pointer, so we need the point in the main db
dictEntry *deMain = dictFind(db->dict, keyname);
auto itr = db->setexpire->end();
if (deMain != nullptr)
itr = db->setexpire->find((sds)dictGetKey(deMain));
int expired = 0;
if (itrDB != db->end() && itrDB->FExpires())
if (itr != db->setexpire->end())
{
if (itrDB->expire.when() < start) {
if (itr->when() < start) {
size_t tried = 0;
expired = activeExpireCycleExpire(g_pserver->db[dbid],itrDB.key(),itrDB->expire,start,tried);
expired = activeExpireCycleExpire(g_pserver->db+dbid,*itr,start,tried);
}
}
@@ -636,7 +516,7 @@ void expireSlaveKeys(void) {
* corresponding bit in the new bitmap we set as value.
* At the end of the loop if the bitmap is zero, it means we
* no longer need to keep track of this key. */
if (itrDB != db->end() && itrDB->FExpires() && !expired) {
if (itr != db->setexpire->end() && !expired) {
noexpire++;
new_dbids |= (uint64_t)1 << dbid;
}
@@ -814,7 +694,7 @@ void ttlGenericCommand(client *c, int output_ms) {
/* The key exists. Return -1 if it has no expire, or the actual
* TTL value otherwise. */
expireEntry *pexpire = c->db->getExpire(c->argv[1]);
expireEntry *pexpire = getExpire(c->db,c->argv[1]);
if (c->argc == 2) {
// primary expire
@@ -872,7 +752,7 @@ void persistCommand(client *c) {
addReply(c,shared.czero);
}
} else if (c->argc == 3) {
if (c->db->removeSubkeyExpire(c->argv[1], c->argv[2])) {
if (removeSubkeyExpire(c->db, c->argv[1], c->argv[2])) {
signalModifiedKey(c,c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_GENERIC,"persist",c->argv[1],c->db->id);
addReply(c,shared.cone);
@@ -896,18 +776,19 @@ void touchCommand(client *c) {
addReplyLongLong(c,touched);
}
expireEntryFat::expireEntryFat(const expireEntryFat &src)
{
m_keyPrimary = sdsdupshared(src.m_keyPrimary);
m_vecexpireEntries = src.m_vecexpireEntries;
m_dictIndex = nullptr;
}
expireEntryFat::~expireEntryFat()
{
if (m_dictIndex != nullptr)
dictRelease(m_dictIndex);
}
expireEntryFat::expireEntryFat(const expireEntryFat &e)
: m_vecexpireEntries(e.m_vecexpireEntries)
{
// Note: dictExpires is not copied
}
void expireEntryFat::createIndex()
{
serverAssert(m_dictIndex == nullptr);
+87 -127
View File
@@ -22,11 +22,9 @@ public:
{}
subexpireEntry(const subexpireEntry &other)
: spsubkey(nullptr, sdsfree)
: spsubkey((const char*)sdsdupshared(other.spsubkey.get()), sdsfree)
{
when = other.when;
if (other.spsubkey != nullptr)
spsubkey = std::unique_ptr<const char, void(*)(const char*)>((const char*)sdsdupshared(other.spsubkey.get()), sdsfree);
}
subexpireEntry(subexpireEntry &&) = default;
@@ -43,52 +41,56 @@ public:
};
private:
sds m_keyPrimary;
std::vector<subexpireEntry> m_vecexpireEntries; // Note a NULL for the sds portion means the expire is for the primary key
dict *m_dictIndex = nullptr;
long long m_whenPrimary = LLONG_MAX;
void createIndex();
public:
expireEntryFat() = default;
expireEntryFat(sds keyPrimary)
: m_keyPrimary(keyPrimary)
{}
expireEntryFat(const expireEntryFat &);
~expireEntryFat();
long long when() const noexcept { return m_vecexpireEntries.front().when; }
const char *key() const noexcept { return m_keyPrimary; }
bool operator<(long long when) const noexcept { return this->when() < when; }
void expireSubKey(const char *szSubkey, long long when);
bool FGetPrimaryExpire(long long *pwhen) const {
if (m_whenPrimary != LLONG_MAX) {
*pwhen = m_whenPrimary;
return true;
}
return false;
}
bool FEmpty() const noexcept { return m_vecexpireEntries.empty(); }
const subexpireEntry &nextExpireEntry() const noexcept { return m_vecexpireEntries.front(); }
void popfrontExpireEntry();
const subexpireEntry &operator[](size_t idx) const { return m_vecexpireEntries[idx]; }
const subexpireEntry &operator[](size_t idx) { return m_vecexpireEntries[idx]; }
size_t size() const noexcept { return m_vecexpireEntries.size(); }
};
class expireEntry {
struct {
uint64_t m_whenAndPtrUnion : 63,
fFat : 1;
} s;
static_assert(sizeof(expireEntryFat*) <= sizeof(int64_t), "The pointer must fit in the union");
union
{
sds m_key;
expireEntryFat *m_pfatentry;
} u;
long long m_when; // bit wise and with FFatMask means this is a fat entry and we should use the pointer
/* Mask to check if an entry is Fat, most significant bit of m_when being set means it is Fat otherwise it is not */
long long FFatMask() const noexcept {
return (1LL) << (sizeof(long long)*CHAR_BIT - 1);
}
expireEntry() = default;
public:
class iter
{
friend class expireEntry;
const expireEntry *m_pentry = nullptr;
expireEntry *m_pentry = nullptr;
size_t m_idx = 0;
public:
iter(const expireEntry *pentry, size_t idx)
iter(expireEntry *pentry, size_t idx)
: m_pentry(pentry), m_idx(idx)
{}
@@ -115,107 +117,77 @@ public:
const iter &operator*() const { return *this; }
};
expireEntry()
{
s.fFat = 0;
s.m_whenAndPtrUnion = 0;
}
expireEntry(const char *subkey, long long when)
expireEntry(sds key, const char *subkey, long long when)
{
if (subkey != nullptr)
{
auto pfatentry = new (MALLOC_LOCAL) expireEntryFat();
pfatentry->expireSubKey(subkey, when);
s.m_whenAndPtrUnion = reinterpret_cast<long long>(pfatentry);
s.fFat = true;
m_when = FFatMask() | INVALID_EXPIRE;
u.m_pfatentry = new (MALLOC_LOCAL) expireEntryFat(key);
u.m_pfatentry->expireSubKey(subkey, when);
}
else
{
s.m_whenAndPtrUnion = when;
s.fFat = false;
u.m_key = key;
m_when = when;
}
}
expireEntry(expireEntryFat *pfatentry)
{
assert(pfatentry != nullptr);
s.m_whenAndPtrUnion = reinterpret_cast<long long>(pfatentry);
s.fFat = true;
}
expireEntry(const expireEntry &e) {
if (e.FFat()) {
s.m_whenAndPtrUnion = reinterpret_cast<long long>(new expireEntryFat(*e.pfatentry()));
s.fFat = true;
} else {
s = e.s;
u.m_pfatentry = pfatentry;
m_when = FFatMask() | INVALID_EXPIRE;
for (auto itr : *this)
{
if (itr.subkey() == nullptr)
{
m_when = FFatMask() | itr.when();
break;
}
}
}
expireEntry(expireEntry &&e)
{
s = e.s;
}
expireEntry &operator=(expireEntry &&e)
{
if (FFat())
delete pfatentry();
s = e.s;
e.s.m_whenAndPtrUnion = 0;
e.s.fFat = false;
return *this;
}
expireEntry &operator=(expireEntry &e) {
if (FFat())
delete pfatentry();
if (e.FFat()) {
s.m_whenAndPtrUnion = reinterpret_cast<long long>(new expireEntryFat(*e.pfatentry()));
s.fFat = true;
} else {
s = e.s;
}
return *this;
u.m_key = e.u.m_key;
m_when = e.m_when;
e.u.m_key = (char*)key(); // we do this so it can still be found in the set
e.m_when = 0;
}
// Duplicate the expire, note this is intended to be passed directly to setExpire
expireEntry duplicate() const {
expireEntry dst;
dst.m_when = m_when;
if (FFat()) {
auto pfatentry = new expireEntryFat(*expireEntry::pfatentry());
dst.s.m_whenAndPtrUnion = reinterpret_cast<long long>(pfatentry);
dst.s.fFat = true;
dst.u.m_pfatentry = new expireEntryFat(*u.m_pfatentry);
} else {
dst.s.m_whenAndPtrUnion = s.m_whenAndPtrUnion;
dst.s.fFat = false;
dst.u.m_key = u.m_key;
}
return dst;
}
void reset() {
if (FFat())
delete pfatentry();
s.fFat = false;
s.m_whenAndPtrUnion = 0;
}
~expireEntry()
{
if (FFat())
delete pfatentry();
delete u.m_pfatentry;
}
inline bool FFat() const noexcept { return s.fFat; }
expireEntryFat *pfatentry() {
assert(FFat());
return reinterpret_cast<expireEntryFat*>(s.m_whenAndPtrUnion);
}
const expireEntryFat *pfatentry() const {
return const_cast<expireEntry*>(this)->pfatentry();
void setKeyUnsafe(sds key)
{
if (FFat())
u.m_pfatentry->m_keyPrimary = key;
else
u.m_key = key;
}
inline bool FFat() const noexcept { return m_when & FFatMask(); }
expireEntryFat *pfatentry() { assert(FFat()); return u.m_pfatentry; }
bool operator==(const char *key) const noexcept
{
return this->key() == key;
}
bool operator<(const expireEntry &e) const noexcept
{
@@ -226,11 +198,17 @@ public:
return this->when() < when;
}
const char *key() const noexcept
{
if (FFat())
return u.m_pfatentry->key();
return u.m_key;
}
long long when() const noexcept
{
if (FFat())
return pfatentry()->when();
return s.m_whenAndPtrUnion;
return u.m_pfatentry->when();
return FGetPrimaryExpire();
}
void update(const char *subkey, long long when)
@@ -239,27 +217,30 @@ public:
{
if (subkey == nullptr)
{
s.m_whenAndPtrUnion = when;
m_when = when;
return;
}
else
{
// we have to upgrade to a fat entry
auto pfatentry = new (MALLOC_LOCAL) expireEntryFat();
pfatentry->expireSubKey(nullptr, s.m_whenAndPtrUnion);
s.m_whenAndPtrUnion = reinterpret_cast<long long>(pfatentry);
s.fFat = true;
long long whenT = m_when;
sds keyPrimary = u.m_key;
m_when |= FFatMask();
u.m_pfatentry = new (MALLOC_LOCAL) expireEntryFat(keyPrimary);
u.m_pfatentry->expireSubKey(nullptr, whenT);
// at this point we're fat so fall through
}
}
pfatentry()->expireSubKey(subkey, when);
if (subkey == nullptr)
m_when = when | FFatMask();
u.m_pfatentry->expireSubKey(subkey, when);
}
iter begin() const { return iter(this, 0); }
iter end() const
iter begin() { return iter(this, 0); }
iter end()
{
if (FFat())
return iter(this, pfatentry()->size());
return iter(this, u.m_pfatentry->size());
return iter(this, 1);
}
@@ -271,39 +252,18 @@ public:
pfatentry()->m_vecexpireEntries.begin() + itr.m_idx);
}
size_t size() const {
if (FFat())
return pfatentry()->size();
return 1;
long long FGetPrimaryExpire() const noexcept
{
return m_when & (~FFatMask());
}
bool FGetPrimaryExpire(long long *pwhen) const noexcept
{
if (FFat()) {
return pfatentry()->FGetPrimaryExpire(pwhen);
} else {
*pwhen = s.m_whenAndPtrUnion;
return true;
}
}
void *release_as_void() {
uint64_t whenT = s.m_whenAndPtrUnion;
whenT |= static_cast<uint64_t>(s.fFat) << 63;
s.m_whenAndPtrUnion = 0;
s.fFat = 0;
return reinterpret_cast<void*>(whenT);
}
static expireEntry *from_void(void **src) {
uintptr_t llV = reinterpret_cast<uintptr_t>(src);
return reinterpret_cast<expireEntry*>(llV);
}
static const expireEntry *from_void(void *const*src) {
uintptr_t llV = reinterpret_cast<uintptr_t>(src);
return reinterpret_cast<expireEntry*>(llV);
*pwhen = FGetPrimaryExpire();
return *pwhen != INVALID_EXPIRE;
}
explicit operator const char*() const noexcept { return key(); }
explicit operator long long() const noexcept { return when(); }
};
static_assert(sizeof(expireEntry) == sizeof(long long), "This must fit in a long long so it can be put in a dictEntry");
typedef semiorderedset<expireEntry, const char *, true /*expireEntry can be memmoved*/> expireset;
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff. Show more