Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb45a32e0c | ||
|
|
4c8603815c | ||
|
|
3ae75c2d2b | ||
|
|
9371c005aa | ||
|
|
16bd6b3f5d | ||
|
|
3dd78a6101 | ||
|
|
41b678814b | ||
|
|
d0ccb074d5 | ||
|
|
cb0fc7cca2 | ||
|
|
5e40ea6ee7 | ||
|
|
427c5999f1 | ||
|
|
f1d2b29450 | ||
|
|
cb93752aff | ||
|
|
549cad378d | ||
|
|
631f863dd8 | ||
|
|
4396682c07 | ||
|
|
ca4ee4e3e4 | ||
|
|
2da09e0732 | ||
|
|
4986dc6da9 | ||
|
|
1a70af2ae1 | ||
|
|
5a8cb77d0d | ||
|
|
600fc241cf | ||
|
|
fa797408d9 | ||
|
|
f5210a8fb0 | ||
|
|
8f1295c00f | ||
|
|
18a3768e07 | ||
|
|
95e3dbc104 | ||
|
|
40355eac3e | ||
|
|
3a3b59a054 | ||
|
|
12e17cfd6e | ||
|
|
203e341bf4 | ||
|
|
6e6cd84ad7 | ||
|
|
252725d50f | ||
|
|
c15633ea9e | ||
|
|
27c9ae667e | ||
|
|
16f96efbe7 | ||
|
|
5787e7adc7 | ||
|
|
4631119179 | ||
|
|
cedea7e400 | ||
|
|
64aa4b80e6 | ||
|
|
551a3cb1aa | ||
|
|
0942188b0a | ||
|
|
070c481871 | ||
|
|
6df4d29422 | ||
|
|
6e1e5bd08b | ||
|
|
ba365298ed | ||
|
|
e1c9620951 | ||
|
|
e776474f68 | ||
|
|
55324aa56a | ||
|
|
18d42a5c35 | ||
|
|
ac595ebe37 | ||
|
|
46a78c69e7 | ||
|
|
33e0b3e1c0 | ||
|
|
4e9bfcf84b | ||
|
|
75c6b4c64a | ||
|
|
8536854266 | ||
|
|
6016dd0f8b | ||
|
|
47ef9e5cbd | ||
|
|
4858fd893c | ||
|
|
cbe5c04a0f | ||
|
|
08b6a04055 | ||
|
|
afe66288fe | ||
|
|
2794cfced4 | ||
|
|
d6b45a56e7 | ||
|
|
a55d980436 | ||
|
|
6037d1f326 | ||
|
|
0b43b51a2e | ||
|
|
184abac694 | ||
|
|
0ba5b2c3d6 | ||
|
|
0b3d74ea67 | ||
|
|
ea3bd614b8 | ||
|
|
d45edc493d | ||
|
|
271df3dad4 | ||
|
|
5a193872f8 | ||
|
|
b5512d77a1 | ||
|
|
42bda8eaba | ||
|
|
7e5d3f4f16 | ||
|
|
5f3920e491 | ||
|
|
3880d2616c | ||
|
|
156e596f9c | ||
|
|
fc58516cca | ||
|
|
a4efcd35af | ||
|
|
27fe1658a2 | ||
|
|
47feb2719c | ||
|
|
c21af6b351 | ||
|
|
821c12c482 | ||
|
|
4602f8c391 | ||
|
|
27a927fe00 | ||
|
|
3cdc6e8d84 | ||
|
|
89b52da387 | ||
|
|
50ad880ad5 | ||
|
|
15bed4bbcc | ||
|
|
10986ae3a8 | ||
|
|
2baa76b2ee | ||
|
|
ee460301fd | ||
|
|
8ebe2fce3d | ||
|
|
8198a697fd | ||
|
|
35acae360a | ||
|
|
8aaa8b0b11 | ||
|
|
bb090b6d20 | ||
|
|
a9c4e3970f | ||
|
|
d5ecc2347a | ||
|
|
58971a430d | ||
|
|
1512274f4c | ||
|
|
e310d33c12 | ||
|
|
ad32ba0343 | ||
|
|
4e30a5b4e5 | ||
|
|
c8516f3dc4 | ||
|
|
aae0fdc114 | ||
|
|
a19d0f67b9 | ||
|
|
971f69fe1f | ||
|
|
7468c691ad | ||
|
|
620c2ec141 | ||
|
|
3081b6f98b | ||
|
|
8630339e43 | ||
|
|
528d10091f | ||
|
|
149c3cf3dd | ||
|
|
f12c3cf9dd | ||
|
|
1f08a0efb3 | ||
|
|
6cf85d1d01 | ||
|
|
b5101a460d | ||
|
|
a5784ef09e | ||
|
|
722446510f | ||
|
|
6eb52e200c | ||
|
|
4c4b7023dd | ||
|
|
2d07883cab | ||
|
|
e8ae07aabf | ||
|
|
677e95e2f5 | ||
|
|
122ec25bf0 | ||
|
|
d013ad9eba | ||
|
|
d918ca6fa5 | ||
|
|
852819180f | ||
|
|
218111eb72 | ||
|
|
a714004738 | ||
|
|
6b29f2d83d | ||
|
|
f099def733 | ||
|
|
3e43aed1ac | ||
|
|
46edb55de9 | ||
|
|
506764b3f8 | ||
|
|
db16a861a1 | ||
|
|
c29f3bcf2e | ||
|
|
45d64f229e | ||
|
|
a28d7918d7 | ||
|
|
1531cfb7ee | ||
|
|
16a89f21dc | ||
|
|
79e5160e37 | ||
|
|
510e966dc0 | ||
|
|
8238d3207e | ||
|
|
e37bc4ad40 | ||
|
|
0f78b8b917 | ||
|
|
19061fe04f | ||
|
|
9c901eb65f | ||
|
|
ae33ff3a6e | ||
|
|
59dbd625c1 | ||
|
|
8eb4e355b9 | ||
|
|
8b76b01bfe | ||
|
|
ec57b4b024 | ||
|
|
dd51fc5a4a | ||
|
|
38cd5fd9f6 | ||
|
|
f54d95e803 | ||
|
|
46d6caa47c | ||
|
|
e2adea2188 | ||
|
|
0cabe0cfa7 | ||
|
|
dd5f437871 | ||
|
|
de035c9481 | ||
|
|
d3ed53f11b | ||
|
|
97b65ce19c | ||
|
|
55d0ef40b0 | ||
|
|
bf963253ec | ||
|
|
a6c56416fc | ||
|
|
cd3c482d5e | ||
|
|
c5cbb77fc7 | ||
|
|
d7f21f02b3 | ||
|
|
87dc8ce9b3 | ||
|
|
2e22aa1a9c | ||
|
|
8c56dbf971 | ||
|
|
a78169e9e0 | ||
|
|
39a60c8120 | ||
|
|
c57d8760bd | ||
|
|
3eed2a8780 | ||
|
|
23b0268a7f | ||
|
|
3d0de946bb | ||
|
|
fd0ee469ab | ||
|
|
7fababd44e | ||
|
|
fd9407dfc8 | ||
|
|
074d24df1e | ||
|
|
caf74e507e | ||
|
|
1a1ba48390 | ||
|
|
9724ca4e22 | ||
|
|
4f4676a142 | ||
|
|
866b8ead91 | ||
|
|
aa274960ff | ||
|
|
54d6eb851b | ||
|
|
86d7276f24 | ||
|
|
0918651438 | ||
|
|
e633254ccf | ||
|
|
34f6d94701 | ||
|
|
1e9b8d853d | ||
|
|
2903c56bda | ||
|
|
6b490e33c4 | ||
|
|
891f4a38f6 | ||
|
|
433f763814 | ||
|
|
402b0d0bd1 | ||
|
|
19c3d5b743 | ||
|
|
1212f22858 | ||
|
|
c64aec9ce7 | ||
|
|
272d9297b6 | ||
|
|
f5bfc71899 | ||
|
|
42e1ded55f | ||
|
|
6c410af5a8 | ||
|
|
57ae676181 | ||
|
|
7896ca6e52 | ||
|
|
c4a315dd5e | ||
|
|
bf26959b72 | ||
|
|
a1fb0be1d7 | ||
|
|
bea09a7fa6 | ||
|
|
fb4ee7f0c5 | ||
|
|
842dd85b26 | ||
|
|
f674e83215 | ||
|
|
48d591a010 | ||
|
|
d9d3d3065b | ||
|
|
340a723b87 | ||
|
|
a72ab70fee | ||
|
|
3d053dbb6d | ||
|
|
5baeb14cf3 | ||
|
|
1c0c436757 | ||
|
|
90d720e7a5 | ||
|
|
6ab6a97fe6 | ||
|
|
647a66ebba | ||
|
|
463ccf8664 | ||
|
|
8d7d2be24f | ||
|
|
63a0ffd36a | ||
|
|
a2245f8ff1 | ||
|
|
dd5b105c73 | ||
|
|
74591fb5bd | ||
|
|
9814b2a5f3 | ||
|
|
30091dc29f | ||
|
|
9bf7f302a7 | ||
|
|
ea35a81c42 | ||
|
|
6f4f36c0fb | ||
|
|
a2dbd9bd97 | ||
|
|
f468e653b5 | ||
|
|
b1c7e3393d | ||
|
|
1c0913dc4e | ||
|
|
9f3679880a | ||
|
|
ba809f26d4 | ||
|
|
0a6090bfd8 | ||
|
|
bcac165fab | ||
|
|
843de8b786 | ||
|
|
5ba908fa5f | ||
|
|
5c5197fe4f | ||
|
|
2d450d1315 | ||
|
|
162208f94d | ||
|
|
4e38ced488 | ||
|
|
bc36404c79 | ||
|
|
d3d96b041a | ||
|
|
fa97ef34ca | ||
|
|
37b2d046be | ||
|
|
fa2e407873 | ||
|
|
c61cf57db5 | ||
|
|
ef3690f2db | ||
|
|
14d01ec7bd | ||
|
|
5dc9f70386 | ||
|
|
88e593bf96 | ||
|
|
efde2e6be6 | ||
|
|
5a78a3bc46 | ||
|
|
b276d803d4 | ||
|
|
da51ac430b | ||
|
|
01eb0a3c7f | ||
|
|
dc2b3cf4f8 | ||
|
|
11f2c6b115 | ||
|
|
c4621a5ed2 | ||
|
|
1c953a4d5b | ||
|
|
c184b32d4c | ||
|
|
26d9d4ec2c | ||
|
|
c64ce7aa9c | ||
|
|
4a5057000a | ||
|
|
487601d85d | ||
|
|
acdc4fdfec | ||
|
|
7ef9c18b72 | ||
|
|
a69b4e79db | ||
|
|
3ccdcbc088 | ||
|
|
d044e33c20 | ||
|
|
9e67691ffb | ||
|
|
6de5d25062 | ||
|
|
d490752d58 | ||
|
|
740fc6c2b8 | ||
|
|
42202c868d | ||
|
|
c24e32041b | ||
|
|
f8a9708aa7 | ||
|
|
75648f99a5 | ||
|
|
8c133b605c | ||
|
|
b50acd7238 | ||
|
|
54db278695 | ||
|
|
011948bcef | ||
|
|
9f95d8b38f | ||
|
|
3d394a6fa2 | ||
|
|
68d2b648e0 | ||
|
|
283998404f | ||
|
|
a7b4d0fea6 | ||
|
|
59051dd59d | ||
|
|
cd836a37e7 | ||
|
|
4326d22380 | ||
|
|
161d3a35ff | ||
|
|
20a9d21dfb | ||
|
|
e902789aa7 | ||
|
|
3745bbd95b | ||
|
|
e63b2880b0 | ||
|
|
a9b70e1ef7 | ||
|
|
e300f753c5 | ||
|
|
efaeca5887 | ||
|
|
4d67305661 | ||
|
|
853bb6ca3e | ||
|
|
b16f23ae8e | ||
|
|
91e6368de0 | ||
|
|
4de88828d9 | ||
|
|
e4451b9628 | ||
|
|
770bb8ef5f | ||
|
|
87b958a210 | ||
|
|
314ac90ba9 | ||
|
|
9f33822083 | ||
|
|
10a4b35bc5 | ||
|
|
7b1dd0b60d | ||
|
|
7a650741f7 | ||
|
|
2ce5f1b944 | ||
|
|
063a14372d | ||
|
|
dd70e1b571 | ||
|
|
acba2fc9b4 | ||
|
|
ec0b6bd2c3 | ||
|
|
822a992f91 | ||
|
|
5e8caca036 | ||
|
|
fcac342955 | ||
|
|
122f42844a | ||
|
|
040e52c77f | ||
|
|
29b0a57695 | ||
|
|
6c0a5fde3d | ||
|
|
4ea3ed896b | ||
|
|
e2626f69ec | ||
|
|
bc269c85e1 | ||
|
|
4a0ee5c6ac | ||
|
|
99c2fe0bcf | ||
|
|
b2e03f8329 | ||
|
|
dd8b4be46b | ||
|
|
8620a434a0 | ||
|
|
a9a6a894e8 | ||
|
|
325fc1cb2e | ||
|
|
2a5aeef79f | ||
|
|
9095e4dc9b | ||
|
|
6711132083 | ||
|
|
c3e187190b | ||
|
|
ad223e2042 | ||
|
|
31110f1caf | ||
|
|
270a111433 | ||
|
|
0f0f787a37 | ||
|
|
4cc43a96f6 |
No files matched your search
+6
-3
@@ -4,23 +4,26 @@ matrix:
|
||||
include:
|
||||
- os: linux
|
||||
script: make
|
||||
env: COMPILER_NAME=gcc CXX=g++-5 CC=gcc-5
|
||||
env: COMPILER_NAME=g++-6 CXX=g++-6 CC=gcc-6
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- g++-5
|
||||
- g++-6
|
||||
- nasm
|
||||
- uuid-dev
|
||||
sources: &sources
|
||||
- llvm-toolchain-precise-3.8
|
||||
- ubuntu-toolchain-r-test
|
||||
- os: linux
|
||||
script: make MALLOC=libc
|
||||
env: COMPILER_NAME=clang CXX=clang++-3.8 CC=clang-3.8 CXXFLAGS="-stdlib=libc++" LDFLAGS="-stdlib=libc++"
|
||||
env: COMPILER_NAME=clang CXX=clang++-3.8 CC=clang-3.8 CXXFLAGS="-I/usr/include/libcxxabi/" LDFLAGS="-lc++"
|
||||
addons:
|
||||
apt:
|
||||
packages:
|
||||
- libc++abi-dev
|
||||
- clang-3.8
|
||||
- libc++-dev
|
||||
- libc++abi-dev
|
||||
- nasm
|
||||
- uuid-dev
|
||||
sources: *sources
|
||||
Vendored
+3
-1
@@ -51,6 +51,8 @@
|
||||
"tuple": "cpp",
|
||||
"type_traits": "cpp",
|
||||
"typeinfo": "cpp",
|
||||
"utility": "cpp"
|
||||
"utility": "cpp",
|
||||
"set": "cpp",
|
||||
"algorithm": "cpp"
|
||||
}
|
||||
}
|
||||
+15
-5
@@ -14,9 +14,7 @@ each source file that you contribute.
|
||||
|
||||
PLEASE DO NOT POST GENERAL QUESTIONS that are not about bugs or suspected
|
||||
bugs in the Github issues system. We'll be very happy to help you and provide
|
||||
all the support at the Reddit sub:
|
||||
|
||||
http://reddit.com/r/redis
|
||||
all the support in the mailing list.
|
||||
|
||||
There is also an active community of Redis users at Stack Overflow:
|
||||
|
||||
@@ -24,7 +22,12 @@ each source file that you contribute.
|
||||
|
||||
# How to provide a patch for a new feature
|
||||
|
||||
1. If it is a major feature or a semantical change, please post it as a new submission in r/redis on Reddit at http://reddit.com/r/redis. Try to be passionate about why the feature is needed, make users upvote your proposal to gain traction and so forth. Read feedbacks about the community. But in this first step **please don't write code yet**.
|
||||
1. If it is a major feature or a semantical change, please don't start coding
|
||||
straight away: if your feature is not a conceptual fit you'll lose a lot of
|
||||
time writing the code without any reason. Start by posting in the mailing list
|
||||
and creating an issue at Github with the description of, exactly, what you want
|
||||
to accomplish and why. Use cases are important for features to be accepted.
|
||||
Here you'll see if there is consensus about your idea.
|
||||
|
||||
2. If in step 1 you get an acknowledgment from the project leaders, use the
|
||||
following procedure to submit a patch:
|
||||
@@ -35,6 +38,13 @@ each source file that you contribute.
|
||||
d. Initiate a pull request on github ( https://help.github.com/articles/creating-a-pull-request/ )
|
||||
e. Done :)
|
||||
|
||||
For minor fixes just open a pull request on Github.
|
||||
3. Keep in mind that we are very overloaded, so issues and PRs sometimes wait
|
||||
for a *very* long time. However this is not lack of interest, as the project
|
||||
gets more and more users, we find ourselves in a constant need to prioritize
|
||||
certain issues/PRs over others. If you think your issue/PR is very important
|
||||
try to popularize it, have other users commenting and sharing their point of
|
||||
view and so forth. This helps.
|
||||
|
||||
4. For minor fixes just open a pull request on Github.
|
||||
|
||||
Thanks!
|
||||
+2
-2
@@ -4,7 +4,7 @@ FROM ubuntu:18.04
|
||||
|
||||
RUN apt-get update \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -qqy \
|
||||
build-essential nasm autotools-dev autoconf libjemalloc-dev tcl tcl-dev \
|
||||
build-essential nasm autotools-dev autoconf libcurl4-openssl-dev libjemalloc-dev tcl tcl-dev uuid-dev \
|
||||
&& apt-get clean
|
||||
|
||||
CMD make
|
||||
CMD make
|
||||
@@ -1,36 +1,48 @@
|
||||

|
||||
[](https://travis-ci.org/JohnSully/KeyDB) [](https://gitter.im/KeyDB/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://stackshare.io/eq-alpha-technology-inc/eq-alpha-technology-inc)
|
||||
|
||||
##### Need Help? Check out our extensive [documentation](https://docs.keydb.dev).
|
||||
|
||||
What is KeyDB?
|
||||
--------------
|
||||
|
||||
KeyDB is a high performance fork of Redis focusing on multithreading, memory efficiency, and high throughput. In addition to multithreading KeyDB also has features only available in Redis Enterprise such as FLASH storage support, and some not available at all such as direct backup to AWS S3.
|
||||
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.
|
||||
|
||||
On the same hardware KeyDB can perform twice as many queries per second as Redis, with 60% lower latency.
|
||||
KeyDB maintains full compatibility with the Redis protocol, modules, and scripts. This includes the atomicity gurantees 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.
|
||||
|
||||
KeyDB has full compatibility with the Redis protocol, modules, and scripts. This includes full support for transactions, and atomic execution of scripts. For more information see our architecture section below.
|
||||
On the same hardware KeyDB can perform twice as many queries per second as Redis, with 60% lower latency. Active-Replication simplifies hot-spare failover allowing you to easily distribute writes over replicas and use simple TCP based load balancing/failover. KeyDB's higher performance allows you to do more on less hardware which reduces operation costs and complexity.
|
||||
|
||||
<img src=https://cdn-images-1.medium.com/max/1400/1*s7mTb7Qb0kxc951mz8bdgA.png width=420 height=300/><img src=https://cdn-images-1.medium.com/max/1400/1*R00A5U4AFGohGOYHMfT6fA.png height=300/>
|
||||
|
||||
Why fork Redis?
|
||||
---------------
|
||||
|
||||
KeyDB has a different philosophy on how the codebase should evolve. We feel that ease of use, high performance, and a "batteries included" approach is the best way to create a good user experience. While we have great respect for the Redis maintainers it is our opinion that the Redis approach focuses too much on simplicity of the code base at the expense of complexity for the user. This results in the need for external components and workarounds to solve common problems - resulting in more complexity overall.
|
||||
|
||||
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.
|
||||
|
||||
Additional Resources
|
||||
--------------------
|
||||
|
||||
Try our docker container: https://hub.docker.com/r/eqalpha/keydb
|
||||
|
||||
Talk on Gitter: https://gitter.im/KeyDB
|
||||
|
||||
New: Active Replica Support
|
||||
---------------------------
|
||||
Visit our Website: https://keydb.dev
|
||||
|
||||
New! KeyDB now has support for Active Replicas. This feature greatly simplifies hot-spare failover and allows you to distribute writes over replicas instead of just a single master. For more information [see the wiki page](https://github.com/JohnSully/KeyDB/wiki/KeyDB-(Redis-Fork):-Active-Replica-Support).
|
||||
See options for channel partners and support contracts: https://keydb.dev/support.html
|
||||
|
||||
Why fork Redis?
|
||||
---------------
|
||||
Learn with KeyDB’s official documentation site: https://docs.keydb.dev
|
||||
|
||||
The Redis maintainers have continually reiterated that they do not plan to support multithreading. While we have great respect for the redis team, we feel the analysis justifying this decision is incorrect. In addition we wanted open source implementations of features currently only available in proprietary modules. We feel a fork is the best way to accelerate development in the areas of most interest to us.
|
||||
[Subscribe to the KeyDB mailing list](https://eqalpha.us20.list-manage.com/subscribe/post?u=978f486c2f95589b24591a9cc&id=4ab9220500)
|
||||
|
||||
Management GUI: We recommend [FastoNoSQL](https://fastonosql.com/) which has official KeyDB support.
|
||||
|
||||
We plan to track the Redis repo closely and hope our projects can learn from each other.
|
||||
|
||||
Benchmarking KeyDB
|
||||
------------------
|
||||
|
||||
<img src=https://cdn-images-1.medium.com/max/1400/1*s7mTb7Qb0kxc951mz8bdgA.png width=420 height=300/><img src=https://cdn-images-1.medium.com/max/1400/1*R00A5U4AFGohGOYHMfT6fA.png height=300/>
|
||||
|
||||
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)
|
||||
@@ -47,27 +59,38 @@ The number of threads used to serve requests. This should be related to the num
|
||||
|
||||
scratch-file-path /path
|
||||
|
||||
If you would like to use the FLASH backed 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.
|
||||
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
|
||||
|
||||
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
|
||||
--------------
|
||||
|
||||
KeyDB can be compiled and is tested for use on Linux. KeyDB currently relies on SO_REUSEADDR's load balancing behavior which is available only in Linux. When we support marshalling connections across threads we plan to support other operating systems such as FreeBSD.
|
||||
KeyDB can be compiled and is tested for use on Linux. KeyDB currently relies on SO_REUSEPORT's load balancing behavior which is available only in Linux. When we support marshalling connections across threads we plan to support other operating systems such as FreeBSD.
|
||||
|
||||
Install dependencies:
|
||||
|
||||
% 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
|
||||
|
||||
You can enable flash support with (Note: autoconf and autotools must be installed):
|
||||
You can enable flash support with:
|
||||
|
||||
% make MALLOC=memkind
|
||||
|
||||
***Note that the following dependencies may be needed:
|
||||
% sudo apt-get install autoconf autotools-dev libnuma-dev libtool
|
||||
|
||||
Fixing build problems with dependencies or cached build options
|
||||
---------
|
||||
|
||||
@@ -170,7 +193,7 @@ then in another terminal try the following:
|
||||
(integer) 2
|
||||
keydb>
|
||||
|
||||
You can find the list of all the available commands at http://redis.io/commands.
|
||||
You can find the list of all the available commands at https://docs.keydb.dev/docs/commands/
|
||||
|
||||
Installing KeyDB
|
||||
-----------------
|
||||
@@ -213,23 +236,18 @@ Future work:
|
||||
|
||||
Docker Build
|
||||
------------
|
||||
|
||||
Run the following commands for a full source download and 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:
|
||||
```
|
||||
git clone git@github.com:JohnSully/KeyDB.git
|
||||
docker run -it --rm `pwd`/KeyDB:/build -w /build devopsdood/keydb-builder make
|
||||
$ 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
|
||||
|
||||
Then you have fresh binaries built, you can also pass any other options to the make command above after the word make. E.g.
|
||||
|
||||
```docker run -it --rm `pwd`/KeyDB:/build -w /build devopsdood/keydb-builder make MAllOC=memkind```
|
||||
|
||||
The above commands will build you binaries in the src directory. Standard `make install` without Docker command will work after if you wish to install
|
||||
|
||||
If you'd prefer you can build the Dockerfile in the repo instead of pulling the above container for use:
|
||||
|
||||
`docker build -t KeyDB .`
|
||||
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
|
||||
-----------------
|
||||
|
||||
Vendored
+1
@@ -31,6 +31,7 @@
|
||||
|
||||
#include "fmacros.h"
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <stdlib.h>
|
||||
#ifndef _MSC_VER
|
||||
#include <unistd.h>
|
||||
|
||||
Vendored
+10
@@ -45,31 +45,41 @@ typedef char *sds;
|
||||
* However is here to document the layout of type 5 SDS strings. */
|
||||
struct __attribute__ ((__packed__)) sdshdr5 {
|
||||
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
|
||||
#ifndef __cplusplus
|
||||
char buf[];
|
||||
#endif
|
||||
};
|
||||
struct __attribute__ ((__packed__)) sdshdr8 {
|
||||
uint8_t len; /* used */
|
||||
uint8_t alloc; /* excluding the header and null terminator */
|
||||
unsigned char flags; /* 3 lsb of type, 5 unused bits */
|
||||
#ifndef __cplusplus
|
||||
char buf[];
|
||||
#endif
|
||||
};
|
||||
struct __attribute__ ((__packed__)) sdshdr16 {
|
||||
uint16_t len; /* used */
|
||||
uint16_t alloc; /* excluding the header and null terminator */
|
||||
unsigned char flags; /* 3 lsb of type, 5 unused bits */
|
||||
#ifndef __cplusplus
|
||||
char buf[];
|
||||
#endif
|
||||
};
|
||||
struct __attribute__ ((__packed__)) sdshdr32 {
|
||||
uint32_t len; /* used */
|
||||
uint32_t alloc; /* excluding the header and null terminator */
|
||||
unsigned char flags; /* 3 lsb of type, 5 unused bits */
|
||||
#ifndef __cplusplus
|
||||
char buf[];
|
||||
#endif
|
||||
};
|
||||
struct __attribute__ ((__packed__)) sdshdr64 {
|
||||
uint64_t len; /* used */
|
||||
uint64_t alloc; /* excluding the header and null terminator */
|
||||
unsigned char flags; /* 3 lsb of type, 5 unused bits */
|
||||
#ifndef __cplusplus
|
||||
char buf[];
|
||||
#endif
|
||||
};
|
||||
|
||||
#define SDS_TYPE_5 0
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
="repl-stream-db"
|
||||
="repl-id"
|
||||
="repl-offset"
|
||||
="lua"
|
||||
="redis-ver"
|
||||
="ctime"
|
||||
="used-mem"
|
||||
="aof-preamble"
|
||||
="redis-bits"
|
||||
="mvcc-tstamp"
|
||||
="keydb-subexpire-key"
|
||||
="keydb-subexpire-when"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
-7
@@ -942,13 +942,7 @@ aof-use-rdb-preamble yes
|
||||
lua-time-limit 5000
|
||||
|
||||
################################ REDIS CLUSTER ###############################
|
||||
#
|
||||
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
# WARNING EXPERIMENTAL: Redis Cluster is considered to be stable code, however
|
||||
# in order to mark it as "mature" we need to wait for a non trivial percentage
|
||||
# of users to deploy it in production.
|
||||
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
#
|
||||
|
||||
# Normal Redis instances can't be part of a Redis Cluster; only nodes that are
|
||||
# started as cluster nodes can. In order to start a Redis instance as a
|
||||
# cluster node enable the cluster support uncommenting the following:
|
||||
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
TCL_VERSIONS="8.5 8.6"
|
||||
TCLSH=""
|
||||
|
||||
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 Redis test"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
make -C tests/modules && \
|
||||
$TCLSH tests/test_helper.tcl --single unit/moduleapi/commandfilter "${@}"
|
||||
+22
-10
@@ -20,8 +20,8 @@ DEPENDENCY_TARGETS=hiredis linenoise lua
|
||||
NODEPS:=clean distclean
|
||||
|
||||
# Default settings
|
||||
STD=-std=c99 -pedantic -DREDIS_STATIC=''
|
||||
CXX_STD=-std=c++14 -pedantic -fno-rtti
|
||||
STD=-std=c11 -pedantic -DREDIS_STATIC=''
|
||||
CXX_STD=-std=c++14 -pedantic -fno-rtti -D__STDC_FORMAT_MACROS
|
||||
ifneq (,$(findstring clang,$(CC)))
|
||||
ifneq (,$(findstring FreeBSD,$(uname_S)))
|
||||
STD+=-Wno-c11-extensions
|
||||
@@ -45,6 +45,15 @@ endif
|
||||
endif
|
||||
|
||||
USEASM?=true
|
||||
|
||||
ifneq ($(SANITIZE),)
|
||||
CFLAGS+= -fsanitize=$(SANITIZE) -DSANITIZE
|
||||
CXXFLAGS+= -fsanitize=$(SANITIZE) -DSANITIZE
|
||||
LDFLAGS+= -fsanitize=$(SANITIZE)
|
||||
MALLOC=libc
|
||||
USEASM=false
|
||||
endif
|
||||
|
||||
# Do we use our assembly spinlock? X64 only
|
||||
ifeq ($(uname_S),Linux)
|
||||
ifeq ($(uname_M),x86_64)
|
||||
@@ -140,6 +149,7 @@ else
|
||||
# All the other OSes (notably Linux)
|
||||
FINAL_LDFLAGS+= -rdynamic
|
||||
FINAL_LIBS+=-ldl -pthread -lrt -luuid
|
||||
FINAL_CFLAGS += -DMOTD
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
@@ -178,7 +188,7 @@ endif
|
||||
|
||||
REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS)
|
||||
REDIS_CXX=$(QUIET_CC)$(CC) $(FINAL_CXXFLAGS)
|
||||
REDIS_NASM=$(QUIET_CC)nasm -felf64
|
||||
KEYDB_AS=$(QUIET_CC) as --64 -g
|
||||
REDIS_LD=$(QUIET_LINK)$(CXX) $(FINAL_LDFLAGS)
|
||||
REDIS_INSTALL=$(QUIET_INSTALL)$(INSTALL)
|
||||
|
||||
@@ -197,11 +207,11 @@ endif
|
||||
|
||||
REDIS_SERVER_NAME=keydb-server
|
||||
REDIS_SENTINEL_NAME=keydb-sentinel
|
||||
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 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 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 lolwut.o lolwut5.o acl.o storage.o rdb-s3.o fastlock.o gopher.o $(ASM_OBJ)
|
||||
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 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 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 $(ASM_OBJ)
|
||||
REDIS_CLI_NAME=keydb-cli
|
||||
REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o siphash.o crc16.o storage-lite.o fastlock.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 crc64.o siphash.o crc16.o storage-lite.o fastlock.o new.o $(ASM_OBJ)
|
||||
REDIS_BENCHMARK_NAME=keydb-benchmark
|
||||
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o dict.o zmalloc.o siphash.o redis-benchmark.o storage-lite.o fastlock.o $(ASM_OBJ)
|
||||
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o dict.o zmalloc.o siphash.o redis-benchmark.o storage-lite.o fastlock.o new.o $(ASM_OBJ)
|
||||
REDIS_CHECK_RDB_NAME=keydb-check-rdb
|
||||
REDIS_CHECK_AOF_NAME=keydb-check-aof
|
||||
|
||||
@@ -230,6 +240,7 @@ persist-settings: distclean
|
||||
echo REDIS_LDFLAGS=$(REDIS_LDFLAGS) >> .make-settings
|
||||
echo PREV_FINAL_CFLAGS=$(FINAL_CFLAGS) >> .make-settings
|
||||
echo PREV_FINAL_LDFLAGS=$(FINAL_LDFLAGS) >> .make-settings
|
||||
-(cd modules && $(MAKE))
|
||||
-(cd ../deps && $(MAKE) $(DEPENDENCY_TARGETS))
|
||||
|
||||
.PHONY: persist-settings
|
||||
@@ -263,13 +274,13 @@ $(REDIS_CHECK_AOF_NAME): $(REDIS_SERVER_NAME)
|
||||
|
||||
# keydb-cli
|
||||
$(REDIS_CLI_NAME): $(REDIS_CLI_OBJ)
|
||||
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS)
|
||||
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS) -lcurl
|
||||
|
||||
# keydb-benchmark
|
||||
$(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ)
|
||||
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS)
|
||||
|
||||
dict-benchmark: dict.c zmalloc.c sds.c siphash.c
|
||||
dict-benchmark: dict.cpp zmalloc.cpp sds.c siphash.c
|
||||
$(REDIS_CC) $(FINAL_CFLAGS) $^ -D DICT_BENCHMARK_MAIN -o $@ $(FINAL_LIBS)
|
||||
|
||||
# Because the jemalloc.h header is generated as a part of the jemalloc build,
|
||||
@@ -282,7 +293,7 @@ dict-benchmark: dict.c zmalloc.c sds.c siphash.c
|
||||
$(REDIS_CXX) -c $<
|
||||
|
||||
%.o: %.asm .make-prerequisites
|
||||
$(REDIS_NASM) $<
|
||||
$(KEYDB_AS) $< -o $@
|
||||
|
||||
clean:
|
||||
rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html Makefile.dep dict-benchmark
|
||||
@@ -291,6 +302,7 @@ clean:
|
||||
|
||||
distclean: clean
|
||||
-(cd ../deps && $(MAKE) distclean)
|
||||
-(cd modules && $(MAKE) clean)
|
||||
-(rm -f .make-*)
|
||||
|
||||
.PHONY: distclean
|
||||
@@ -310,7 +322,7 @@ lcov:
|
||||
@genhtml --legend -o lcov-html redis.info
|
||||
|
||||
test-sds: sds.c sds.h
|
||||
$(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN $(FINAL_LIBS) -o /tmp/sds_test
|
||||
$(REDIS_CC) sds.c zmalloc.cpp -DSDS_TEST_MAIN $(FINAL_LIBS) -o /tmp/sds_test
|
||||
/tmp/sds_test
|
||||
|
||||
.PHONY: lcov
|
||||
|
||||
+73
-71
@@ -157,17 +157,17 @@ uint64_t ACLGetCommandCategoryFlagByName(const char *name) {
|
||||
/* Method for passwords/pattern comparison used for the user->passwords list
|
||||
* so that we can search for items with listSearchKey(). */
|
||||
int ACLListMatchSds(void *a, void *b) {
|
||||
return sdscmp(a,b) == 0;
|
||||
return sdscmp((sds)a,(sds)b) == 0;
|
||||
}
|
||||
|
||||
/* Method to free list elements from ACL users password/ptterns lists. */
|
||||
void ACLListFreeSds(void *item) {
|
||||
sdsfree(item);
|
||||
void ACLListFreeSds(const void *item) {
|
||||
sdsfree((sds)item);
|
||||
}
|
||||
|
||||
/* Method to duplicate list elements from ACL users password/ptterns lists. */
|
||||
void *ACLListDupSds(void *item) {
|
||||
return sdsdup(item);
|
||||
return sdsdup((sds)item);
|
||||
}
|
||||
|
||||
/* Create a new user with the specified name, store it in the list
|
||||
@@ -177,7 +177,7 @@ void *ACLListDupSds(void *item) {
|
||||
* If the user with such name already exists NULL is returned. */
|
||||
user *ACLCreateUser(const char *name, size_t namelen) {
|
||||
if (raxFind(Users,(unsigned char*)name,namelen) != raxNotFound) return NULL;
|
||||
user *u = zmalloc(sizeof(*u), MALLOC_LOCAL);
|
||||
user *u = (user*)zmalloc(sizeof(*u), MALLOC_LOCAL);
|
||||
u->name = sdsnewlen(name,namelen);
|
||||
u->flags = USER_FLAG_DISABLED;
|
||||
u->allowed_subcommands = NULL;
|
||||
@@ -227,9 +227,9 @@ void ACLFreeUser(user *u) {
|
||||
void ACLFreeUserAndKillClients(user *u) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(server.clients,&li);
|
||||
listRewind(g_pserver->clients,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
client *c = listNodeValue(ln);
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
if (c->puser == u) {
|
||||
/* We'll free the conenction asynchronously, so
|
||||
* in theory to set a different user is not needed.
|
||||
@@ -295,7 +295,7 @@ int ACLGetCommandBitCoordinates(uint64_t id, uint64_t *word, uint64_t *bit) {
|
||||
* Note that this function does not check the ALLCOMMANDS flag of the user
|
||||
* but just the lowlevel bitmask.
|
||||
*
|
||||
* If the bit overflows the user internal represetation, zero is returned
|
||||
* If the bit overflows the user internal representation, zero is returned
|
||||
* in order to disallow the execution of the command in such edge case. */
|
||||
int ACLGetUserCommandBit(user *u, unsigned long id) {
|
||||
uint64_t word, bit;
|
||||
@@ -311,7 +311,7 @@ int ACLUserCanExecuteFutureCommands(user *u) {
|
||||
}
|
||||
|
||||
/* Set the specified command bit for the specified user to 'value' (0 or 1).
|
||||
* If the bit overflows the user internal represetation, no operation
|
||||
* If the bit overflows the user internal representation, no operation
|
||||
* is performed. As a side effect of calling this function with a value of
|
||||
* zero, the user flag ALLCOMMANDS is cleared since it is no longer possible
|
||||
* to skip the command bit explicit test. */
|
||||
@@ -334,10 +334,10 @@ void ACLSetUserCommandBit(user *u, unsigned long id, int value) {
|
||||
int ACLSetUserCommandBitsForCategory(user *u, const char *category, int value) {
|
||||
uint64_t cflag = ACLGetCommandCategoryFlagByName(category);
|
||||
if (!cflag) return C_ERR;
|
||||
dictIterator *di = dictGetIterator(server.orig_commands);
|
||||
dictIterator *di = dictGetIterator(g_pserver->orig_commands);
|
||||
dictEntry *de;
|
||||
while ((de = dictNext(di)) != NULL) {
|
||||
struct redisCommand *cmd = dictGetVal(de);
|
||||
struct redisCommand *cmd = (redisCommand*)dictGetVal(de);
|
||||
if (cmd->flags & CMD_MODULE) continue; /* Ignore modules commands. */
|
||||
if (cmd->flags & cflag) {
|
||||
ACLSetUserCommandBit(u,cmd->id,value);
|
||||
@@ -350,7 +350,7 @@ int ACLSetUserCommandBitsForCategory(user *u, const char *category, int value) {
|
||||
|
||||
/* Return the number of commands allowed (on) and denied (off) for the user 'u'
|
||||
* in the subset of commands flagged with the specified category name.
|
||||
* If the categoty name is not valid, C_ERR is returend, otherwise C_OK is
|
||||
* If the category name is not valid, C_ERR is returned, otherwise C_OK is
|
||||
* returned and on and off are populated by reference. */
|
||||
int ACLCountCategoryBitsForUser(user *u, unsigned long *on, unsigned long *off,
|
||||
const char *category)
|
||||
@@ -359,10 +359,10 @@ int ACLCountCategoryBitsForUser(user *u, unsigned long *on, unsigned long *off,
|
||||
if (!cflag) return C_ERR;
|
||||
|
||||
*on = *off = 0;
|
||||
dictIterator *di = dictGetIterator(server.orig_commands);
|
||||
dictIterator *di = dictGetIterator(g_pserver->orig_commands);
|
||||
dictEntry *de;
|
||||
while ((de = dictNext(di)) != NULL) {
|
||||
struct redisCommand *cmd = dictGetVal(de);
|
||||
struct redisCommand *cmd = (redisCommand*)dictGetVal(de);
|
||||
if (cmd->flags & cflag) {
|
||||
if (ACLGetUserCommandBit(u,cmd->id))
|
||||
(*on)++;
|
||||
@@ -428,10 +428,10 @@ sds ACLDescribeUserCommandRules(user *u) {
|
||||
}
|
||||
|
||||
/* Fix the final ACLs with single commands differences. */
|
||||
dictIterator *di = dictGetIterator(server.orig_commands);
|
||||
dictIterator *di = dictGetIterator(g_pserver->orig_commands);
|
||||
dictEntry *de;
|
||||
while ((de = dictNext(di)) != NULL) {
|
||||
struct redisCommand *cmd = dictGetVal(de);
|
||||
struct redisCommand *cmd = (redisCommand*)dictGetVal(de);
|
||||
int userbit = ACLGetUserCommandBit(u,cmd->id);
|
||||
int fakebit = ACLGetUserCommandBit(fakeuser,cmd->id);
|
||||
if (userbit != fakebit) {
|
||||
@@ -501,7 +501,7 @@ sds ACLDescribeUser(user *u) {
|
||||
listNode *ln;
|
||||
listRewind(u->passwords,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
sds thispass = listNodeValue(ln);
|
||||
sds thispass = (sds)listNodeValue(ln);
|
||||
res = sdscatlen(res,">",1);
|
||||
res = sdscatsds(res,thispass);
|
||||
res = sdscatlen(res," ",1);
|
||||
@@ -513,7 +513,7 @@ sds ACLDescribeUser(user *u) {
|
||||
} else {
|
||||
listRewind(u->patterns,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
sds thispat = listNodeValue(ln);
|
||||
sds thispat = (sds)listNodeValue(ln);
|
||||
res = sdscatlen(res,"~",1);
|
||||
res = sdscatsds(res,thispat);
|
||||
res = sdscatlen(res," ",1);
|
||||
@@ -533,7 +533,7 @@ sds ACLDescribeUser(user *u) {
|
||||
struct redisCommand *ACLLookupCommand(const char *name) {
|
||||
struct redisCommand *cmd;
|
||||
sds sdsname = sdsnew(name);
|
||||
cmd = dictFetchValue(server.orig_commands, sdsname);
|
||||
cmd = (redisCommand*)dictFetchValue(g_pserver->orig_commands, sdsname);
|
||||
sdsfree(sdsname);
|
||||
return cmd;
|
||||
}
|
||||
@@ -542,6 +542,8 @@ struct redisCommand *ACLLookupCommand(const char *name) {
|
||||
* and command ID. */
|
||||
void ACLResetSubcommandsForCommand(user *u, unsigned long id) {
|
||||
if (u->allowed_subcommands && u->allowed_subcommands[id]) {
|
||||
for (int i = 0; u->allowed_subcommands[id][i]; i++)
|
||||
sdsfree(u->allowed_subcommands[id][i]);
|
||||
zfree(u->allowed_subcommands[id]);
|
||||
u->allowed_subcommands[id] = NULL;
|
||||
}
|
||||
@@ -570,7 +572,7 @@ void ACLAddAllowedSubcommand(user *u, unsigned long id, const char *sub) {
|
||||
/* If this is the first subcommand to be configured for
|
||||
* this user, we have to allocate the subcommands array. */
|
||||
if (u->allowed_subcommands == NULL) {
|
||||
u->allowed_subcommands = zcalloc(USER_COMMAND_BITS_COUNT *
|
||||
u->allowed_subcommands = (sds**)zcalloc(USER_COMMAND_BITS_COUNT *
|
||||
sizeof(sds*), MALLOC_LOCAL);
|
||||
}
|
||||
|
||||
@@ -589,7 +591,7 @@ void ACLAddAllowedSubcommand(user *u, unsigned long id, const char *sub) {
|
||||
|
||||
/* Now we can make space for the new item (and the null term). */
|
||||
items += 2;
|
||||
u->allowed_subcommands[id] = zrealloc(u->allowed_subcommands[id],
|
||||
u->allowed_subcommands[id] = (sds*)zrealloc(u->allowed_subcommands[id],
|
||||
sizeof(sds)*items, MALLOC_LOCAL);
|
||||
u->allowed_subcommands[id][items-2] = sdsnew(sub);
|
||||
u->allowed_subcommands[id][items-1] = NULL;
|
||||
@@ -624,7 +626,7 @@ void ACLAddAllowedSubcommand(user *u, unsigned long id, const char *sub) {
|
||||
* It is possible to specify multiple patterns.
|
||||
* allkeys Alias for ~*
|
||||
* resetkeys Flush the list of allowed keys patterns.
|
||||
* ><password> Add this passowrd to the list of valid password for the user.
|
||||
* ><password> Add this password to the list of valid password for the user.
|
||||
* For example >mypass will add "mypass" to the list.
|
||||
* This directive clears the "nopass" flag (see later).
|
||||
* <<password> Remove this password from the list of valid passwords.
|
||||
@@ -802,8 +804,8 @@ int ACLSetUser(user *u, const char *op, ssize_t oplen) {
|
||||
|
||||
/* Return a description of the error that occurred in ACLSetUser() according to
|
||||
* the errno value set by the function on error. */
|
||||
char *ACLSetUserStringError(void) {
|
||||
char *errmsg = "Wrong format";
|
||||
const char *ACLSetUserStringError(void) {
|
||||
const char *errmsg = "Wrong format";
|
||||
if (errno == ENOENT)
|
||||
errmsg = "Unknown command or category name in ACL";
|
||||
else if (errno == EINVAL)
|
||||
@@ -830,7 +832,7 @@ char *ACLSetUserStringError(void) {
|
||||
sds ACLDefaultUserFirstPassword(void) {
|
||||
if (listLength(DefaultUser->passwords) == 0) return NULL;
|
||||
listNode *first = listFirst(DefaultUser->passwords);
|
||||
return listNodeValue(first);
|
||||
return (sds)listNodeValue(first);
|
||||
}
|
||||
|
||||
/* Initialize the default user, that will always exist for all the process
|
||||
@@ -857,7 +859,7 @@ void ACLInit(void) {
|
||||
* ENONENT: if the specified user does not exist at all.
|
||||
*/
|
||||
int ACLCheckUserCredentials(robj *username, robj *password) {
|
||||
user *u = ACLGetUserByName(ptrFromObj(username),sdslen(ptrFromObj(username)));
|
||||
user *u = ACLGetUserByName(szFromObj(username),sdslen(szFromObj(username)));
|
||||
if (u == NULL) {
|
||||
errno = ENOENT;
|
||||
return C_ERR;
|
||||
@@ -878,8 +880,8 @@ int ACLCheckUserCredentials(robj *username, robj *password) {
|
||||
listNode *ln;
|
||||
listRewind(u->passwords,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
sds thispass = listNodeValue(ln);
|
||||
if (!time_independent_strcmp(ptrFromObj(password), thispass))
|
||||
sds thispass = (sds)listNodeValue(ln);
|
||||
if (!time_independent_strcmp(szFromObj(password), thispass))
|
||||
return C_OK;
|
||||
}
|
||||
|
||||
@@ -944,12 +946,12 @@ unsigned long ACLGetCommandID(const char *cmdname) {
|
||||
user *ACLGetUserByName(const char *name, size_t namelen) {
|
||||
void *myuser = raxFind(Users,(unsigned char*)name,namelen);
|
||||
if (myuser == raxNotFound) return NULL;
|
||||
return myuser;
|
||||
return (user*)myuser;
|
||||
}
|
||||
|
||||
/* Check if the command ready to be excuted in the client 'c', and already
|
||||
* referenced by c->cmd, can be executed by this client according to the
|
||||
* ACls associated to the client user c->user.
|
||||
/* Check if the command is ready to be executed in the client 'c', already
|
||||
* referenced by c->cmd, and can be executed by this client according to the
|
||||
* ACLs associated to the client user c->user.
|
||||
*
|
||||
* If the user can execute the command ACL_OK is returned, otherwise
|
||||
* ACL_DENIED_CMD or ACL_DENIED_KEY is returned: the first in case the
|
||||
@@ -982,7 +984,7 @@ int ACLCheckCommandPerm(client *c) {
|
||||
while (1) {
|
||||
if (u->allowed_subcommands[id][subid] == NULL)
|
||||
return ACL_DENIED_CMD;
|
||||
if (!strcasecmp(ptrFromObj(c->argv[1]),
|
||||
if (!strcasecmp(szFromObj(c->argv[1]),
|
||||
u->allowed_subcommands[id][subid]))
|
||||
break; /* Subcommand match found. Stop here. */
|
||||
subid++;
|
||||
@@ -1005,11 +1007,11 @@ int ACLCheckCommandPerm(client *c) {
|
||||
/* Test this key against every pattern. */
|
||||
int match = 0;
|
||||
while((ln = listNext(&li))) {
|
||||
sds pattern = listNodeValue(ln);
|
||||
sds pattern = (sds)listNodeValue(ln);
|
||||
size_t plen = sdslen(pattern);
|
||||
int idx = keyidx[j];
|
||||
if (stringmatchlen(pattern,plen,ptrFromObj(c->argv[idx]),
|
||||
sdslen(ptrFromObj(c->argv[idx])),0))
|
||||
if (stringmatchlen(pattern,plen,szFromObj(c->argv[idx]),
|
||||
sdslen(szFromObj(c->argv[idx])),0))
|
||||
{
|
||||
match = 1;
|
||||
break;
|
||||
@@ -1071,7 +1073,7 @@ int ACLAppendUserForLoading(sds *argv, int argc, int *argc_err) {
|
||||
}
|
||||
|
||||
/* Rules look valid, let's append the user to the list. */
|
||||
sds *copy = zmalloc(sizeof(sds)*argc, MALLOC_LOCAL);
|
||||
sds *copy = (sds*)zmalloc(sizeof(sds)*argc, MALLOC_LOCAL);
|
||||
for (int j = 1; j < argc; j++) copy[j-1] = sdsdup(argv[j]);
|
||||
copy[argc-1] = NULL;
|
||||
listAddNodeTail(UsersToLoad,copy);
|
||||
@@ -1087,7 +1089,7 @@ int ACLLoadConfiguredUsers(void) {
|
||||
listNode *ln;
|
||||
listRewind(UsersToLoad,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sds *aclrules = listNodeValue(ln);
|
||||
sds *aclrules = (sds*)listNodeValue(ln);
|
||||
sds username = aclrules[0];
|
||||
user *u = ACLCreateUser(username,sdslen(username));
|
||||
if (!u) {
|
||||
@@ -1099,7 +1101,7 @@ int ACLLoadConfiguredUsers(void) {
|
||||
/* Load every rule defined for this user. */
|
||||
for (int j = 1; aclrules[j]; j++) {
|
||||
if (ACLSetUser(u,aclrules[j],sdslen(aclrules[j])) != C_OK) {
|
||||
char *errmsg = ACLSetUserStringError();
|
||||
const char *errmsg = ACLSetUserStringError();
|
||||
serverLog(LL_WARNING,"Error loading ACL rule '%s' for "
|
||||
"the user named '%s': %s",
|
||||
aclrules[j],aclrules[0],errmsg);
|
||||
@@ -1120,7 +1122,7 @@ int ACLLoadConfiguredUsers(void) {
|
||||
}
|
||||
|
||||
/* This function loads the ACL from the specified filename: every line
|
||||
* is validated and shold be either empty or in the format used to specify
|
||||
* is validated and should be either empty or in the format used to specify
|
||||
* users in the redis.conf configuration or in the ACL file, that is:
|
||||
*
|
||||
* user <username> ... rules ...
|
||||
@@ -1170,7 +1172,7 @@ sds ACLLoadFromFile(const char *filename) {
|
||||
* to the real user mentioned in the ACL line. */
|
||||
user *fakeuser = ACLCreateUnlinkedUser();
|
||||
|
||||
/* We do all the loading in a fresh insteance of the Users radix tree,
|
||||
/* We do all the loading in a fresh instance of the Users radix tree,
|
||||
* so if there are errors loading the ACL file we can rollback to the
|
||||
* old version. */
|
||||
rax *old_users = Users;
|
||||
@@ -1194,7 +1196,7 @@ sds ACLLoadFromFile(const char *filename) {
|
||||
if (argv == NULL) {
|
||||
errors = sdscatprintf(errors,
|
||||
"%s:%d: unbalanced quotes in acl line. ",
|
||||
server.acl_filename, linenum);
|
||||
g_pserver->acl_filename, linenum);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1208,7 +1210,7 @@ sds ACLLoadFromFile(const char *filename) {
|
||||
if (strcmp(argv[0],"user") || argc < 2) {
|
||||
errors = sdscatprintf(errors,
|
||||
"%s:%d should start with user keyword followed "
|
||||
"by the username. ", server.acl_filename,
|
||||
"by the username. ", g_pserver->acl_filename,
|
||||
linenum);
|
||||
sdsfreesplitres(argv,argc);
|
||||
continue;
|
||||
@@ -1220,10 +1222,10 @@ sds ACLLoadFromFile(const char *filename) {
|
||||
int j;
|
||||
for (j = 2; j < argc; j++) {
|
||||
if (ACLSetUser(fakeuser,argv[j],sdslen(argv[j])) != C_OK) {
|
||||
char *errmsg = ACLSetUserStringError();
|
||||
const char *errmsg = ACLSetUserStringError();
|
||||
errors = sdscatprintf(errors,
|
||||
"%s:%d: %s. ",
|
||||
server.acl_filename, linenum, errmsg);
|
||||
g_pserver->acl_filename, linenum, errmsg);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -1246,7 +1248,7 @@ sds ACLLoadFromFile(const char *filename) {
|
||||
}
|
||||
|
||||
/* Note that the same rules already applied to the fake user, so
|
||||
* we just assert that everything goess well: it should. */
|
||||
* we just assert that everything goes well: it should. */
|
||||
for (j = 2; j < argc; j++)
|
||||
serverAssert(ACLSetUser(u,argv[j],sdslen(argv[j])) == C_OK);
|
||||
|
||||
@@ -1262,10 +1264,10 @@ sds ACLLoadFromFile(const char *filename) {
|
||||
/* The default user pointer is referenced in different places: instead
|
||||
* of replacing such occurrences it is much simpler to copy the new
|
||||
* default user configuration in the old one. */
|
||||
user *new = ACLGetUserByName("default",7);
|
||||
serverAssert(new != NULL);
|
||||
ACLCopyUser(DefaultUser,new);
|
||||
ACLFreeUser(new);
|
||||
user *newuser = ACLGetUserByName("default",7);
|
||||
serverAssert(newuser != NULL);
|
||||
ACLCopyUser(DefaultUser,newuser);
|
||||
ACLFreeUser(newuser);
|
||||
raxInsert(Users,(unsigned char*)"default",7,DefaultUser,NULL);
|
||||
raxRemove(old_users,(unsigned char*)"default",7,NULL);
|
||||
ACLFreeUsersSet(old_users);
|
||||
@@ -1294,7 +1296,7 @@ int ACLSaveToFile(const char *filename) {
|
||||
raxStart(&ri,Users);
|
||||
raxSeek(&ri,"^",NULL,0);
|
||||
while(raxNext(&ri)) {
|
||||
user *u = ri.data;
|
||||
user *u = (user*)ri.data;
|
||||
/* Return information in the configuration file format. */
|
||||
sds user = sdsnew("user ");
|
||||
user = sdscatsds(user,u->name);
|
||||
@@ -1349,7 +1351,7 @@ cleanup:
|
||||
* The function will just exit with an error if the user is trying to mix
|
||||
* both the loading methods. */
|
||||
void ACLLoadUsersAtStartup(void) {
|
||||
if (server.acl_filename[0] != '\0' && listLength(UsersToLoad) != 0) {
|
||||
if (g_pserver->acl_filename[0] != '\0' && listLength(UsersToLoad) != 0) {
|
||||
serverLog(LL_WARNING,
|
||||
"Configuring Redis with users defined in redis.conf and at "
|
||||
"the same setting an ACL file path is invalid. This setup "
|
||||
@@ -1365,8 +1367,8 @@ void ACLLoadUsersAtStartup(void) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (server.acl_filename[0] != '\0') {
|
||||
sds errors = ACLLoadFromFile(server.acl_filename);
|
||||
if (g_pserver->acl_filename[0] != '\0') {
|
||||
sds errors = ACLLoadFromFile(g_pserver->acl_filename);
|
||||
if (errors) {
|
||||
serverLog(LL_WARNING,
|
||||
"Aborting Redis startup because of ACL errors: %s", errors);
|
||||
@@ -1393,9 +1395,9 @@ void ACLLoadUsersAtStartup(void) {
|
||||
* ACL WHOAMI
|
||||
*/
|
||||
void aclCommand(client *c) {
|
||||
char *sub = ptrFromObj(c->argv[1]);
|
||||
char *sub = szFromObj(c->argv[1]);
|
||||
if (!strcasecmp(sub,"setuser") && c->argc >= 3) {
|
||||
sds username = ptrFromObj(c->argv[2]);
|
||||
sds username = szFromObj(c->argv[2]);
|
||||
/* Create a temporary user to validate and stage all changes against
|
||||
* before applying to an existing user or creating a new user. If all
|
||||
* arguments are valid the user parameters will all be applied together.
|
||||
@@ -1405,8 +1407,8 @@ void aclCommand(client *c) {
|
||||
if (u) ACLCopyUser(tempu, u);
|
||||
|
||||
for (int j = 3; j < c->argc; j++) {
|
||||
if (ACLSetUser(tempu,ptrFromObj(c->argv[j]),sdslen(ptrFromObj(c->argv[j]))) != C_OK) {
|
||||
char *errmsg = ACLSetUserStringError();
|
||||
if (ACLSetUser(tempu,szFromObj(c->argv[j]),sdslen(szFromObj(c->argv[j]))) != C_OK) {
|
||||
const char *errmsg = ACLSetUserStringError();
|
||||
addReplyErrorFormat(c,
|
||||
"Error in ACL SETUSER modifier '%s': %s",
|
||||
(char*)ptrFromObj(c->argv[j]), errmsg);
|
||||
@@ -1425,7 +1427,7 @@ void aclCommand(client *c) {
|
||||
} else if (!strcasecmp(sub,"deluser") && c->argc >= 3) {
|
||||
int deleted = 0;
|
||||
for (int j = 2; j < c->argc; j++) {
|
||||
sds username = ptrFromObj(c->argv[j]);
|
||||
sds username = szFromObj(c->argv[j]);
|
||||
if (!strcmp(username,"default")) {
|
||||
addReplyError(c,"The 'default' user cannot be removed");
|
||||
return;
|
||||
@@ -1433,7 +1435,7 @@ void aclCommand(client *c) {
|
||||
}
|
||||
|
||||
for (int j = 2; j < c->argc; j++) {
|
||||
sds username = ptrFromObj(c->argv[j]);
|
||||
sds username = szFromObj(c->argv[j]);
|
||||
user *u;
|
||||
if (raxRemove(Users,(unsigned char*)username,
|
||||
sdslen(username),
|
||||
@@ -1445,7 +1447,7 @@ void aclCommand(client *c) {
|
||||
}
|
||||
addReplyLongLong(c,deleted);
|
||||
} else if (!strcasecmp(sub,"getuser") && c->argc == 3) {
|
||||
user *u = ACLGetUserByName(ptrFromObj(c->argv[2]),sdslen(ptrFromObj(c->argv[2])));
|
||||
user *u = ACLGetUserByName(szFromObj(c->argv[2]),sdslen(szFromObj(c->argv[2])));
|
||||
if (u == NULL) {
|
||||
addReplyNull(c);
|
||||
return;
|
||||
@@ -1472,7 +1474,7 @@ void aclCommand(client *c) {
|
||||
listNode *ln;
|
||||
listRewind(u->passwords,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
sds thispass = listNodeValue(ln);
|
||||
sds thispass = (sds)listNodeValue(ln);
|
||||
addReplyBulkCBuffer(c,thispass,sdslen(thispass));
|
||||
}
|
||||
|
||||
@@ -1492,7 +1494,7 @@ void aclCommand(client *c) {
|
||||
listNode *ln;
|
||||
listRewind(u->patterns,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
sds thispat = listNodeValue(ln);
|
||||
sds thispat = (sds)listNodeValue(ln);
|
||||
addReplyBulkCBuffer(c,thispat,sdslen(thispat));
|
||||
}
|
||||
}
|
||||
@@ -1505,7 +1507,7 @@ void aclCommand(client *c) {
|
||||
raxStart(&ri,Users);
|
||||
raxSeek(&ri,"^",NULL,0);
|
||||
while(raxNext(&ri)) {
|
||||
user *u = ri.data;
|
||||
user *u = (user*)ri.data;
|
||||
if (justnames) {
|
||||
addReplyBulkCBuffer(c,u->name,sdslen(u->name));
|
||||
} else {
|
||||
@@ -1526,13 +1528,13 @@ void aclCommand(client *c) {
|
||||
} else {
|
||||
addReplyNull(c);
|
||||
}
|
||||
} else if (server.acl_filename[0] == '\0' &&
|
||||
} else if (g_pserver->acl_filename[0] == '\0' &&
|
||||
(!strcasecmp(sub,"load") || !strcasecmp(sub,"save")))
|
||||
{
|
||||
addReplyError(c,"This Redis instance is not configured to use an ACL file. You may want to specify users via the ACL SETUSER command and then issue a CONFIG REWRITE (assuming you have a Redis configuration file set) in order to store users in the Redis configuration.");
|
||||
return;
|
||||
} else if (!strcasecmp(sub,"load") && c->argc == 2) {
|
||||
sds errors = ACLLoadFromFile(server.acl_filename);
|
||||
sds errors = ACLLoadFromFile(g_pserver->acl_filename);
|
||||
if (errors == NULL) {
|
||||
addReply(c,shared.ok);
|
||||
} else {
|
||||
@@ -1540,7 +1542,7 @@ void aclCommand(client *c) {
|
||||
sdsfree(errors);
|
||||
}
|
||||
} else if (!strcasecmp(sub,"save") && c->argc == 2) {
|
||||
if (ACLSaveToFile(server.acl_filename) == C_OK) {
|
||||
if (ACLSaveToFile(g_pserver->acl_filename) == C_OK) {
|
||||
addReply(c,shared.ok);
|
||||
} else {
|
||||
addReplyError(c,"There was an error trying to save the ACLs. "
|
||||
@@ -1554,17 +1556,17 @@ void aclCommand(client *c) {
|
||||
addReplyBulkCString(c,ACLCommandCategories[j].name);
|
||||
setDeferredArrayLen(c,dl,j);
|
||||
} else if (!strcasecmp(sub,"cat") && c->argc == 3) {
|
||||
uint64_t cflag = ACLGetCommandCategoryFlagByName(ptrFromObj(c->argv[2]));
|
||||
uint64_t cflag = ACLGetCommandCategoryFlagByName(szFromObj(c->argv[2]));
|
||||
if (cflag == 0) {
|
||||
addReplyErrorFormat(c, "Unknown category '%s'", (char*)ptrFromObj(c->argv[2]));
|
||||
return;
|
||||
}
|
||||
int arraylen = 0;
|
||||
void *dl = addReplyDeferredLen(c);
|
||||
dictIterator *di = dictGetIterator(server.orig_commands);
|
||||
dictIterator *di = dictGetIterator(g_pserver->orig_commands);
|
||||
dictEntry *de;
|
||||
while ((de = dictNext(di)) != NULL) {
|
||||
struct redisCommand *cmd = dictGetVal(de);
|
||||
struct redisCommand *cmd = (redisCommand*)dictGetVal(de);
|
||||
if (cmd->flags & CMD_MODULE) continue;
|
||||
if (cmd->flags & cflag) {
|
||||
addReplyBulkCString(c,cmd->name);
|
||||
@@ -1609,7 +1611,7 @@ void addReplyCommandCategories(client *c, struct redisCommand *cmd) {
|
||||
setDeferredSetLen(c, flaglen, flagcount);
|
||||
}
|
||||
|
||||
/* AUTH <passowrd>
|
||||
/* AUTH <password>
|
||||
* AUTH <username> <password> (Redis >= 6.0 form)
|
||||
*
|
||||
* When the user is omitted it means that we are trying to authenticate
|
||||
+1
-1
@@ -52,7 +52,7 @@ typedef struct list {
|
||||
listNode *head;
|
||||
listNode *tail;
|
||||
void *(*dup)(void *ptr);
|
||||
void (*free)(void *ptr);
|
||||
void (*free)(const void *ptr);
|
||||
int (*match)(void *ptr, void *key);
|
||||
unsigned long len;
|
||||
} list;
|
||||
|
||||
+43
-14
@@ -46,10 +46,8 @@
|
||||
|
||||
#include "ae.h"
|
||||
#include "fastlock.h"
|
||||
extern "C" {
|
||||
#include "zmalloc.h"
|
||||
#include "config.h"
|
||||
}
|
||||
|
||||
#ifdef USE_MUTEX
|
||||
thread_local int cOwnLock = 0;
|
||||
@@ -82,11 +80,11 @@ public:
|
||||
mutex_wrapper g_lock;
|
||||
|
||||
#else
|
||||
fastlock g_lock;
|
||||
fastlock g_lock("AE (global)");
|
||||
#endif
|
||||
thread_local aeEventLoop *g_eventLoopThisThread = NULL;
|
||||
|
||||
#define AE_ASSERT(x) if (!(x)) do { fprintf(stderr, "AE_ASSER FAILURE\n"); *((volatile int*)0) = 1; } while(0)
|
||||
#define AE_ASSERT(x) if (!(x)) do { fprintf(stderr, "AE_ASSERT FAILURE %s: %d\n", __FILE__, __LINE__); *((volatile int*)0) = 1; } while(0)
|
||||
|
||||
/* Include the best multiplexing layer supported by this system.
|
||||
* The following should be ordered by performances, descending. */
|
||||
@@ -193,6 +191,36 @@ void aeProcessCmd(aeEventLoop *eventLoop, int fd, void *, int )
|
||||
}
|
||||
}
|
||||
|
||||
// Unlike write() this is an all or nothing thing. We will block if a partial write is hit
|
||||
ssize_t safe_write(int fd, const void *pv, size_t cb)
|
||||
{
|
||||
const char *pcb = (const char*)pv;
|
||||
ssize_t written = 0;
|
||||
do
|
||||
{
|
||||
ssize_t rval = write(fd, pcb, cb);
|
||||
if (rval > 0)
|
||||
{
|
||||
pcb += rval;
|
||||
cb -= rval;
|
||||
written += rval;
|
||||
}
|
||||
else if (errno == EAGAIN)
|
||||
{
|
||||
if (written == 0)
|
||||
break;
|
||||
// if we've already written something then we're committed so keep trying
|
||||
}
|
||||
else
|
||||
{
|
||||
if (rval == 0)
|
||||
return written;
|
||||
return rval;
|
||||
}
|
||||
} while (cb);
|
||||
return written;
|
||||
}
|
||||
|
||||
int aeCreateRemoteFileEvent(aeEventLoop *eventLoop, int fd, int mask,
|
||||
aeFileProc *proc, void *clientData, int fSynchronous)
|
||||
{
|
||||
@@ -201,7 +229,7 @@ int aeCreateRemoteFileEvent(aeEventLoop *eventLoop, int fd, int mask,
|
||||
|
||||
int ret = AE_OK;
|
||||
|
||||
aeCommand cmd;
|
||||
aeCommand cmd = {};
|
||||
cmd.op = AE_ASYNC_OP::CreateFileEvent;
|
||||
cmd.fd = fd;
|
||||
cmd.mask = mask;
|
||||
@@ -209,14 +237,15 @@ int aeCreateRemoteFileEvent(aeEventLoop *eventLoop, int fd, int mask,
|
||||
cmd.clientData = clientData;
|
||||
cmd.pctl = nullptr;
|
||||
if (fSynchronous)
|
||||
cmd.pctl = new aeCommandControl();
|
||||
cmd.pctl = new (MALLOC_LOCAL) aeCommandControl();
|
||||
|
||||
std::unique_lock<std::mutex> ulock(cmd.pctl->mutexcv, std::defer_lock);
|
||||
if (fSynchronous)
|
||||
cmd.pctl->mutexcv.lock();
|
||||
auto size = write(eventLoop->fdCmdWrite, &cmd, sizeof(cmd));
|
||||
auto size = safe_write(eventLoop->fdCmdWrite, &cmd, sizeof(cmd));
|
||||
if (size != sizeof(cmd))
|
||||
{
|
||||
AE_ASSERT(size == sizeof(cmd) || size <= 0);
|
||||
AE_ASSERT(errno == EAGAIN);
|
||||
ret = AE_ERR;
|
||||
}
|
||||
@@ -238,7 +267,7 @@ int aePostFunction(aeEventLoop *eventLoop, aePostFunctionProc *proc, void *arg)
|
||||
proc(arg);
|
||||
return AE_OK;
|
||||
}
|
||||
aeCommand cmd;
|
||||
aeCommand cmd = {};
|
||||
cmd.op = AE_ASYNC_OP::PostFunction;
|
||||
cmd.proc = proc;
|
||||
cmd.clientData = arg;
|
||||
@@ -255,12 +284,12 @@ int aePostFunction(aeEventLoop *eventLoop, std::function<void()> fn, bool fSynch
|
||||
return AE_OK;
|
||||
}
|
||||
|
||||
aeCommand cmd;
|
||||
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.pctl = nullptr;
|
||||
if (fSynchronous)
|
||||
cmd.pctl = new aeCommandControl();
|
||||
cmd.pctl = new (MALLOC_LOCAL) aeCommandControl();
|
||||
std::unique_lock<std::mutex> ulock(cmd.pctl->mutexcv, std::defer_lock);
|
||||
if (fSynchronous)
|
||||
cmd.pctl->mutexcv.lock();
|
||||
@@ -298,7 +327,7 @@ aeEventLoop *aeCreateEventLoop(int setsize) {
|
||||
for (i = 0; i < setsize; i++)
|
||||
eventLoop->events[i].mask = AE_NONE;
|
||||
|
||||
fastlock_init(&eventLoop->flock);
|
||||
fastlock_init(&eventLoop->flock, "event loop");
|
||||
int rgfd[2];
|
||||
if (pipe(rgfd) < 0)
|
||||
goto err;
|
||||
@@ -805,9 +834,9 @@ void aeAcquireLock()
|
||||
g_lock.lock();
|
||||
}
|
||||
|
||||
int aeTryAcquireLock()
|
||||
int aeTryAcquireLock(int fWeak)
|
||||
{
|
||||
return g_lock.try_lock();
|
||||
return g_lock.try_lock(!!fWeak);
|
||||
}
|
||||
|
||||
void aeReleaseLock()
|
||||
|
||||
@@ -159,7 +159,7 @@ int aeGetSetSize(aeEventLoop *eventLoop);
|
||||
int aeResizeSetSize(aeEventLoop *eventLoop, int setsize);
|
||||
|
||||
void aeAcquireLock();
|
||||
int aeTryAcquireLock();
|
||||
int aeTryAcquireLock(int fWeak);
|
||||
void aeReleaseLock();
|
||||
int aeThreadOwnsLock();
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
class AeLocker
|
||||
{
|
||||
bool m_fArmed = false;
|
||||
|
||||
public:
|
||||
AeLocker()
|
||||
{
|
||||
}
|
||||
|
||||
void arm(client *c) // if a client is passed, then the client is already locked
|
||||
{
|
||||
if (c != nullptr)
|
||||
{
|
||||
serverAssert(!m_fArmed);
|
||||
serverAssert(c->lock.fOwnLock());
|
||||
|
||||
if (!aeTryAcquireLock(true /*fWeak*/)) // avoid locking the client if we can
|
||||
{
|
||||
bool fOwnClientLock = true;
|
||||
int clientNesting = 1;
|
||||
for (;;)
|
||||
{
|
||||
if (fOwnClientLock)
|
||||
{
|
||||
clientNesting = c->lock.unlock_recursive();
|
||||
fOwnClientLock = false;
|
||||
}
|
||||
aeAcquireLock();
|
||||
if (!c->lock.try_lock(false)) // ensure a strong try because aeAcquireLock is expensive
|
||||
{
|
||||
aeReleaseLock();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
c->lock.lock_recursive(clientNesting);
|
||||
}
|
||||
|
||||
m_fArmed = true;
|
||||
}
|
||||
else if (!m_fArmed)
|
||||
{
|
||||
m_fArmed = true;
|
||||
aeAcquireLock();
|
||||
}
|
||||
}
|
||||
|
||||
void disarm()
|
||||
{
|
||||
serverAssert(m_fArmed);
|
||||
m_fArmed = false;
|
||||
aeReleaseLock();
|
||||
}
|
||||
|
||||
bool isArmed() const
|
||||
{
|
||||
return m_fArmed;
|
||||
}
|
||||
|
||||
void release()
|
||||
{
|
||||
m_fArmed = false;
|
||||
}
|
||||
|
||||
~AeLocker()
|
||||
{
|
||||
if (m_fArmed)
|
||||
aeReleaseLock();
|
||||
}
|
||||
};
|
||||
+11
-7
@@ -476,7 +476,7 @@ static int anetV6Only(char *err, int s) {
|
||||
return ANET_OK;
|
||||
}
|
||||
|
||||
static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backlog, int fReusePort)
|
||||
static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backlog, int fReusePort, int fFirstListen)
|
||||
{
|
||||
int s = -1, rv;
|
||||
char _port[6]; /* strlen("65535") */
|
||||
@@ -498,8 +498,12 @@ static int _anetTcpServer(char *err, int port, char *bindaddr, int af, int backl
|
||||
|
||||
if (af == AF_INET6 && anetV6Only(err,s) == ANET_ERR) goto error;
|
||||
if (anetSetReuseAddr(err,s) == ANET_ERR) goto error;
|
||||
if (fReusePort && anetSetReusePort(err,s) == ANET_ERR) goto error;
|
||||
if (anetListen(err,s,p->ai_addr,p->ai_addrlen,backlog) == ANET_ERR) s = ANET_ERR;
|
||||
if (fReusePort && !fFirstListen && anetSetReusePort(err,s) == ANET_ERR) goto error;
|
||||
if (anetListen(err,s,p->ai_addr,p->ai_addrlen,backlog) == ANET_ERR) {
|
||||
s = ANET_ERR;
|
||||
goto end;
|
||||
}
|
||||
if (fReusePort && fFirstListen && anetSetReusePort(err,s) == ANET_ERR) goto error;
|
||||
goto end;
|
||||
}
|
||||
if (p == NULL) {
|
||||
@@ -515,14 +519,14 @@ end:
|
||||
return s;
|
||||
}
|
||||
|
||||
int anetTcpServer(char *err, int port, char *bindaddr, int backlog, int fReusePort)
|
||||
int anetTcpServer(char *err, int port, char *bindaddr, int backlog, int fReusePort, int fFirstListen)
|
||||
{
|
||||
return _anetTcpServer(err, port, bindaddr, AF_INET, backlog, fReusePort);
|
||||
return _anetTcpServer(err, port, bindaddr, AF_INET, backlog, fReusePort, fFirstListen);
|
||||
}
|
||||
|
||||
int anetTcp6Server(char *err, int port, char *bindaddr, int backlog, int fReusePort)
|
||||
int anetTcp6Server(char *err, int port, char *bindaddr, int backlog, int fReusePort, int fFirstListen)
|
||||
{
|
||||
return _anetTcpServer(err, port, bindaddr, AF_INET6, backlog, fReusePort);
|
||||
return _anetTcpServer(err, port, bindaddr, AF_INET6, backlog, fReusePort, fFirstListen);
|
||||
}
|
||||
|
||||
int anetUnixServer(char *err, char *path, mode_t perm, int backlog)
|
||||
|
||||
+2
-2
@@ -62,8 +62,8 @@ int anetUnixNonBlockConnect(char *err, char *path);
|
||||
int anetRead(int fd, char *buf, int count);
|
||||
int anetResolve(char *err, char *host, char *ipbuf, size_t ipbuf_len);
|
||||
int anetResolveIP(char *err, char *host, char *ipbuf, size_t ipbuf_len);
|
||||
int anetTcpServer(char *err, int port, char *bindaddr, int backlog, int fReusePort);
|
||||
int anetTcp6Server(char *err, int port, char *bindaddr, int backlog, int fReusePort);
|
||||
int anetTcpServer(char *err, int port, char *bindaddr, int backlog, int fReusePort, int fFirstListen);
|
||||
int anetTcp6Server(char *err, int port, char *bindaddr, int backlog, int fReusePort, int fFirstListen);
|
||||
int anetUnixServer(char *err, char *path, mode_t perm, int backlog);
|
||||
int anetTcpAccept(char *err, int serversock, char *ip, size_t ip_len, int *port);
|
||||
int anetUnixAccept(char *err, int serversock);
|
||||
|
||||
+265
-219
File diff suppressed because it is too large.
Load diff
@@ -36,4 +36,7 @@ const char *ascii_logo =
|
||||
" Port: %d\n"
|
||||
" PID: %ld\n"
|
||||
" \n"
|
||||
" Like KeyDB? Star us on GitHub! \n"
|
||||
" \n"
|
||||
" https://github.com/JohnSully/KeyDB \n"
|
||||
" \n\n";
|
||||
@@ -4,7 +4,7 @@
|
||||
* Currently there is only a single operation, that is a background close(2)
|
||||
* system call. This is needed as when the process is the last owner of a
|
||||
* reference to a file closing it means unlinking it, and the deletion of the
|
||||
* file is slow, blocking the server.
|
||||
* file is slow, blocking the g_pserver->
|
||||
*
|
||||
* In the future we'll either continue implementing new things we need or
|
||||
* we'll switch to libeio. However there are probably long term uses for this
|
||||
@@ -85,7 +85,7 @@ struct bio_job {
|
||||
|
||||
void *bioProcessBackgroundJobs(void *arg);
|
||||
void lazyfreeFreeObjectFromBioThread(robj *o);
|
||||
void lazyfreeFreeDatabaseFromBioThread(dict *ht1, dict *ht2);
|
||||
void lazyfreeFreeDatabaseFromBioThread(dict *ht1, expireset *set);
|
||||
void lazyfreeFreeSlotsMapFromBioThread(rax *rt);
|
||||
|
||||
/* Make sure we have enough stack to perform all the things we do in the
|
||||
@@ -129,7 +129,7 @@ void bioInit(void) {
|
||||
}
|
||||
|
||||
void bioCreateBackgroundJob(int type, void *arg1, void *arg2, void *arg3) {
|
||||
struct bio_job *job = zmalloc(sizeof(*job), MALLOC_LOCAL);
|
||||
struct bio_job *job = (bio_job*)zmalloc(sizeof(*job), MALLOC_LOCAL);
|
||||
|
||||
job->time = time(NULL);
|
||||
job->arg1 = arg1;
|
||||
@@ -178,7 +178,7 @@ void *bioProcessBackgroundJobs(void *arg) {
|
||||
}
|
||||
/* Pop the job from the queue. */
|
||||
ln = listFirst(bio_jobs[type]);
|
||||
job = ln->value;
|
||||
job = (bio_job*)ln->value;
|
||||
/* It is now possible to unlock the background system as we know have
|
||||
* a stand alone job structure to process.*/
|
||||
pthread_mutex_unlock(&bio_mutex[type]);
|
||||
@@ -194,11 +194,11 @@ void *bioProcessBackgroundJobs(void *arg) {
|
||||
* arg2 & arg3 -> free two dictionaries (a Redis DB).
|
||||
* only arg3 -> free the skiplist. */
|
||||
if (job->arg1)
|
||||
lazyfreeFreeObjectFromBioThread(job->arg1);
|
||||
lazyfreeFreeObjectFromBioThread((robj*)job->arg1);
|
||||
else if (job->arg2 && job->arg3)
|
||||
lazyfreeFreeDatabaseFromBioThread(job->arg2,job->arg3);
|
||||
lazyfreeFreeDatabaseFromBioThread((dict*)job->arg2,(expireset*)job->arg3);
|
||||
else if (job->arg3)
|
||||
lazyfreeFreeSlotsMapFromBioThread(job->arg3);
|
||||
lazyfreeFreeSlotsMapFromBioThread((rax*)job->arg3);
|
||||
} else {
|
||||
serverPanic("Wrong job type in bioProcessBackgroundJobs().");
|
||||
}
|
||||
+210
-130
@@ -37,9 +37,9 @@
|
||||
/* Count number of bits set in the binary array pointed by 's' and long
|
||||
* 'count' bytes. The implementation of this function is required to
|
||||
* work with a input string length up to 512 MB. */
|
||||
size_t redisPopcount(void *s, long count) {
|
||||
size_t redisPopcount(const void *s, long count) {
|
||||
size_t bits = 0;
|
||||
unsigned char *p = s;
|
||||
unsigned char *p = (unsigned char*)s;
|
||||
uint32_t *p4;
|
||||
static const unsigned char bitsinbyte[256] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};
|
||||
|
||||
@@ -98,7 +98,7 @@ size_t redisPopcount(void *s, long count) {
|
||||
* no zero bit is found, it returns count*8 assuming the string is zero
|
||||
* padded on the right. However if 'bit' is 1 it is possible that there is
|
||||
* not a single set bit in the bitmap. In this special case -1 is returned. */
|
||||
long redisBitpos(void *s, unsigned long count, int bit) {
|
||||
long redisBitpos(const void *s, unsigned long count, int bit) {
|
||||
unsigned long *l;
|
||||
unsigned char *c;
|
||||
unsigned long skipval, word = 0, one;
|
||||
@@ -396,6 +396,8 @@ void printBits(unsigned char *p, unsigned long count) {
|
||||
#define BITOP_OR 1
|
||||
#define BITOP_XOR 2
|
||||
#define BITOP_NOT 3
|
||||
#define BITOP_LSHIFT 4
|
||||
#define BITOP_RSHIFT 5
|
||||
|
||||
#define BITFIELDOP_GET 0
|
||||
#define BITFIELDOP_SET 1
|
||||
@@ -410,8 +412,8 @@ void printBits(unsigned char *p, unsigned long count) {
|
||||
* is multiplied by 'bits'. This is useful for the BITFIELD command. */
|
||||
int getBitOffsetFromArgument(client *c, robj *o, size_t *offset, int hash, int bits) {
|
||||
long long loffset;
|
||||
char *err = "bit offset is not an integer or out of range";
|
||||
char *p = ptrFromObj(o);
|
||||
const char *err = "bit offset is not an integer or out of range";
|
||||
char *p = szFromObj(o);
|
||||
size_t plen = sdslen(p);
|
||||
int usehash = 0;
|
||||
|
||||
@@ -445,8 +447,8 @@ int getBitOffsetFromArgument(client *c, robj *o, size_t *offset, int hash, int b
|
||||
*
|
||||
* On error C_ERR is returned and an error is sent to the client. */
|
||||
int getBitfieldTypeFromArgument(client *c, robj *o, int *sign, int *bits) {
|
||||
char *p = ptrFromObj(o);
|
||||
char *err = "Invalid bitfield type. Use something like i16 u8. Note that u64 is not supported but i64 is.";
|
||||
char *p = szFromObj(o);
|
||||
const char *err = "Invalid bitfield type. Use something like i16 u8. Note that u64 is not supported but i64 is.";
|
||||
long long llbits;
|
||||
|
||||
if (p[0] == 'i') {
|
||||
@@ -485,7 +487,7 @@ robj *lookupStringForBitCommand(client *c, size_t maxbit) {
|
||||
} else {
|
||||
if (checkType(c,o,OBJ_STRING)) return NULL;
|
||||
o = dbUnshareStringValue(c->db,c->argv[1],o);
|
||||
o->m_ptr = sdsgrowzero(ptrFromObj(o),byte+1);
|
||||
o->m_ptr = sdsgrowzero(szFromObj(o),byte+1);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
@@ -503,18 +505,18 @@ robj *lookupStringForBitCommand(client *c, size_t maxbit) {
|
||||
*
|
||||
* If the source object is NULL the function is guaranteed to return NULL
|
||||
* and set 'len' to 0. */
|
||||
unsigned char *getObjectReadOnlyString(robj *o, long *len, char *llbuf) {
|
||||
const unsigned char *getObjectReadOnlyString(robj_roptr o, long *len, char *llbuf) {
|
||||
serverAssert(o->type == OBJ_STRING);
|
||||
unsigned char *p = NULL;
|
||||
const unsigned char *p = NULL;
|
||||
|
||||
/* Set the 'p' pointer to the string, that can be just a stack allocated
|
||||
* array if our string was integer encoded. */
|
||||
if (o && o->encoding == OBJ_ENCODING_INT) {
|
||||
p = (unsigned char*) llbuf;
|
||||
p = (const unsigned char*) llbuf;
|
||||
if (len) *len = ll2string(llbuf,LONG_STR_SIZE,(long)ptrFromObj(o));
|
||||
} else if (o) {
|
||||
p = (unsigned char*) ptrFromObj(o);
|
||||
if (len) *len = sdslen(ptrFromObj(o));
|
||||
p = (const unsigned char*) ptrFromObj(o);
|
||||
if (len) *len = sdslen(szFromObj(o));
|
||||
} else {
|
||||
if (len) *len = 0;
|
||||
}
|
||||
@@ -524,7 +526,7 @@ unsigned char *getObjectReadOnlyString(robj *o, long *len, char *llbuf) {
|
||||
/* SETBIT key offset bitvalue */
|
||||
void setbitCommand(client *c) {
|
||||
robj *o;
|
||||
char *err = "bit is not an integer or out of range";
|
||||
const char *err = "bit is not an integer or out of range";
|
||||
size_t bitoffset;
|
||||
ssize_t byte, bit;
|
||||
int byteval, bitval;
|
||||
@@ -556,13 +558,13 @@ void setbitCommand(client *c) {
|
||||
((uint8_t*)ptrFromObj(o))[byte] = byteval;
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(NOTIFY_STRING,"setbit",c->argv[1],c->db->id);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
addReply(c, bitval ? shared.cone : shared.czero);
|
||||
}
|
||||
|
||||
/* GETBIT key offset */
|
||||
void getbitCommand(client *c) {
|
||||
robj *o;
|
||||
robj_roptr o;
|
||||
char llbuf[32];
|
||||
size_t bitoffset;
|
||||
size_t byte, bit;
|
||||
@@ -571,13 +573,13 @@ void getbitCommand(client *c) {
|
||||
if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset,0,0) != C_OK)
|
||||
return;
|
||||
|
||||
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
|
||||
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == nullptr ||
|
||||
checkType(c,o,OBJ_STRING)) return;
|
||||
|
||||
byte = bitoffset >> 3;
|
||||
bit = 7 - (bitoffset & 0x7);
|
||||
if (sdsEncodedObject(o)) {
|
||||
if (byte < sdslen(ptrFromObj(o)))
|
||||
if (byte < sdslen(szFromObj(o)))
|
||||
bitval = ((uint8_t*)ptrFromObj(o))[byte] & (1 << bit);
|
||||
} else {
|
||||
if (byte < (size_t)ll2string(llbuf,sizeof(llbuf),(long)ptrFromObj(o)))
|
||||
@@ -589,10 +591,12 @@ void getbitCommand(client *c) {
|
||||
|
||||
/* BITOP op_name target_key src_key1 src_key2 src_key3 ... src_keyN */
|
||||
void bitopCommand(client *c) {
|
||||
char *opname = ptrFromObj(c->argv[1]);
|
||||
robj *o, *targetkey = c->argv[2];
|
||||
unsigned long op, j, numkeys;
|
||||
robj **objects; /* Array of source objects. */
|
||||
char *opname = szFromObj(c->argv[1]);
|
||||
robj *targetkey = c->argv[2];
|
||||
robj_roptr o;
|
||||
int op;
|
||||
unsigned long j, numkeys;
|
||||
robj_roptr *objects; /* Array of source objects. */
|
||||
unsigned char **src; /* Array of source strings pointers. */
|
||||
unsigned long *len, maxlen = 0; /* Array of length of src strings,
|
||||
and max len. */
|
||||
@@ -608,6 +612,10 @@ void bitopCommand(client *c) {
|
||||
op = BITOP_XOR;
|
||||
else if((opname[0] == 'n' || opname[0] == 'N') && !strcasecmp(opname,"not"))
|
||||
op = BITOP_NOT;
|
||||
else if (!strcasecmp(opname, "lshift"))
|
||||
op = BITOP_LSHIFT;
|
||||
else if (!strcasecmp(opname, "rshift"))
|
||||
op = BITOP_RSHIFT;
|
||||
else {
|
||||
addReply(c,shared.syntaxerr);
|
||||
return;
|
||||
@@ -619,16 +627,33 @@ void bitopCommand(client *c) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool fShiftOp = (op == BITOP_LSHIFT) || (op == BITOP_RSHIFT);
|
||||
long long shift = 0;
|
||||
|
||||
/* Sanity check: SHIFTS only accept a single arg and an integer */
|
||||
if (fShiftOp) {
|
||||
if (c->argc != 5) {
|
||||
addReplyError(c,"BITOP SHIFT must be called with a single source key and an integer shift.");
|
||||
return;
|
||||
}
|
||||
if (getLongLongFromObject(c->argv[4], &shift) != C_OK) {
|
||||
addReplyError(c, "BITOP SHIFT's last parameter must be an integer");
|
||||
return;
|
||||
}
|
||||
if (op == BITOP_RSHIFT)
|
||||
shift = -shift;
|
||||
}
|
||||
|
||||
/* Lookup keys, and store pointers to the string objects into an array. */
|
||||
numkeys = c->argc - 3;
|
||||
src = zmalloc(sizeof(unsigned char*) * numkeys, MALLOC_LOCAL);
|
||||
len = zmalloc(sizeof(long) * numkeys, MALLOC_LOCAL);
|
||||
objects = zmalloc(sizeof(robj*) * numkeys, MALLOC_LOCAL);
|
||||
numkeys = c->argc - (fShiftOp ? 4 : 3);
|
||||
src = (unsigned char**)zmalloc(sizeof(unsigned char*) * numkeys, MALLOC_LOCAL);
|
||||
len = (unsigned long*)zmalloc(sizeof(long) * numkeys, MALLOC_LOCAL);
|
||||
objects = (robj_roptr*)zmalloc(sizeof(robj_roptr) * numkeys, MALLOC_LOCAL);
|
||||
for (j = 0; j < numkeys; j++) {
|
||||
o = lookupKeyRead(c->db,c->argv[j+3]);
|
||||
/* Handle non-existing keys as empty strings. */
|
||||
if (o == NULL) {
|
||||
objects[j] = NULL;
|
||||
if (o == nullptr) {
|
||||
objects[j] = nullptr;
|
||||
src[j] = NULL;
|
||||
len[j] = 0;
|
||||
minlen = 0;
|
||||
@@ -647,100 +672,149 @@ void bitopCommand(client *c) {
|
||||
return;
|
||||
}
|
||||
objects[j] = getDecodedObject(o);
|
||||
src[j] = ptrFromObj(objects[j]);
|
||||
len[j] = sdslen(ptrFromObj(objects[j]));
|
||||
src[j] = (unsigned char*)ptrFromObj(objects[j]);
|
||||
len[j] = sdslen(szFromObj(objects[j]));
|
||||
if (len[j] > maxlen) maxlen = len[j];
|
||||
if (j == 0 || len[j] < minlen) minlen = len[j];
|
||||
}
|
||||
|
||||
/* Compute the bit operation, if at least one string is not empty. */
|
||||
if (maxlen) {
|
||||
res = (unsigned char*) sdsnewlen(NULL,maxlen);
|
||||
unsigned char output, byte;
|
||||
unsigned long i;
|
||||
if (fShiftOp)
|
||||
{
|
||||
long newlen = (long)maxlen + shift/CHAR_BIT;
|
||||
if (shift > 0 && (shift % CHAR_BIT) != 0)
|
||||
newlen++;
|
||||
|
||||
/* Fast path: as far as we have data for all the input bitmaps we
|
||||
* can take a fast path that performs much better than the
|
||||
* vanilla algorithm. On ARM we skip the fast path since it will
|
||||
* result in GCC compiling the code using multiple-words load/store
|
||||
* operations that are not supported even in ARM >= v6. */
|
||||
j = 0;
|
||||
#ifndef USE_ALIGNED_ACCESS
|
||||
if (minlen >= sizeof(unsigned long)*4 && numkeys <= 16) {
|
||||
unsigned long *lp[16];
|
||||
unsigned long *lres = (unsigned long*) res;
|
||||
if (newlen < 0)
|
||||
newlen = 0;
|
||||
|
||||
if (newlen)
|
||||
{
|
||||
res = (unsigned char*) sdsnewlen(NULL,newlen);
|
||||
if (shift >= 0)
|
||||
{ // left shift
|
||||
long byteoffset = shift/CHAR_BIT;
|
||||
memset(res, 0, byteoffset);
|
||||
long srcLen = newlen - byteoffset - ((shift % CHAR_BIT) ? 1 : 0);
|
||||
|
||||
/* Note: sds pointer is always aligned to 8 byte boundary. */
|
||||
memcpy(lp,src,sizeof(unsigned long*)*numkeys);
|
||||
memcpy(res,src[0],minlen);
|
||||
|
||||
/* Different branches per different operations for speed (sorry). */
|
||||
if (op == BITOP_AND) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
lres[0] &= lp[i][0];
|
||||
lres[1] &= lp[i][1];
|
||||
lres[2] &= lp[i][2];
|
||||
lres[3] &= lp[i][3];
|
||||
lp[i]+=4;
|
||||
}
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
// now the bitshift+copy
|
||||
unsigned bitshift = shift % CHAR_BIT;
|
||||
unsigned char carry = 0;
|
||||
for (long iSrc = 0; iSrc < srcLen; ++iSrc)
|
||||
{
|
||||
res[byteoffset+iSrc] = (src[0][iSrc] << bitshift) | carry;
|
||||
carry = src[0][iSrc] >> (CHAR_BIT - bitshift);
|
||||
}
|
||||
} else if (op == BITOP_OR) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
lres[0] |= lp[i][0];
|
||||
lres[1] |= lp[i][1];
|
||||
lres[2] |= lp[i][2];
|
||||
lres[3] |= lp[i][3];
|
||||
lp[i]+=4;
|
||||
}
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
}
|
||||
} else if (op == BITOP_XOR) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
lres[0] ^= lp[i][0];
|
||||
lres[1] ^= lp[i][1];
|
||||
lres[2] ^= lp[i][2];
|
||||
lres[3] ^= lp[i][3];
|
||||
lp[i]+=4;
|
||||
}
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
}
|
||||
} else if (op == BITOP_NOT) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
lres[0] = ~lres[0];
|
||||
lres[1] = ~lres[1];
|
||||
lres[2] = ~lres[2];
|
||||
lres[3] = ~lres[3];
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
if (bitshift)
|
||||
res[newlen-1] = carry;
|
||||
}
|
||||
else
|
||||
{ // right shift
|
||||
long byteoffset = -shift/CHAR_BIT;
|
||||
unsigned bitshift = -shift % CHAR_BIT;
|
||||
if (bitshift)
|
||||
++byteoffset;
|
||||
res[0] = (src[0][byteoffset] << (CHAR_BIT-bitshift));
|
||||
if (byteoffset > 0)
|
||||
res[0] |= (src[0][byteoffset-1] >> bitshift);
|
||||
for (long idx = 1; idx < newlen; ++idx)
|
||||
{
|
||||
res[idx] = (src[0][byteoffset+idx] << (CHAR_BIT-bitshift)) | (src[0][byteoffset+idx-1] >> bitshift);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
maxlen = newlen; // this is to ensure we DEL below if newlen was 0
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Compute the bit operation, if at least one string is not empty. */
|
||||
if (maxlen) {
|
||||
res = (unsigned char*) sdsnewlen(NULL,maxlen);
|
||||
unsigned char output, byte;
|
||||
unsigned long i;
|
||||
|
||||
/* j is set to the next byte to process by the previous loop. */
|
||||
for (; j < maxlen; j++) {
|
||||
output = (len[0] <= j) ? 0 : src[0][j];
|
||||
if (op == BITOP_NOT) output = ~output;
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
byte = (len[i] <= j) ? 0 : src[i][j];
|
||||
switch(op) {
|
||||
case BITOP_AND: output &= byte; break;
|
||||
case BITOP_OR: output |= byte; break;
|
||||
case BITOP_XOR: output ^= byte; break;
|
||||
/* Fast path: as far as we have data for all the input bitmaps we
|
||||
* can take a fast path that performs much better than the
|
||||
* vanilla algorithm. On ARM we skip the fast path since it will
|
||||
* result in GCC compiling the code using multiple-words load/store
|
||||
* operations that are not supported even in ARM >= v6. */
|
||||
j = 0;
|
||||
#ifndef USE_ALIGNED_ACCESS
|
||||
if (minlen >= sizeof(unsigned long)*4 && numkeys <= 16) {
|
||||
unsigned long *lp[16];
|
||||
unsigned long *lres = (unsigned long*) res;
|
||||
|
||||
/* Note: sds pointer is always aligned to 8 byte boundary. */
|
||||
memcpy(lp,src,sizeof(unsigned long*)*numkeys);
|
||||
memcpy(res,src[0],minlen);
|
||||
|
||||
/* Different branches per different operations for speed (sorry). */
|
||||
if (op == BITOP_AND) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
lres[0] &= lp[i][0];
|
||||
lres[1] &= lp[i][1];
|
||||
lres[2] &= lp[i][2];
|
||||
lres[3] &= lp[i][3];
|
||||
lp[i]+=4;
|
||||
}
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
}
|
||||
} else if (op == BITOP_OR) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
lres[0] |= lp[i][0];
|
||||
lres[1] |= lp[i][1];
|
||||
lres[2] |= lp[i][2];
|
||||
lres[3] |= lp[i][3];
|
||||
lp[i]+=4;
|
||||
}
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
}
|
||||
} else if (op == BITOP_XOR) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
lres[0] ^= lp[i][0];
|
||||
lres[1] ^= lp[i][1];
|
||||
lres[2] ^= lp[i][2];
|
||||
lres[3] ^= lp[i][3];
|
||||
lp[i]+=4;
|
||||
}
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
}
|
||||
} else if (op == BITOP_NOT) {
|
||||
while(minlen >= sizeof(unsigned long)*4) {
|
||||
lres[0] = ~lres[0];
|
||||
lres[1] = ~lres[1];
|
||||
lres[2] = ~lres[2];
|
||||
lres[3] = ~lres[3];
|
||||
lres+=4;
|
||||
j += sizeof(unsigned long)*4;
|
||||
minlen -= sizeof(unsigned long)*4;
|
||||
}
|
||||
}
|
||||
}
|
||||
res[j] = output;
|
||||
#endif
|
||||
|
||||
/* j is set to the next byte to process by the previous loop. */
|
||||
for (; j < maxlen; j++) {
|
||||
output = (len[0] <= j) ? 0 : src[0][j];
|
||||
if (op == BITOP_NOT) output = ~output;
|
||||
for (i = 1; i < numkeys; i++) {
|
||||
byte = (len[i] <= j) ? 0 : src[i][j];
|
||||
switch(op) {
|
||||
case BITOP_AND: output &= byte; break;
|
||||
case BITOP_OR: output |= byte; break;
|
||||
case BITOP_XOR: output ^= byte; break;
|
||||
}
|
||||
}
|
||||
res[j] = output;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (j = 0; j < numkeys; j++) {
|
||||
@@ -753,7 +827,7 @@ void bitopCommand(client *c) {
|
||||
|
||||
/* Store the computed value into the target key */
|
||||
if (maxlen) {
|
||||
o = createObject(OBJ_STRING,res);
|
||||
robj *o = createObject(OBJ_STRING,res);
|
||||
setKey(c->db,targetkey,o);
|
||||
notifyKeyspaceEvent(NOTIFY_STRING,"set",targetkey,c->db->id);
|
||||
decrRefCount(o);
|
||||
@@ -761,19 +835,19 @@ void bitopCommand(client *c) {
|
||||
signalModifiedKey(c->db,targetkey);
|
||||
notifyKeyspaceEvent(NOTIFY_GENERIC,"del",targetkey,c->db->id);
|
||||
}
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
addReplyLongLong(c,maxlen); /* Return the output string length in bytes. */
|
||||
}
|
||||
|
||||
/* BITCOUNT key [start end] */
|
||||
void bitcountCommand(client *c) {
|
||||
robj *o;
|
||||
robj_roptr o;
|
||||
long start, end, strlen;
|
||||
unsigned char *p;
|
||||
const unsigned char *p;
|
||||
char llbuf[LONG_STR_SIZE];
|
||||
|
||||
/* Lookup, check for type, and return 0 for non existing keys. */
|
||||
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
|
||||
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == nullptr ||
|
||||
checkType(c,o,OBJ_STRING)) return;
|
||||
p = getObjectReadOnlyString(o,&strlen,llbuf);
|
||||
|
||||
@@ -816,9 +890,9 @@ void bitcountCommand(client *c) {
|
||||
|
||||
/* BITPOS key bit [start [end]] */
|
||||
void bitposCommand(client *c) {
|
||||
robj *o;
|
||||
robj_roptr o;
|
||||
long bit, start, end, strlen;
|
||||
unsigned char *p;
|
||||
const unsigned char *p;
|
||||
char llbuf[LONG_STR_SIZE];
|
||||
int end_given = 0;
|
||||
|
||||
@@ -834,7 +908,7 @@ void bitposCommand(client *c) {
|
||||
/* If the key does not exist, from our point of view it is an infinite
|
||||
* array of 0 bits. If the user is looking for the fist clear bit return 0,
|
||||
* If the user is looking for the first set bit, return -1. */
|
||||
if ((o = lookupKeyRead(c->db,c->argv[1])) == NULL) {
|
||||
if ((o = lookupKeyRead(c->db,c->argv[1])) == nullptr) {
|
||||
addReplyLongLong(c, bit ? -1 : 0);
|
||||
return;
|
||||
}
|
||||
@@ -912,7 +986,7 @@ struct bitfieldOp {
|
||||
};
|
||||
|
||||
void bitfieldCommand(client *c) {
|
||||
robj *o;
|
||||
robj_roptr o;
|
||||
size_t bitoffset;
|
||||
int j, numops = 0, changes = 0;
|
||||
struct bitfieldOp *ops = NULL; /* Array of ops to execute at end. */
|
||||
@@ -922,7 +996,7 @@ void bitfieldCommand(client *c) {
|
||||
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
int remargs = c->argc-j-1; /* Remaining args other than current. */
|
||||
char *subcmd = ptrFromObj(c->argv[j]); /* Current command name. */
|
||||
char *subcmd = szFromObj(c->argv[j]); /* Current command name. */
|
||||
int opcode; /* Current operation code. */
|
||||
long long i64 = 0; /* Signed SET value. */
|
||||
int sign = 0; /* Signed or unsigned type? */
|
||||
@@ -935,7 +1009,7 @@ void bitfieldCommand(client *c) {
|
||||
else if (!strcasecmp(subcmd,"incrby") && remargs >= 3)
|
||||
opcode = BITFIELDOP_INCRBY;
|
||||
else if (!strcasecmp(subcmd,"overflow") && remargs >= 1) {
|
||||
char *owtypename = ptrFromObj(c->argv[j+1]);
|
||||
char *owtypename = szFromObj(c->argv[j+1]);
|
||||
j++;
|
||||
if (!strcasecmp(owtypename,"wrap"))
|
||||
owtype = BFOVERFLOW_WRAP;
|
||||
@@ -978,7 +1052,7 @@ void bitfieldCommand(client *c) {
|
||||
}
|
||||
|
||||
/* Populate the array of operations we'll process. */
|
||||
ops = zrealloc(ops,sizeof(*ops)*(numops+1), MALLOC_SHARED);
|
||||
ops = (bitfieldOp*)zrealloc(ops,sizeof(*ops)*(numops+1), MALLOC_SHARED);
|
||||
ops[numops].offset = bitoffset;
|
||||
ops[numops].i64 = i64;
|
||||
ops[numops].opcode = opcode;
|
||||
@@ -994,12 +1068,18 @@ void bitfieldCommand(client *c) {
|
||||
/* Lookup for read is ok if key doesn't exit, but errors
|
||||
* if it's not a string. */
|
||||
o = lookupKeyRead(c->db,c->argv[1]);
|
||||
if (o != NULL && checkType(c,o,OBJ_STRING)) return;
|
||||
if (o != nullptr && checkType(c,o,OBJ_STRING)) {
|
||||
zfree(ops);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
/* Lookup by making room up to the farest bit reached by
|
||||
* this operation. */
|
||||
if ((o = lookupStringForBitCommand(c,
|
||||
highest_write_offset)) == NULL) return;
|
||||
highest_write_offset)) == nullptr) {
|
||||
zfree(ops);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
addReplyArrayLen(c,numops);
|
||||
@@ -1023,7 +1103,7 @@ void bitfieldCommand(client *c) {
|
||||
int64_t oldval, newval, wrapped, retval;
|
||||
int overflow;
|
||||
|
||||
oldval = getSignedBitfield(ptrFromObj(o),thisop->offset,
|
||||
oldval = getSignedBitfield((unsigned char*)ptrFromObj(o),thisop->offset,
|
||||
thisop->bits);
|
||||
|
||||
if (thisop->opcode == BITFIELDOP_INCRBY) {
|
||||
@@ -1044,7 +1124,7 @@ void bitfieldCommand(client *c) {
|
||||
* NULL to signal the condition. */
|
||||
if (!(overflow && thisop->owtype == BFOVERFLOW_FAIL)) {
|
||||
addReplyLongLong(c,retval);
|
||||
setSignedBitfield(ptrFromObj(o),thisop->offset,
|
||||
setSignedBitfield((unsigned char*)ptrFromObj(o),thisop->offset,
|
||||
thisop->bits,newval);
|
||||
} else {
|
||||
addReplyNull(c);
|
||||
@@ -1053,7 +1133,7 @@ void bitfieldCommand(client *c) {
|
||||
uint64_t oldval, newval, wrapped, retval;
|
||||
int overflow;
|
||||
|
||||
oldval = getUnsignedBitfield(ptrFromObj(o),thisop->offset,
|
||||
oldval = getUnsignedBitfield((unsigned char*)ptrFromObj(o),thisop->offset,
|
||||
thisop->bits);
|
||||
|
||||
if (thisop->opcode == BITFIELDOP_INCRBY) {
|
||||
@@ -1073,7 +1153,7 @@ void bitfieldCommand(client *c) {
|
||||
* NULL to signal the condition. */
|
||||
if (!(overflow && thisop->owtype == BFOVERFLOW_FAIL)) {
|
||||
addReplyLongLong(c,retval);
|
||||
setUnsignedBitfield(ptrFromObj(o),thisop->offset,
|
||||
setUnsignedBitfield((unsigned char*)ptrFromObj(o),thisop->offset,
|
||||
thisop->bits,newval);
|
||||
} else {
|
||||
addReplyNull(c);
|
||||
@@ -1084,10 +1164,10 @@ void bitfieldCommand(client *c) {
|
||||
/* GET */
|
||||
unsigned char buf[9];
|
||||
long strlen = 0;
|
||||
unsigned char *src = NULL;
|
||||
const unsigned char *src = NULL;
|
||||
char llbuf[LONG_STR_SIZE];
|
||||
|
||||
if (o != NULL)
|
||||
if (o != nullptr)
|
||||
src = getObjectReadOnlyString(o,&strlen,llbuf);
|
||||
|
||||
/* For GET we use a trick: before executing the operation
|
||||
@@ -1119,7 +1199,7 @@ void bitfieldCommand(client *c) {
|
||||
if (changes) {
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(NOTIFY_STRING,"setbit",c->argv[1],c->db->id);
|
||||
server.dirty += changes;
|
||||
g_pserver->dirty += changes;
|
||||
}
|
||||
zfree(ops);
|
||||
}
|
||||
@@ -64,6 +64,7 @@
|
||||
*/
|
||||
|
||||
#include "server.h"
|
||||
#include <mutex>
|
||||
|
||||
int serveClientBlockedOnList(client *receiver, robj *key, robj *dstkey, redisDb *db, robj *value, int where);
|
||||
|
||||
@@ -110,8 +111,8 @@ void blockClient(client *c, int btype) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
c->flags |= CLIENT_BLOCKED;
|
||||
c->btype = btype;
|
||||
server.blocked_clients++;
|
||||
server.blocked_clients_by_type[btype]++;
|
||||
g_pserver->blocked_clients++;
|
||||
g_pserver->blocked_clients_by_type[btype]++;
|
||||
}
|
||||
|
||||
/* This function is called in the beforeSleep() function of the event loop
|
||||
@@ -122,13 +123,13 @@ void processUnblockedClients(int iel) {
|
||||
|
||||
listNode *ln;
|
||||
client *c;
|
||||
list *unblocked_clients = server.rgthreadvar[iel].unblocked_clients;
|
||||
serverAssert(iel == (serverTL - server.rgthreadvar));
|
||||
list *unblocked_clients = g_pserver->rgthreadvar[iel].unblocked_clients;
|
||||
serverAssert(iel == (serverTL - g_pserver->rgthreadvar));
|
||||
|
||||
while (listLength(unblocked_clients)) {
|
||||
ln = listFirst(unblocked_clients);
|
||||
serverAssert(ln != NULL);
|
||||
c = ln->value;
|
||||
c = (client*)ln->value;
|
||||
listDelNode(unblocked_clients,ln);
|
||||
AssertCorrectThread(c);
|
||||
|
||||
@@ -171,7 +172,7 @@ void queueClientForReprocessing(client *c) {
|
||||
fastlock_lock(&c->lock);
|
||||
if (!(c->flags & CLIENT_UNBLOCKED)) {
|
||||
c->flags |= CLIENT_UNBLOCKED;
|
||||
listAddNodeTail(server.rgthreadvar[c->iel].unblocked_clients,c);
|
||||
listAddNodeTail(g_pserver->rgthreadvar[c->iel].unblocked_clients,c);
|
||||
}
|
||||
fastlock_unlock(&c->lock);
|
||||
}
|
||||
@@ -180,6 +181,7 @@ void queueClientForReprocessing(client *c) {
|
||||
* of operation the client is blocking for. */
|
||||
void unblockClient(client *c) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
serverAssert(c->lock.fOwnLock());
|
||||
if (c->btype == BLOCKED_LIST ||
|
||||
c->btype == BLOCKED_ZSET ||
|
||||
c->btype == BLOCKED_STREAM) {
|
||||
@@ -193,8 +195,8 @@ void unblockClient(client *c) {
|
||||
}
|
||||
/* Clear the flags, and put the client in the unblocked list so that
|
||||
* we'll process new commands in its query buffer ASAP. */
|
||||
server.blocked_clients--;
|
||||
server.blocked_clients_by_type[c->btype]--;
|
||||
g_pserver->blocked_clients--;
|
||||
g_pserver->blocked_clients_by_type[c->btype]--;
|
||||
c->flags &= ~CLIENT_BLOCKED;
|
||||
c->btype = BLOCKED_NONE;
|
||||
queueClientForReprocessing(c);
|
||||
@@ -219,8 +221,8 @@ void replyToBlockedClientTimedOut(client *c) {
|
||||
|
||||
/* Mass-unblock clients because something changed in the instance that makes
|
||||
* blocking no longer safe. For example clients blocked in list operations
|
||||
* in an instance which turns from master to slave is unsafe, so this function
|
||||
* is called when a master turns into a slave.
|
||||
* in an instance which turns from master to replica is unsafe, so this function
|
||||
* is called when a master turns into a replica.
|
||||
*
|
||||
* The semantics is to send an -UNBLOCKED error to the client, disconnecting
|
||||
* it at the same time. */
|
||||
@@ -229,9 +231,9 @@ void disconnectAllBlockedClients(void) {
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
|
||||
listRewind(server.clients,&li);
|
||||
listRewind(g_pserver->clients,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
client *c = listNodeValue(ln);
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
|
||||
fastlock_lock(&c->lock);
|
||||
if (c->flags & CLIENT_BLOCKED) {
|
||||
@@ -252,7 +254,7 @@ void disconnectAllBlockedClients(void) {
|
||||
*
|
||||
* All the keys with at least one client blocked that received at least
|
||||
* one new element via some write operation are accumulated into
|
||||
* the server.ready_keys list. This function will run the list and will
|
||||
* the g_pserver->ready_keys list. This function will run the list and will
|
||||
* serve clients accordingly. Note that the function will iterate again and
|
||||
* again as a result of serving BRPOPLPUSH we can have new blocking clients
|
||||
* to serve because of the PUSH side of BRPOPLPUSH.
|
||||
@@ -268,19 +270,19 @@ void disconnectAllBlockedClients(void) {
|
||||
* do, the function is already fair. */
|
||||
void handleClientsBlockedOnKeys(void) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
while(listLength(server.ready_keys) != 0) {
|
||||
while(listLength(g_pserver->ready_keys) != 0) {
|
||||
list *l;
|
||||
|
||||
/* Point server.ready_keys to a fresh list and save the current one
|
||||
/* Point g_pserver->ready_keys to a fresh list and save the current one
|
||||
* locally. This way as we run the old list we are free to call
|
||||
* signalKeyAsReady() that may push new elements in server.ready_keys
|
||||
* signalKeyAsReady() that may push new elements in g_pserver->ready_keys
|
||||
* when handling clients blocked into BRPOPLPUSH. */
|
||||
l = server.ready_keys;
|
||||
server.ready_keys = listCreate();
|
||||
l = g_pserver->ready_keys;
|
||||
g_pserver->ready_keys = listCreate();
|
||||
|
||||
while(listLength(l) != 0) {
|
||||
listNode *ln = listFirst(l);
|
||||
readyList *rl = ln->value;
|
||||
readyList *rl = (readyList*)ln->value;
|
||||
|
||||
/* First of all remove this key from db->ready_keys so that
|
||||
* we can safely call signalKeyAsReady() against this key. */
|
||||
@@ -295,12 +297,13 @@ void handleClientsBlockedOnKeys(void) {
|
||||
* this key, from the first blocked to the last. */
|
||||
de = dictFind(rl->db->blocking_keys,rl->key);
|
||||
if (de) {
|
||||
list *clients = dictGetVal(de);
|
||||
list *clients = (list*)dictGetVal(de);
|
||||
int numclients = listLength(clients);
|
||||
|
||||
while(numclients--) {
|
||||
listNode *clientnode = listFirst(clients);
|
||||
client *receiver = clientnode->value;
|
||||
client *receiver = (client*)clientnode->value;
|
||||
std::unique_lock<decltype(client::lock)> lock(receiver->lock);
|
||||
|
||||
if (receiver->btype != BLOCKED_LIST) {
|
||||
/* Put at the tail, so that at the next call
|
||||
@@ -358,13 +361,13 @@ void handleClientsBlockedOnKeys(void) {
|
||||
* this key, from the first blocked to the last. */
|
||||
de = dictFind(rl->db->blocking_keys,rl->key);
|
||||
if (de) {
|
||||
list *clients = dictGetVal(de);
|
||||
list *clients = (list*)dictGetVal(de);
|
||||
int numclients = listLength(clients);
|
||||
unsigned long zcard = zsetLength(o);
|
||||
|
||||
while(numclients-- && zcard) {
|
||||
listNode *clientnode = listFirst(clients);
|
||||
client *receiver = clientnode->value;
|
||||
client *receiver = (client*)clientnode->value;
|
||||
|
||||
if (receiver->btype != BLOCKED_ZSET) {
|
||||
/* Put at the tail, so that at the next call
|
||||
@@ -385,8 +388,8 @@ void handleClientsBlockedOnKeys(void) {
|
||||
/* Replicate the command. */
|
||||
robj *argv[2];
|
||||
struct redisCommand *cmd = where == ZSET_MIN ?
|
||||
server.zpopminCommand :
|
||||
server.zpopmaxCommand;
|
||||
cserver.zpopminCommand :
|
||||
cserver.zpopmaxCommand;
|
||||
argv[0] = createStringObject(cmd->name,strlen(cmd->name));
|
||||
argv[1] = rl->key;
|
||||
incrRefCount(rl->key);
|
||||
@@ -402,21 +405,21 @@ void handleClientsBlockedOnKeys(void) {
|
||||
/* Serve clients blocked on stream key. */
|
||||
else if (o != NULL && o->type == OBJ_STREAM) {
|
||||
dictEntry *de = dictFind(rl->db->blocking_keys,rl->key);
|
||||
stream *s = ptrFromObj(o);
|
||||
stream *s = (stream*)ptrFromObj(o);
|
||||
|
||||
/* We need to provide the new data arrived on the stream
|
||||
* to all the clients that are waiting for an offset smaller
|
||||
* than the current top item. */
|
||||
if (de) {
|
||||
list *clients = dictGetVal(de);
|
||||
list *clients = (list*)dictGetVal(de);
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
listRewind(clients,&li);
|
||||
|
||||
while((ln = listNext(&li))) {
|
||||
client *receiver = listNodeValue(ln);
|
||||
client *receiver = (client*)listNodeValue(ln);
|
||||
if (receiver->btype != BLOCKED_STREAM) continue;
|
||||
streamID *gt = dictFetchValue(receiver->bpop.keys,
|
||||
streamID *gt = (streamID*)dictFetchValue(receiver->bpop.keys,
|
||||
rl->key);
|
||||
|
||||
/* If we blocked in the context of a consumer
|
||||
@@ -431,7 +434,7 @@ void handleClientsBlockedOnKeys(void) {
|
||||
streamCG *group = NULL;
|
||||
if (receiver->bpop.xread_group) {
|
||||
group = streamLookupCG(s,
|
||||
ptrFromObj(receiver->bpop.xread_group));
|
||||
szFromObj(receiver->bpop.xread_group));
|
||||
/* If the group was not found, send an error
|
||||
* to the consumer. */
|
||||
if (!group) {
|
||||
@@ -457,7 +460,7 @@ void handleClientsBlockedOnKeys(void) {
|
||||
|
||||
if (group) {
|
||||
consumer = streamLookupConsumer(group,
|
||||
ptrFromObj(receiver->bpop.xread_consumer),
|
||||
szFromObj(receiver->bpop.xread_consumer),
|
||||
1);
|
||||
noack = receiver->bpop.xread_group_noack;
|
||||
}
|
||||
@@ -568,7 +571,7 @@ void blockForKeys(client *c, int btype, robj **keys, int numkeys, mstime_t timeo
|
||||
incrRefCount(keys[j]);
|
||||
serverAssertWithInfo(c,keys[j],retval == DICT_OK);
|
||||
} else {
|
||||
l = dictGetVal(de);
|
||||
l = (list*)dictGetVal(de);
|
||||
}
|
||||
listAddNodeTail(l,c);
|
||||
}
|
||||
@@ -586,10 +589,10 @@ void unblockClientWaitingData(client *c) {
|
||||
di = dictGetIterator(c->bpop.keys);
|
||||
/* The client may wait for multiple keys, so unblock it for every key. */
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
robj *key = dictGetKey(de);
|
||||
robj *key = (robj*)dictGetKey(de);
|
||||
|
||||
/* Remove this client from the list of clients waiting for this key. */
|
||||
l = dictFetchValue(c->db->blocking_keys,key);
|
||||
l = (list*)dictFetchValue(c->db->blocking_keys,key);
|
||||
serverAssertWithInfo(c,key,l != NULL);
|
||||
listDelNode(l,listSearchKey(l,c));
|
||||
/* If the list is empty we need to remove it to avoid wasting memory */
|
||||
@@ -613,7 +616,7 @@ void unblockClientWaitingData(client *c) {
|
||||
}
|
||||
|
||||
/* If the specified key has clients blocked waiting for list pushes, this
|
||||
* function will put the key reference into the server.ready_keys list.
|
||||
* function will put the key reference into the g_pserver->ready_keys list.
|
||||
* Note that db->ready_keys is a hash table that allows us to avoid putting
|
||||
* the same key again and again in the list in case of multiple pushes
|
||||
* made by a script or in the context of MULTI/EXEC.
|
||||
@@ -628,12 +631,12 @@ void signalKeyAsReady(redisDb *db, robj *key) {
|
||||
/* Key was already signaled? No need to queue it again. */
|
||||
if (dictFind(db->ready_keys,key) != NULL) return;
|
||||
|
||||
/* Ok, we need to queue this key into server.ready_keys. */
|
||||
rl = zmalloc(sizeof(*rl), MALLOC_SHARED);
|
||||
/* Ok, we need to queue this key into g_pserver->ready_keys. */
|
||||
rl = (readyList*)zmalloc(sizeof(*rl), MALLOC_SHARED);
|
||||
rl->key = key;
|
||||
rl->db = db;
|
||||
incrRefCount(key);
|
||||
listAddNodeTail(server.ready_keys,rl);
|
||||
listAddNodeTail(g_pserver->ready_keys,rl);
|
||||
|
||||
/* We also add the key in the db->ready_keys dictionary in order
|
||||
* to avoid adding it multiple times into a list with a simple O(1)
|
||||
@@ -34,52 +34,52 @@
|
||||
* RDB / AOF saving process from the child to the parent (for instance
|
||||
* the amount of copy on write memory used) */
|
||||
void openChildInfoPipe(void) {
|
||||
if (pipe(server.child_info_pipe) == -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 cloesChildInfoPipe() since can't hurt. */
|
||||
closeChildInfoPipe();
|
||||
} else if (anetNonBlock(NULL,server.child_info_pipe[0]) != ANET_OK) {
|
||||
} else if (anetNonBlock(NULL,g_pserver->child_info_pipe[0]) != ANET_OK) {
|
||||
closeChildInfoPipe();
|
||||
} else {
|
||||
memset(&server.child_info_data,0,sizeof(server.child_info_data));
|
||||
memset(&g_pserver->child_info_data,0,sizeof(g_pserver->child_info_data));
|
||||
}
|
||||
}
|
||||
|
||||
/* Close the pipes opened with openChildInfoPipe(). */
|
||||
void closeChildInfoPipe(void) {
|
||||
if (server.child_info_pipe[0] != -1 ||
|
||||
server.child_info_pipe[1] != -1)
|
||||
if (g_pserver->child_info_pipe[0] != -1 ||
|
||||
g_pserver->child_info_pipe[1] != -1)
|
||||
{
|
||||
close(server.child_info_pipe[0]);
|
||||
close(server.child_info_pipe[1]);
|
||||
server.child_info_pipe[0] = -1;
|
||||
server.child_info_pipe[1] = -1;
|
||||
close(g_pserver->child_info_pipe[0]);
|
||||
close(g_pserver->child_info_pipe[1]);
|
||||
g_pserver->child_info_pipe[0] = -1;
|
||||
g_pserver->child_info_pipe[1] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Send COW data to parent. The child should call this function after populating
|
||||
* the corresponding fields it want to sent (according to the process type). */
|
||||
void sendChildInfo(int ptype) {
|
||||
if (server.child_info_pipe[1] == -1) return;
|
||||
server.child_info_data.magic = CHILD_INFO_MAGIC;
|
||||
server.child_info_data.process_type = ptype;
|
||||
ssize_t wlen = sizeof(server.child_info_data);
|
||||
if (write(server.child_info_pipe[1],&server.child_info_data,wlen) != wlen) {
|
||||
if (g_pserver->child_info_pipe[1] == -1) return;
|
||||
g_pserver->child_info_data.magic = CHILD_INFO_MAGIC;
|
||||
g_pserver->child_info_data.process_type = ptype;
|
||||
ssize_t wlen = sizeof(g_pserver->child_info_data);
|
||||
if (write(g_pserver->child_info_pipe[1],&g_pserver->child_info_data,wlen) != wlen) {
|
||||
/* Nothing to do on error, this will be detected by the other side. */
|
||||
}
|
||||
}
|
||||
|
||||
/* Receive COW data from parent. */
|
||||
void receiveChildInfo(void) {
|
||||
if (server.child_info_pipe[0] == -1) return;
|
||||
ssize_t wlen = sizeof(server.child_info_data);
|
||||
if (read(server.child_info_pipe[0],&server.child_info_data,wlen) == wlen &&
|
||||
server.child_info_data.magic == CHILD_INFO_MAGIC)
|
||||
if (g_pserver->child_info_pipe[0] == -1) return;
|
||||
ssize_t wlen = sizeof(g_pserver->child_info_data);
|
||||
if (read(g_pserver->child_info_pipe[0],&g_pserver->child_info_data,wlen) == wlen &&
|
||||
g_pserver->child_info_data.magic == CHILD_INFO_MAGIC)
|
||||
{
|
||||
if (server.child_info_data.process_type == CHILD_INFO_TYPE_RDB) {
|
||||
server.stat_rdb_cow_bytes = server.child_info_data.cow_size;
|
||||
} else if (server.child_info_data.process_type == CHILD_INFO_TYPE_AOF) {
|
||||
server.stat_aof_cow_bytes = server.child_info_data.cow_size;
|
||||
if (g_pserver->child_info_data.process_type == CHILD_INFO_TYPE_RDB) {
|
||||
g_pserver->stat_rdb_cow_bytes = g_pserver->child_info_data.cow_size;
|
||||
} else if (g_pserver->child_info_data.process_type == CHILD_INFO_TYPE_AOF) {
|
||||
g_pserver->stat_aof_cow_bytes = g_pserver->child_info_data.cow_size;
|
||||
}
|
||||
}
|
||||
}
|
||||
+591
-522
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
||||
#pragma once
|
||||
|
||||
#include <type_traits>
|
||||
#include <assert.h>
|
||||
|
||||
/*************************************************
|
||||
* compactvector - similar to std::vector but optimized for minimal memory
|
||||
*
|
||||
* Notable differences:
|
||||
* - Limited to 2^32 elements
|
||||
* - Grows linearly not exponentially
|
||||
*
|
||||
*************************************************/
|
||||
|
||||
template<typename T, bool MEMMOVE_SAFE=false>
|
||||
class compactvector
|
||||
{
|
||||
static_assert(MEMMOVE_SAFE || std::is_trivially_copyable<T>::value, "compactvector requires trivially copyable types");
|
||||
T *m_data = nullptr;
|
||||
unsigned m_celem = 0;
|
||||
unsigned m_max = 0;
|
||||
|
||||
public:
|
||||
typedef T* iterator;
|
||||
|
||||
compactvector() noexcept = default;
|
||||
~compactvector() noexcept
|
||||
{
|
||||
clear(); // call dtors
|
||||
zfree(m_data);
|
||||
}
|
||||
|
||||
compactvector(compactvector &) noexcept = delete;
|
||||
|
||||
compactvector(compactvector &&src) noexcept
|
||||
{
|
||||
m_data = src.m_data;
|
||||
m_celem = src.m_celem;
|
||||
m_max = src.m_max;
|
||||
src.m_data = nullptr;
|
||||
src.m_celem = 0;
|
||||
src.m_max = 0;
|
||||
}
|
||||
|
||||
compactvector &operator=(const compactvector&) noexcept = delete;
|
||||
compactvector &operator=(compactvector &&src) noexcept
|
||||
{
|
||||
zfree(m_data);
|
||||
m_data = src.m_data;
|
||||
m_celem = src.m_celem;
|
||||
m_max = src.m_max;
|
||||
src.m_data = nullptr;
|
||||
src.m_celem = 0;
|
||||
src.m_max = 0;
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline T* begin() { return m_data; }
|
||||
inline const T* begin() const { return m_data; }
|
||||
|
||||
inline T* end() { return m_data + m_celem; }
|
||||
inline const T* end() const { return m_data + m_celem; }
|
||||
|
||||
T* insert(T* where, T &val)
|
||||
{
|
||||
assert(where >= m_data);
|
||||
size_t idx = where - m_data;
|
||||
if (m_celem >= m_max)
|
||||
{
|
||||
if (m_max < 2)
|
||||
m_max = 2;
|
||||
else
|
||||
m_max = m_max + 4;
|
||||
|
||||
m_data = (T*)zrealloc(m_data, sizeof(T) * m_max, MALLOC_LOCAL);
|
||||
m_max = zmalloc_usable(m_data) / sizeof(T);
|
||||
}
|
||||
assert(idx < m_max);
|
||||
where = m_data + idx;
|
||||
memmove(reinterpret_cast<void*>(m_data + idx + 1), reinterpret_cast<const void*>(m_data + idx), (m_celem - idx)*sizeof(T));
|
||||
new(m_data + idx) T(std::move(val));
|
||||
++m_celem;
|
||||
return where;
|
||||
}
|
||||
|
||||
T &operator[](size_t idx)
|
||||
{
|
||||
assert(idx < m_celem);
|
||||
return m_data[idx];
|
||||
}
|
||||
const T &operator[](size_t idx) const
|
||||
{
|
||||
assert(idx < m_celem);
|
||||
return m_data[idx];
|
||||
}
|
||||
|
||||
T& back() { assert(m_celem > 0); return m_data[m_celem-1]; }
|
||||
const T& back() const { assert(m_celem > 0); return m_data[m_celem-1]; }
|
||||
|
||||
void erase(T* where)
|
||||
{
|
||||
assert(where >= m_data);
|
||||
size_t idx = where - m_data;
|
||||
assert(idx < m_celem);
|
||||
where->~T();
|
||||
memmove(reinterpret_cast<void*>(where), reinterpret_cast<const void*>(where+1), ((m_celem - idx - 1)*sizeof(T)));
|
||||
--m_celem;
|
||||
|
||||
if (m_celem == 0)
|
||||
{
|
||||
zfree(m_data);
|
||||
m_data = nullptr;
|
||||
m_max = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void shrink_to_fit()
|
||||
{
|
||||
if (m_max == m_celem)
|
||||
return;
|
||||
m_data = (T*)zrealloc(m_data, sizeof(T) * m_celem, MALLOC_LOCAL);
|
||||
m_max = m_celem; // NOTE: We do not get the usable size here, because this could cause us to continually realloc
|
||||
}
|
||||
|
||||
size_t bytes_used() const
|
||||
{
|
||||
return sizeof(this) + (m_max * sizeof(T));
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
for (size_t idx = 0; idx < m_celem; ++idx)
|
||||
m_data[idx].~T();
|
||||
zfree(m_data);
|
||||
m_data = nullptr;
|
||||
m_celem = 0;
|
||||
m_max = 0;
|
||||
}
|
||||
|
||||
bool empty() const noexcept
|
||||
{
|
||||
return m_celem == 0;
|
||||
}
|
||||
|
||||
size_t size() const noexcept
|
||||
{
|
||||
return m_celem;
|
||||
}
|
||||
|
||||
T* data() noexcept { return m_data; }
|
||||
const T* data() const noexcept { return m_data; }
|
||||
};
|
||||
static_assert(sizeof(compactvector<void*>) <= 16, "not compact");
|
||||
+607
-748
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -1,5 +1,3 @@
|
||||
#include "server.h"
|
||||
|
||||
/*
|
||||
* Copyright 2001-2010 Georges Menie (www.menie.org)
|
||||
* Copyright 2010-2012 Salvatore Sanfilippo (adapted to Redis coding style)
|
||||
@@ -29,6 +27,8 @@
|
||||
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
/* CRC16 implementation according to CCITT standards.
|
||||
*
|
||||
* Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the
|
||||
|
||||
+480
-213
File diff suppressed because it is too large.
Load diff
+182
-114
@@ -27,6 +27,7 @@
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#define NO_DEPRECATE_FREE 1 // we are required to call the real free() in this CU
|
||||
#include "server.h"
|
||||
#include "sha1.h" /* SHA1 is used for DEBUG DIGEST */
|
||||
#include "crc64.h"
|
||||
@@ -45,6 +46,7 @@ typedef ucontext_t sigcontext_t;
|
||||
#include <fcntl.h>
|
||||
#include "bio.h"
|
||||
#include <unistd.h>
|
||||
#include <cxxabi.h>
|
||||
#endif /* HAVE_BACKTRACE */
|
||||
|
||||
#ifdef __CYGWIN__
|
||||
@@ -53,6 +55,8 @@ typedef ucontext_t sigcontext_t;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
int g_fInCrash = false;
|
||||
|
||||
/* ================================= Debugging ============================== */
|
||||
|
||||
/* Compute the sha1 of string at 's' with 'len' bytes long.
|
||||
@@ -61,9 +65,10 @@ typedef ucontext_t sigcontext_t;
|
||||
* "add" digests relative to unordered elements.
|
||||
*
|
||||
* So digest(a,b,c,d) will be the same of digest(b,a,c,d) */
|
||||
void xorDigest(unsigned char *digest, void *ptr, size_t len) {
|
||||
void xorDigest(unsigned char *digest, const void *ptr, size_t len) {
|
||||
SHA1_CTX ctx;
|
||||
unsigned char hash[20], *s = ptr;
|
||||
unsigned char hash[20];
|
||||
const unsigned char *s = (const unsigned char*)ptr;
|
||||
int j;
|
||||
|
||||
SHA1Init(&ctx);
|
||||
@@ -76,7 +81,7 @@ void xorDigest(unsigned char *digest, void *ptr, size_t len) {
|
||||
|
||||
void xorStringObjectDigest(unsigned char *digest, robj *o) {
|
||||
o = getDecodedObject(o);
|
||||
xorDigest(digest,ptrFromObj(o),sdslen(ptrFromObj(o)));
|
||||
xorDigest(digest,(const unsigned char*)ptrFromObj(o),sdslen(szFromObj(o)));
|
||||
decrRefCount(o);
|
||||
}
|
||||
|
||||
@@ -94,9 +99,9 @@ void xorStringObjectDigest(unsigned char *digest, robj *o) {
|
||||
* Also note that mixdigest("foo") followed by mixdigest("bar")
|
||||
* will lead to a different digest compared to "fo", "obar".
|
||||
*/
|
||||
void mixDigest(unsigned char *digest, void *ptr, size_t len) {
|
||||
void mixDigest(unsigned char *digest, const void *ptr, size_t len) {
|
||||
SHA1_CTX ctx;
|
||||
char *s = ptr;
|
||||
const char *s = (const char*)ptr;
|
||||
|
||||
xorDigest(digest,s,len);
|
||||
SHA1Init(&ctx);
|
||||
@@ -104,9 +109,9 @@ void mixDigest(unsigned char *digest, void *ptr, size_t len) {
|
||||
SHA1Final(digest,&ctx);
|
||||
}
|
||||
|
||||
void mixStringObjectDigest(unsigned char *digest, robj *o) {
|
||||
void mixStringObjectDigest(unsigned char *digest, robj_roptr o) {
|
||||
o = getDecodedObject(o);
|
||||
mixDigest(digest,ptrFromObj(o),sdslen(ptrFromObj(o)));
|
||||
mixDigest(digest,ptrFromObj(o),sdslen(szFromObj(o)));
|
||||
decrRefCount(o);
|
||||
}
|
||||
|
||||
@@ -118,12 +123,16 @@ void mixStringObjectDigest(unsigned char *digest, robj *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(redisDb *db, robj *keyobj, unsigned char *digest, robj *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));
|
||||
long long expiretime = getExpire(db,keyobj);
|
||||
expireEntry *pexpire = getExpire(db,keyobj);
|
||||
long long expiretime = -1;
|
||||
char buf[128];
|
||||
|
||||
if (pexpire != nullptr)
|
||||
pexpire->FGetPrimaryExpire(&expiretime);
|
||||
|
||||
/* Save the key and associated value */
|
||||
if (o->type == OBJ_STRING) {
|
||||
mixStringObjectDigest(digest,o);
|
||||
@@ -148,7 +157,7 @@ void xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o)
|
||||
unsigned char eledigest[20];
|
||||
|
||||
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
unsigned char *zl = ptrFromObj(o);
|
||||
unsigned char *zl = (unsigned char*)ptrFromObj(o);
|
||||
unsigned char *eptr, *sptr;
|
||||
unsigned char *vstr;
|
||||
unsigned int vlen;
|
||||
@@ -178,13 +187,13 @@ void xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o)
|
||||
zzlNext(zl,&eptr,&sptr);
|
||||
}
|
||||
} else if (o->encoding == OBJ_ENCODING_SKIPLIST) {
|
||||
zset *zs = ptrFromObj(o);
|
||||
zset *zs = (zset*)ptrFromObj(o);
|
||||
dictIterator *di = dictGetIterator(zs->pdict);
|
||||
dictEntry *de;
|
||||
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sds sdsele = dictGetKey(de);
|
||||
double *score = dictGetVal(de);
|
||||
sds sdsele = (sds)dictGetKey(de);
|
||||
double *score = (double*)dictGetVal(de);
|
||||
|
||||
snprintf(buf,sizeof(buf),"%.17g",*score);
|
||||
memset(eledigest,0,20);
|
||||
@@ -214,7 +223,7 @@ void xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o)
|
||||
hashTypeReleaseIterator(hi);
|
||||
} else if (o->type == OBJ_STREAM) {
|
||||
streamIterator si;
|
||||
streamIteratorStart(&si,ptrFromObj(o),NULL,NULL,0);
|
||||
streamIteratorStart(&si,(stream*)ptrFromObj(o),NULL,NULL,0);
|
||||
streamID id;
|
||||
int64_t numfields;
|
||||
|
||||
@@ -235,7 +244,7 @@ void xorObjectDigest(redisDb *db, robj *keyobj, unsigned char *digest, robj *o)
|
||||
streamIteratorStop(&si);
|
||||
} else if (o->type == OBJ_MODULE) {
|
||||
RedisModuleDigest md;
|
||||
moduleValue *mv = ptrFromObj(o);
|
||||
moduleValue *mv = (moduleValue*)ptrFromObj(o);
|
||||
moduleType *mt = mv->type;
|
||||
moduleInitDigestContext(md);
|
||||
if (mt->digest) {
|
||||
@@ -264,8 +273,8 @@ void computeDatasetDigest(unsigned char *final) {
|
||||
|
||||
memset(final,0,20); /* Start with a clean result */
|
||||
|
||||
for (j = 0; j < server.dbnum; j++) {
|
||||
redisDb *db = server.db+j;
|
||||
for (j = 0; j < cserver.dbnum; j++) {
|
||||
redisDb *db = g_pserver->db+j;
|
||||
|
||||
if (dictSize(db->pdict) == 0) continue;
|
||||
di = dictGetSafeIterator(db->pdict);
|
||||
@@ -281,12 +290,12 @@ void computeDatasetDigest(unsigned char *final) {
|
||||
robj *keyobj, *o;
|
||||
|
||||
memset(digest,0,20); /* This key-val digest */
|
||||
key = dictGetKey(de);
|
||||
key = (sds)dictGetKey(de);
|
||||
keyobj = createStringObject(key,sdslen(key));
|
||||
|
||||
mixDigest(digest,key,sdslen(key));
|
||||
|
||||
o = dictGetVal(de);
|
||||
o = (robj*)dictGetVal(de);
|
||||
xorObjectDigest(db,keyobj,digest,o);
|
||||
|
||||
/* We can finally xor the key-val digest to the final digest */
|
||||
@@ -298,7 +307,7 @@ void computeDatasetDigest(unsigned char *final) {
|
||||
}
|
||||
|
||||
void debugCommand(client *c) {
|
||||
if (c->argc == 2 && !strcasecmp(ptrFromObj(c->argv[1]),"help")) {
|
||||
if (c->argc == 2 && !strcasecmp(szFromObj(c->argv[1]),"help")) {
|
||||
const char *help[] = {
|
||||
"ASSERT -- Crash by assertion failed.",
|
||||
"CHANGE-REPL-ID -- Change the replication IDs of the instance. Dangerous, should be used only for testing the replication subsystem.",
|
||||
@@ -326,12 +335,12 @@ void debugCommand(client *c) {
|
||||
NULL
|
||||
};
|
||||
addReplyHelp(c, help);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"segfault")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"segfault")) {
|
||||
*((char*)-1) = 'x';
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"panic")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"panic")) {
|
||||
serverPanic("DEBUG PANIC called at Unix time %ld", time(NULL));
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"restart") ||
|
||||
!strcasecmp(ptrFromObj(c->argv[1]),"crash-and-recover"))
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"restart") ||
|
||||
!strcasecmp(szFromObj(c->argv[1]),"crash-and-recover"))
|
||||
{
|
||||
long long delay = 0;
|
||||
if (c->argc >= 3) {
|
||||
@@ -339,21 +348,21 @@ NULL
|
||||
!= C_OK) return;
|
||||
if (delay < 0) delay = 0;
|
||||
}
|
||||
int flags = !strcasecmp(ptrFromObj(c->argv[1]),"restart") ?
|
||||
int flags = !strcasecmp(szFromObj(c->argv[1]),"restart") ?
|
||||
(RESTART_SERVER_GRACEFULLY|RESTART_SERVER_CONFIG_REWRITE) :
|
||||
RESTART_SERVER_NONE;
|
||||
restartServer(flags,delay);
|
||||
addReplyError(c,"failed to restart the server. Check server logs.");
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"oom")) {
|
||||
addReplyError(c,"failed to restart the g_pserver-> Check server logs.");
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"oom")) {
|
||||
void *ptr = zmalloc(ULONG_MAX, MALLOC_LOCAL); /* Should trigger an out of memory. */
|
||||
zfree(ptr);
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"assert")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"assert")) {
|
||||
serverAssertWithInfo(c,c->argv[0],1 == 2);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"log") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"log") && c->argc == 3) {
|
||||
serverLog(LL_WARNING, "DEBUG LOG: %s", (char*)ptrFromObj(c->argv[2]));
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"reload")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"reload")) {
|
||||
rdbSaveInfo rsi, *rsiptr;
|
||||
rsiptr = rdbPopulateSaveInfo(&rsi);
|
||||
if (rdbSave(rsiptr) != C_OK) {
|
||||
@@ -362,7 +371,8 @@ NULL
|
||||
}
|
||||
emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
|
||||
protectClient(c);
|
||||
int ret = rdbLoad(NULL);
|
||||
rdbSaveInfo rsiDft = RDB_SAVE_INFO_INIT;
|
||||
int ret = rdbLoad(&rsiDft);
|
||||
unprotectClient(c);
|
||||
if (ret != C_OK) {
|
||||
addReplyError(c,"Error trying to load the RDB dump");
|
||||
@@ -370,36 +380,36 @@ NULL
|
||||
}
|
||||
serverLog(LL_WARNING,"DB reloaded by DEBUG RELOAD");
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"loadaof")) {
|
||||
if (server.aof_state != AOF_OFF) flushAppendOnlyFile(1);
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"loadaof")) {
|
||||
if (g_pserver->aof_state != AOF_OFF) flushAppendOnlyFile(1);
|
||||
emptyDb(-1,EMPTYDB_NO_FLAGS,NULL);
|
||||
protectClient(c);
|
||||
int ret = loadAppendOnlyFile(server.aof_filename);
|
||||
int ret = loadAppendOnlyFile(g_pserver->aof_filename);
|
||||
unprotectClient(c);
|
||||
if (ret != C_OK) {
|
||||
addReply(c,shared.err);
|
||||
return;
|
||||
}
|
||||
server.dirty = 0; /* Prevent AOF / replication */
|
||||
g_pserver->dirty = 0; /* Prevent AOF / replication */
|
||||
serverLog(LL_WARNING,"Append Only File loaded by DEBUG LOADAOF");
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"object") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"object") && c->argc == 3) {
|
||||
dictEntry *de;
|
||||
robj *val;
|
||||
char *strenc;
|
||||
const char *strenc;
|
||||
|
||||
if ((de = dictFind(c->db->pdict,ptrFromObj(c->argv[2]))) == NULL) {
|
||||
addReply(c,shared.nokeyerr);
|
||||
return;
|
||||
}
|
||||
val = dictGetVal(de);
|
||||
val = (robj*)dictGetVal(de);
|
||||
strenc = strEncoding(val->encoding);
|
||||
|
||||
char extra[138] = {0};
|
||||
if (val->encoding == OBJ_ENCODING_QUICKLIST) {
|
||||
char *nextra = extra;
|
||||
int remaining = sizeof(extra);
|
||||
quicklist *ql = val->m_ptr;
|
||||
quicklist *ql = (quicklist*)val->m_ptr;
|
||||
/* Add number of quicklist nodes */
|
||||
int used = snprintf(nextra, remaining, " ql_nodes:%lu", ql->len);
|
||||
nextra += used;
|
||||
@@ -432,10 +442,10 @@ NULL
|
||||
"Value at:%p refcount:%d "
|
||||
"encoding:%s serializedlength:%zu "
|
||||
"lru:%d lru_seconds_idle:%llu%s",
|
||||
(void*)val, val->refcount,
|
||||
(void*)val, static_cast<int>(val->getrefcount(std::memory_order_relaxed)),
|
||||
strenc, rdbSavedObjectLen(val),
|
||||
val->lru, estimateObjectIdleTime(val)/1000, extra);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"sdslen") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"sdslen") && c->argc == 3) {
|
||||
dictEntry *de;
|
||||
robj *val;
|
||||
sds key;
|
||||
@@ -444,8 +454,8 @@ NULL
|
||||
addReply(c,shared.nokeyerr);
|
||||
return;
|
||||
}
|
||||
val = dictGetVal(de);
|
||||
key = dictGetKey(de);
|
||||
val = (robj*)dictGetVal(de);
|
||||
key = (sds)dictGetKey(de);
|
||||
|
||||
if (val->type != OBJ_STRING || !sdsEncodedObject(val)) {
|
||||
addReplyError(c,"Not an sds encoded string.");
|
||||
@@ -456,11 +466,11 @@ NULL
|
||||
(long long) sdslen(key),
|
||||
(long long) sdsavail(key),
|
||||
(long long) sdsZmallocSize(key),
|
||||
(long long) sdslen(ptrFromObj(val)),
|
||||
(long long) sdsavail(ptrFromObj(val)),
|
||||
(long long) sdslen(szFromObj(val)),
|
||||
(long long) sdsavail(szFromObj(val)),
|
||||
(long long) getStringObjectSdsUsedMemory(val));
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"ziplist") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"ziplist") && c->argc == 3) {
|
||||
robj *o;
|
||||
|
||||
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.nokeyerr))
|
||||
@@ -469,10 +479,10 @@ NULL
|
||||
if (o->encoding != OBJ_ENCODING_ZIPLIST) {
|
||||
addReplyError(c,"Not an sds encoded string.");
|
||||
} else {
|
||||
ziplistRepr(ptrFromObj(o));
|
||||
ziplistRepr((unsigned char*)ptrFromObj(o));
|
||||
addReplyStatus(c,"Ziplist structure printed on stdout");
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"populate") &&
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"populate") &&
|
||||
c->argc >= 3 && c->argc <= 5) {
|
||||
long keys, j;
|
||||
robj *key, *val;
|
||||
@@ -506,7 +516,7 @@ NULL
|
||||
decrRefCount(key);
|
||||
}
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"digest") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"digest") && c->argc == 2) {
|
||||
/* DEBUG DIGEST (form without keys specified) */
|
||||
unsigned char digest[20];
|
||||
sds d = sdsempty();
|
||||
@@ -515,13 +525,13 @@ NULL
|
||||
for (int i = 0; i < 20; i++) d = sdscatprintf(d, "%02x",digest[i]);
|
||||
addReplyStatus(c,d);
|
||||
sdsfree(d);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"digest-value") && c->argc >= 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"digest-value") && c->argc >= 2) {
|
||||
/* DEBUG DIGEST-VALUE key key key ... key. */
|
||||
addReplyArrayLen(c,c->argc-2);
|
||||
for (int j = 2; j < c->argc; j++) {
|
||||
unsigned char digest[20];
|
||||
memset(digest,0,20); /* Start with a clean result */
|
||||
robj *o = lookupKeyReadWithFlags(c->db,c->argv[j],LOOKUP_NOTOUCH);
|
||||
robj_roptr o = lookupKeyReadWithFlags(c->db,c->argv[j],LOOKUP_NOTOUCH);
|
||||
if (o) xorObjectDigest(c->db,c->argv[j],digest,o);
|
||||
|
||||
sds d = sdsempty();
|
||||
@@ -529,10 +539,10 @@ NULL
|
||||
addReplyStatus(c,d);
|
||||
sdsfree(d);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"protocol") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"protocol") && c->argc == 3) {
|
||||
/* DEBUG PROTOCOL [string|integer|double|bignum|null|array|set|map|
|
||||
* attrib|push|verbatim|true|false|state|err|bloberr] */
|
||||
char *name = ptrFromObj(c->argv[2]);
|
||||
char *name = szFromObj(c->argv[2]);
|
||||
if (!strcasecmp(name,"string")) {
|
||||
addReplyBulkCString(c,"Hello World");
|
||||
} else if (!strcasecmp(name,"integer")) {
|
||||
@@ -581,8 +591,8 @@ NULL
|
||||
} else {
|
||||
addReplyError(c,"Wrong protocol type name. Please use one of the following: string|integer|double|bignum|null|array|set|map|attrib|push|verbatim|true|false|state|err|bloberr");
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"sleep") && c->argc == 3) {
|
||||
double dtime = strtod(ptrFromObj(c->argv[2]),NULL);
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"sleep") && c->argc == 3) {
|
||||
double dtime = strtod(szFromObj(c->argv[2]),NULL);
|
||||
long long utime = dtime*1000000;
|
||||
struct timespec tv;
|
||||
|
||||
@@ -590,24 +600,24 @@ NULL
|
||||
tv.tv_nsec = (utime % 1000000) * 1000;
|
||||
nanosleep(&tv, NULL);
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"set-active-expire") &&
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"set-active-expire") &&
|
||||
c->argc == 3)
|
||||
{
|
||||
server.active_expire_enabled = atoi(ptrFromObj(c->argv[2]));
|
||||
g_pserver->active_expire_enabled = atoi(szFromObj(c->argv[2]));
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"lua-always-replicate-commands") &&
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"lua-always-replicate-commands") &&
|
||||
c->argc == 3)
|
||||
{
|
||||
server.lua_always_replicate_commands = atoi(ptrFromObj(c->argv[2]));
|
||||
g_pserver->lua_always_replicate_commands = atoi(szFromObj(c->argv[2]));
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"error") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"error") && c->argc == 3) {
|
||||
sds errstr = sdsnewlen("-",1);
|
||||
|
||||
errstr = sdscatsds(errstr,ptrFromObj(c->argv[2]));
|
||||
errstr = sdscatsds(errstr,szFromObj(c->argv[2]));
|
||||
errstr = sdsmapchars(errstr,"\n\r"," ",2); /* no newlines in errors. */
|
||||
errstr = sdscatlen(errstr,"\r\n",2);
|
||||
addReplySds(c,errstr);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"structsize") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"structsize") && c->argc == 2) {
|
||||
sds sizes = sdsempty();
|
||||
sizes = sdscatprintf(sizes,"bits:%d ",(sizeof(void*) == 8)?64:32);
|
||||
sizes = sdscatprintf(sizes,"robj:%d ",(int)sizeof(robj));
|
||||
@@ -618,28 +628,28 @@ NULL
|
||||
sizes = sdscatprintf(sizes,"sdshdr32:%d ",(int)sizeof(struct sdshdr32));
|
||||
sizes = sdscatprintf(sizes,"sdshdr64:%d ",(int)sizeof(struct sdshdr64));
|
||||
addReplyBulkSds(c,sizes);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"htstats") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"htstats") && c->argc == 3) {
|
||||
long dbid;
|
||||
sds stats = sdsempty();
|
||||
char buf[4096];
|
||||
|
||||
if (getLongFromObjectOrReply(c, c->argv[2], &dbid, NULL) != C_OK)
|
||||
return;
|
||||
if (dbid < 0 || dbid >= server.dbnum) {
|
||||
if (dbid < 0 || dbid >= cserver.dbnum) {
|
||||
addReplyError(c,"Out of range database");
|
||||
return;
|
||||
}
|
||||
|
||||
stats = sdscatprintf(stats,"[Dictionary HT]\n");
|
||||
dictGetStats(buf,sizeof(buf),server.db[dbid].pdict);
|
||||
dictGetStats(buf,sizeof(buf),g_pserver->db[dbid].pdict);
|
||||
stats = sdscat(stats,buf);
|
||||
|
||||
stats = sdscatprintf(stats,"[Expires HT]\n");
|
||||
dictGetStats(buf,sizeof(buf),server.db[dbid].expires);
|
||||
stats = sdscat(stats,buf);
|
||||
stats = sdscatprintf(stats,"[Expires set]\n");
|
||||
g_pserver->db[dbid].setexpire->getstats(buf, sizeof(buf));
|
||||
stats = sdscat(stats, buf);
|
||||
|
||||
addReplyBulkSds(c,stats);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"htstats-key") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"htstats-key") && c->argc == 3) {
|
||||
robj *o;
|
||||
dict *ht = NULL;
|
||||
|
||||
@@ -650,12 +660,12 @@ NULL
|
||||
switch (o->encoding) {
|
||||
case OBJ_ENCODING_SKIPLIST:
|
||||
{
|
||||
zset *zs = ptrFromObj(o);
|
||||
zset *zs = (zset*)ptrFromObj(o);
|
||||
ht = zs->pdict;
|
||||
}
|
||||
break;
|
||||
case OBJ_ENCODING_HT:
|
||||
ht = ptrFromObj(o);
|
||||
ht = (dict*)ptrFromObj(o);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -667,15 +677,17 @@ NULL
|
||||
dictGetStats(buf,sizeof(buf),ht);
|
||||
addReplyBulkCString(c,buf);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"change-repl-id") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"change-repl-id") && c->argc == 2) {
|
||||
serverLog(LL_WARNING,"Changing replication IDs after receiving DEBUG change-repl-id");
|
||||
changeReplicationId();
|
||||
clearReplicationId2();
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"stringmatch-test") && c->argc == 2)
|
||||
{
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"stringmatch-test") && c->argc == 2) {
|
||||
stringmatchlen_fuzz_test();
|
||||
addReplyStatus(c,"Apparently Redis did not crash: test passed");
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]), "force-master") && c->argc == 2) {
|
||||
c->flags |= CLIENT_MASTER | CLIENT_MASTER_FORCE_REPLY;
|
||||
addReply(c, shared.ok);
|
||||
} else {
|
||||
addReplySubcommandSyntaxError(c);
|
||||
return;
|
||||
@@ -689,9 +701,9 @@ void _serverAssert(const char *estr, const char *file, int line) {
|
||||
serverLog(LL_WARNING,"=== ASSERTION FAILED ===");
|
||||
serverLog(LL_WARNING,"==> %s:%d '%s' is not true",file,line,estr);
|
||||
#ifdef HAVE_BACKTRACE
|
||||
server.assert_failed = estr;
|
||||
server.assert_file = file;
|
||||
server.assert_line = line;
|
||||
g_pserver->assert_failed = estr;
|
||||
g_pserver->assert_file = file;
|
||||
g_pserver->assert_line = line;
|
||||
serverLog(LL_WARNING,"(forcing SIGSEGV to print the bug report.)");
|
||||
#endif
|
||||
*((char*)-1) = 'x';
|
||||
@@ -702,7 +714,7 @@ void _serverAssertPrintClientInfo(const client *c) {
|
||||
|
||||
bugReportStart();
|
||||
serverLog(LL_WARNING,"=== ASSERTION FAILED CLIENT CONTEXT ===");
|
||||
serverLog(LL_WARNING,"client->flags = %d", c->flags);
|
||||
serverLog(LL_WARNING,"client->flags = %llu", static_cast<unsigned long long>(c->flags));
|
||||
serverLog(LL_WARNING,"client->fd = %d", c->fd);
|
||||
serverLog(LL_WARNING,"client->argc = %d", c->argc);
|
||||
for (j=0; j < c->argc; j++) {
|
||||
@@ -717,18 +729,18 @@ void _serverAssertPrintClientInfo(const client *c) {
|
||||
arg = buf;
|
||||
}
|
||||
serverLog(LL_WARNING,"client->argv[%d] = \"%s\" (refcount: %d)",
|
||||
j, arg, c->argv[j]->refcount);
|
||||
j, arg, static_cast<int>(c->argv[j]->getrefcount(std::memory_order_relaxed)));
|
||||
}
|
||||
}
|
||||
|
||||
void serverLogObjectDebugInfo(const robj *o) {
|
||||
void serverLogObjectDebugInfo(robj_roptr o) {
|
||||
serverLog(LL_WARNING,"Object type: %d", o->type);
|
||||
serverLog(LL_WARNING,"Object encoding: %d", o->encoding);
|
||||
serverLog(LL_WARNING,"Object refcount: %d", o->refcount);
|
||||
serverLog(LL_WARNING,"Object refcount: %d", static_cast<int>(o->getrefcount(std::memory_order_relaxed)));
|
||||
if (o->type == OBJ_STRING && sdsEncodedObject(o)) {
|
||||
serverLog(LL_WARNING,"Object raw string len: %zu", sdslen(ptrFromObj(o)));
|
||||
if (sdslen(ptrFromObj(o)) < 4096) {
|
||||
sds repr = sdscatrepr(sdsempty(),ptrFromObj(o),sdslen(ptrFromObj(o)));
|
||||
serverLog(LL_WARNING,"Object raw string len: %zu", sdslen(szFromObj(o)));
|
||||
if (sdslen(szFromObj(o)) < 4096) {
|
||||
sds repr = sdscatrepr(sdsempty(),szFromObj(o),sdslen(szFromObj(o)));
|
||||
serverLog(LL_WARNING,"Object raw string content: %s", repr);
|
||||
sdsfree(repr);
|
||||
}
|
||||
@@ -745,13 +757,13 @@ void serverLogObjectDebugInfo(const robj *o) {
|
||||
}
|
||||
}
|
||||
|
||||
void _serverAssertPrintObject(const robj *o) {
|
||||
void _serverAssertPrintObject(robj_roptr o) {
|
||||
bugReportStart();
|
||||
serverLog(LL_WARNING,"=== ASSERTION FAILED OBJECT CONTEXT ===");
|
||||
serverLogObjectDebugInfo(o);
|
||||
}
|
||||
|
||||
void _serverAssertWithInfo(const client *c, const robj *o, const char *estr, const char *file, int line) {
|
||||
void _serverAssertWithInfo(const client *c, robj_roptr o, const char *estr, const char *file, int line) {
|
||||
if (c) _serverAssertPrintClientInfo(c);
|
||||
if (o) _serverAssertPrintObject(o);
|
||||
_serverAssert(estr,file,line);
|
||||
@@ -776,10 +788,10 @@ void _serverPanic(const char *file, int line, const char *msg, ...) {
|
||||
}
|
||||
|
||||
void bugReportStart(void) {
|
||||
if (server.bug_report_start == 0) {
|
||||
if (g_pserver->bug_report_start == 0) {
|
||||
serverLogRaw(LL_WARNING|LL_RAW,
|
||||
"\n\n=== REDIS BUG REPORT START: Cut & paste starting from here ===\n");
|
||||
server.bug_report_start = 1;
|
||||
"\n\n=== KEYDB BUG REPORT START: Cut & paste starting from here ===\n");
|
||||
g_pserver->bug_report_start = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1123,19 +1135,74 @@ void logRegisters(ucontext_t *uc) {
|
||||
*
|
||||
* Close it with closeDirectLogFiledes(). */
|
||||
int openDirectLogFiledes(void) {
|
||||
int log_to_stdout = server.logfile[0] == '\0';
|
||||
int log_to_stdout = g_pserver->logfile[0] == '\0';
|
||||
int fd = log_to_stdout ?
|
||||
STDOUT_FILENO :
|
||||
open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);
|
||||
open(g_pserver->logfile, O_APPEND|O_CREAT|O_WRONLY, 0644);
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* Used to close what closeDirectLogFiledes() returns. */
|
||||
void closeDirectLogFiledes(int fd) {
|
||||
int log_to_stdout = server.logfile[0] == '\0';
|
||||
int log_to_stdout = g_pserver->logfile[0] == '\0';
|
||||
if (!log_to_stdout) close(fd);
|
||||
}
|
||||
|
||||
void safe_write(int fd, const void *pv, ssize_t cb)
|
||||
{
|
||||
ssize_t offset = 0;
|
||||
do
|
||||
{
|
||||
ssize_t cbWrite = write(fd, reinterpret_cast<const char*>(pv)+offset, cb-offset);
|
||||
if (cbWrite <= 0)
|
||||
return;
|
||||
offset += cbWrite;
|
||||
} while (offset < cb);
|
||||
}
|
||||
|
||||
void backtrace_symbols_demangle_fd(void **trace, size_t csym, int fd)
|
||||
{
|
||||
char **syms = backtrace_symbols(trace, csym);
|
||||
char symbuf[1024];
|
||||
for (size_t itrace = 0; itrace < csym; ++itrace)
|
||||
{
|
||||
int status = 0;
|
||||
|
||||
// First find the symbol (preceded by a '(')
|
||||
char *pchSymStart = syms[itrace];
|
||||
while (*pchSymStart != '(' && *pchSymStart != '\0')
|
||||
++pchSymStart;
|
||||
if (*pchSymStart != '\0')
|
||||
++pchSymStart; // skip the '('
|
||||
char *pchSymEnd = pchSymStart;
|
||||
while (*pchSymEnd != '+' && *pchSymEnd != '\0')
|
||||
++pchSymEnd;
|
||||
|
||||
if ((pchSymEnd - pchSymStart) < 1023)
|
||||
{
|
||||
memcpy(symbuf, pchSymStart, pchSymEnd - pchSymStart);
|
||||
symbuf[pchSymEnd - pchSymStart] = '\0';
|
||||
char *sz = abi::__cxa_demangle(symbuf, nullptr, nullptr, &status);
|
||||
if (status == 0)
|
||||
{
|
||||
safe_write(fd, syms[itrace], pchSymStart - syms[itrace]);
|
||||
safe_write(fd, sz, strlen(sz));
|
||||
safe_write(fd, pchSymEnd, (syms[itrace] + strlen(syms[itrace])-pchSymEnd));
|
||||
}
|
||||
else
|
||||
{
|
||||
safe_write(fd, syms[itrace], strlen(syms[itrace]));
|
||||
}
|
||||
free(sz);
|
||||
}
|
||||
else {
|
||||
safe_write(fd, syms[itrace], strlen(syms[itrace]));
|
||||
}
|
||||
safe_write(fd, "\n", 1);
|
||||
}
|
||||
free(syms);
|
||||
}
|
||||
|
||||
/* Logs the stack trace using the backtrace() call. This function is designed
|
||||
* to be called from signal handlers safely. */
|
||||
void logStackTrace(ucontext_t *uc) {
|
||||
@@ -1148,16 +1215,16 @@ void logStackTrace(ucontext_t *uc) {
|
||||
trace_size = backtrace(trace+1, 100);
|
||||
|
||||
if (getMcontextEip(uc) != NULL) {
|
||||
char *msg1 = "EIP:\n";
|
||||
char *msg2 = "\nBacktrace:\n";
|
||||
const char *msg1 = "EIP:\n";
|
||||
const char *msg2 = "\nBacktrace:\n";
|
||||
if (write(fd,msg1,strlen(msg1)) == -1) {/* Avoid warning. */};
|
||||
trace[0] = getMcontextEip(uc);
|
||||
backtrace_symbols_fd(trace, 1, fd);
|
||||
backtrace_symbols_demangle_fd(trace, 1, fd);
|
||||
if (write(fd,msg2,strlen(msg2)) == -1) {/* Avoid warning. */};
|
||||
}
|
||||
|
||||
/* Write symbols to log file */
|
||||
backtrace_symbols_fd(trace+1, trace_size, fd);
|
||||
backtrace_symbols_demangle_fd(trace+1, trace_size, fd);
|
||||
|
||||
/* Cleanup */
|
||||
closeDirectLogFiledes(fd);
|
||||
@@ -1167,9 +1234,9 @@ void logStackTrace(ucontext_t *uc) {
|
||||
* currently being served by Redis. May be NULL if Redis is not serving a
|
||||
* client right now. */
|
||||
void logCurrentClient(void) {
|
||||
if (server.current_client == NULL) return;
|
||||
if (serverTL->current_client == NULL) return;
|
||||
|
||||
client *cc = server.current_client;
|
||||
client *cc = serverTL->current_client;
|
||||
sds client;
|
||||
int j;
|
||||
|
||||
@@ -1194,7 +1261,7 @@ void logCurrentClient(void) {
|
||||
key = getDecodedObject(cc->argv[1]);
|
||||
de = dictFind(cc->db->pdict, ptrFromObj(key));
|
||||
if (de) {
|
||||
val = dictGetVal(de);
|
||||
val = (robj*)dictGetVal(de);
|
||||
serverLog(LL_WARNING,"key '%s' found in DB containing the following object:", (char*)ptrFromObj(key));
|
||||
serverLogObjectDebugInfo(val);
|
||||
}
|
||||
@@ -1255,7 +1322,7 @@ int memtest_test_linux_anonymous_maps(void) {
|
||||
int errors = 0;
|
||||
for (j = 0; j < regions; j++) {
|
||||
if (write(fd,".",1) == -1) { /* Nothing to do. */ }
|
||||
errors += memtest_preserving_test((void*)start_vect[j],size_vect[j],1);
|
||||
errors += memtest_preserving_test((unsigned long*)start_vect[j],size_vect[j],1);
|
||||
if (write(fd, errors ? "E" : "O",1) == -1) { /* Nothing to do. */ }
|
||||
}
|
||||
if (write(fd,"\n",1) == -1) { /* Nothing to do. */ }
|
||||
@@ -1274,7 +1341,7 @@ int memtest_test_linux_anonymous_maps(void) {
|
||||
* and the call offset if they appear to be valid. */
|
||||
void dumpX86Calls(void *addr, size_t len) {
|
||||
size_t j;
|
||||
unsigned char *p = addr;
|
||||
unsigned char *p = (unsigned char*)addr;
|
||||
Dl_info info;
|
||||
/* Hash table to best-effort avoid printing the same symbol
|
||||
* multiple times. */
|
||||
@@ -1297,6 +1364,7 @@ void dumpX86Calls(void *addr, size_t len) {
|
||||
|
||||
void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
ucontext_t *uc = (ucontext_t*) secret;
|
||||
g_fInCrash = true;
|
||||
void *eip = getMcontextEip(uc);
|
||||
sds infostring, clients;
|
||||
struct sigaction act;
|
||||
@@ -1304,7 +1372,7 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
|
||||
bugReportStart();
|
||||
serverLog(LL_WARNING,
|
||||
"Redis %s crashed by signal: %d", REDIS_VERSION, sig);
|
||||
"KeyDB %s crashed by signal: %d", KEYDB_REAL_VERSION, sig);
|
||||
if (eip != NULL) {
|
||||
serverLog(LL_WARNING,
|
||||
"Crashed running the instruction at: %p", eip);
|
||||
@@ -1314,8 +1382,8 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
"Accessing address: %p", (void*)info->si_addr);
|
||||
}
|
||||
serverLog(LL_WARNING,
|
||||
"Failed assertion: %s (%s:%d)", server.assert_failed,
|
||||
server.assert_file, server.assert_line);
|
||||
"Failed assertion: %s (%s:%d)", g_pserver->assert_failed,
|
||||
g_pserver->assert_file, g_pserver->assert_line);
|
||||
|
||||
/* Log the stack trace */
|
||||
serverLogRaw(LL_WARNING|LL_RAW, "\n------ STACK TRACE ------\n");
|
||||
@@ -1380,14 +1448,14 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
}
|
||||
|
||||
serverLogRaw(LL_WARNING|LL_RAW,
|
||||
"\n=== REDIS BUG REPORT END. Make sure to include from START to END. ===\n\n"
|
||||
"\n=== KEYDB BUG REPORT END. Make sure to include from START to END. ===\n\n"
|
||||
" Please report the crash by opening an issue on github:\n\n"
|
||||
" http://github.com/antirez/redis/issues\n\n"
|
||||
" https://github.com/JohnSully/KeyDB/issues\n\n"
|
||||
" Suspect RAM error? Use keydb-server --test-memory to verify it.\n\n"
|
||||
);
|
||||
|
||||
/* free(messages); Don't call free() with possibly corrupted memory. */
|
||||
if (server.daemonize && server.supervised == 0) unlink(server.pidfile);
|
||||
if (cserver.daemonize && cserver.supervised == 0) unlink(cserver.pidfile);
|
||||
|
||||
/* Make sure we exit with the right signal at the end. So for instance
|
||||
* the core will be dumped if enabled. */
|
||||
@@ -1401,9 +1469,9 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
|
||||
/* ==================== Logging functions for debugging ===================== */
|
||||
|
||||
void serverLogHexDump(int level, char *descr, void *value, size_t len) {
|
||||
void serverLogHexDump(int level, const char *descr, void *value, size_t len) {
|
||||
char buf[65], *b;
|
||||
unsigned char *v = value;
|
||||
unsigned char *v = (unsigned char*)value;
|
||||
char charset[] = "0123456789abcdef";
|
||||
|
||||
serverLog(level,"%s (hexdump of %zu bytes):", descr, len);
|
||||
@@ -1463,7 +1531,7 @@ void watchdogScheduleSignal(int period) {
|
||||
void enableWatchdog(int period) {
|
||||
int min_period;
|
||||
|
||||
if (server.watchdog_period == 0) {
|
||||
if (g_pserver->watchdog_period == 0) {
|
||||
struct sigaction act;
|
||||
|
||||
/* Watchdog was actually disabled, so we have to setup the signal
|
||||
@@ -1476,16 +1544,16 @@ void enableWatchdog(int period) {
|
||||
/* If the configured period is smaller than twice the timer period, it is
|
||||
* too short for the software watchdog to work reliably. Fix it now
|
||||
* if needed. */
|
||||
min_period = (1000/server.hz)*2;
|
||||
min_period = (1000/g_pserver->hz)*2;
|
||||
if (period < min_period) period = min_period;
|
||||
watchdogScheduleSignal(period); /* Adjust the current timer. */
|
||||
server.watchdog_period = period;
|
||||
g_pserver->watchdog_period = period;
|
||||
}
|
||||
|
||||
/* Disable the software watchdog. */
|
||||
void disableWatchdog(void) {
|
||||
struct sigaction act;
|
||||
if (server.watchdog_period == 0) return; /* Already disabled. */
|
||||
if (g_pserver->watchdog_period == 0) return; /* Already disabled. */
|
||||
watchdogScheduleSignal(0); /* Stop the current timer. */
|
||||
|
||||
/* Set the signal handler to SIG_IGN, this will also remove pending
|
||||
@@ -1494,5 +1562,5 @@ void disableWatchdog(void) {
|
||||
act.sa_flags = 0;
|
||||
act.sa_handler = SIG_IGN;
|
||||
sigaction(SIGALRM, &act, NULL);
|
||||
server.watchdog_period = 0;
|
||||
g_pserver->watchdog_period = 0;
|
||||
}
|
||||
+165
-157
@@ -43,11 +43,12 @@
|
||||
|
||||
/* this method was added to jemalloc in order to help us understand which
|
||||
* pointers are worthwhile moving and which aren't */
|
||||
int je_get_defrag_hint(void* ptr, int *bin_util, int *run_util);
|
||||
extern "C" int je_get_defrag_hint(void* ptr, int *bin_util, int *run_util);
|
||||
|
||||
/* forward declarations*/
|
||||
void defragDictBucketCallback(void *privdata, dictEntry **bucketref);
|
||||
dictEntry* replaceSateliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, sds newkey, unsigned int hash, long *defragged);
|
||||
dictEntry* replaceSateliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, sds newkey, uint64_t hash, long *defragged);
|
||||
void replaceSateliteOSetKeyPtr(expireset &set, sds oldkey, sds newkey);
|
||||
|
||||
/* Defrag helper for generic allocations.
|
||||
*
|
||||
@@ -59,14 +60,14 @@ void* activeDefragAlloc(void *ptr) {
|
||||
size_t size;
|
||||
void *newptr;
|
||||
if(!je_get_defrag_hint(ptr, &bin_util, &run_util)) {
|
||||
server.stat_active_defrag_misses++;
|
||||
g_pserver->stat_active_defrag_misses++;
|
||||
return NULL;
|
||||
}
|
||||
/* if this run is more utilized than the average utilization in this bin
|
||||
* (or it is full), skip it. This will eventually move all the allocations
|
||||
* from relatively empty runs into relatively full runs. */
|
||||
if (run_util > bin_util || run_util == 1<<16) {
|
||||
server.stat_active_defrag_misses++;
|
||||
g_pserver->stat_active_defrag_misses++;
|
||||
return NULL;
|
||||
}
|
||||
/* move this allocation to a new allocation.
|
||||
@@ -102,12 +103,12 @@ sds activeDefragSds(sds sdsptr) {
|
||||
* and should NOT be accessed. */
|
||||
robj *activeDefragStringOb(robj* ob, long *defragged) {
|
||||
robj *ret = NULL;
|
||||
if (ob->refcount!=1)
|
||||
if (ob->getrefcount(std::memory_order_relaxed)!=1)
|
||||
return NULL;
|
||||
|
||||
/* try to defrag robj (only if not an EMBSTR type (handled below). */
|
||||
if (ob->type!=OBJ_STRING || ob->encoding!=OBJ_ENCODING_EMBSTR) {
|
||||
if ((ret = activeDefragAlloc(ob))) {
|
||||
if ((ret = (robj*)activeDefragAlloc(ob))) {
|
||||
ob = ret;
|
||||
(*defragged)++;
|
||||
}
|
||||
@@ -124,7 +125,7 @@ robj *activeDefragStringOb(robj* ob, long *defragged) {
|
||||
} else if (ob->encoding==OBJ_ENCODING_EMBSTR) {
|
||||
/* The sds is embedded in the object allocation, calculate the
|
||||
* offset and update the pointer in the new allocation. */
|
||||
if ((ret = activeDefragAlloc(ob))) {
|
||||
if ((ret = (robj*)activeDefragAlloc(ob))) {
|
||||
(*defragged)++;
|
||||
}
|
||||
} else if (ob->encoding!=OBJ_ENCODING_INT) {
|
||||
@@ -145,7 +146,7 @@ long dictIterDefragEntry(dictIterator *iter) {
|
||||
/* Handle the next entry (if there is one), and update the pointer in the
|
||||
* current entry. */
|
||||
if (iter->nextEntry) {
|
||||
dictEntry *newde = activeDefragAlloc(iter->nextEntry);
|
||||
dictEntry *newde = (dictEntry*)activeDefragAlloc(iter->nextEntry);
|
||||
if (newde) {
|
||||
defragged++;
|
||||
iter->nextEntry = newde;
|
||||
@@ -155,7 +156,7 @@ long dictIterDefragEntry(dictIterator *iter) {
|
||||
/* handle the case of the first entry in the hash bucket. */
|
||||
ht = &iter->d->ht[iter->table];
|
||||
if (ht->table[iter->index] == iter->entry) {
|
||||
dictEntry *newde = activeDefragAlloc(iter->entry);
|
||||
dictEntry *newde = (dictEntry*)activeDefragAlloc(iter->entry);
|
||||
if (newde) {
|
||||
iter->entry = newde;
|
||||
ht->table[iter->index] = newde;
|
||||
@@ -172,12 +173,12 @@ long dictDefragTables(dict* d) {
|
||||
dictEntry **newtable;
|
||||
long defragged = 0;
|
||||
/* handle the first hash table */
|
||||
newtable = activeDefragAlloc(d->ht[0].table);
|
||||
newtable = (dictEntry**)activeDefragAlloc(d->ht[0].table);
|
||||
if (newtable)
|
||||
defragged++, d->ht[0].table = newtable;
|
||||
/* handle the second hash table */
|
||||
if (d->ht[1].table) {
|
||||
newtable = activeDefragAlloc(d->ht[1].table);
|
||||
newtable = (dictEntry**)activeDefragAlloc(d->ht[1].table);
|
||||
if (newtable)
|
||||
defragged++, d->ht[1].table = newtable;
|
||||
}
|
||||
@@ -188,13 +189,13 @@ long dictDefragTables(dict* d) {
|
||||
void zslUpdateNode(zskiplist *zsl, zskiplistNode *oldnode, zskiplistNode *newnode, zskiplistNode **update) {
|
||||
int i;
|
||||
for (i = 0; i < zsl->level; i++) {
|
||||
if (update[i]->level[i].forward == oldnode)
|
||||
update[i]->level[i].forward = newnode;
|
||||
if (update[i]->level(i)->forward == oldnode)
|
||||
update[i]->level(i)->forward = newnode;
|
||||
}
|
||||
serverAssert(zsl->header!=oldnode);
|
||||
if (newnode->level[0].forward) {
|
||||
serverAssert(newnode->level[0].forward->backward==oldnode);
|
||||
newnode->level[0].forward->backward = newnode;
|
||||
if (newnode->level(0)->forward) {
|
||||
serverAssert(newnode->level(0)->forward->backward==oldnode);
|
||||
newnode->level(0)->forward->backward = newnode;
|
||||
} else {
|
||||
serverAssert(zsl->tail==oldnode);
|
||||
zsl->tail = newnode;
|
||||
@@ -217,25 +218,25 @@ double *zslDefrag(zskiplist *zsl, double score, sds oldele, sds newele) {
|
||||
* and all pointers that need to be updated if we'll end up moving the skiplist node. */
|
||||
x = zsl->header;
|
||||
for (i = zsl->level-1; i >= 0; i--) {
|
||||
while (x->level[i].forward &&
|
||||
x->level[i].forward->ele != oldele && /* make sure not to access the
|
||||
while (x->level(i)->forward &&
|
||||
x->level(i)->forward->ele != oldele && /* make sure not to access the
|
||||
->obj pointer if it matches
|
||||
oldele */
|
||||
(x->level[i].forward->score < score ||
|
||||
(x->level[i].forward->score == score &&
|
||||
sdscmp(x->level[i].forward->ele,ele) < 0)))
|
||||
x = x->level[i].forward;
|
||||
(x->level(i)->forward->score < score ||
|
||||
(x->level(i)->forward->score == score &&
|
||||
sdscmp(x->level(i)->forward->ele,ele) < 0)))
|
||||
x = x->level(i)->forward;
|
||||
update[i] = x;
|
||||
}
|
||||
|
||||
/* update the robj pointer inside the skip list record. */
|
||||
x = x->level[0].forward;
|
||||
x = x->level(0)->forward;
|
||||
serverAssert(x && score == x->score && x->ele==oldele);
|
||||
if (newele)
|
||||
x->ele = newele;
|
||||
|
||||
/* try to defrag the skiplist record itself */
|
||||
newx = activeDefragAlloc(x);
|
||||
newx = (zskiplistNode*)activeDefragAlloc(x);
|
||||
if (newx) {
|
||||
zslUpdateNode(zsl, x, newx, update);
|
||||
return &newx->score;
|
||||
@@ -249,7 +250,7 @@ long activeDefragZsetEntry(zset *zs, dictEntry *de) {
|
||||
sds newsds;
|
||||
double* newscore;
|
||||
long defragged = 0;
|
||||
sds sdsele = dictGetKey(de);
|
||||
sds sdsele = (sds)dictGetKey(de);
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
defragged++, de->key = newsds;
|
||||
newscore = zslDefrag(zs->zsl, *(double*)dictGetVal(de), sdsele, newsds);
|
||||
@@ -272,16 +273,16 @@ long activeDefragSdsDict(dict* d, int val_type) {
|
||||
long defragged = 0;
|
||||
di = dictGetIterator(d);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sds sdsele = dictGetKey(de), newsds;
|
||||
sds sdsele = (sds)dictGetKey(de), newsds;
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
de->key = newsds, defragged++;
|
||||
/* defrag the value */
|
||||
if (val_type == DEFRAG_SDS_DICT_VAL_IS_SDS) {
|
||||
sdsele = dictGetVal(de);
|
||||
sdsele = (sds)dictGetVal(de);
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
de->v.val = newsds, defragged++;
|
||||
} else if (val_type == DEFRAG_SDS_DICT_VAL_IS_STROB) {
|
||||
robj *newele, *ele = dictGetVal(de);
|
||||
robj *newele, *ele = (robj*)dictGetVal(de);
|
||||
if ((newele = activeDefragStringOb(ele, &defragged)))
|
||||
de->v.val = newele;
|
||||
} else if (val_type == DEFRAG_SDS_DICT_VAL_VOID_PTR) {
|
||||
@@ -300,7 +301,7 @@ long activeDefragList(list *l, int val_type) {
|
||||
long defragged = 0;
|
||||
listNode *ln, *newln;
|
||||
for (ln = l->head; ln; ln = ln->next) {
|
||||
if ((newln = activeDefragAlloc(ln))) {
|
||||
if ((newln = (listNode*)activeDefragAlloc(ln))) {
|
||||
if (newln->prev)
|
||||
newln->prev->next = newln;
|
||||
else
|
||||
@@ -313,11 +314,11 @@ long activeDefragList(list *l, int val_type) {
|
||||
defragged++;
|
||||
}
|
||||
if (val_type == DEFRAG_SDS_DICT_VAL_IS_SDS) {
|
||||
sds newsds, sdsele = ln->value;
|
||||
sds newsds, sdsele = (sds)ln->value;
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
ln->value = newsds, defragged++;
|
||||
} else if (val_type == DEFRAG_SDS_DICT_VAL_IS_STROB) {
|
||||
robj *newele, *ele = ln->value;
|
||||
robj *newele, *ele = (robj*)ln->value;
|
||||
if ((newele = activeDefragStringOb(ele, &defragged)))
|
||||
ln->value = newele;
|
||||
} else if (val_type == DEFRAG_SDS_DICT_VAL_VOID_PTR) {
|
||||
@@ -338,7 +339,7 @@ long activeDefragSdsListAndDict(list *l, dict *d, int dict_val_type) {
|
||||
dictEntry *de;
|
||||
/* Defrag the list and it's sds values */
|
||||
for (ln = l->head; ln; ln = ln->next) {
|
||||
if ((newln = activeDefragAlloc(ln))) {
|
||||
if ((newln = (listNode*)activeDefragAlloc(ln))) {
|
||||
if (newln->prev)
|
||||
newln->prev->next = newln;
|
||||
else
|
||||
@@ -350,10 +351,10 @@ long activeDefragSdsListAndDict(list *l, dict *d, int dict_val_type) {
|
||||
ln = newln;
|
||||
defragged++;
|
||||
}
|
||||
sdsele = ln->value;
|
||||
sdsele = (sds)ln->value;
|
||||
if ((newsds = activeDefragSds(sdsele))) {
|
||||
/* When defragging an sds value, we need to update the dict key */
|
||||
unsigned int hash = dictGetHash(d, sdsele);
|
||||
uint64_t hash = dictGetHash(d, sdsele);
|
||||
replaceSateliteDictKeyPtrAndOrDefragDictEntry(d, sdsele, newsds, hash, &defragged);
|
||||
ln->value = newsds;
|
||||
defragged++;
|
||||
@@ -364,11 +365,11 @@ long activeDefragSdsListAndDict(list *l, dict *d, int dict_val_type) {
|
||||
di = dictGetIterator(d);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
if (dict_val_type == DEFRAG_SDS_DICT_VAL_IS_SDS) {
|
||||
sds newsds, sdsele = dictGetVal(de);
|
||||
sds newsds, sdsele = (sds)dictGetVal(de);
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
de->v.val = newsds, defragged++;
|
||||
} else if (dict_val_type == DEFRAG_SDS_DICT_VAL_IS_STROB) {
|
||||
robj *newele, *ele = dictGetVal(de);
|
||||
robj *newele, *ele = (robj*)dictGetVal(de);
|
||||
if ((newele = activeDefragStringOb(ele, &defragged)))
|
||||
de->v.val = newele, defragged++;
|
||||
} else if (dict_val_type == DEFRAG_SDS_DICT_VAL_VOID_PTR) {
|
||||
@@ -390,11 +391,11 @@ long activeDefragSdsListAndDict(list *l, dict *d, int dict_val_type) {
|
||||
* moved. Return value is the the dictEntry if found, or NULL if not found.
|
||||
* NOTE: this is very ugly code, but it let's us avoid the complication of
|
||||
* doing a scan on another dict. */
|
||||
dictEntry* replaceSateliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, sds newkey, unsigned int hash, long *defragged) {
|
||||
dictEntry* replaceSateliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, sds newkey, uint64_t hash, long *defragged) {
|
||||
dictEntry **deref = dictFindEntryRefByPtrAndHash(d, oldkey, hash);
|
||||
if (deref) {
|
||||
dictEntry *de = *deref;
|
||||
dictEntry *newde = activeDefragAlloc(de);
|
||||
dictEntry *newde = (dictEntry*)activeDefragAlloc(de);
|
||||
if (newde) {
|
||||
de = *deref = newde;
|
||||
(*defragged)++;
|
||||
@@ -406,12 +407,23 @@ dictEntry* replaceSateliteDictKeyPtrAndOrDefragDictEntry(dict *d, sds oldkey, sd
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void replaceSateliteOSetKeyPtr(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);
|
||||
}
|
||||
}
|
||||
|
||||
long activeDefragQuickListNodes(quicklist *ql) {
|
||||
quicklistNode *node = ql->head, *newnode;
|
||||
long defragged = 0;
|
||||
unsigned char *newzl;
|
||||
while (node) {
|
||||
if ((newnode = activeDefragAlloc(node))) {
|
||||
if ((newnode = (quicklistNode*)activeDefragAlloc(node))) {
|
||||
if (newnode->prev)
|
||||
newnode->prev->next = newnode;
|
||||
else
|
||||
@@ -423,7 +435,7 @@ long activeDefragQuickListNodes(quicklist *ql) {
|
||||
node = newnode;
|
||||
defragged++;
|
||||
}
|
||||
if ((newzl = activeDefragAlloc(node->zl)))
|
||||
if ((newzl = (unsigned char*)activeDefragAlloc(node->zl)))
|
||||
defragged++, node->zl = newzl;
|
||||
node = node->next;
|
||||
}
|
||||
@@ -434,15 +446,15 @@ long activeDefragQuickListNodes(quicklist *ql) {
|
||||
* oart of the main dictionary scan. this is needed in order to prevent latency
|
||||
* spikes when handling large items */
|
||||
void defragLater(redisDb *db, dictEntry *kde) {
|
||||
sds key = sdsdup(dictGetKey(kde));
|
||||
sds key = sdsdup((sds)dictGetKey(kde));
|
||||
listAddNodeTail(db->defrag_later, key);
|
||||
}
|
||||
|
||||
long scanLaterList(robj *ob) {
|
||||
quicklist *ql = ptrFromObj(ob);
|
||||
quicklist *ql = (quicklist*)ptrFromObj(ob);
|
||||
if (ob->type != OBJ_LIST || ob->encoding != OBJ_ENCODING_QUICKLIST)
|
||||
return 0;
|
||||
server.stat_active_defrag_scanned+=ql->len;
|
||||
g_pserver->stat_active_defrag_scanned+=ql->len;
|
||||
return activeDefragQuickListNodes(ql);
|
||||
}
|
||||
|
||||
@@ -453,9 +465,9 @@ typedef struct {
|
||||
|
||||
void scanLaterZsetCallback(void *privdata, const dictEntry *_de) {
|
||||
dictEntry *de = (dictEntry*)_de;
|
||||
scanLaterZsetData *data = privdata;
|
||||
scanLaterZsetData *data = (scanLaterZsetData*)privdata;
|
||||
data->defragged += activeDefragZsetEntry(data->zs, de);
|
||||
server.stat_active_defrag_scanned++;
|
||||
g_pserver->stat_active_defrag_scanned++;
|
||||
}
|
||||
|
||||
long scanLaterZset(robj *ob, unsigned long *cursor) {
|
||||
@@ -470,51 +482,51 @@ long scanLaterZset(robj *ob, unsigned long *cursor) {
|
||||
|
||||
void scanLaterSetCallback(void *privdata, const dictEntry *_de) {
|
||||
dictEntry *de = (dictEntry*)_de;
|
||||
long *defragged = privdata;
|
||||
sds sdsele = dictGetKey(de), newsds;
|
||||
long *defragged = (long*)privdata;
|
||||
sds sdsele = (sds)dictGetKey(de), newsds;
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
(*defragged)++, de->key = newsds;
|
||||
server.stat_active_defrag_scanned++;
|
||||
g_pserver->stat_active_defrag_scanned++;
|
||||
}
|
||||
|
||||
long scanLaterSet(robj *ob, unsigned long *cursor) {
|
||||
long defragged = 0;
|
||||
if (ob->type != OBJ_SET || ob->encoding != OBJ_ENCODING_HT)
|
||||
return 0;
|
||||
dict *d = ptrFromObj(ob);
|
||||
dict *d = (dict*)ptrFromObj(ob);
|
||||
*cursor = dictScan(d, *cursor, scanLaterSetCallback, defragDictBucketCallback, &defragged);
|
||||
return defragged;
|
||||
}
|
||||
|
||||
void scanLaterHashCallback(void *privdata, const dictEntry *_de) {
|
||||
dictEntry *de = (dictEntry*)_de;
|
||||
long *defragged = privdata;
|
||||
sds sdsele = dictGetKey(de), newsds;
|
||||
long *defragged = (long*)privdata;
|
||||
sds sdsele = (sds)dictGetKey(de), newsds;
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
(*defragged)++, de->key = newsds;
|
||||
sdsele = dictGetVal(de);
|
||||
sdsele = (sds)dictGetVal(de);
|
||||
if ((newsds = activeDefragSds(sdsele)))
|
||||
(*defragged)++, de->v.val = newsds;
|
||||
server.stat_active_defrag_scanned++;
|
||||
g_pserver->stat_active_defrag_scanned++;
|
||||
}
|
||||
|
||||
long scanLaterHash(robj *ob, unsigned long *cursor) {
|
||||
long defragged = 0;
|
||||
if (ob->type != OBJ_HASH || ob->encoding != OBJ_ENCODING_HT)
|
||||
return 0;
|
||||
dict *d = ptrFromObj(ob);
|
||||
dict *d = (dict*)ptrFromObj(ob);
|
||||
*cursor = dictScan(d, *cursor, scanLaterHashCallback, defragDictBucketCallback, &defragged);
|
||||
return defragged;
|
||||
}
|
||||
|
||||
long defragQuicklist(redisDb *db, dictEntry *kde) {
|
||||
robj *ob = dictGetVal(kde);
|
||||
robj *ob = (robj*)dictGetVal(kde);
|
||||
long defragged = 0;
|
||||
quicklist *ql = ptrFromObj(ob), *newql;
|
||||
quicklist *ql = (quicklist*)ptrFromObj(ob), *newql;
|
||||
serverAssert(ob->type == OBJ_LIST && ob->encoding == OBJ_ENCODING_QUICKLIST);
|
||||
if ((newql = activeDefragAlloc(ql)))
|
||||
if ((newql = (quicklist*)activeDefragAlloc(ql)))
|
||||
defragged++, ob->m_ptr = ql = newql;
|
||||
if (ql->len > server.active_defrag_max_scan_fields)
|
||||
if (ql->len > cserver.active_defrag_max_scan_fields)
|
||||
defragLater(db, kde);
|
||||
else
|
||||
defragged += activeDefragQuickListNodes(ql);
|
||||
@@ -522,7 +534,7 @@ long defragQuicklist(redisDb *db, dictEntry *kde) {
|
||||
}
|
||||
|
||||
long defragZsetSkiplist(redisDb *db, dictEntry *kde) {
|
||||
robj *ob = dictGetVal(kde);
|
||||
robj *ob = (robj*)dictGetVal(kde);
|
||||
long defragged = 0;
|
||||
zset *zs = (zset*)ptrFromObj(ob);
|
||||
zset *newzs;
|
||||
@@ -531,13 +543,13 @@ long defragZsetSkiplist(redisDb *db, dictEntry *kde) {
|
||||
dictEntry *de;
|
||||
struct zskiplistNode *newheader;
|
||||
serverAssert(ob->type == OBJ_ZSET && ob->encoding == OBJ_ENCODING_SKIPLIST);
|
||||
if ((newzs = activeDefragAlloc(zs)))
|
||||
if ((newzs = (zset*)activeDefragAlloc(zs)))
|
||||
defragged++, ob->m_ptr = zs = newzs;
|
||||
if ((newzsl = activeDefragAlloc(zs->zsl)))
|
||||
if ((newzsl = (zskiplist*)activeDefragAlloc(zs->zsl)))
|
||||
defragged++, zs->zsl = newzsl;
|
||||
if ((newheader = activeDefragAlloc(zs->zsl->header)))
|
||||
if ((newheader = (zskiplistNode*)activeDefragAlloc(zs->zsl->header)))
|
||||
defragged++, zs->zsl->header = newheader;
|
||||
if (dictSize(zs->pdict) > server.active_defrag_max_scan_fields)
|
||||
if (dictSize(zs->pdict) > cserver.active_defrag_max_scan_fields)
|
||||
defragLater(db, kde);
|
||||
else {
|
||||
dictIterator *di = dictGetIterator(zs->pdict);
|
||||
@@ -547,7 +559,7 @@ long defragZsetSkiplist(redisDb *db, dictEntry *kde) {
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
/* handle the dict struct */
|
||||
if ((newdict = activeDefragAlloc(zs->pdict)))
|
||||
if ((newdict = (dict*)activeDefragAlloc(zs->pdict)))
|
||||
defragged++, zs->pdict = newdict;
|
||||
/* defrag the dict tables */
|
||||
defragged += dictDefragTables(zs->pdict);
|
||||
@@ -556,44 +568,44 @@ long defragZsetSkiplist(redisDb *db, dictEntry *kde) {
|
||||
|
||||
long defragHash(redisDb *db, dictEntry *kde) {
|
||||
long defragged = 0;
|
||||
robj *ob = dictGetVal(kde);
|
||||
robj *ob = (robj*)dictGetVal(kde);
|
||||
dict *d, *newd;
|
||||
serverAssert(ob->type == OBJ_HASH && ob->encoding == OBJ_ENCODING_HT);
|
||||
d = ptrFromObj(ob);
|
||||
if (dictSize(d) > server.active_defrag_max_scan_fields)
|
||||
d = (dict*)ptrFromObj(ob);
|
||||
if (dictSize(d) > cserver.active_defrag_max_scan_fields)
|
||||
defragLater(db, kde);
|
||||
else
|
||||
defragged += activeDefragSdsDict(d, DEFRAG_SDS_DICT_VAL_IS_SDS);
|
||||
/* handle the dict struct */
|
||||
if ((newd = activeDefragAlloc(ptrFromObj(ob))))
|
||||
if ((newd = (dict*)activeDefragAlloc(ptrFromObj(ob))))
|
||||
defragged++, ob->m_ptr = newd;
|
||||
/* defrag the dict tables */
|
||||
defragged += dictDefragTables(ptrFromObj(ob));
|
||||
defragged += dictDefragTables((dict*)ptrFromObj(ob));
|
||||
return defragged;
|
||||
}
|
||||
|
||||
long defragSet(redisDb *db, dictEntry *kde) {
|
||||
long defragged = 0;
|
||||
robj *ob = dictGetVal(kde);
|
||||
robj *ob = (robj*)dictGetVal(kde);
|
||||
dict *d, *newd;
|
||||
serverAssert(ob->type == OBJ_SET && ob->encoding == OBJ_ENCODING_HT);
|
||||
d = ptrFromObj(ob);
|
||||
if (dictSize(d) > server.active_defrag_max_scan_fields)
|
||||
d = (dict*)ptrFromObj(ob);
|
||||
if (dictSize(d) > cserver.active_defrag_max_scan_fields)
|
||||
defragLater(db, kde);
|
||||
else
|
||||
defragged += activeDefragSdsDict(d, DEFRAG_SDS_DICT_NO_VAL);
|
||||
/* handle the dict struct */
|
||||
if ((newd = activeDefragAlloc(ptrFromObj(ob))))
|
||||
if ((newd = (dict*)activeDefragAlloc(ptrFromObj(ob))))
|
||||
defragged++, ob->m_ptr = newd;
|
||||
/* defrag the dict tables */
|
||||
defragged += dictDefragTables(ptrFromObj(ob));
|
||||
defragged += dictDefragTables((dict*)ptrFromObj(ob));
|
||||
return defragged;
|
||||
}
|
||||
|
||||
/* Defrag callback for radix tree iterator, called for each node,
|
||||
* used in order to defrag the nodes allocations. */
|
||||
int defragRaxNode(raxNode **noderef) {
|
||||
raxNode *newnode = activeDefragAlloc(*noderef);
|
||||
raxNode *newnode = (raxNode*)activeDefragAlloc(*noderef);
|
||||
if (newnode) {
|
||||
*noderef = newnode;
|
||||
return 1;
|
||||
@@ -611,7 +623,7 @@ int scanLaterStraemListpacks(robj *ob, unsigned long *cursor, long long endtime,
|
||||
return 0;
|
||||
}
|
||||
|
||||
stream *s = ptrFromObj(ob);
|
||||
stream *s = (stream*)ptrFromObj(ob);
|
||||
raxStart(&ri,s->prax);
|
||||
if (*cursor == 0) {
|
||||
/* if cursor is 0, we start new iteration */
|
||||
@@ -662,8 +674,8 @@ typedef void *(raxDefragFunction)(raxIterator *ri, void *privdata, long *defragg
|
||||
long defragRadixTree(rax **raxref, int defrag_data, raxDefragFunction *element_cb, void *element_cb_data) {
|
||||
long defragged = 0;
|
||||
raxIterator ri;
|
||||
rax* rax;
|
||||
if ((rax = activeDefragAlloc(*raxref)))
|
||||
::rax* rax;
|
||||
if ((rax = (::rax*)activeDefragAlloc(*raxref)))
|
||||
defragged++, *raxref = rax;
|
||||
rax = *raxref;
|
||||
raxStart(&ri,rax);
|
||||
@@ -690,10 +702,10 @@ typedef struct {
|
||||
|
||||
void* defragStreamConsumerPendingEntry(raxIterator *ri, void *privdata, long *defragged) {
|
||||
UNUSED(defragged);
|
||||
PendingEntryContext *ctx = privdata;
|
||||
streamNACK *nack = ri->data, *newnack;
|
||||
PendingEntryContext *ctx = (PendingEntryContext*)privdata;
|
||||
streamNACK *nack = (streamNACK*)ri->data, *newnack;
|
||||
nack->consumer = ctx->c; /* update nack pointer to consumer */
|
||||
newnack = activeDefragAlloc(nack);
|
||||
newnack = (streamNACK*)activeDefragAlloc(nack);
|
||||
if (newnack) {
|
||||
/* update consumer group pointer to the nack */
|
||||
void *prev;
|
||||
@@ -705,12 +717,12 @@ void* defragStreamConsumerPendingEntry(raxIterator *ri, void *privdata, long *de
|
||||
}
|
||||
|
||||
void* defragStreamConsumer(raxIterator *ri, void *privdata, long *defragged) {
|
||||
streamConsumer *c = ri->data;
|
||||
streamCG *cg = privdata;
|
||||
streamConsumer *c = (streamConsumer*)ri->data;
|
||||
streamCG *cg = (streamCG*)privdata;
|
||||
void *newc = activeDefragAlloc(c);
|
||||
if (newc) {
|
||||
/* note: we don't increment 'defragged' that's done by the caller */
|
||||
c = newc;
|
||||
c = (streamConsumer*)newc;
|
||||
}
|
||||
sds newsds = activeDefragSds(c->name);
|
||||
if (newsds)
|
||||
@@ -723,7 +735,7 @@ void* defragStreamConsumer(raxIterator *ri, void *privdata, long *defragged) {
|
||||
}
|
||||
|
||||
void* defragStreamConsumerGroup(raxIterator *ri, void *privdata, long *defragged) {
|
||||
streamCG *cg = ri->data;
|
||||
streamCG *cg = (streamCG*)ri->data;
|
||||
UNUSED(privdata);
|
||||
if (cg->consumers)
|
||||
*defragged += defragRadixTree(&cg->consumers, 0, defragStreamConsumer, cg);
|
||||
@@ -734,16 +746,16 @@ void* defragStreamConsumerGroup(raxIterator *ri, void *privdata, long *defragged
|
||||
|
||||
long defragStream(redisDb *db, dictEntry *kde) {
|
||||
long defragged = 0;
|
||||
robj *ob = dictGetVal(kde);
|
||||
robj *ob = (robj*)dictGetVal(kde);
|
||||
serverAssert(ob->type == OBJ_STREAM && ob->encoding == OBJ_ENCODING_STREAM);
|
||||
stream *s = ptrFromObj(ob), *news;
|
||||
stream *s = (stream*)ptrFromObj(ob), *news;
|
||||
|
||||
/* handle the main struct */
|
||||
if ((news = activeDefragAlloc(s)))
|
||||
if ((news = (stream*)activeDefragAlloc(s)))
|
||||
defragged++, ob->m_ptr = s = news;
|
||||
|
||||
if (raxSize(s->prax) > server.active_defrag_max_scan_fields) {
|
||||
rax *newrax = activeDefragAlloc(s->prax);
|
||||
if (raxSize(s->prax) > cserver.active_defrag_max_scan_fields) {
|
||||
rax *newrax = (rax*)activeDefragAlloc(s->prax);
|
||||
if (newrax)
|
||||
defragged++, s->prax = newrax;
|
||||
defragLater(db, kde);
|
||||
@@ -759,7 +771,7 @@ long defragStream(redisDb *db, dictEntry *kde) {
|
||||
* all the various pointers it has. Returns a stat of how many pointers were
|
||||
* moved. */
|
||||
long defragKey(redisDb *db, dictEntry *de) {
|
||||
sds keysds = dictGetKey(de);
|
||||
sds keysds = (sds)dictGetKey(de);
|
||||
robj *newob, *ob;
|
||||
unsigned char *newzl;
|
||||
long defragged = 0;
|
||||
@@ -769,16 +781,12 @@ long defragKey(redisDb *db, dictEntry *de) {
|
||||
newsds = activeDefragSds(keysds);
|
||||
if (newsds)
|
||||
defragged++, de->key = newsds;
|
||||
if (dictSize(db->expires)) {
|
||||
/* Dirty code:
|
||||
* I can't search in db->expires for that key after i already released
|
||||
* the pointer it holds it won't be able to do the string compare */
|
||||
uint64_t hash = dictGetHash(db->pdict, de->key);
|
||||
replaceSateliteDictKeyPtrAndOrDefragDictEntry(db->expires, keysds, newsds, hash, &defragged);
|
||||
if (!db->setexpire->empty()) {
|
||||
replaceSateliteOSetKeyPtr(*db->setexpire, keysds, newsds);
|
||||
}
|
||||
|
||||
/* Try to defrag robj and / or string value. */
|
||||
ob = dictGetVal(de);
|
||||
ob = (robj*)dictGetVal(de);
|
||||
if ((newob = activeDefragStringOb(ob, &defragged))) {
|
||||
de->v.val = newob;
|
||||
ob = newob;
|
||||
@@ -790,7 +798,7 @@ long defragKey(redisDb *db, dictEntry *de) {
|
||||
if (ob->encoding == OBJ_ENCODING_QUICKLIST) {
|
||||
defragged += defragQuicklist(db, de);
|
||||
} else if (ob->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
if ((newzl = activeDefragAlloc(ptrFromObj(ob))))
|
||||
if ((newzl = (unsigned char*)activeDefragAlloc(ptrFromObj(ob))))
|
||||
defragged++, ob->m_ptr = newzl;
|
||||
} else {
|
||||
serverPanic("Unknown list encoding");
|
||||
@@ -799,15 +807,15 @@ long defragKey(redisDb *db, dictEntry *de) {
|
||||
if (ob->encoding == OBJ_ENCODING_HT) {
|
||||
defragged += defragSet(db, de);
|
||||
} else if (ob->encoding == OBJ_ENCODING_INTSET) {
|
||||
intset *newis, *is = ptrFromObj(ob);
|
||||
if ((newis = activeDefragAlloc(is)))
|
||||
intset *newis, *is = (intset*)ptrFromObj(ob);
|
||||
if ((newis = (intset*)activeDefragAlloc(is)))
|
||||
defragged++, ob->m_ptr = newis;
|
||||
} else {
|
||||
serverPanic("Unknown set encoding");
|
||||
}
|
||||
} else if (ob->type == OBJ_ZSET) {
|
||||
if (ob->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
if ((newzl = activeDefragAlloc(ptrFromObj(ob))))
|
||||
if ((newzl = (unsigned char*)activeDefragAlloc(ptrFromObj(ob))))
|
||||
defragged++, ob->m_ptr = newzl;
|
||||
} else if (ob->encoding == OBJ_ENCODING_SKIPLIST) {
|
||||
defragged += defragZsetSkiplist(db, de);
|
||||
@@ -816,7 +824,7 @@ long defragKey(redisDb *db, dictEntry *de) {
|
||||
}
|
||||
} else if (ob->type == OBJ_HASH) {
|
||||
if (ob->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
if ((newzl = activeDefragAlloc(ptrFromObj(ob))))
|
||||
if ((newzl = (unsigned char*)activeDefragAlloc(ptrFromObj(ob))))
|
||||
defragged++, ob->m_ptr = newzl;
|
||||
} else if (ob->encoding == OBJ_ENCODING_HT) {
|
||||
defragged += defragHash(db, de);
|
||||
@@ -837,12 +845,12 @@ long defragKey(redisDb *db, dictEntry *de) {
|
||||
/* Defrag scan callback for the main db dictionary. */
|
||||
void defragScanCallback(void *privdata, const dictEntry *de) {
|
||||
long defragged = defragKey((redisDb*)privdata, (dictEntry*)de);
|
||||
server.stat_active_defrag_hits += defragged;
|
||||
g_pserver->stat_active_defrag_hits += defragged;
|
||||
if(defragged)
|
||||
server.stat_active_defrag_key_hits++;
|
||||
g_pserver->stat_active_defrag_key_hits++;
|
||||
else
|
||||
server.stat_active_defrag_key_misses++;
|
||||
server.stat_active_defrag_scanned++;
|
||||
g_pserver->stat_active_defrag_key_misses++;
|
||||
g_pserver->stat_active_defrag_scanned++;
|
||||
}
|
||||
|
||||
/* Defrag scan callback for each hash table bicket,
|
||||
@@ -851,7 +859,7 @@ void defragDictBucketCallback(void *privdata, dictEntry **bucketref) {
|
||||
UNUSED(privdata); /* NOTE: this function is also used by both activeDefragCycle and scanLaterHash, etc. don't use privdata */
|
||||
while(*bucketref) {
|
||||
dictEntry *de = *bucketref, *newde;
|
||||
if ((newde = activeDefragAlloc(de))) {
|
||||
if ((newde = (dictEntry*)activeDefragAlloc(de))) {
|
||||
*bucketref = newde;
|
||||
}
|
||||
bucketref = &(*bucketref)->next;
|
||||
@@ -887,8 +895,8 @@ long defragOtherGlobals() {
|
||||
/* there are many more pointers to defrag (e.g. client argv, output / aof buffers, etc.
|
||||
* but we assume most of these are short lived, we only need to defrag allocations
|
||||
* that remain static for a long time */
|
||||
defragged += activeDefragSdsDict(server.lua_scripts, DEFRAG_SDS_DICT_VAL_IS_STROB);
|
||||
defragged += activeDefragSdsListAndDict(server.repl_scriptcache_fifo, server.repl_scriptcache_dict, DEFRAG_SDS_DICT_NO_VAL);
|
||||
defragged += activeDefragSdsDict(g_pserver->lua_scripts, DEFRAG_SDS_DICT_VAL_IS_STROB);
|
||||
defragged += activeDefragSdsListAndDict(g_pserver->repl_scriptcache_fifo, g_pserver->repl_scriptcache_dict, DEFRAG_SDS_DICT_NO_VAL);
|
||||
return defragged;
|
||||
}
|
||||
|
||||
@@ -896,18 +904,18 @@ long defragOtherGlobals() {
|
||||
* and 1 if time is up and more work is needed. */
|
||||
int defragLaterItem(dictEntry *de, unsigned long *cursor, long long endtime) {
|
||||
if (de) {
|
||||
robj *ob = dictGetVal(de);
|
||||
robj *ob = (robj*)dictGetVal(de);
|
||||
if (ob->type == OBJ_LIST) {
|
||||
server.stat_active_defrag_hits += scanLaterList(ob);
|
||||
g_pserver->stat_active_defrag_hits += scanLaterList(ob);
|
||||
*cursor = 0; /* list has no scan, we must finish it in one go */
|
||||
} else if (ob->type == OBJ_SET) {
|
||||
server.stat_active_defrag_hits += scanLaterSet(ob, cursor);
|
||||
g_pserver->stat_active_defrag_hits += scanLaterSet(ob, cursor);
|
||||
} else if (ob->type == OBJ_ZSET) {
|
||||
server.stat_active_defrag_hits += scanLaterZset(ob, cursor);
|
||||
g_pserver->stat_active_defrag_hits += scanLaterZset(ob, cursor);
|
||||
} else if (ob->type == OBJ_HASH) {
|
||||
server.stat_active_defrag_hits += scanLaterHash(ob, cursor);
|
||||
g_pserver->stat_active_defrag_hits += scanLaterHash(ob, cursor);
|
||||
} else if (ob->type == OBJ_STREAM) {
|
||||
return scanLaterStraemListpacks(ob, cursor, endtime, &server.stat_active_defrag_hits);
|
||||
return scanLaterStraemListpacks(ob, cursor, endtime, &g_pserver->stat_active_defrag_hits);
|
||||
} else {
|
||||
*cursor = 0; /* object type may have changed since we schedule it for later */
|
||||
}
|
||||
@@ -922,8 +930,8 @@ int defragLaterStep(redisDb *db, long long endtime) {
|
||||
static sds current_key = NULL;
|
||||
static unsigned long cursor = 0;
|
||||
unsigned int iterations = 0;
|
||||
unsigned long long prev_defragged = server.stat_active_defrag_hits;
|
||||
unsigned long long prev_scanned = server.stat_active_defrag_scanned;
|
||||
unsigned long long prev_defragged = g_pserver->stat_active_defrag_hits;
|
||||
unsigned long long prev_scanned = g_pserver->stat_active_defrag_scanned;
|
||||
long long key_defragged;
|
||||
|
||||
do {
|
||||
@@ -934,7 +942,7 @@ int defragLaterStep(redisDb *db, long long endtime) {
|
||||
/* Move on to next key */
|
||||
if (current_key) {
|
||||
serverAssert(current_key == head->value);
|
||||
sdsfree(head->value);
|
||||
sdsfree((sds)head->value);
|
||||
listDelNode(db->defrag_later, head);
|
||||
cursor = 0;
|
||||
current_key = NULL;
|
||||
@@ -946,13 +954,13 @@ int defragLaterStep(redisDb *db, long long endtime) {
|
||||
return 0;
|
||||
|
||||
/* start a new key */
|
||||
current_key = head->value;
|
||||
current_key = (sds)head->value;
|
||||
cursor = 0;
|
||||
}
|
||||
|
||||
/* each time we enter this function we need to fetch the key from the dict again (if it still exists) */
|
||||
dictEntry *de = dictFind(db->pdict, current_key);
|
||||
key_defragged = server.stat_active_defrag_hits;
|
||||
key_defragged = g_pserver->stat_active_defrag_hits;
|
||||
do {
|
||||
int quit = 0;
|
||||
if (defragLaterItem(de, &cursor, endtime))
|
||||
@@ -967,24 +975,24 @@ int defragLaterStep(redisDb *db, long long endtime) {
|
||||
* (if we have a lot of pointers in one hash bucket, or rehashing),
|
||||
* check if we reached the time limit. */
|
||||
if (quit || (++iterations > 16 ||
|
||||
server.stat_active_defrag_hits - prev_defragged > 512 ||
|
||||
server.stat_active_defrag_scanned - prev_scanned > 64)) {
|
||||
g_pserver->stat_active_defrag_hits - prev_defragged > 512 ||
|
||||
g_pserver->stat_active_defrag_scanned - prev_scanned > 64)) {
|
||||
if (quit || ustime() > endtime) {
|
||||
if(key_defragged != server.stat_active_defrag_hits)
|
||||
server.stat_active_defrag_key_hits++;
|
||||
if(key_defragged != g_pserver->stat_active_defrag_hits)
|
||||
g_pserver->stat_active_defrag_key_hits++;
|
||||
else
|
||||
server.stat_active_defrag_key_misses++;
|
||||
g_pserver->stat_active_defrag_key_misses++;
|
||||
return 1;
|
||||
}
|
||||
iterations = 0;
|
||||
prev_defragged = server.stat_active_defrag_hits;
|
||||
prev_scanned = server.stat_active_defrag_scanned;
|
||||
prev_defragged = g_pserver->stat_active_defrag_hits;
|
||||
prev_scanned = g_pserver->stat_active_defrag_scanned;
|
||||
}
|
||||
} while(cursor);
|
||||
if(key_defragged != server.stat_active_defrag_hits)
|
||||
server.stat_active_defrag_key_hits++;
|
||||
if(key_defragged != g_pserver->stat_active_defrag_hits)
|
||||
g_pserver->stat_active_defrag_key_hits++;
|
||||
else
|
||||
server.stat_active_defrag_key_misses++;
|
||||
g_pserver->stat_active_defrag_key_misses++;
|
||||
} while(1);
|
||||
}
|
||||
|
||||
@@ -996,26 +1004,26 @@ void computeDefragCycles() {
|
||||
size_t frag_bytes;
|
||||
float frag_pct = getAllocatorFragmentation(&frag_bytes);
|
||||
/* If we're not already running, and below the threshold, exit. */
|
||||
if (!server.active_defrag_running) {
|
||||
if(frag_pct < server.active_defrag_threshold_lower || frag_bytes < server.active_defrag_ignore_bytes)
|
||||
if (!g_pserver->active_defrag_running) {
|
||||
if(frag_pct < cserver.active_defrag_threshold_lower || frag_bytes < cserver.active_defrag_ignore_bytes)
|
||||
return;
|
||||
}
|
||||
|
||||
/* Calculate the adaptive aggressiveness of the defrag */
|
||||
int cpu_pct = INTERPOLATE(frag_pct,
|
||||
server.active_defrag_threshold_lower,
|
||||
server.active_defrag_threshold_upper,
|
||||
server.active_defrag_cycle_min,
|
||||
server.active_defrag_cycle_max);
|
||||
cserver.active_defrag_threshold_lower,
|
||||
cserver.active_defrag_threshold_upper,
|
||||
cserver.active_defrag_cycle_min,
|
||||
cserver.active_defrag_cycle_max);
|
||||
cpu_pct = LIMIT(cpu_pct,
|
||||
server.active_defrag_cycle_min,
|
||||
server.active_defrag_cycle_max);
|
||||
cserver.active_defrag_cycle_min,
|
||||
cserver.active_defrag_cycle_max);
|
||||
/* We allow increasing the aggressiveness during a scan, but don't
|
||||
* reduce it. */
|
||||
if (!server.active_defrag_running ||
|
||||
cpu_pct > server.active_defrag_running)
|
||||
if (!g_pserver->active_defrag_running ||
|
||||
cpu_pct > g_pserver->active_defrag_running)
|
||||
{
|
||||
server.active_defrag_running = cpu_pct;
|
||||
g_pserver->active_defrag_running = cpu_pct;
|
||||
serverLog(LL_VERBOSE,
|
||||
"Starting active defrag, frag=%.0f%%, frag_bytes=%zu, cpu=%d%%",
|
||||
frag_pct, frag_bytes, cpu_pct);
|
||||
@@ -1031,13 +1039,13 @@ void activeDefragCycle(void) {
|
||||
static redisDb *db = NULL;
|
||||
static long long start_scan, start_stat;
|
||||
unsigned int iterations = 0;
|
||||
unsigned long long prev_defragged = server.stat_active_defrag_hits;
|
||||
unsigned long long prev_scanned = server.stat_active_defrag_scanned;
|
||||
unsigned long long prev_defragged = g_pserver->stat_active_defrag_hits;
|
||||
unsigned long long prev_scanned = g_pserver->stat_active_defrag_scanned;
|
||||
long long start, timelimit, endtime;
|
||||
mstime_t latency;
|
||||
int quit = 0;
|
||||
|
||||
if (server.aof_child_pid!=-1 || server.rdb_child_pid!=-1)
|
||||
if (g_pserver->aof_child_pid!=-1 || g_pserver->rdb_child_pid!=-1)
|
||||
return; /* Defragging memory while there's a fork will just do damage. */
|
||||
|
||||
/* Once a second, check if we the fragmentation justfies starting a scan
|
||||
@@ -1045,12 +1053,12 @@ void activeDefragCycle(void) {
|
||||
run_with_period(1000) {
|
||||
computeDefragCycles();
|
||||
}
|
||||
if (!server.active_defrag_running)
|
||||
if (!g_pserver->active_defrag_running)
|
||||
return;
|
||||
|
||||
/* See activeExpireCycle for how timelimit is handled. */
|
||||
start = ustime();
|
||||
timelimit = 1000000*server.active_defrag_running/server.hz/100;
|
||||
timelimit = 1000000*g_pserver->active_defrag_running/g_pserver->hz/100;
|
||||
if (timelimit <= 0) timelimit = 1;
|
||||
endtime = start + timelimit;
|
||||
latencyStartMonitor(latency);
|
||||
@@ -1065,7 +1073,7 @@ void activeDefragCycle(void) {
|
||||
}
|
||||
|
||||
/* Move on to next database, and stop if we reached the last one. */
|
||||
if (++current_db >= server.dbnum) {
|
||||
if (++current_db >= cserver.dbnum) {
|
||||
/* defrag other items not part of the db / keys */
|
||||
defragOtherGlobals();
|
||||
|
||||
@@ -1074,26 +1082,26 @@ void activeDefragCycle(void) {
|
||||
float frag_pct = getAllocatorFragmentation(&frag_bytes);
|
||||
serverLog(LL_VERBOSE,
|
||||
"Active defrag done in %dms, reallocated=%d, frag=%.0f%%, frag_bytes=%zu",
|
||||
(int)((now - start_scan)/1000), (int)(server.stat_active_defrag_hits - start_stat), frag_pct, frag_bytes);
|
||||
(int)((now - start_scan)/1000), (int)(g_pserver->stat_active_defrag_hits - start_stat), frag_pct, frag_bytes);
|
||||
|
||||
start_scan = now;
|
||||
current_db = -1;
|
||||
cursor = 0;
|
||||
db = NULL;
|
||||
server.active_defrag_running = 0;
|
||||
g_pserver->active_defrag_running = 0;
|
||||
|
||||
computeDefragCycles(); /* if another scan is needed, start it right away */
|
||||
if (server.active_defrag_running != 0 && ustime() < endtime)
|
||||
if (g_pserver->active_defrag_running != 0 && ustime() < endtime)
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
else if (current_db==0) {
|
||||
/* Start a scan from the first database. */
|
||||
start_scan = ustime();
|
||||
start_stat = server.stat_active_defrag_hits;
|
||||
start_stat = g_pserver->stat_active_defrag_hits;
|
||||
}
|
||||
|
||||
db = &server.db[current_db];
|
||||
db = &g_pserver->db[current_db];
|
||||
cursor = 0;
|
||||
}
|
||||
|
||||
@@ -1112,15 +1120,15 @@ void activeDefragCycle(void) {
|
||||
* But regardless, don't start a new db in this loop, this is because after
|
||||
* the last db we call defragOtherGlobals, which must be done in once cycle */
|
||||
if (!cursor || (++iterations > 16 ||
|
||||
server.stat_active_defrag_hits - prev_defragged > 512 ||
|
||||
server.stat_active_defrag_scanned - prev_scanned > 64)) {
|
||||
g_pserver->stat_active_defrag_hits - prev_defragged > 512 ||
|
||||
g_pserver->stat_active_defrag_scanned - prev_scanned > 64)) {
|
||||
if (!cursor || ustime() > endtime) {
|
||||
quit = 1;
|
||||
break;
|
||||
}
|
||||
iterations = 0;
|
||||
prev_defragged = server.stat_active_defrag_hits;
|
||||
prev_scanned = server.stat_active_defrag_scanned;
|
||||
prev_defragged = g_pserver->stat_active_defrag_hits;
|
||||
prev_scanned = g_pserver->stat_active_defrag_scanned;
|
||||
}
|
||||
} while(cursor && !quit);
|
||||
} while(!quit);
|
||||
@@ -84,11 +84,11 @@ uint8_t *dictGetHashFunctionSeed(void) {
|
||||
/* The default hashing function uses SipHash implementation
|
||||
* in siphash.c. */
|
||||
|
||||
uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k);
|
||||
uint64_t siphash_nocase(const uint8_t *in, const size_t inlen, const uint8_t *k);
|
||||
extern "C" uint64_t siphash(const uint8_t *in, const size_t inlen, const uint8_t *k);
|
||||
extern "C" uint64_t siphash_nocase(const uint8_t *in, const size_t inlen, const uint8_t *k);
|
||||
|
||||
uint64_t dictGenHashFunction(const void *key, int len) {
|
||||
return siphash(key,len,dict_hash_function_seed);
|
||||
return siphash((const uint8_t*)key,len,dict_hash_function_seed);
|
||||
}
|
||||
|
||||
uint64_t dictGenCaseHashFunction(const unsigned char *buf, int len) {
|
||||
@@ -111,7 +111,7 @@ static void _dictReset(dictht *ht)
|
||||
dict *dictCreate(dictType *type,
|
||||
void *privDataPtr)
|
||||
{
|
||||
dict *d = zmalloc(sizeof(*d), MALLOC_SHARED);
|
||||
dict *d = (dict*)zmalloc(sizeof(*d), MALLOC_SHARED);
|
||||
|
||||
_dictInit(d,type,privDataPtr);
|
||||
return d;
|
||||
@@ -160,7 +160,7 @@ int dictExpand(dict *d, unsigned long size)
|
||||
/* Allocate the new hash table and initialize all pointers to NULL */
|
||||
n.size = realsize;
|
||||
n.sizemask = realsize-1;
|
||||
n.table = zcalloc(realsize*sizeof(dictEntry*), MALLOC_SHARED);
|
||||
n.table = (dictEntry**)zcalloc(realsize*sizeof(dictEntry*), MALLOC_SHARED);
|
||||
n.used = 0;
|
||||
|
||||
/* Is this the first initialization? If so it's not really a rehashing
|
||||
@@ -307,7 +307,7 @@ dictEntry *dictAddRaw(dict *d, void *key, dictEntry **existing)
|
||||
* system it is more likely that recently added entries are accessed
|
||||
* more frequently. */
|
||||
ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
|
||||
entry = zmalloc(sizeof(*entry), MALLOC_SHARED);
|
||||
entry = (dictEntry*)zmalloc(sizeof(*entry), MALLOC_SHARED);
|
||||
entry->next = ht->table[index];
|
||||
ht->table[index] = entry;
|
||||
ht->used++;
|
||||
@@ -541,7 +541,7 @@ long long dictFingerprint(dict *d) {
|
||||
|
||||
dictIterator *dictGetIterator(dict *d)
|
||||
{
|
||||
dictIterator *iter = zmalloc(sizeof(*iter), MALLOC_LOCAL);
|
||||
dictIterator *iter = (dictIterator*)zmalloc(sizeof(*iter), MALLOC_LOCAL);
|
||||
|
||||
iter->d = d;
|
||||
iter->table = 0;
|
||||
@@ -39,6 +39,10 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#ifndef __cplusplus
|
||||
#error "C++ Only"
|
||||
#endif
|
||||
|
||||
#ifndef __DICT_H
|
||||
#define __DICT_H
|
||||
|
||||
|
||||
+178
-151
@@ -77,8 +77,8 @@ unsigned int getLRUClock(void) {
|
||||
* precomputed value, otherwise we need to resort to a system call. */
|
||||
unsigned int LRU_CLOCK(void) {
|
||||
unsigned int lruclock;
|
||||
if (1000/server.hz <= LRU_CLOCK_RESOLUTION) {
|
||||
atomicGet(server.lruclock,lruclock);
|
||||
if (1000/g_pserver->hz <= LRU_CLOCK_RESOLUTION) {
|
||||
lruclock = g_pserver->lruclock;
|
||||
} else {
|
||||
lruclock = getLRUClock();
|
||||
}
|
||||
@@ -111,7 +111,7 @@ unsigned long long estimateObjectIdleTime(robj *o) {
|
||||
* If all the bytes needed to return back under the limit were freed the
|
||||
* function returns C_OK, otherwise C_ERR is returned, and the caller
|
||||
* should block the execution of commands that will result in more memory
|
||||
* used by the server.
|
||||
* used by the g_pserver->
|
||||
*
|
||||
* ------------------------------------------------------------------------
|
||||
*
|
||||
@@ -140,7 +140,7 @@ void evictionPoolAlloc(void) {
|
||||
struct evictionPoolEntry *ep;
|
||||
int j;
|
||||
|
||||
ep = zmalloc(sizeof(*ep)*EVPOOL_SIZE, MALLOC_LOCAL);
|
||||
ep = (evictionPoolEntry*)zmalloc(sizeof(*ep)*EVPOOL_SIZE, MALLOC_LOCAL);
|
||||
for (j = 0; j < EVPOOL_SIZE; j++) {
|
||||
ep[j].idle = 0;
|
||||
ep[j].key = NULL;
|
||||
@@ -150,6 +150,84 @@ void evictionPoolAlloc(void) {
|
||||
EvictionPoolLRU = ep;
|
||||
}
|
||||
|
||||
void processEvictionCandidate(int dbid, sds key, robj *o, const expireEntry *e, struct evictionPoolEntry *pool)
|
||||
{
|
||||
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
|
||||
* bucket that has an idle time smaller than our idle time. */
|
||||
int k = 0;
|
||||
while (k < EVPOOL_SIZE &&
|
||||
pool[k].key &&
|
||||
pool[k].idle < idle) k++;
|
||||
if (k == 0 && pool[EVPOOL_SIZE-1].key != NULL) {
|
||||
/* Can't insert if the element is < the worst element we have
|
||||
* and there are no empty buckets. */
|
||||
return;
|
||||
} else if (k < EVPOOL_SIZE && pool[k].key == NULL) {
|
||||
/* Inserting into empty position. No setup needed before insert. */
|
||||
} else {
|
||||
/* Inserting in the middle. Now k points to the first element
|
||||
* greater than the element to insert. */
|
||||
if (pool[EVPOOL_SIZE-1].key == NULL) {
|
||||
/* Free space on the right? Insert at k shifting
|
||||
* all the elements from k to end to the right. */
|
||||
|
||||
/* Save SDS before overwriting. */
|
||||
sds cached = pool[EVPOOL_SIZE-1].cached;
|
||||
memmove(pool+k+1,pool+k,
|
||||
sizeof(pool[0])*(EVPOOL_SIZE-k-1));
|
||||
pool[k].cached = cached;
|
||||
} else {
|
||||
/* No free space on right? Insert at k-1 */
|
||||
k--;
|
||||
/* Shift all elements on the left of k (included) to the
|
||||
* left, so we discard the element with smaller idle time. */
|
||||
sds cached = pool[0].cached; /* Save SDS before overwriting. */
|
||||
if (pool[0].key != pool[0].cached) sdsfree(pool[0].key);
|
||||
memmove(pool,pool+1,sizeof(pool[0])*k);
|
||||
pool[k].cached = cached;
|
||||
}
|
||||
}
|
||||
|
||||
/* Try to reuse the cached SDS string allocated in the pool entry,
|
||||
* because allocating and deallocating this object is costly
|
||||
* (according to the profiler, not my fantasy. Remember:
|
||||
* premature optimizbla bla bla bla. */
|
||||
int klen = sdslen(key);
|
||||
if (klen > EVPOOL_CACHED_SDS_SIZE) {
|
||||
pool[k].key = sdsdup(key);
|
||||
} else {
|
||||
memcpy(pool[k].cached,key,klen+1);
|
||||
sdssetlen(pool[k].cached,klen);
|
||||
pool[k].key = pool[k].cached;
|
||||
}
|
||||
pool[k].idle = idle;
|
||||
pool[k].dbid = dbid;
|
||||
}
|
||||
|
||||
/* This is an helper function for freeMemoryIfNeeded(), it is used in order
|
||||
* to populate the evictionPool with a few entries every time we want to
|
||||
* expire a key. Keys with idle time smaller than one of the current
|
||||
@@ -159,100 +237,36 @@ void evictionPoolAlloc(void) {
|
||||
* idle time are on the left, and keys with the higher idle time on the
|
||||
* right. */
|
||||
|
||||
void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) {
|
||||
int j, k, count;
|
||||
dictEntry *samples[server.maxmemory_samples];
|
||||
struct visitFunctor
|
||||
{
|
||||
int dbid;
|
||||
dict *dbdict;
|
||||
struct evictionPoolEntry *pool;
|
||||
int count;
|
||||
|
||||
count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples);
|
||||
for (j = 0; j < count; j++) {
|
||||
unsigned long long idle;
|
||||
sds key;
|
||||
robj *o;
|
||||
dictEntry *de;
|
||||
|
||||
de = samples[j];
|
||||
key = dictGetKey(de);
|
||||
|
||||
/* If the dictionary we are sampling from is not the main
|
||||
* dictionary (but the expires one) we need to lookup the key
|
||||
* again in the key dictionary to obtain the value object. */
|
||||
if (server.maxmemory_policy != MAXMEMORY_VOLATILE_TTL) {
|
||||
if (sampledict != keydict) de = dictFind(keydict, key);
|
||||
o = dictGetVal(de);
|
||||
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);
|
||||
}
|
||||
|
||||
/* 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 (server.maxmemory_policy & MAXMEMORY_FLAG_LRU) {
|
||||
idle = estimateObjectIdleTime(o);
|
||||
} else if (server.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 (server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL) {
|
||||
/* In this case the sooner the expire the better. */
|
||||
idle = ULLONG_MAX - (long)dictGetVal(de);
|
||||
} else {
|
||||
serverPanic("Unknown eviction policy in evictionPoolPopulate()");
|
||||
}
|
||||
|
||||
/* Insert the element inside the pool.
|
||||
* First, find the first empty bucket or the first populated
|
||||
* bucket that has an idle time smaller than our idle time. */
|
||||
k = 0;
|
||||
while (k < EVPOOL_SIZE &&
|
||||
pool[k].key &&
|
||||
pool[k].idle < idle) k++;
|
||||
if (k == 0 && pool[EVPOOL_SIZE-1].key != NULL) {
|
||||
/* Can't insert if the element is < the worst element we have
|
||||
* and there are no empty buckets. */
|
||||
continue;
|
||||
} else if (k < EVPOOL_SIZE && pool[k].key == NULL) {
|
||||
/* Inserting into empty position. No setup needed before insert. */
|
||||
} else {
|
||||
/* Inserting in the middle. Now k points to the first element
|
||||
* greater than the element to insert. */
|
||||
if (pool[EVPOOL_SIZE-1].key == NULL) {
|
||||
/* Free space on the right? Insert at k shifting
|
||||
* all the elements from k to end to the right. */
|
||||
|
||||
/* Save SDS before overwriting. */
|
||||
sds cached = pool[EVPOOL_SIZE-1].cached;
|
||||
memmove(pool+k+1,pool+k,
|
||||
sizeof(pool[0])*(EVPOOL_SIZE-k-1));
|
||||
pool[k].cached = cached;
|
||||
} else {
|
||||
/* No free space on right? Insert at k-1 */
|
||||
k--;
|
||||
/* Shift all elements on the left of k (included) to the
|
||||
* left, so we discard the element with smaller idle time. */
|
||||
sds cached = pool[0].cached; /* Save SDS before overwriting. */
|
||||
if (pool[0].key != pool[0].cached) sdsfree(pool[0].key);
|
||||
memmove(pool,pool+1,sizeof(pool[0])*k);
|
||||
pool[k].cached = cached;
|
||||
}
|
||||
}
|
||||
|
||||
/* Try to reuse the cached SDS string allocated in the pool entry,
|
||||
* because allocating and deallocating this object is costly
|
||||
* (according to the profiler, not my fantasy. Remember:
|
||||
* premature optimizbla bla bla bla. */
|
||||
int klen = sdslen(key);
|
||||
if (klen > EVPOOL_CACHED_SDS_SIZE) {
|
||||
pool[k].key = sdsdup(key);
|
||||
} else {
|
||||
memcpy(pool[k].cached,key,klen+1);
|
||||
sdssetlen(pool[k].cached,klen);
|
||||
pool[k].key = pool[k].cached;
|
||||
}
|
||||
pool[k].idle = idle;
|
||||
pool[k].dbid = dbid;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,7 +311,7 @@ void evictionPoolPopulate(int dbid, dict *sampledict, dict *keydict, struct evic
|
||||
* 16 bits. The returned time is suitable to be stored as LDT (last decrement
|
||||
* time) for the LFU implementation. */
|
||||
unsigned long LFUGetTimeInMinutes(void) {
|
||||
return (server.unixtime/60) & 65535;
|
||||
return (g_pserver->unixtime/60) & 65535;
|
||||
}
|
||||
|
||||
/* Given an object last access time, compute the minimum number of minutes
|
||||
@@ -317,7 +331,7 @@ uint8_t LFULogIncr(uint8_t counter) {
|
||||
double r = (double)rand()/RAND_MAX;
|
||||
double baseval = counter - LFU_INIT_VAL;
|
||||
if (baseval < 0) baseval = 0;
|
||||
double p = 1.0/(baseval*server.lfu_log_factor+1);
|
||||
double p = 1.0/(baseval*g_pserver->lfu_log_factor+1);
|
||||
if (r < p) counter++;
|
||||
return counter;
|
||||
}
|
||||
@@ -326,7 +340,7 @@ uint8_t LFULogIncr(uint8_t counter) {
|
||||
* do not update LFU fields of the object, we update the access time
|
||||
* and counter in an explicit way when the object is really accessed.
|
||||
* And we will times halve the counter according to the times of
|
||||
* elapsed time than server.lfu_decay_time.
|
||||
* elapsed time than g_pserver->lfu_decay_time.
|
||||
* Return the object frequency counter.
|
||||
*
|
||||
* This function is used in order to scan the dataset for the best object
|
||||
@@ -335,7 +349,7 @@ uint8_t LFULogIncr(uint8_t counter) {
|
||||
unsigned long LFUDecrAndReturn(robj *o) {
|
||||
unsigned long ldt = o->lru >> 8;
|
||||
unsigned long counter = o->lru & 255;
|
||||
unsigned long num_periods = server.lfu_decay_time ? LFUTimeElapsed(ldt) / server.lfu_decay_time : 0;
|
||||
unsigned long num_periods = g_pserver->lfu_decay_time ? LFUTimeElapsed(ldt) / g_pserver->lfu_decay_time : 0;
|
||||
if (num_periods)
|
||||
counter = (num_periods > counter) ? 0 : counter - num_periods;
|
||||
return counter;
|
||||
@@ -352,20 +366,20 @@ unsigned long LFUDecrAndReturn(robj *o) {
|
||||
size_t freeMemoryGetNotCountedMemory(void) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
size_t overhead = 0;
|
||||
int slaves = listLength(server.slaves);
|
||||
int slaves = listLength(g_pserver->slaves);
|
||||
|
||||
if (slaves) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
|
||||
listRewind(server.slaves,&li);
|
||||
listRewind(g_pserver->slaves,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
client *slave = listNodeValue(ln);
|
||||
overhead += getClientOutputBufferMemoryUsage(slave);
|
||||
client *replica = (client*)listNodeValue(ln);
|
||||
overhead += getClientOutputBufferMemoryUsage(replica);
|
||||
}
|
||||
}
|
||||
if (server.aof_state != AOF_OFF) {
|
||||
overhead += sdsalloc(server.aof_buf)+aofRewriteBufferSize();
|
||||
if (g_pserver->aof_state != AOF_OFF) {
|
||||
overhead += sdsalloc(g_pserver->aof_buf)+aofRewriteBufferSize();
|
||||
}
|
||||
return overhead;
|
||||
}
|
||||
@@ -403,7 +417,7 @@ int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *lev
|
||||
if (total) *total = mem_reported;
|
||||
|
||||
/* We may return ASAP if there is no need to compute the level. */
|
||||
int return_ok_asap = !server.maxmemory || mem_reported <= server.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
|
||||
@@ -414,20 +428,20 @@ int getMaxmemoryState(size_t *total, size_t *logical, size_t *tofree, float *lev
|
||||
|
||||
/* Compute the ratio of memory usage. */
|
||||
if (level) {
|
||||
if (!server.maxmemory) {
|
||||
if (!g_pserver->maxmemory) {
|
||||
*level = 0;
|
||||
} else {
|
||||
*level = (float)mem_used / (float)server.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 <= server.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 - server.maxmemory;
|
||||
mem_tofree = mem_used - g_pserver->maxmemory;
|
||||
|
||||
if (logical) *logical = mem_used;
|
||||
if (tofree) *tofree = mem_tofree;
|
||||
@@ -448,12 +462,12 @@ int freeMemoryIfNeeded(void) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
/* By default replicas should ignore maxmemory
|
||||
* and just be masters exact copies. */
|
||||
if (server.masterhost && server.repl_slave_ignore_maxmemory) return C_OK;
|
||||
if (listLength(g_pserver->masters) && g_pserver->repl_slave_ignore_maxmemory) return C_OK;
|
||||
|
||||
size_t mem_reported, mem_tofree, mem_freed;
|
||||
mstime_t latency, eviction_latency;
|
||||
long long delta;
|
||||
int slaves = listLength(server.slaves);
|
||||
int slaves = listLength(g_pserver->slaves);
|
||||
|
||||
/* 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
|
||||
@@ -464,7 +478,7 @@ int freeMemoryIfNeeded(void) {
|
||||
|
||||
mem_freed = 0;
|
||||
|
||||
if (server.maxmemory_policy == MAXMEMORY_NO_EVICTION)
|
||||
if (g_pserver->maxmemory_policy == MAXMEMORY_NO_EVICTION)
|
||||
goto cant_free; /* We need to free memory, but policy forbids. */
|
||||
|
||||
latencyStartMonitor(latency);
|
||||
@@ -474,11 +488,9 @@ int freeMemoryIfNeeded(void) {
|
||||
sds bestkey = NULL;
|
||||
int bestdbid;
|
||||
redisDb *db;
|
||||
dict *dict;
|
||||
dictEntry *de;
|
||||
|
||||
if (server.maxmemory_policy & (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
|
||||
server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL)
|
||||
if (g_pserver->maxmemory_policy & (MAXMEMORY_FLAG_LRU|MAXMEMORY_FLAG_LFU) ||
|
||||
g_pserver->maxmemory_policy == MAXMEMORY_VOLATILE_TTL)
|
||||
{
|
||||
struct evictionPoolEntry *pool = EvictionPoolLRU;
|
||||
|
||||
@@ -488,12 +500,20 @@ int freeMemoryIfNeeded(void) {
|
||||
/* We don't want to make local-db choices when expiring keys,
|
||||
* so to start populate the eviction pool sampling keys from
|
||||
* every DB. */
|
||||
for (i = 0; i < server.dbnum; i++) {
|
||||
db = server.db+i;
|
||||
dict = (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) ?
|
||||
db->pdict : db->expires;
|
||||
if ((keys = dictSize(dict)) != 0) {
|
||||
evictionPoolPopulate(i, dict, db->pdict, pool);
|
||||
for (i = 0; i < cserver.dbnum; i++) {
|
||||
db = g_pserver->db+i;
|
||||
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS)
|
||||
{
|
||||
if ((keys = dictSize(db->pdict)) != 0) {
|
||||
evictionPoolPopulate(i, db->pdict, nullptr, pool);
|
||||
total_keys += keys;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
keys = db->setexpire->size();
|
||||
if (keys != 0)
|
||||
evictionPoolPopulate(i, db->pdict, db->setexpire, pool);
|
||||
total_keys += keys;
|
||||
}
|
||||
}
|
||||
@@ -503,14 +523,11 @@ int freeMemoryIfNeeded(void) {
|
||||
for (k = EVPOOL_SIZE-1; k >= 0; k--) {
|
||||
if (pool[k].key == NULL) continue;
|
||||
bestdbid = pool[k].dbid;
|
||||
sds key = nullptr;
|
||||
|
||||
if (server.maxmemory_policy & MAXMEMORY_FLAG_ALLKEYS) {
|
||||
de = dictFind(server.db[pool[k].dbid].pdict,
|
||||
pool[k].key);
|
||||
} else {
|
||||
de = dictFind(server.db[pool[k].dbid].expires,
|
||||
pool[k].key);
|
||||
}
|
||||
dictEntry *de = dictFind(g_pserver->db[pool[k].dbid].pdict,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)
|
||||
@@ -520,8 +537,8 @@ int freeMemoryIfNeeded(void) {
|
||||
|
||||
/* If the key exists, is our pick. Otherwise it is
|
||||
* a ghost and we need to try the next element. */
|
||||
if (de) {
|
||||
bestkey = dictGetKey(de);
|
||||
if (key) {
|
||||
bestkey = key;
|
||||
break;
|
||||
} else {
|
||||
/* Ghost... Iterate again. */
|
||||
@@ -531,31 +548,41 @@ int freeMemoryIfNeeded(void) {
|
||||
}
|
||||
|
||||
/* volatile-random and allkeys-random policy */
|
||||
else if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM ||
|
||||
server.maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM)
|
||||
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 < server.dbnum; i++) {
|
||||
j = (++next_db) % server.dbnum;
|
||||
db = server.db+j;
|
||||
dict = (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM) ?
|
||||
db->pdict : db->expires;
|
||||
if (dictSize(dict) != 0) {
|
||||
de = dictGetRandomKey(dict);
|
||||
bestkey = dictGetKey(de);
|
||||
bestdbid = j;
|
||||
break;
|
||||
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)
|
||||
{
|
||||
if (dictSize(db->pdict) != 0) {
|
||||
dictEntry *de = dictGetRandomKey(db->pdict);
|
||||
bestkey = (sds)dictGetKey(de);
|
||||
bestdbid = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!db->setexpire->empty())
|
||||
{
|
||||
bestkey = (sds)db->setexpire->random_value().key();
|
||||
bestdbid = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Finally remove the selected key. */
|
||||
if (bestkey) {
|
||||
db = server.db+bestdbid;
|
||||
db = g_pserver->db+bestdbid;
|
||||
robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
|
||||
propagateExpire(db,keyobj,server.lazyfree_lazy_eviction);
|
||||
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
|
||||
@@ -566,7 +593,7 @@ int freeMemoryIfNeeded(void) {
|
||||
* we only care about memory used by the key space. */
|
||||
delta = (long long) zmalloc_used_memory();
|
||||
latencyStartMonitor(eviction_latency);
|
||||
if (server.lazyfree_lazy_eviction)
|
||||
if (g_pserver->lazyfree_lazy_eviction)
|
||||
dbAsyncDelete(db,keyobj);
|
||||
else
|
||||
dbSyncDelete(db,keyobj);
|
||||
@@ -575,7 +602,7 @@ int freeMemoryIfNeeded(void) {
|
||||
latencyRemoveNestedEvent(latency,eviction_latency);
|
||||
delta -= (long long) zmalloc_used_memory();
|
||||
mem_freed += delta;
|
||||
server.stat_evictedkeys++;
|
||||
g_pserver->stat_evictedkeys++;
|
||||
notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted",
|
||||
keyobj, db->id);
|
||||
decrRefCount(keyobj);
|
||||
@@ -594,7 +621,7 @@ int freeMemoryIfNeeded(void) {
|
||||
* memory, since the "mem_freed" amount is computed only
|
||||
* across the dbAsyncDelete() call, while the thread can
|
||||
* release the memory all the time. */
|
||||
if (server.lazyfree_lazy_eviction && !(keys_freed % 16)) {
|
||||
if (g_pserver->lazyfree_lazy_eviction && !(keys_freed % 16)) {
|
||||
if (getMaxmemoryState(NULL,NULL,NULL,NULL) == C_OK) {
|
||||
/* Let's satisfy our stop condition. */
|
||||
mem_freed = mem_tofree;
|
||||
@@ -632,6 +659,6 @@ cant_free:
|
||||
*
|
||||
*/
|
||||
int freeMemoryIfNeededAndSafe(void) {
|
||||
if (server.lua_timedout || server.loading) return C_OK;
|
||||
if (g_pserver->lua_timedout || g_pserver->loading) return C_OK;
|
||||
return freeMemoryIfNeeded();
|
||||
}
|
||||
+268
-122
@@ -32,6 +32,21 @@
|
||||
|
||||
#include "server.h"
|
||||
|
||||
void activeExpireCycleExpireFullKey(redisDb *db, const char *key) {
|
||||
robj *keyobj = createStringObject(key,sdslen(key));
|
||||
|
||||
propagateExpire(db,keyobj,g_pserver->lazyfree_lazy_expire);
|
||||
if (g_pserver->lazyfree_lazy_expire)
|
||||
dbAsyncDelete(db,keyobj);
|
||||
else
|
||||
dbSyncDelete(db,keyobj);
|
||||
notifyKeyspaceEvent(NOTIFY_EXPIRED,
|
||||
"expired",keyobj,db->id);
|
||||
if (g_pserver->tracking_clients) trackingInvalidateKey(keyobj);
|
||||
decrRefCount(keyobj);
|
||||
g_pserver->stat_expiredkeys++;
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------------------------
|
||||
* Incremental collection of expired keys.
|
||||
*
|
||||
@@ -47,31 +62,153 @@
|
||||
* If the key is found to be expired, it is removed from the database and
|
||||
* 1 is returned. Otherwise no operation is performed and 0 is returned.
|
||||
*
|
||||
* When a key is expired, server.stat_expiredkeys is incremented.
|
||||
* When a key is expired, g_pserver->stat_expiredkeys is incremented.
|
||||
*
|
||||
* The parameter 'now' is the current time in milliseconds as is passed
|
||||
* to the function to avoid too many gettimeofday() syscalls. */
|
||||
int activeExpireCycleTryExpire(redisDb *db, dictEntry *de, long long now) {
|
||||
long long t = dictGetSignedIntegerVal(de);
|
||||
if (now > t) {
|
||||
sds key = dictGetKey(de);
|
||||
robj *keyobj = createStringObject(key,sdslen(key));
|
||||
void activeExpireCycleExpire(redisDb *db, expireEntry &e, long long now) {
|
||||
if (!e.FFat())
|
||||
{
|
||||
activeExpireCycleExpireFullKey(db, e.key());
|
||||
return;
|
||||
}
|
||||
|
||||
propagateExpire(db,keyobj,server.lazyfree_lazy_expire);
|
||||
if (server.lazyfree_lazy_expire)
|
||||
dbAsyncDelete(db,keyobj);
|
||||
else
|
||||
dbSyncDelete(db,keyobj);
|
||||
notifyKeyspaceEvent(NOTIFY_EXPIRED,
|
||||
"expired",keyobj,db->id);
|
||||
expireEntryFat *pfat = e.pfatentry();
|
||||
dictEntry *de = dictFind(db->pdict, e.key());
|
||||
robj *val = (robj*)dictGetVal(de);
|
||||
int deleted = 0;
|
||||
while (!pfat->FEmpty())
|
||||
{
|
||||
if (pfat->nextExpireEntry().when > now)
|
||||
break;
|
||||
|
||||
// Is it the full key expiration?
|
||||
if (pfat->nextExpireEntry().spsubkey == nullptr)
|
||||
{
|
||||
activeExpireCycleExpireFullKey(db, e.key());
|
||||
return;
|
||||
}
|
||||
|
||||
switch (val->type)
|
||||
{
|
||||
case OBJ_SET:
|
||||
if (setTypeRemove(val,pfat->nextExpireEntry().spsubkey.get())) {
|
||||
deleted++;
|
||||
if (setTypeSize(val) == 0) {
|
||||
activeExpireCycleExpireFullKey(db, e.key());
|
||||
return;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case OBJ_LIST:
|
||||
case OBJ_ZSET:
|
||||
case OBJ_HASH:
|
||||
default:
|
||||
serverAssert(false);
|
||||
}
|
||||
pfat->popfrontExpireEntry();
|
||||
}
|
||||
|
||||
if (deleted)
|
||||
{
|
||||
robj objT;
|
||||
switch (val->type)
|
||||
{
|
||||
case OBJ_SET:
|
||||
initStaticStringObject(objT, (char*)e.key());
|
||||
signalModifiedKey(db,&objT);
|
||||
notifyKeyspaceEvent(NOTIFY_SET,"srem",&objT,db->id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (pfat->FEmpty())
|
||||
{
|
||||
robj *keyobj = createStringObject(e.key(),sdslen(e.key()));
|
||||
removeExpire(db, keyobj);
|
||||
decrRefCount(keyobj);
|
||||
server.stat_expiredkeys++;
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int parseUnitString(const char *sz)
|
||||
{
|
||||
if (strcasecmp(sz, "s") == 0)
|
||||
return UNIT_SECONDS;
|
||||
if (strcasecmp(sz, "ms") == 0)
|
||||
return UNIT_MILLISECONDS;
|
||||
return -1;
|
||||
}
|
||||
|
||||
void expireMemberCore(client *c, robj *key, robj *subkey, long long basetime, long long when, int unit)
|
||||
{
|
||||
switch (unit)
|
||||
{
|
||||
case UNIT_SECONDS:
|
||||
when *= 1000;
|
||||
case UNIT_MILLISECONDS:
|
||||
break;
|
||||
|
||||
default:
|
||||
addReplyError(c, "Invalid unit arg");
|
||||
return;
|
||||
}
|
||||
|
||||
when += basetime;
|
||||
|
||||
/* No key, return zero. */
|
||||
robj *val = lookupKeyWriteOrReply(c, key, shared.czero);
|
||||
if (val == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (val->type)
|
||||
{
|
||||
case OBJ_SET:
|
||||
if (!setTypeIsMember(val, szFromObj(subkey))) {
|
||||
addReply(c,shared.czero);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
addReplyError(c, "object type is unsupported");
|
||||
return;
|
||||
}
|
||||
|
||||
setExpire(c, c->db, key, subkey, when);
|
||||
|
||||
addReply(c, shared.cone);
|
||||
}
|
||||
|
||||
void expireMemberCommand(client *c)
|
||||
{
|
||||
long long when;
|
||||
if (getLongLongFromObjectOrReply(c, c->argv[3], &when, NULL) != C_OK)
|
||||
return;
|
||||
|
||||
if (c->argc > 5) {
|
||||
addReplyError(c, "Invalid number of arguments");
|
||||
return;
|
||||
}
|
||||
|
||||
int unit = UNIT_SECONDS;
|
||||
if (c->argc == 5) {
|
||||
unit = parseUnitString(szFromObj(c->argv[4]));
|
||||
}
|
||||
|
||||
expireMemberCore(c, c->argv[1], c->argv[2], mstime(), when, unit);
|
||||
}
|
||||
|
||||
void expireMemberAtCommand(client *c)
|
||||
{
|
||||
long long when;
|
||||
if (getLongLongFromObjectOrReply(c, c->argv[3], &when, NULL) != C_OK)
|
||||
return;
|
||||
|
||||
expireMemberCore(c, c->argv[1], c->argv[2], 0, when, UNIT_SECONDS);
|
||||
}
|
||||
|
||||
|
||||
/* Try to expire a few timed out keys. The algorithm used is adaptive and
|
||||
* will use few CPU cycles if there are few expiring keys, otherwise
|
||||
* it will get more aggressive to avoid that too much memory is used by
|
||||
@@ -126,14 +263,14 @@ void activeExpireCycle(int type) {
|
||||
* 2) If last time we hit the time limit, we want to scan all DBs
|
||||
* in this iteration, as there is work to do in some DB and we don't want
|
||||
* expired keys to use memory for too much time. */
|
||||
if (dbs_per_call > server.dbnum || timelimit_exit)
|
||||
dbs_per_call = server.dbnum;
|
||||
if (dbs_per_call > cserver.dbnum || timelimit_exit)
|
||||
dbs_per_call = cserver.dbnum;
|
||||
|
||||
/* 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
|
||||
* server.hz times per second, the following is the max amount of
|
||||
* g_pserver->hz times per second, the following is the max amount of
|
||||
* microseconds we can spend in this function. */
|
||||
timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100;
|
||||
timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/g_pserver->hz/100;
|
||||
timelimit_exit = 0;
|
||||
if (timelimit <= 0) timelimit = 1;
|
||||
|
||||
@@ -147,86 +284,53 @@ void activeExpireCycle(int type) {
|
||||
long total_expired = 0;
|
||||
|
||||
for (j = 0; j < dbs_per_call && timelimit_exit == 0; j++) {
|
||||
int expired;
|
||||
redisDb *db = server.db+(current_db % server.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++;
|
||||
|
||||
/* Continue to expire if at the end of the cycle more than 25%
|
||||
* of the keys were expired. */
|
||||
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 ((num = dictSize(db->expires)) == 0) {
|
||||
db->avg_ttl = 0;
|
||||
break;
|
||||
/* 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)
|
||||
{
|
||||
activeExpireCycleExpire(db, e, now);
|
||||
++expired;
|
||||
}
|
||||
slots = dictSlots(db->expires);
|
||||
now = mstime();
|
||||
++tried;
|
||||
|
||||
/* When there are less than 1% filled slots getting random
|
||||
* keys is expensive, so stop here waiting for better times...
|
||||
* The dictionary will be resized asap. */
|
||||
if (num && 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;
|
||||
ttl_sum = 0;
|
||||
ttl_samples = 0;
|
||||
|
||||
if (num > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP)
|
||||
num = ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP;
|
||||
|
||||
while (num--) {
|
||||
dictEntry *de;
|
||||
long long ttl;
|
||||
|
||||
if ((de = dictGetRandomKey(db->expires)) == NULL) break;
|
||||
ttl = dictGetSignedIntegerVal(de)-now;
|
||||
if (activeExpireCycleTryExpire(db,de,now)) expired++;
|
||||
if (ttl > 0) {
|
||||
/* We want the average TTL of keys yet not expired. */
|
||||
ttl_sum += ttl;
|
||||
ttl_samples++;
|
||||
}
|
||||
total_sampled++;
|
||||
}
|
||||
total_expired += expired;
|
||||
|
||||
/* 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);
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
elapsed = ustime()-start;
|
||||
if (elapsed > timelimit) {
|
||||
timelimit_exit = 1;
|
||||
server.stat_expired_time_cap_reached_count++;
|
||||
break;
|
||||
g_pserver->stat_expired_time_cap_reached_count++;
|
||||
return false;
|
||||
}
|
||||
check = ACTIVE_EXPIRE_CYCLE_FAST_DURATION;
|
||||
}
|
||||
/* We don't repeat the cycle if there are less than 25% of keys
|
||||
* found expired in the current DB. */
|
||||
} while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4);
|
||||
return true;
|
||||
}, &check);
|
||||
|
||||
total_expired += expired;
|
||||
}
|
||||
|
||||
elapsed = ustime()-start;
|
||||
@@ -239,8 +343,8 @@ void activeExpireCycle(int type) {
|
||||
current_perc = (double)total_expired/total_sampled;
|
||||
} else
|
||||
current_perc = 0;
|
||||
server.stat_expired_stale_perc = (current_perc*0.05)+
|
||||
(server.stat_expired_stale_perc*0.95);
|
||||
g_pserver->stat_expired_stale_perc = (current_perc*0.05)+
|
||||
(g_pserver->stat_expired_stale_perc*0.95);
|
||||
}
|
||||
|
||||
/*-----------------------------------------------------------------------------
|
||||
@@ -248,17 +352,17 @@ void activeExpireCycle(int type) {
|
||||
*
|
||||
* Normally slaves do not process expires: they wait the masters to synthesize
|
||||
* DEL operations in order to retain consistency. However writable slaves are
|
||||
* an exception: if a key is created in the slave and an expire is assigned
|
||||
* an exception: if a key is created in the replica and an expire is assigned
|
||||
* to it, we need a way to expire such a key, since the master does not know
|
||||
* anything about such a key.
|
||||
*
|
||||
* In order to do so, we track keys created in the slave side with an expire
|
||||
* In order to do so, we track keys created in the replica side with an expire
|
||||
* set, and call the expireSlaveKeys() function from time to time in order to
|
||||
* reclaim the keys if they already expired.
|
||||
*
|
||||
* Note that the use case we are trying to cover here, is a popular one where
|
||||
* slaves are put in writable mode in order to compute slow operations in
|
||||
* the slave side that are mostly useful to actually read data in a more
|
||||
* the replica side that are mostly useful to actually read data in a more
|
||||
* processed way. Think at sets intersections in a tmp key, with an expire so
|
||||
* that it is also used as a cache to avoid intersecting every time.
|
||||
*
|
||||
@@ -267,7 +371,7 @@ void activeExpireCycle(int type) {
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
/* The dictionary where we remember key names and database ID of keys we may
|
||||
* want to expire from the slave. Since this function is not often used we
|
||||
* want to expire from the replica. Since this function is not often used we
|
||||
* don't even care to initialize the database at startup. We'll do it once
|
||||
* the feature is used the first time, that is, when rememberSlaveKeyWithExpire()
|
||||
* is called.
|
||||
@@ -290,30 +394,37 @@ void expireSlaveKeys(void) {
|
||||
mstime_t start = mstime();
|
||||
while(1) {
|
||||
dictEntry *de = dictGetRandomKey(slaveKeysWithExpire);
|
||||
sds keyname = dictGetKey(de);
|
||||
sds keyname = (sds)dictGetKey(de);
|
||||
uint64_t dbids = dictGetUnsignedIntegerVal(de);
|
||||
uint64_t new_dbids = 0;
|
||||
|
||||
/* Check the key against every database corresponding to the
|
||||
* bits set in the value bitmap. */
|
||||
int dbid = 0;
|
||||
while(dbids && dbid < server.dbnum) {
|
||||
while(dbids && dbid < cserver.dbnum) {
|
||||
if ((dbids & 1) != 0) {
|
||||
redisDb *db = server.db+dbid;
|
||||
dictEntry *expire = dictFind(db->expires,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->pdict, keyname);
|
||||
auto itr = db->setexpire->end();
|
||||
if (deMain != nullptr)
|
||||
itr = db->setexpire->find((sds)dictGetKey(deMain));
|
||||
int expired = 0;
|
||||
|
||||
if (expire &&
|
||||
activeExpireCycleTryExpire(server.db+dbid,expire,start))
|
||||
if (itr != db->setexpire->end())
|
||||
{
|
||||
expired = 1;
|
||||
if (itr->when() < start) {
|
||||
activeExpireCycleExpire(g_pserver->db+dbid,*itr,start);
|
||||
expired = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* If the key was not expired in this DB, we need to set the
|
||||
* 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 (expire && !expired) {
|
||||
if (itr != db->setexpire->end() && !expired) {
|
||||
noexpire++;
|
||||
new_dbids |= (uint64_t)1 << dbid;
|
||||
}
|
||||
@@ -323,7 +434,7 @@ void expireSlaveKeys(void) {
|
||||
}
|
||||
|
||||
/* Set the new bitmap as value of the key, in the dictionary
|
||||
* of keys with an expire set directly in the writable slave. Otherwise
|
||||
* of keys with an expire set directly in the writable replica. Otherwise
|
||||
* if the bitmap is zero, we no longer need to keep track of it. */
|
||||
if (new_dbids)
|
||||
dictSetUnsignedIntegerVal(de,new_dbids);
|
||||
@@ -340,7 +451,7 @@ void expireSlaveKeys(void) {
|
||||
}
|
||||
|
||||
/* Track keys that received an EXPIRE or similar command in the context
|
||||
* of a writable slave. */
|
||||
* of a writable replica. */
|
||||
void rememberSlaveKeyWithExpire(redisDb *db, robj *key) {
|
||||
if (slaveKeysWithExpire == NULL) {
|
||||
static dictType dt = {
|
||||
@@ -361,7 +472,7 @@ void rememberSlaveKeyWithExpire(redisDb *db, robj *key) {
|
||||
* in sync with the main DB. The keys will be removed by expireSlaveKeys()
|
||||
* as it scans to find keys to remove. */
|
||||
if (de->key == ptrFromObj(key)) {
|
||||
de->key = sdsdup(ptrFromObj(key));
|
||||
de->key = sdsdup(szFromObj(key));
|
||||
dictSetUnsignedIntegerVal(de,0);
|
||||
}
|
||||
|
||||
@@ -377,12 +488,12 @@ size_t getSlaveKeyWithExpireCount(void) {
|
||||
}
|
||||
|
||||
/* Remove the keys in the hash table. We need to do that when data is
|
||||
* flushed from the server. We may receive new keys from the master with
|
||||
* flushed from the g_pserver-> We may receive new keys from the master with
|
||||
* the same name/db and it is no longer a good idea to expire them.
|
||||
*
|
||||
* Note: technically we should handle the case of a single DB being flushed
|
||||
* but it is not worth it since anyway race conditions using the same set
|
||||
* of key names in a wriatable slave and in its master will lead to
|
||||
* of key names in a wriatable replica and in its master will lead to
|
||||
* inconsistencies. This is just a best-effort thing we do. */
|
||||
void flushSlaveKeysWithExpireList(void) {
|
||||
if (slaveKeysWithExpire) {
|
||||
@@ -420,31 +531,31 @@ void expireGenericCommand(client *c, long long basetime, int unit) {
|
||||
|
||||
/* EXPIRE with negative TTL, or EXPIREAT with a timestamp into the past
|
||||
* should never be executed as a DEL when load the AOF or in the context
|
||||
* of a slave instance.
|
||||
* of a replica instance.
|
||||
*
|
||||
* Instead we take the other branch of the IF statement setting an expire
|
||||
* (possibly in the past) and wait for an explicit DEL from the master. */
|
||||
if (when <= mstime() && !server.loading && !server.masterhost) {
|
||||
if (when <= mstime() && !g_pserver->loading && !listLength(g_pserver->masters)) {
|
||||
robj *aux;
|
||||
|
||||
int deleted = server.lazyfree_lazy_expire ? dbAsyncDelete(c->db,key) :
|
||||
int deleted = g_pserver->lazyfree_lazy_expire ? dbAsyncDelete(c->db,key) :
|
||||
dbSyncDelete(c->db,key);
|
||||
serverAssertWithInfo(c,key,deleted);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
|
||||
/* Replicate/AOF this as an explicit DEL or UNLINK. */
|
||||
aux = server.lazyfree_lazy_expire ? shared.unlink : shared.del;
|
||||
aux = g_pserver->lazyfree_lazy_expire ? shared.unlink : shared.del;
|
||||
rewriteClientCommandVector(c,2,aux,key);
|
||||
signalModifiedKey(c->db,key);
|
||||
notifyKeyspaceEvent(NOTIFY_GENERIC,"del",key,c->db->id);
|
||||
addReply(c, shared.cone);
|
||||
return;
|
||||
} else {
|
||||
setExpire(c,c->db,key,when);
|
||||
setExpire(c,c->db,key,nullptr,when);
|
||||
addReply(c,shared.cone);
|
||||
signalModifiedKey(c->db,key);
|
||||
notifyKeyspaceEvent(NOTIFY_GENERIC,"expire",key,c->db->id);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -471,16 +582,40 @@ void pexpireatCommand(client *c) {
|
||||
|
||||
/* Implements TTL and PTTL */
|
||||
void ttlGenericCommand(client *c, int output_ms) {
|
||||
long long expire, ttl = -1;
|
||||
long long expire = -1, ttl = -1;
|
||||
|
||||
/* If the key does not exist at all, return -2 */
|
||||
if (lookupKeyReadWithFlags(c->db,c->argv[1],LOOKUP_NOTOUCH) == NULL) {
|
||||
if (lookupKeyReadWithFlags(c->db,c->argv[1],LOOKUP_NOTOUCH) == nullptr) {
|
||||
addReplyLongLong(c,-2);
|
||||
return;
|
||||
}
|
||||
|
||||
/* The key exists. Return -1 if it has no expire, or the actual
|
||||
* TTL value otherwise. */
|
||||
expire = getExpire(c->db,c->argv[1]);
|
||||
* TTL value otherwise. */
|
||||
expireEntry *pexpire = getExpire(c->db,c->argv[1]);
|
||||
|
||||
if (c->argc == 2) {
|
||||
// primary expire
|
||||
if (pexpire != nullptr)
|
||||
pexpire->FGetPrimaryExpire(&expire);
|
||||
} else if (c->argc == 3) {
|
||||
// We want a subkey expire
|
||||
if (pexpire && pexpire->FFat()) {
|
||||
for (auto itr : *pexpire) {
|
||||
if (itr.subkey() == nullptr)
|
||||
continue;
|
||||
if (sdscmp((sds)itr.subkey(), szFromObj(c->argv[2])) == 0) {
|
||||
expire = itr.when();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
addReplyError(c, "Invalid arguments");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (expire != -1) {
|
||||
ttl = expire-mstime();
|
||||
if (ttl < 0) ttl = 0;
|
||||
@@ -505,11 +640,22 @@ void pttlCommand(client *c) {
|
||||
/* PERSIST key */
|
||||
void persistCommand(client *c) {
|
||||
if (lookupKeyWrite(c->db,c->argv[1])) {
|
||||
if (removeExpire(c->db,c->argv[1])) {
|
||||
addReply(c,shared.cone);
|
||||
server.dirty++;
|
||||
if (c->argc == 2) {
|
||||
if (removeExpire(c->db,c->argv[1])) {
|
||||
addReply(c,shared.cone);
|
||||
g_pserver->dirty++;
|
||||
} else {
|
||||
addReply(c,shared.czero);
|
||||
}
|
||||
} else if (c->argc == 3) {
|
||||
if (removeSubkeyExpire(c->db, c->argv[1], c->argv[2])) {
|
||||
addReply(c,shared.cone);
|
||||
g_pserver->dirty++;
|
||||
} else {
|
||||
addReply(c,shared.czero);
|
||||
}
|
||||
} else {
|
||||
addReply(c,shared.czero);
|
||||
addReplyError(c, "Invalid arguments");
|
||||
}
|
||||
} else {
|
||||
addReply(c,shared.czero);
|
||||
@@ -520,7 +666,7 @@ void persistCommand(client *c) {
|
||||
void touchCommand(client *c) {
|
||||
int touched = 0;
|
||||
for (int j = 1; j < c->argc; j++)
|
||||
if (lookupKeyRead(c->db,c->argv[j]) != NULL) touched++;
|
||||
if (lookupKeyRead(c->db,c->argv[j]) != nullptr) touched++;
|
||||
addReplyLongLong(c,touched);
|
||||
}
|
||||
|
||||
+265
-24
@@ -36,6 +36,13 @@
|
||||
#include <assert.h>
|
||||
#include <pthread.h>
|
||||
#include <limits.h>
|
||||
#include <map>
|
||||
#ifdef __linux__
|
||||
#include <linux/futex.h>
|
||||
#endif
|
||||
#include <string.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef __APPLE__
|
||||
#include <TargetConditionals.h>
|
||||
@@ -49,6 +56,12 @@
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef UNUSED
|
||||
#define UNUSED(x) ((void)x)
|
||||
#endif
|
||||
|
||||
extern int g_fInCrash;
|
||||
|
||||
/****************************************************
|
||||
*
|
||||
* Implementation of a fair spinlock. To promote fairness we
|
||||
@@ -56,14 +69,158 @@
|
||||
*
|
||||
****************************************************/
|
||||
|
||||
|
||||
#if !defined(__has_feature)
|
||||
#define __has_feature(x) 0
|
||||
#endif
|
||||
|
||||
#if __has_feature(thread_sanitizer)
|
||||
|
||||
/* Report that a lock has been created at address "lock". */
|
||||
#define ANNOTATE_RWLOCK_CREATE(lock) \
|
||||
AnnotateRWLockCreate(__FILE__, __LINE__, lock)
|
||||
|
||||
/* Report that the lock at address "lock" is about to be destroyed. */
|
||||
#define ANNOTATE_RWLOCK_DESTROY(lock) \
|
||||
AnnotateRWLockDestroy(__FILE__, __LINE__, lock)
|
||||
|
||||
/* Report that the lock at address "lock" has been acquired.
|
||||
is_w=1 for writer lock, is_w=0 for reader lock. */
|
||||
#define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \
|
||||
AnnotateRWLockAcquired(__FILE__, __LINE__, lock, is_w)
|
||||
|
||||
/* Report that the lock at address "lock" is about to be released. */
|
||||
#define ANNOTATE_RWLOCK_RELEASED(lock, is_w) \
|
||||
AnnotateRWLockReleased(__FILE__, __LINE__, lock, is_w)
|
||||
|
||||
#if defined(DYNAMIC_ANNOTATIONS_WANT_ATTRIBUTE_WEAK)
|
||||
#if defined(__GNUC__)
|
||||
#define DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK __attribute__((weak))
|
||||
#else
|
||||
/* TODO(glider): for Windows support we may want to change this macro in order
|
||||
to prepend __declspec(selectany) to the annotations' declarations. */
|
||||
#error weak annotations are not supported for your compiler
|
||||
#endif
|
||||
#else
|
||||
#define DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK
|
||||
#endif
|
||||
|
||||
extern "C" {
|
||||
void AnnotateRWLockCreate(
|
||||
const char *file, int line,
|
||||
const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
|
||||
void AnnotateRWLockDestroy(
|
||||
const char *file, int line,
|
||||
const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
|
||||
void AnnotateRWLockAcquired(
|
||||
const char *file, int line,
|
||||
const volatile void *lock, long is_w) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
|
||||
void AnnotateRWLockReleased(
|
||||
const char *file, int line,
|
||||
const volatile void *lock, long is_w) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
#define ANNOTATE_RWLOCK_CREATE(lock)
|
||||
#define ANNOTATE_RWLOCK_DESTROY(lock)
|
||||
#define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w)
|
||||
#define ANNOTATE_RWLOCK_RELEASED(lock, is_w)
|
||||
|
||||
#endif
|
||||
|
||||
#pragma weak _serverPanic
|
||||
extern "C" __attribute__((weak)) void _serverPanic(const char * /*file*/, int /*line*/, const char * /*msg*/, ...)
|
||||
{
|
||||
*((char*)-1) = 'x';
|
||||
}
|
||||
|
||||
#pragma weak serverLog
|
||||
__attribute__((weak)) void serverLog(int , const char *fmt, ...)
|
||||
{
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
vprintf(fmt, args);
|
||||
va_end(args);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
class DeadlockDetector
|
||||
{
|
||||
std::map<pid_t, fastlock *> m_mapwait;
|
||||
fastlock m_lock { "deadlock detector" };
|
||||
public:
|
||||
void registerwait(fastlock *lock, pid_t thispid)
|
||||
{
|
||||
if (lock == &m_lock || g_fInCrash)
|
||||
return;
|
||||
fastlock_lock(&m_lock);
|
||||
m_mapwait.insert(std::make_pair(thispid, lock));
|
||||
|
||||
// Detect cycles
|
||||
pid_t pidCheck = thispid;
|
||||
size_t cchecks = 0;
|
||||
for (;;)
|
||||
{
|
||||
auto itr = m_mapwait.find(pidCheck);
|
||||
if (itr == m_mapwait.end())
|
||||
break;
|
||||
pidCheck = itr->second->m_pidOwner;
|
||||
if (pidCheck == thispid)
|
||||
{
|
||||
// Deadlock detected, printout some debugging info and crash
|
||||
serverLog(3 /*LL_WARNING*/, "\n\n");
|
||||
serverLog(3 /*LL_WARNING*/, "!!! ERROR: Deadlock detected !!!");
|
||||
pidCheck = thispid;
|
||||
for (;;)
|
||||
{
|
||||
auto itr = m_mapwait.find(pidCheck);
|
||||
serverLog(3 /* LL_WARNING */, "\t%d: (%p) %s", pidCheck, itr->second, itr->second->szName);
|
||||
pidCheck = itr->second->m_pidOwner;
|
||||
if (pidCheck == thispid)
|
||||
break;
|
||||
}
|
||||
serverLog(3 /*LL_WARNING*/, "!!! KeyDB Will Now Crash !!!");
|
||||
_serverPanic(__FILE__, __LINE__, "Deadlock detected");
|
||||
}
|
||||
|
||||
if (cchecks > m_mapwait.size())
|
||||
break; // There is a cycle but we're not in it
|
||||
++cchecks;
|
||||
}
|
||||
fastlock_unlock(&m_lock);
|
||||
}
|
||||
|
||||
void clearwait(fastlock *lock, pid_t thispid)
|
||||
{
|
||||
if (lock == &m_lock || g_fInCrash)
|
||||
return;
|
||||
fastlock_lock(&m_lock);
|
||||
m_mapwait.erase(thispid);
|
||||
fastlock_unlock(&m_lock);
|
||||
}
|
||||
};
|
||||
|
||||
DeadlockDetector g_dlock;
|
||||
|
||||
static_assert(sizeof(pid_t) <= sizeof(fastlock::m_pidOwner), "fastlock::m_pidOwner not large enough");
|
||||
uint64_t g_longwaits = 0;
|
||||
|
||||
uint64_t fastlock_getlongwaitcount()
|
||||
{
|
||||
return g_longwaits;
|
||||
uint64_t rval;
|
||||
__atomic_load(&g_longwaits, &rval, __ATOMIC_RELAXED);
|
||||
return rval;
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
static int futex(volatile unsigned *uaddr, int futex_op, int val,
|
||||
const struct timespec *timeout, int val3)
|
||||
{
|
||||
return syscall(SYS_futex, uaddr, futex_op, val,
|
||||
timeout, uaddr, val3);
|
||||
}
|
||||
#endif
|
||||
|
||||
extern "C" pid_t gettid()
|
||||
{
|
||||
@@ -82,78 +239,145 @@ extern "C" pid_t gettid()
|
||||
return pidCache;
|
||||
}
|
||||
|
||||
extern "C" void fastlock_init(struct fastlock *lock)
|
||||
extern "C" void fastlock_sleep(fastlock *lock, pid_t pid, unsigned wake, unsigned mask)
|
||||
{
|
||||
#ifdef __linux__
|
||||
g_dlock.registerwait(lock, pid);
|
||||
__atomic_fetch_or(&lock->futex, mask, __ATOMIC_ACQUIRE);
|
||||
futex(&lock->m_ticket.u, FUTEX_WAIT_BITSET_PRIVATE, wake, nullptr, mask);
|
||||
__atomic_fetch_and(&lock->futex, ~mask, __ATOMIC_RELEASE);
|
||||
g_dlock.clearwait(lock, pid);
|
||||
#endif
|
||||
__atomic_fetch_add(&g_longwaits, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
extern "C" void fastlock_init(struct fastlock *lock, const char *name)
|
||||
{
|
||||
lock->m_ticket.m_active = 0;
|
||||
lock->m_ticket.m_avail = 0;
|
||||
lock->m_depth = 0;
|
||||
lock->m_pidOwner = -1;
|
||||
lock->futex = 0;
|
||||
int cch = strlen(name);
|
||||
cch = std::min<int>(cch, sizeof(lock->szName)-1);
|
||||
memcpy(lock->szName, name, cch);
|
||||
lock->szName[cch] = '\0';
|
||||
ANNOTATE_RWLOCK_CREATE(lock);
|
||||
}
|
||||
|
||||
#ifndef ASM_SPINLOCK
|
||||
extern "C" void fastlock_lock(struct fastlock *lock)
|
||||
{
|
||||
if ((int)__atomic_load_4(&lock->m_pidOwner, __ATOMIC_ACQUIRE) == gettid())
|
||||
int pidOwner;
|
||||
__atomic_load(&lock->m_pidOwner, &pidOwner, __ATOMIC_ACQUIRE);
|
||||
if (pidOwner == gettid())
|
||||
{
|
||||
++lock->m_depth;
|
||||
return;
|
||||
}
|
||||
|
||||
int tid = gettid();
|
||||
unsigned myticket = __atomic_fetch_add(&lock->m_ticket.m_avail, 1, __ATOMIC_RELEASE);
|
||||
|
||||
unsigned mask = (1U << (myticket % 32));
|
||||
int cloops = 0;
|
||||
while (__atomic_load_2(&lock->m_ticket.m_active, __ATOMIC_ACQUIRE) != myticket)
|
||||
ticket ticketT;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
if ((++cloops % 1024*1024) == 0)
|
||||
{
|
||||
sched_yield();
|
||||
++g_longwaits;
|
||||
}
|
||||
__atomic_load(&lock->m_ticket.u, &ticketT.u, __ATOMIC_ACQUIRE);
|
||||
if ((ticketT.u & 0xffff) == myticket)
|
||||
break;
|
||||
|
||||
#if defined(__i386__) || defined(__amd64__)
|
||||
__asm__ ("pause");
|
||||
#endif
|
||||
if ((++cloops % 1024*1024) == 0)
|
||||
{
|
||||
fastlock_sleep(lock, tid, ticketT.u, mask);
|
||||
}
|
||||
}
|
||||
|
||||
lock->m_depth = 1;
|
||||
__atomic_store_4(&lock->m_pidOwner, gettid(), __ATOMIC_RELEASE);
|
||||
__atomic_store(&lock->m_pidOwner, &tid, __ATOMIC_RELEASE);
|
||||
ANNOTATE_RWLOCK_ACQUIRED(lock, true);
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
extern "C" int fastlock_trylock(struct fastlock *lock)
|
||||
extern "C" int fastlock_trylock(struct fastlock *lock, int fWeak)
|
||||
{
|
||||
if ((int)__atomic_load_4(&lock->m_pidOwner, __ATOMIC_ACQUIRE) == gettid())
|
||||
int tid;
|
||||
__atomic_load(&lock->m_pidOwner, &tid, __ATOMIC_ACQUIRE);
|
||||
if (tid == gettid())
|
||||
{
|
||||
++lock->m_depth;
|
||||
return true;
|
||||
}
|
||||
|
||||
// cheap test
|
||||
if (lock->m_ticket.m_active != lock->m_ticket.m_avail)
|
||||
struct ticket ticketT;
|
||||
__atomic_load(&lock->m_ticket.u, &ticketT.u, __ATOMIC_ACQUIRE);
|
||||
if (ticketT.m_active != ticketT.m_avail)
|
||||
return false;
|
||||
|
||||
uint16_t active = __atomic_load_2(&lock->m_ticket.m_active, __ATOMIC_RELAXED);
|
||||
uint16_t active = ticketT.m_active;
|
||||
uint16_t next = active + 1;
|
||||
|
||||
struct ticket ticket_expect { active, active };
|
||||
struct ticket ticket_setiflocked { active, next };
|
||||
if (__atomic_compare_exchange(&lock->m_ticket, &ticket_expect, &ticket_setiflocked, false /*weak*/, __ATOMIC_ACQUIRE, __ATOMIC_ACQUIRE))
|
||||
struct ticket ticket_expect { { { active, active } } };
|
||||
struct ticket ticket_setiflocked { { { active, next } } };
|
||||
if (__atomic_compare_exchange(&lock->m_ticket, &ticket_expect, &ticket_setiflocked, fWeak /*weak*/, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED))
|
||||
{
|
||||
lock->m_depth = 1;
|
||||
__atomic_store_4(&lock->m_pidOwner, gettid(), __ATOMIC_RELEASE);
|
||||
tid = gettid();
|
||||
__atomic_store(&lock->m_pidOwner, &tid, __ATOMIC_RELEASE);
|
||||
ANNOTATE_RWLOCK_ACQUIRED(lock, true);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef __linux__
|
||||
#define ROL32(v, shift) ((v << shift) | (v >> (32-shift)))
|
||||
void unlock_futex(struct fastlock *lock, uint16_t ifutex)
|
||||
{
|
||||
unsigned mask = (1U << (ifutex % 32));
|
||||
unsigned futexT;
|
||||
__atomic_load(&lock->futex, &futexT, __ATOMIC_RELAXED);
|
||||
futexT &= mask;
|
||||
|
||||
if (futexT == 0)
|
||||
return;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
__atomic_load(&lock->futex, &futexT, __ATOMIC_ACQUIRE);
|
||||
futexT &= mask;
|
||||
if (!futexT)
|
||||
break;
|
||||
|
||||
if (futex(&lock->m_ticket.u, FUTEX_WAKE_BITSET_PRIVATE, INT_MAX, nullptr, mask) == 1)
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extern "C" void fastlock_unlock(struct fastlock *lock)
|
||||
{
|
||||
--lock->m_depth;
|
||||
if (lock->m_depth == 0)
|
||||
{
|
||||
assert((int)__atomic_load_4(&lock->m_pidOwner, __ATOMIC_RELAXED) >= 0); // unlock after free
|
||||
lock->m_pidOwner = -1;
|
||||
std::atomic_thread_fence(std::memory_order_acquire);
|
||||
__atomic_fetch_add(&lock->m_ticket.m_active, 1, __ATOMIC_ACQ_REL); // on x86 the atomic is not required here, but ASM handles that case
|
||||
int pidT;
|
||||
__atomic_load(&lock->m_pidOwner, &pidT, __ATOMIC_RELAXED);
|
||||
assert(pidT >= 0); // unlock after free
|
||||
int t = -1;
|
||||
__atomic_store(&lock->m_pidOwner, &t, __ATOMIC_RELEASE);
|
||||
std::atomic_thread_fence(std::memory_order_release);
|
||||
ANNOTATE_RWLOCK_RELEASED(lock, true);
|
||||
uint16_t activeNew = __atomic_add_fetch(&lock->m_ticket.m_active, 1, __ATOMIC_RELEASE); // on x86 the atomic is not required here, but ASM handles that case
|
||||
#ifdef __linux__
|
||||
unlock_futex(lock, activeNew);
|
||||
#else
|
||||
UNUSED(activeNew);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -164,10 +388,27 @@ extern "C" void fastlock_free(struct fastlock *lock)
|
||||
assert((lock->m_ticket.m_active == lock->m_ticket.m_avail) // Asser the lock is unlocked
|
||||
|| (lock->m_pidOwner == gettid() && (lock->m_ticket.m_active == lock->m_ticket.m_avail-1))); // OR we own the lock and nobody else is waiting
|
||||
lock->m_pidOwner = -2; // sentinal value indicating free
|
||||
ANNOTATE_RWLOCK_DESTROY(lock);
|
||||
}
|
||||
|
||||
|
||||
bool fastlock::fOwnLock()
|
||||
{
|
||||
return gettid() == m_pidOwner;
|
||||
int tid;
|
||||
__atomic_load(&m_pidOwner, &tid, __ATOMIC_RELAXED);
|
||||
return gettid() == tid;
|
||||
}
|
||||
|
||||
int fastlock_unlock_recursive(struct fastlock *lock)
|
||||
{
|
||||
int rval = lock->m_depth;
|
||||
lock->m_depth = 1;
|
||||
fastlock_unlock(lock);
|
||||
return rval;
|
||||
}
|
||||
|
||||
void fastlock_lock_recursive(struct fastlock *lock, int nesting)
|
||||
{
|
||||
fastlock_lock(lock);
|
||||
lock->m_depth = nesting;
|
||||
}
|
||||
+41
-12
@@ -1,5 +1,6 @@
|
||||
#pragma once
|
||||
#include <inttypes.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
@@ -7,11 +8,13 @@ extern "C" {
|
||||
|
||||
/* Begin C API */
|
||||
struct fastlock;
|
||||
void fastlock_init(struct fastlock *lock);
|
||||
void fastlock_init(struct fastlock *lock, const char *name);
|
||||
void fastlock_lock(struct fastlock *lock);
|
||||
int fastlock_trylock(struct fastlock *lock);
|
||||
int fastlock_trylock(struct fastlock *lock, int fWeak);
|
||||
void fastlock_unlock(struct fastlock *lock);
|
||||
void fastlock_free(struct fastlock *lock);
|
||||
int fastlock_unlock_recursive(struct fastlock *lock);
|
||||
void fastlock_lock_recursive(struct fastlock *lock, int nesting);
|
||||
|
||||
uint64_t fastlock_getlongwaitcount(); // this is a global value
|
||||
|
||||
@@ -20,39 +23,65 @@ uint64_t fastlock_getlongwaitcount(); // this is a global value
|
||||
}
|
||||
#endif
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wpedantic"
|
||||
struct ticket
|
||||
{
|
||||
uint16_t m_active;
|
||||
uint16_t m_avail;
|
||||
union
|
||||
{
|
||||
struct
|
||||
{
|
||||
uint16_t m_active;
|
||||
uint16_t m_avail;
|
||||
};
|
||||
unsigned u;
|
||||
};
|
||||
};
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
struct fastlock
|
||||
{
|
||||
volatile struct ticket m_ticket;
|
||||
|
||||
volatile int m_pidOwner;
|
||||
volatile int m_depth;
|
||||
char szName[56];
|
||||
/* Volatile data on seperate cache line */
|
||||
volatile struct ticket m_ticket;
|
||||
unsigned futex;
|
||||
char padding[56]; // ensure ticket and futex are on their own independent cache line
|
||||
|
||||
#ifdef __cplusplus
|
||||
fastlock()
|
||||
fastlock(const char *name)
|
||||
{
|
||||
fastlock_init(this);
|
||||
fastlock_init(this, name);
|
||||
}
|
||||
|
||||
void lock()
|
||||
inline void lock()
|
||||
{
|
||||
fastlock_lock(this);
|
||||
}
|
||||
|
||||
bool try_lock()
|
||||
inline bool try_lock(bool fWeak = false)
|
||||
{
|
||||
return !!fastlock_trylock(this);
|
||||
return !!fastlock_trylock(this, fWeak);
|
||||
}
|
||||
|
||||
void unlock()
|
||||
inline void unlock()
|
||||
{
|
||||
fastlock_unlock(this);
|
||||
}
|
||||
|
||||
int unlock_recursive()
|
||||
{
|
||||
return fastlock_unlock_recursive(this);
|
||||
}
|
||||
|
||||
void lock_recursive(int nesting)
|
||||
{
|
||||
fastlock_lock_recursive(this, nesting);
|
||||
}
|
||||
|
||||
bool fOwnLock(); // true if this thread owns the lock, NOTE: not 100% reliable, use for debugging only
|
||||
#endif
|
||||
};
|
||||
|
||||
static_assert(offsetof(struct fastlock, m_ticket) == 64, "ensure padding is correct");
|
||||
+204
-92
@@ -1,122 +1,234 @@
|
||||
section .text
|
||||
.intel_syntax noprefix
|
||||
.section .note.GNU-stack,"",@progbits
|
||||
|
||||
extern gettid
|
||||
extern sched_yield
|
||||
extern g_longwaits
|
||||
.extern gettid
|
||||
.extern fastlock_sleep
|
||||
|
||||
; This is the first use of assembly in this codebase, a valid question is WHY?
|
||||
; The spinlock we implement here is performance critical, and simply put GCC
|
||||
; emits awful code. The original C code is left in fastlock.cpp for reference
|
||||
; and x-plat.
|
||||
.data
|
||||
.align 8
|
||||
fastlock_unlock_vec:
|
||||
.quad fastlock_unlock_vanilla
|
||||
fastlock_lock_vec:
|
||||
.quad cpuid_check_tsxrtm_polyphill
|
||||
fastlock_trylock_vec:
|
||||
.quad fastlock_trylock_vanilla
|
||||
|
||||
ALIGN 16
|
||||
global fastlock_lock
|
||||
.text
|
||||
.global fastlock_unlock
|
||||
fastlock_unlock:
|
||||
mov rax, [rip + fastlock_unlock_vec]
|
||||
jmp rax
|
||||
.global fastlock_lock
|
||||
.type fastlock_lock,@function
|
||||
fastlock_lock:
|
||||
; RDI points to the struct:
|
||||
; uint16_t active
|
||||
; uint16_t avail
|
||||
; int32_t m_pidOwner
|
||||
; int32_t m_depth
|
||||
|
||||
; First get our TID and put it in ecx
|
||||
push rdi ; we need our struct pointer (also balance the stack for the call)
|
||||
call gettid ; get our thread ID (TLS is nasty in ASM so don't bother inlining)
|
||||
mov esi, eax ; back it up in esi
|
||||
mov rdi, [rsp] ; get our pointer back
|
||||
mov rax, [rip + fastlock_lock_vec]
|
||||
jmp rax
|
||||
.global fastlock_trylock
|
||||
.type fastlock_trylock,@function
|
||||
fastlock_trylock:
|
||||
mov rax, [rip + fastlock_trylock_vec]
|
||||
jmp rax
|
||||
|
||||
cmp [rdi+4], esi ; Is the TID we got back the owner of the lock?
|
||||
je .LLocked ; Don't spin in that case
|
||||
# This is the first use of assembly in this codebase, a valid question is WHY?
|
||||
# The spinlock we implement here is performance critical, and simply put GCC
|
||||
# emits awful code. The original C code is left in fastlock.cpp for reference
|
||||
# and x-plat.
|
||||
|
||||
xor eax, eax ; eliminate partial register dependency
|
||||
inc eax ; we want to add one
|
||||
lock xadd [rdi+2], ax ; do the xadd, ax contains the value before the addition
|
||||
; eax now contains the ticket
|
||||
cpuid_check_tsxrtm_polyphill:
|
||||
mov eax, 7
|
||||
xor ecx, ecx
|
||||
ALIGN 16
|
||||
cpuid
|
||||
and ebx, 0x800
|
||||
jnz .LHasTSX
|
||||
# CPU does not have TSX RTM support
|
||||
lea rax, [rip+fastlock_lock_vanilla]
|
||||
mov [rip + fastlock_lock_vec], rax
|
||||
jmp rax
|
||||
.LHasTSX:
|
||||
lea rax, [rip+fastlock_lock_tsxrtm]
|
||||
mov [rip + fastlock_lock_vec], rax
|
||||
lea rax, [rip+fastlock_trylock_tsxrtm]
|
||||
mov [rip + fastlock_trylock_vec], rax
|
||||
lea rax, [rip+fastlock_unlock_tsxrtm]
|
||||
mov [rip + fastlock_unlock_vec], rax
|
||||
jmp fastlock_lock_tsxrtm
|
||||
|
||||
.ALIGN 16
|
||||
fastlock_lock_tsxrtm:
|
||||
xbegin fastlock_lock_vanilla
|
||||
fastlock_lock_tsxrtmcore:
|
||||
# make sure the lock is not taken (do this inside the TX)
|
||||
mov eax, [rdi+64]
|
||||
mov ecx, eax # duplicate in ecx
|
||||
ror ecx, 16 # swap upper and lower 16-bits
|
||||
cmp eax, ecx # are the upper and lower 16-bits the same?
|
||||
jne .LContested
|
||||
mov eax, 1 # this is not needed for the regular lock, but is for try lock which shares this body
|
||||
ret
|
||||
.LContested:
|
||||
xabort 0
|
||||
|
||||
.ALIGN 16
|
||||
fastlock_trylock_tsxrtm:
|
||||
xbegin fastlock_trylock_vanilla
|
||||
jmp fastlock_lock_tsxrtmcore
|
||||
|
||||
.ALIGN 16
|
||||
fastlock_unlock_tsxrtm:
|
||||
mov eax, [rdi+64]
|
||||
mov ecx, eax # duplicate in ecx
|
||||
ror ecx, 16 # swap upper and lower 16-bits
|
||||
cmp eax, ecx # are the upper and lower 16-bits the same?
|
||||
jne fastlock_unlock_vanilla
|
||||
xend
|
||||
ret
|
||||
|
||||
.ALIGN 16
|
||||
fastlock_lock_vanilla:
|
||||
.cfi_startproc
|
||||
.cfi_def_cfa rsp, 8
|
||||
# RDI points to the struct:
|
||||
# int32_t m_pidOwner
|
||||
# int32_t m_depth
|
||||
# [rdi+64] ...
|
||||
# uint16_t active
|
||||
# uint16_t avail
|
||||
|
||||
# First get our TID and put it in ecx
|
||||
push rdi # we need our struct pointer (also balance the stack for the call)
|
||||
.cfi_adjust_cfa_offset 8
|
||||
call gettid # get our thread ID (TLS is nasty in ASM so don't bother inlining)
|
||||
mov esi, eax # back it up in esi
|
||||
pop rdi # get our pointer back
|
||||
.cfi_adjust_cfa_offset -8
|
||||
|
||||
cmp [rdi], esi # Is the TID we got back the owner of the lock?
|
||||
je .LLocked # Don't spin in that case
|
||||
|
||||
xor eax, eax # eliminate partial register dependency
|
||||
inc eax # we want to add one
|
||||
lock xadd [rdi+66], ax # do the xadd, ax contains the value before the addition
|
||||
# ax now contains the ticket
|
||||
# OK Start the wait loop
|
||||
xor ecx, ecx
|
||||
.ALIGN 16
|
||||
.LLoop:
|
||||
cmp [rdi], ax ; is our ticket up?
|
||||
je .LLocked ; leave the loop
|
||||
mov edx, [rdi+64]
|
||||
cmp dx, ax # is our ticket up?
|
||||
je .LLocked # leave the loop
|
||||
pause
|
||||
add ecx, 1000h ; Have we been waiting a long time? (oflow if we have)
|
||||
; 1000h is set so we overflow on the 1024*1024'th iteration (like the C code)
|
||||
jnc .LLoop ; If so, give up our timeslice to someone who's doing real work
|
||||
; Like the compiler, you're probably thinking: "Hey! I should take these pushs out of the loop"
|
||||
; But the compiler doesn't know that we rarely hit this, and when we do we know the lock is
|
||||
; taking a long time to be released anyways. We optimize for the common case of short
|
||||
; lock intervals. That's why we're using a spinlock in the first place
|
||||
add ecx, 0x1000 # Have we been waiting a long time? (oflow if we have)
|
||||
# 1000h is set so we overflow on the 1024*1024'th iteration (like the C code)
|
||||
jnc .LLoop # If so, give up our timeslice to someone who's doing real work
|
||||
# Like the compiler, you're probably thinking: "Hey! I should take these pushs out of the loop"
|
||||
# But the compiler doesn't know that we rarely hit this, and when we do we know the lock is
|
||||
# taking a long time to be released anyways. We optimize for the common case of short
|
||||
# lock intervals. That's why we're using a spinlock in the first place
|
||||
# If we get here we're going to sleep in the kernel with a futex
|
||||
push rdi
|
||||
push rsi
|
||||
push rax
|
||||
mov rax, 24 ; sys_sched_yield
|
||||
syscall ; give up our timeslice we'll be here a while
|
||||
.cfi_adjust_cfa_offset 24
|
||||
# Setup the syscall args
|
||||
|
||||
# rdi ARG1 futex (already in rdi)
|
||||
# rsi ARG2 tid (already in esi)
|
||||
# rdx ARG3 ticketT.u (already in edx)
|
||||
bts ecx, eax # rcx ARG4 mask
|
||||
call fastlock_sleep
|
||||
# cleanup and continue
|
||||
pop rax
|
||||
pop rsi
|
||||
mov rcx, g_longwaits
|
||||
inc qword [rcx] ; increment our long wait counter
|
||||
mov rdi, [rsp] ; our struct pointer is on the stack already
|
||||
xor ecx, ecx ; Reset our loop counter
|
||||
jmp .LLoop ; Get back in the game
|
||||
ALIGN 16
|
||||
pop rdi
|
||||
.cfi_adjust_cfa_offset -24
|
||||
xor ecx, ecx # Reset our loop counter
|
||||
jmp .LLoop # Get back in the game
|
||||
.ALIGN 16
|
||||
.LLocked:
|
||||
mov [rdi+4], esi ; lock->m_pidOwner = gettid()
|
||||
inc dword [rdi+8] ; lock->m_depth++
|
||||
add rsp, 8 ; fix stack
|
||||
mov [rdi], esi # lock->m_pidOwner = gettid()
|
||||
inc dword ptr [rdi+4] # lock->m_depth++
|
||||
ret
|
||||
.cfi_endproc
|
||||
|
||||
ALIGN 16
|
||||
global fastlock_trylock
|
||||
fastlock_trylock:
|
||||
; RDI points to the struct:
|
||||
; uint16_t active
|
||||
; uint16_t avail
|
||||
; int32_t m_pidOwner
|
||||
; int32_t m_depth
|
||||
.ALIGN 16
|
||||
fastlock_trylock_vanilla:
|
||||
# RDI points to the struct:
|
||||
# int32_t m_pidOwner
|
||||
# int32_t m_depth
|
||||
# [rdi+64] ...
|
||||
# uint16_t active
|
||||
# uint16_t avail
|
||||
|
||||
; First get our TID and put it in ecx
|
||||
push rdi ; we need our struct pointer (also balance the stack for the call)
|
||||
call gettid ; get our thread ID (TLS is nasty in ASM so don't bother inlining)
|
||||
mov esi, eax ; back it up in esi
|
||||
pop rdi ; get our pointer back
|
||||
# First get our TID and put it in ecx
|
||||
push rdi # we need our struct pointer (also balance the stack for the call)
|
||||
call gettid # get our thread ID (TLS is nasty in ASM so don't bother inlining)
|
||||
mov esi, eax # back it up in esi
|
||||
pop rdi # get our pointer back
|
||||
|
||||
cmp [rdi+4], esi ; Is the TID we got back the owner of the lock?
|
||||
je .LRecursive ; Don't spin in that case
|
||||
cmp [rdi], esi # Is the TID we got back the owner of the lock?
|
||||
je .LRecursive # Don't spin in that case
|
||||
|
||||
mov eax, [rdi] ; get both active and avail counters
|
||||
mov ecx, eax ; duplicate in ecx
|
||||
ror ecx, 16 ; swap upper and lower 16-bits
|
||||
cmp eax, ecx ; are the upper and lower 16-bits the same?
|
||||
jnz .LAlreadyLocked ; If not return failure
|
||||
mov eax, [rdi+64] # get both active and avail counters
|
||||
mov ecx, eax # duplicate in ecx
|
||||
ror ecx, 16 # swap upper and lower 16-bits
|
||||
cmp eax, ecx # are the upper and lower 16-bits the same?
|
||||
jnz .LAlreadyLocked # If not return failure
|
||||
|
||||
; at this point we know eax+ecx have [avail][active] and they are both the same
|
||||
add ecx, 10000h ; increment avail, ecx is now our wanted value
|
||||
lock cmpxchg [rdi], ecx ; If rdi still contains the value in eax, put in ecx (inc avail)
|
||||
jnz .LAlreadyLocked ; If Z is not set then someone locked it while we were preparing
|
||||
# at this point we know eax+ecx have [avail][active] and they are both the same
|
||||
add ecx, 0x10000 # increment avail, ecx is now our wanted value
|
||||
lock cmpxchg [rdi+64], ecx # If rdi still contains the value in eax, put in ecx (inc avail)
|
||||
jnz .LAlreadyLocked # If Z is not set then someone locked it while we were preparing
|
||||
xor eax, eax
|
||||
inc eax ; return SUCCESS! (eax=1)
|
||||
mov [rdi+4], esi ; lock->m_pidOwner = gettid()
|
||||
mov dword [rdi+8], eax ; lock->m_depth = 1
|
||||
inc eax # return SUCCESS! (eax=1)
|
||||
mov [rdi], esi # lock->m_pidOwner = gettid()
|
||||
mov dword ptr [rdi+4], eax # lock->m_depth = 1
|
||||
ret
|
||||
ALIGN 16
|
||||
.ALIGN 16
|
||||
.LRecursive:
|
||||
xor eax, eax
|
||||
inc eax ; return SUCCESS! (eax=1)
|
||||
inc dword [rdi+8] ; lock->m_depth++
|
||||
inc eax # return SUCCESS! (eax=1)
|
||||
inc dword ptr [rdi+4] # lock->m_depth++
|
||||
ret
|
||||
ALIGN 16
|
||||
.ALIGN 16
|
||||
.LAlreadyLocked:
|
||||
xor eax, eax ; return 0;
|
||||
xor eax, eax # return 0
|
||||
ret
|
||||
|
||||
ALIGN 16
|
||||
global fastlock_unlock
|
||||
fastlock_unlock:
|
||||
; RDI points to the struct:
|
||||
; uint16_t active
|
||||
; uint16_t avail
|
||||
; int32_t m_pidOwner
|
||||
; int32_t m_depth
|
||||
sub dword [rdi+8], 1 ; decrement m_depth, don't use dec because it partially writes the flag register and we don't know its state
|
||||
jnz .LDone ; if depth is non-zero this is a recursive unlock, and we still hold it
|
||||
mov dword [rdi+4], -1 ; pidOwner = -1 (we don't own it anymore)
|
||||
inc word [rdi] ; give up our ticket (note: lock is not required here because the spinlock itself guards this variable)
|
||||
.ALIGN 16
|
||||
fastlock_unlock_vanilla:
|
||||
# RDI points to the struct:
|
||||
# int32_t m_pidOwner
|
||||
# int32_t m_depth
|
||||
# [rdi+64] ...
|
||||
# uint16_t active
|
||||
# uint16_t avail
|
||||
push r11
|
||||
sub dword ptr [rdi+4], 1 # decrement m_depth, don't use dec because it partially writes the flag register and we don't know its state
|
||||
jnz .LDone # if depth is non-zero this is a recursive unlock, and we still hold it
|
||||
mov dword ptr [rdi], -1 # pidOwner = -1 (we don't own it anymore)
|
||||
mov ecx, [rdi+64] # get current active (this one)
|
||||
inc ecx # bump it to the next thread
|
||||
mov [rdi+64], cx # give up our ticket (note: lock is not required here because the spinlock itself guards this variable)
|
||||
# At this point the lock is removed, however we must wake up any pending futexs
|
||||
mov r9d, 1 # eax is the bitmask for 2 threads
|
||||
rol r9d, cl # place the mask in the right spot for the next 2 threads
|
||||
add rdi, 64 # rdi now points to the token
|
||||
.ALIGN 16
|
||||
.LRetryWake:
|
||||
mov r11d, [rdi+4] # load the futex mask
|
||||
and r11d, r9d # are any threads waiting on a futex?
|
||||
jz .LDone # if not we're done.
|
||||
# we have to wake the futexs
|
||||
# rdi ARG1 futex (already in rdi)
|
||||
mov esi, (10 | 128) # rsi ARG2 FUTEX_WAKE_BITSET_PRIVATE
|
||||
mov edx, 0x7fffffff # rdx ARG3 INT_MAX (number of threads to wake)
|
||||
xor r10d, r10d # r10 ARG4 NULL
|
||||
mov r8, rdi # r8 ARG5 dup rdi
|
||||
# r9 ARG6 mask (already set above)
|
||||
mov eax, 202 # sys_futex
|
||||
syscall
|
||||
cmp eax, 1 # did we wake as many as we expected?
|
||||
jnz .LRetryWake
|
||||
.LDone:
|
||||
pop r11
|
||||
ret
|
||||
+30
-30
@@ -51,7 +51,7 @@ int zslValueLteMax(double value, zrangespec *spec);
|
||||
|
||||
/* Create a new array of geoPoints. */
|
||||
geoArray *geoArrayCreate(void) {
|
||||
geoArray *ga = zmalloc(sizeof(*ga), MALLOC_SHARED);
|
||||
geoArray *ga = (geoArray*)zmalloc(sizeof(*ga), MALLOC_SHARED);
|
||||
/* It gets allocated on first geoArrayAppend() call. */
|
||||
ga->array = NULL;
|
||||
ga->buckets = 0;
|
||||
@@ -64,7 +64,7 @@ geoArray *geoArrayCreate(void) {
|
||||
geoPoint *geoArrayAppend(geoArray *ga) {
|
||||
if (ga->used == ga->buckets) {
|
||||
ga->buckets = (ga->buckets == 0) ? 8 : ga->buckets*2;
|
||||
ga->array = zrealloc(ga->array,sizeof(geoPoint)*ga->buckets, MALLOC_SHARED);
|
||||
ga->array = (geoPoint*)zrealloc(ga->array,sizeof(geoPoint)*ga->buckets, MALLOC_SHARED);
|
||||
}
|
||||
geoPoint *gp = ga->array+ga->used;
|
||||
ga->used++;
|
||||
@@ -83,7 +83,7 @@ void geoArrayFree(geoArray *ga) {
|
||||
* Helpers
|
||||
* ==================================================================== */
|
||||
int decodeGeohash(double bits, double *xy) {
|
||||
GeoHashBits hash = { .bits = (uint64_t)bits, .step = GEO_STEP_MAX };
|
||||
GeoHashBits hash = { (uint64_t)bits, GEO_STEP_MAX };
|
||||
return geohashDecodeToLongLatWGS84(hash, xy);
|
||||
}
|
||||
|
||||
@@ -110,10 +110,10 @@ int extractLongLatOrReply(client *c, robj **argv, double *xy) {
|
||||
/* Input Argument Helper */
|
||||
/* Decode lat/long from a zset member's score.
|
||||
* Returns C_OK on successful decoding, otherwise C_ERR is returned. */
|
||||
int longLatFromMember(robj *zobj, robj *member, double *xy) {
|
||||
int longLatFromMember(robj_roptr zobj, robj *member, double *xy) {
|
||||
double score = 0;
|
||||
|
||||
if (zsetScore(zobj, ptrFromObj(member), &score) == C_ERR) return C_ERR;
|
||||
if (zsetScore(zobj, szFromObj(member), &score) == C_ERR) return C_ERR;
|
||||
if (!decodeGeohash(score, xy)) return C_ERR;
|
||||
return C_OK;
|
||||
}
|
||||
@@ -125,7 +125,7 @@ int longLatFromMember(robj *zobj, robj *member, double *xy) {
|
||||
* If the unit is not valid, an error is reported to the client, and a value
|
||||
* less than zero is returned. */
|
||||
double extractUnitOrReply(client *c, robj *unit) {
|
||||
char *u = ptrFromObj(unit);
|
||||
char *u = szFromObj(unit);
|
||||
|
||||
if (!strcmp(u, "m")) {
|
||||
return 1;
|
||||
@@ -222,15 +222,15 @@ int geoAppendIfWithinRadius(geoArray *ga, double lon, double lat, double radius,
|
||||
* using multiple queries to the sorted set, that we later need to sort
|
||||
* via qsort. Similarly we need to be able to reject points outside the search
|
||||
* radius area ASAP in order to allocate and process more points than needed. */
|
||||
int geoGetPointsInRange(robj *zobj, double min, double max, double lon, double lat, double radius, geoArray *ga) {
|
||||
int geoGetPointsInRange(robj_roptr zobj, double min, double max, double lon, double lat, double radius, geoArray *ga) {
|
||||
/* minex 0 = include min in range; maxex 1 = exclude max in range */
|
||||
/* That's: min <= val < max */
|
||||
zrangespec range = { .min = min, .max = max, .minex = 0, .maxex = 1 };
|
||||
zrangespec range = { min, max, 0, 1 };
|
||||
size_t origincount = ga->used;
|
||||
sds member;
|
||||
|
||||
if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
unsigned char *zl = zobj->m_ptr;
|
||||
unsigned char *zl = (unsigned char*)zobj->m_ptr;
|
||||
unsigned char *eptr, *sptr;
|
||||
unsigned char *vstr = NULL;
|
||||
unsigned int vlen = 0;
|
||||
@@ -259,7 +259,7 @@ int geoGetPointsInRange(robj *zobj, double min, double max, double lon, double l
|
||||
zzlNext(zl, &eptr, &sptr);
|
||||
}
|
||||
} else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
|
||||
zset *zs = zobj->m_ptr;
|
||||
zset *zs = (zset*)zobj->m_ptr;
|
||||
zskiplist *zsl = zs->zsl;
|
||||
zskiplistNode *ln;
|
||||
|
||||
@@ -277,7 +277,7 @@ int geoGetPointsInRange(robj *zobj, double min, double max, double lon, double l
|
||||
ele = sdsdup(ele);
|
||||
if (geoAppendIfWithinRadius(ga,lon,lat,radius,ln->score,ele)
|
||||
== C_ERR) sdsfree(ele);
|
||||
ln = ln->level[0].forward;
|
||||
ln = ln->level(0)->forward;
|
||||
}
|
||||
}
|
||||
return ga->used - origincount;
|
||||
@@ -315,7 +315,7 @@ void scoresOfGeoHashBox(GeoHashBits hash, GeoHashFix52Bits *min, GeoHashFix52Bit
|
||||
/* Obtain all members between the min/max of this geohash bounding box.
|
||||
* Populate a geoArray of GeoPoints by calling geoGetPointsInRange().
|
||||
* Return the number of points added to the array. */
|
||||
int membersOfGeoHashBox(robj *zobj, GeoHashBits hash, geoArray *ga, double lon, double lat, double radius) {
|
||||
int membersOfGeoHashBox(robj_roptr zobj, GeoHashBits hash, geoArray *ga, double lon, double lat, double radius) {
|
||||
GeoHashFix52Bits min, max;
|
||||
|
||||
scoresOfGeoHashBox(hash,&min,&max);
|
||||
@@ -323,7 +323,7 @@ int membersOfGeoHashBox(robj *zobj, GeoHashBits hash, geoArray *ga, double lon,
|
||||
}
|
||||
|
||||
/* Search all eight neighbors + self geohash box */
|
||||
int membersOfAllNeighbors(robj *zobj, GeoHashRadius n, double lon, double lat, double radius, geoArray *ga) {
|
||||
int membersOfAllNeighbors(robj_roptr zobj, GeoHashRadius n, double lon, double lat, double radius, geoArray *ga) {
|
||||
GeoHashBits neighbors[9];
|
||||
unsigned int i, count = 0, last_processed = 0;
|
||||
int debugmsg = 0;
|
||||
@@ -382,7 +382,7 @@ int membersOfAllNeighbors(robj *zobj, GeoHashRadius n, double lon, double lat, d
|
||||
|
||||
/* Sort comparators for qsort() */
|
||||
static int sort_gp_asc(const void *a, const void *b) {
|
||||
const struct geoPoint *gpa = a, *gpb = b;
|
||||
const struct geoPoint *gpa = (geoPoint*)a, *gpb = (geoPoint*)b;
|
||||
/* We can't do adist - bdist because they are doubles and
|
||||
* the comparator returns an int. */
|
||||
if (gpa->dist > gpb->dist)
|
||||
@@ -413,7 +413,7 @@ void geoaddCommand(client *c) {
|
||||
|
||||
int elements = (c->argc - 2) / 3;
|
||||
int argc = 2+elements*2; /* ZADD key score ele ... */
|
||||
robj **argv = zcalloc(argc*sizeof(robj*), MALLOC_LOCAL);
|
||||
robj **argv = (robj**)zcalloc(argc*sizeof(robj*), MALLOC_LOCAL);
|
||||
argv[0] = createRawStringObject("zadd",4);
|
||||
argv[1] = c->argv[1]; /* key */
|
||||
incrRefCount(argv[1]);
|
||||
@@ -465,8 +465,8 @@ void georadiusGeneric(client *c, int flags) {
|
||||
int storedist = 0; /* 0 for STORE, 1 for STOREDIST. */
|
||||
|
||||
/* Look up the requested zset */
|
||||
robj *zobj = NULL;
|
||||
if ((zobj = lookupKeyReadOrReply(c, key, shared.null[c->resp])) == NULL ||
|
||||
robj_roptr zobj;
|
||||
if ((zobj = lookupKeyReadOrReply(c, key, shared.null[c->resp])) == nullptr ||
|
||||
checkType(c, zobj, OBJ_ZSET)) {
|
||||
return;
|
||||
}
|
||||
@@ -504,7 +504,7 @@ void georadiusGeneric(client *c, int flags) {
|
||||
if (c->argc > base_args) {
|
||||
int remaining = c->argc - base_args;
|
||||
for (int i = 0; i < remaining; i++) {
|
||||
char *arg = ptrFromObj(c->argv[base_args + i]);
|
||||
char *arg = szFromObj(c->argv[base_args + i]);
|
||||
if (!strcasecmp(arg, "withdist")) {
|
||||
withdist = 1;
|
||||
} else if (!strcasecmp(arg, "withhash")) {
|
||||
@@ -639,7 +639,7 @@ void georadiusGeneric(client *c, int flags) {
|
||||
|
||||
if (returned_items) {
|
||||
zobj = createZsetObject();
|
||||
zs = zobj->m_ptr;
|
||||
zs = (zset*)zobj->m_ptr;
|
||||
}
|
||||
|
||||
for (i = 0; i < returned_items; i++) {
|
||||
@@ -661,11 +661,11 @@ void georadiusGeneric(client *c, int flags) {
|
||||
decrRefCount(zobj);
|
||||
notifyKeyspaceEvent(NOTIFY_ZSET,"georadiusstore",storekey,
|
||||
c->db->id);
|
||||
server.dirty += returned_items;
|
||||
g_pserver->dirty += returned_items;
|
||||
} else if (dbDelete(c->db,storekey)) {
|
||||
signalModifiedKey(c->db,storekey);
|
||||
notifyKeyspaceEvent(NOTIFY_GENERIC,"del",storekey,c->db->id);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
}
|
||||
addReplyLongLong(c, returned_items);
|
||||
}
|
||||
@@ -697,11 +697,11 @@ void georadiusbymemberroCommand(client *c) {
|
||||
* Returns an array with an 11 characters geohash representation of the
|
||||
* position of the specified elements. */
|
||||
void geohashCommand(client *c) {
|
||||
char *geoalphabet= "0123456789bcdefghjkmnpqrstuvwxyz";
|
||||
const char *geoalphabet= "0123456789bcdefghjkmnpqrstuvwxyz";
|
||||
int j;
|
||||
|
||||
/* Look up the requested zset */
|
||||
robj *zobj = lookupKeyRead(c->db, c->argv[1]);
|
||||
robj_roptr zobj = lookupKeyRead(c->db, c->argv[1]);
|
||||
if (zobj && checkType(c, zobj, OBJ_ZSET)) return;
|
||||
|
||||
/* Geohash elements one after the other, using a null bulk reply for
|
||||
@@ -709,7 +709,7 @@ void geohashCommand(client *c) {
|
||||
addReplyArrayLen(c,c->argc-2);
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
double score;
|
||||
if (!zobj || zsetScore(zobj, ptrFromObj(c->argv[j]), &score) == C_ERR) {
|
||||
if (!zobj || zsetScore(zobj, szFromObj(c->argv[j]), &score) == C_ERR) {
|
||||
addReplyNull(c);
|
||||
} else {
|
||||
/* The internal format we use for geocoding is a bit different
|
||||
@@ -754,7 +754,7 @@ void geoposCommand(client *c) {
|
||||
int j;
|
||||
|
||||
/* Look up the requested zset */
|
||||
robj *zobj = lookupKeyRead(c->db, c->argv[1]);
|
||||
robj_roptr zobj = lookupKeyRead(c->db, c->argv[1]);
|
||||
if (zobj && checkType(c, zobj, OBJ_ZSET)) return;
|
||||
|
||||
/* Report elements one after the other, using a null bulk reply for
|
||||
@@ -762,7 +762,7 @@ void geoposCommand(client *c) {
|
||||
addReplyArrayLen(c,c->argc-2);
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
double score;
|
||||
if (!zobj || zsetScore(zobj, ptrFromObj(c->argv[j]), &score) == C_ERR) {
|
||||
if (!zobj || zsetScore(zobj, szFromObj(c->argv[j]), &score) == C_ERR) {
|
||||
addReplyNullArray(c);
|
||||
} else {
|
||||
/* Decode... */
|
||||
@@ -796,14 +796,14 @@ void geodistCommand(client *c) {
|
||||
}
|
||||
|
||||
/* Look up the requested zset */
|
||||
robj *zobj = NULL;
|
||||
robj_roptr zobj = NULL;
|
||||
if ((zobj = lookupKeyReadOrReply(c, c->argv[1], shared.null[c->resp]))
|
||||
== NULL || checkType(c, zobj, OBJ_ZSET)) return;
|
||||
== nullptr || checkType(c, zobj, OBJ_ZSET)) return;
|
||||
|
||||
/* Get the scores. We need both otherwise NULL is returned. */
|
||||
double score1, score2, xyxy[4];
|
||||
if (zsetScore(zobj, ptrFromObj(c->argv[2]), &score1) == C_ERR ||
|
||||
zsetScore(zobj, ptrFromObj(c->argv[3]), &score2) == C_ERR)
|
||||
if (zsetScore(zobj, szFromObj(c->argv[2]), &score1) == C_ERR ||
|
||||
zsetScore(zobj, szFromObj(c->argv[3]), &score2) == C_ERR)
|
||||
{
|
||||
addReplyNull(c);
|
||||
return;
|
||||
File renamed without changes.
@@ -1,97 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2019, Salvatore Sanfilippo <antirez at gmail dot com>
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* * 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.
|
||||
* * Neither the name of Redis 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 OWNER 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.
|
||||
*/
|
||||
|
||||
#include "server.h"
|
||||
|
||||
/* Emit an item in Gopher directory listing format:
|
||||
* <type><descr><TAB><selector><TAB><hostname><TAB><port>
|
||||
* If descr or selector are NULL, then the "(NULL)" string is used instead. */
|
||||
void addReplyGopherItem(client *c, const char *type, const char *descr,
|
||||
const char *selector, const char *hostname, int port)
|
||||
{
|
||||
sds item = sdscatfmt(sdsempty(),"%s%s\t%s\t%s\t%i\r\n",
|
||||
type, descr,
|
||||
selector ? selector : "(NULL)",
|
||||
hostname ? hostname : "(NULL)",
|
||||
port);
|
||||
addReplyProto(c,item,sdslen(item));
|
||||
sdsfree(item);
|
||||
}
|
||||
|
||||
/* This is called by processInputBuffer() when an inline request is processed
|
||||
* with Gopher mode enabled, and the request happens to have zero or just one
|
||||
* argument. In such case we get the relevant key and reply using the Gopher
|
||||
* protocol. */
|
||||
void processGopherRequest(client *c) {
|
||||
robj *keyname = c->argc == 0 ? createStringObject("/",1) : c->argv[0];
|
||||
robj *o = lookupKeyRead(c->db,keyname);
|
||||
|
||||
/* If there is no such key, return with a Gopher error. */
|
||||
if (o == NULL || o->type != OBJ_STRING) {
|
||||
char *errstr;
|
||||
if (o == NULL)
|
||||
errstr = "Error: no content at the specified key";
|
||||
else
|
||||
errstr = "Error: selected key type is invalid "
|
||||
"for Gopher output";
|
||||
addReplyGopherItem(c,"i",errstr,NULL,NULL,0);
|
||||
addReplyGopherItem(c,"i","Redis Gopher server",NULL,NULL,0);
|
||||
} else {
|
||||
addReply(c,o);
|
||||
}
|
||||
|
||||
/* Cleanup, also make sure to emit the final ".CRLF" line. Note that
|
||||
* the connection will be closed immediately after this because the client
|
||||
* will be flagged with CLIENT_CLOSE_AFTER_REPLY, in accordance with the
|
||||
* Gopher protocol. */
|
||||
if (c->argc == 0) decrRefCount(keyname);
|
||||
|
||||
/* Note that in theory we should terminate the Gopher request with
|
||||
* ".<CR><LF>" (called Lastline in the RFC) like that:
|
||||
*
|
||||
* addReplyProto(c,".\r\n",3);
|
||||
*
|
||||
* However after examining the current clients landscape, it's probably
|
||||
* going to do more harm than good for several reasons:
|
||||
*
|
||||
* 1. Clients should not have any issue with missing .<CR><LF> as for
|
||||
* specification, and in the real world indeed certain servers
|
||||
* implementations never used to send the terminator.
|
||||
*
|
||||
* 2. Redis does not know if it's serving a text file or a binary file:
|
||||
* at the same time clients will not remove the ".<CR><LF>" bytes at
|
||||
* tne end when downloading a binary file from the server, so adding
|
||||
* the "Lastline" terminator without knowing the content is just
|
||||
* dangerous.
|
||||
*
|
||||
* 3. The utility gopher2redis.rb that we provide for Redis, and any
|
||||
* other similar tool you may use as Gopher authoring system for
|
||||
* Redis, can just add the "Lastline" when needed.
|
||||
*/
|
||||
}
|
||||
+12
-6
@@ -343,6 +343,12 @@ struct commandHelp {
|
||||
"Set the expiration for a key as a UNIX timestamp",
|
||||
0,
|
||||
"1.2.0" },
|
||||
{ "EXPIREMEMBER",
|
||||
"key subkey delay [Unit: s,ms]",
|
||||
"set a subkey's time to live in seconds (or milliseconds)"},
|
||||
{ "EXPIREMEMBERAT",
|
||||
"key subkey timestamp",
|
||||
"Set the expiration for a subkey as a UNIX timestamp"},
|
||||
{ "FLUSHALL",
|
||||
"[ASYNC]",
|
||||
"Remove all keys from all databases",
|
||||
@@ -629,8 +635,8 @@ struct commandHelp {
|
||||
0,
|
||||
"2.2.3" },
|
||||
{ "PERSIST",
|
||||
"key",
|
||||
"Remove the expiration from a key",
|
||||
"key [subkey]",
|
||||
"Remove the expiration from a key or subkey",
|
||||
0,
|
||||
"2.2.0" },
|
||||
{ "PEXPIRE",
|
||||
@@ -674,8 +680,8 @@ struct commandHelp {
|
||||
6,
|
||||
"2.0.0" },
|
||||
{ "PTTL",
|
||||
"key",
|
||||
"Get the time to live for a key in milliseconds",
|
||||
"key [subkey]",
|
||||
"Get the time to live for a key or subkey in milliseconds",
|
||||
0,
|
||||
"2.6.0" },
|
||||
{ "PUBLISH",
|
||||
@@ -949,8 +955,8 @@ struct commandHelp {
|
||||
0,
|
||||
"3.2.1" },
|
||||
{ "TTL",
|
||||
"key",
|
||||
"Get the time to live for a key",
|
||||
"key [subkey]",
|
||||
"Get the time to live for a key or subkey",
|
||||
0,
|
||||
"1.0.0" },
|
||||
{ "TYPE",
|
||||
|
||||
@@ -176,7 +176,7 @@
|
||||
* involved in updating the sparse representation is not justified by the
|
||||
* memory savings. The exact maximum length of the sparse representation
|
||||
* when this implementation switches to the dense representation is
|
||||
* configured via the define server.hll_sparse_max_bytes.
|
||||
* configured via the define g_pserver->hll_sparse_max_bytes.
|
||||
*/
|
||||
|
||||
struct hllhdr {
|
||||
@@ -184,7 +184,9 @@ struct hllhdr {
|
||||
uint8_t encoding; /* HLL_DENSE or HLL_SPARSE. */
|
||||
uint8_t notused[3]; /* Reserved for future use, must be zero. */
|
||||
uint8_t card[8]; /* Cached cardinality, little endian. */
|
||||
uint8_t registers[]; /* Data bytes. */
|
||||
uint8_t *registers() { /* Data bytes. */
|
||||
return reinterpret_cast<uint8_t*>(this+1);
|
||||
}
|
||||
};
|
||||
|
||||
/* The cached cardinality MSB is used to signal validity of the cached value. */
|
||||
@@ -205,7 +207,7 @@ struct hllhdr {
|
||||
#define HLL_RAW 255 /* Only used internally, never exposed. */
|
||||
#define HLL_MAX_ENCODING 1
|
||||
|
||||
static char *invalid_hll_err = "-INVALIDOBJ Corrupted HLL object detected\r\n";
|
||||
static const char *invalid_hll_err = "-INVALIDOBJ Corrupted HLL object detected\r\n";
|
||||
|
||||
/* =========================== Low level bit macros ========================= */
|
||||
|
||||
@@ -582,7 +584,7 @@ void hllDenseRegHisto(uint8_t *registers, int* reghisto) {
|
||||
* The function returns C_OK if the sparse representation was valid,
|
||||
* otherwise C_ERR is returned if the representation was corrupted. */
|
||||
int hllSparseToDense(robj *o) {
|
||||
sds sparse = ptrFromObj(o), dense;
|
||||
sds sparse = szFromObj(o), dense;
|
||||
struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse;
|
||||
int idx = 0, runlen, regval;
|
||||
uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse);
|
||||
@@ -616,7 +618,7 @@ int hllSparseToDense(robj *o) {
|
||||
regval = HLL_SPARSE_VAL_VALUE(p);
|
||||
if ((runlen + idx) > HLL_REGISTERS) break; /* Overflow. */
|
||||
while(runlen--) {
|
||||
HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval);
|
||||
HLL_DENSE_SET_REGISTER(hdr->registers(),idx,regval);
|
||||
idx++;
|
||||
}
|
||||
p++;
|
||||
@@ -631,7 +633,7 @@ int hllSparseToDense(robj *o) {
|
||||
}
|
||||
|
||||
/* Free the old representation and set the new one. */
|
||||
sdsfree(ptrFromObj(o));
|
||||
sdsfree(szFromObj(o));
|
||||
o->m_ptr = dense;
|
||||
return C_OK;
|
||||
}
|
||||
@@ -650,12 +652,19 @@ int hllSparseToDense(robj *o) {
|
||||
* As a side effect the function may promote the HLL representation from
|
||||
* sparse to dense: this happens when a register requires to be set to a value
|
||||
* not representable with the sparse representation, or when the resulting
|
||||
* size would be greater than server.hll_sparse_max_bytes. */
|
||||
* size would be greater than g_pserver->hll_sparse_max_bytes. */
|
||||
int hllSparseSet(robj *o, long index, uint8_t count) {
|
||||
struct hllhdr *hdr;
|
||||
uint8_t oldcount, *sparse, *end, *p, *prev, *next;
|
||||
long first, span;
|
||||
long is_zero = 0, is_xzero = 0, is_val = 0, runlen = 0;
|
||||
uint8_t seq[5], *n = nullptr;
|
||||
int last;
|
||||
int len;
|
||||
int seqlen = 0;
|
||||
int oldlen = 0;
|
||||
int deltalen = 0;
|
||||
int scanlen = 0;
|
||||
|
||||
/* If the count is too big to be representable by the sparse representation
|
||||
* switch to dense representation. */
|
||||
@@ -666,12 +675,12 @@ int hllSparseSet(robj *o, long index, uint8_t count) {
|
||||
* into XZERO-VAL-XZERO). Make sure there is enough space right now
|
||||
* so that the pointers we take during the execution of the function
|
||||
* will be valid all the time. */
|
||||
o->m_ptr = sdsMakeRoomFor(ptrFromObj(o),3);
|
||||
o->m_ptr = sdsMakeRoomFor(szFromObj(o),3);
|
||||
|
||||
/* Step 1: we need to locate the opcode we need to modify to check
|
||||
* if a value update is actually needed. */
|
||||
sparse = p = ((uint8_t*)ptrFromObj(o)) + HLL_HDR_SIZE;
|
||||
end = p + sdslen(ptrFromObj(o)) - HLL_HDR_SIZE;
|
||||
end = p + sdslen(szFromObj(o)) - HLL_HDR_SIZE;
|
||||
|
||||
first = 0;
|
||||
prev = NULL; /* Points to previous opcode at the end of the loop. */
|
||||
@@ -701,6 +710,7 @@ int hllSparseSet(robj *o, long index, uint8_t count) {
|
||||
first += span;
|
||||
}
|
||||
if (span == 0) return -1; /* Invalid format. */
|
||||
if (p >= end) return -1; /* Invalid format. */
|
||||
|
||||
next = HLL_SPARSE_IS_XZERO(p) ? p+2 : p+1;
|
||||
if (next >= end) next = NULL;
|
||||
@@ -774,9 +784,8 @@ int hllSparseSet(robj *o, long index, uint8_t count) {
|
||||
* with 'newlen' as length. Later the new sequence is inserted in place
|
||||
* of the old one, possibly moving what is on the right a few bytes
|
||||
* if the new sequence is longer than the older one. */
|
||||
uint8_t seq[5], *n = seq;
|
||||
int last = first+span-1; /* Last register covered by the sequence. */
|
||||
int len;
|
||||
n = seq;
|
||||
last = first+span-1; /* Last register covered by the sequence. */
|
||||
|
||||
if (is_zero || is_xzero) {
|
||||
/* Handle splitting of ZERO / XZERO. */
|
||||
@@ -824,14 +833,14 @@ int hllSparseSet(robj *o, long index, uint8_t count) {
|
||||
*
|
||||
* Note that we already allocated space on the sds string
|
||||
* calling sdsMakeRoomFor(). */
|
||||
int seqlen = n-seq;
|
||||
int oldlen = is_xzero ? 2 : 1;
|
||||
int deltalen = seqlen-oldlen;
|
||||
seqlen = n-seq;
|
||||
oldlen = is_xzero ? 2 : 1;
|
||||
deltalen = seqlen-oldlen;
|
||||
|
||||
if (deltalen > 0 &&
|
||||
sdslen(ptrFromObj(o))+deltalen > server.hll_sparse_max_bytes) goto promote;
|
||||
sdslen(szFromObj(o))+deltalen > g_pserver->hll_sparse_max_bytes) goto promote;
|
||||
if (deltalen && next) memmove(next+deltalen,next,end-next);
|
||||
sdsIncrLen(ptrFromObj(o),deltalen);
|
||||
sdsIncrLen(szFromObj(o),deltalen);
|
||||
memcpy(p,seq,seqlen);
|
||||
end += deltalen;
|
||||
|
||||
@@ -842,7 +851,7 @@ updated:
|
||||
* may not be optimal: adjacent VAL opcodes can sometimes be merged into
|
||||
* a single one. */
|
||||
p = prev ? prev : sparse;
|
||||
int scanlen = 5; /* Scan up to 5 upcodes starting from prev. */
|
||||
scanlen = 5; /* Scan up to 5 upcodes starting from prev. */
|
||||
while (p < end && scanlen--) {
|
||||
if (HLL_SPARSE_IS_XZERO(p)) {
|
||||
p += 2;
|
||||
@@ -861,7 +870,7 @@ updated:
|
||||
if (len <= HLL_SPARSE_VAL_MAX_LEN) {
|
||||
HLL_SPARSE_VAL_SET(p+1,v1,len);
|
||||
memmove(p,p+1,end-p);
|
||||
sdsIncrLen(ptrFromObj(o),-1);
|
||||
sdsIncrLen(szFromObj(o),-1);
|
||||
end--;
|
||||
/* After a merge we reiterate without incrementing 'p'
|
||||
* in order to try to merge the just merged value with
|
||||
@@ -874,13 +883,13 @@ updated:
|
||||
}
|
||||
|
||||
/* Invalidate the cached cardinality. */
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
HLL_INVALIDATE_CACHE(hdr);
|
||||
return 1;
|
||||
|
||||
promote: /* Promote to dense representation. */
|
||||
if (hllSparseToDense(o) == C_ERR) return -1; /* Corrupted HLL. */
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
|
||||
/* We need to call hllDenseAdd() to perform the operation after the
|
||||
* conversion. However the result must be 1, since if we need to
|
||||
@@ -889,7 +898,7 @@ promote: /* Promote to dense representation. */
|
||||
* Note that this in turn means that PFADD will make sure the command
|
||||
* is propagated to slaves / AOF, so if there is a sparse -> dense
|
||||
* conversion, it will be performed in all the slaves as well. */
|
||||
int dense_retval = hllDenseSet(hdr->registers,index,count);
|
||||
int dense_retval = hllDenseSet(hdr->registers(),index,count);
|
||||
serverAssert(dense_retval == 1);
|
||||
return dense_retval;
|
||||
}
|
||||
@@ -1007,7 +1016,7 @@ double hllTau(double x) {
|
||||
* pointed by 'invalid' is set to non-zero, otherwise it is left untouched.
|
||||
*
|
||||
* hllCount() supports a special internal-only encoding of HLL_RAW, that
|
||||
* is, hdr->registers will point to an uint8_t array of HLL_REGISTERS element.
|
||||
* is, hdr->registers() will point to an uint8_t array of HLL_REGISTERS element.
|
||||
* This is useful in order to speedup PFCOUNT when called against multiple
|
||||
* keys (no need to work with 6-bit integers encoding). */
|
||||
uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
|
||||
@@ -1023,12 +1032,12 @@ uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
|
||||
|
||||
/* Compute register histogram */
|
||||
if (hdr->encoding == HLL_DENSE) {
|
||||
hllDenseRegHisto(hdr->registers,reghisto);
|
||||
hllDenseRegHisto(hdr->registers(),reghisto);
|
||||
} else if (hdr->encoding == HLL_SPARSE) {
|
||||
hllSparseRegHisto(hdr->registers,
|
||||
hllSparseRegHisto(hdr->registers(),
|
||||
sdslen((sds)hdr)-HLL_HDR_SIZE,invalid,reghisto);
|
||||
} else if (hdr->encoding == HLL_RAW) {
|
||||
hllRawRegHisto(hdr->registers,reghisto);
|
||||
hllRawRegHisto(hdr->registers(),reghisto);
|
||||
} else {
|
||||
serverPanic("Unknown HyperLogLog encoding in hllCount()");
|
||||
}
|
||||
@@ -1049,9 +1058,9 @@ uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
|
||||
|
||||
/* Call hllDenseAdd() or hllSparseAdd() according to the HLL encoding. */
|
||||
int hllAdd(robj *o, unsigned char *ele, size_t elesize) {
|
||||
struct hllhdr *hdr = ptrFromObj(o);
|
||||
struct hllhdr *hdr = (hllhdr*)ptrFromObj(o);
|
||||
switch(hdr->encoding) {
|
||||
case HLL_DENSE: return hllDenseAdd(hdr->registers,ele,elesize);
|
||||
case HLL_DENSE: return hllDenseAdd(hdr->registers(),ele,elesize);
|
||||
case HLL_SPARSE: return hllSparseAdd(o,ele,elesize);
|
||||
default: return -1; /* Invalid representation. */
|
||||
}
|
||||
@@ -1065,19 +1074,19 @@ int hllAdd(robj *o, unsigned char *ele, size_t elesize) {
|
||||
*
|
||||
* If the HyperLogLog is sparse and is found to be invalid, C_ERR
|
||||
* is returned, otherwise the function always succeeds. */
|
||||
int hllMerge(uint8_t *max, size_t cmax, robj *hll) {
|
||||
struct hllhdr *hdr = ptrFromObj(hll);
|
||||
int hllMerge(uint8_t *max, size_t cmax, robj_roptr hll) {
|
||||
struct hllhdr *hdr = (hllhdr*)ptrFromObj(hll);
|
||||
int i;
|
||||
|
||||
if (hdr->encoding == HLL_DENSE) {
|
||||
uint8_t val;
|
||||
|
||||
for (i = 0; i < HLL_REGISTERS; i++) {
|
||||
HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
|
||||
HLL_DENSE_GET_REGISTER(val,hdr->registers(),i);
|
||||
if (val > max[i]) max[i] = val;
|
||||
}
|
||||
} else {
|
||||
uint8_t *p = ptrFromObj(hll), *end = p + sdslen(ptrFromObj(hll));
|
||||
const uint8_t *p = (const uint8_t*)ptrFromObj(hll), *end = p + sdslen(szFromObj(hll));
|
||||
long runlen, regval;
|
||||
|
||||
p += HLL_HDR_SIZE;
|
||||
@@ -1139,7 +1148,7 @@ robj *createHLLObject(void) {
|
||||
|
||||
/* Create the actual object. */
|
||||
o = createObject(OBJ_STRING,s);
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
memcpy(hdr->magic,"HYLL",4);
|
||||
hdr->encoding = HLL_SPARSE;
|
||||
return o;
|
||||
@@ -1148,7 +1157,7 @@ robj *createHLLObject(void) {
|
||||
/* Check if the object is a String with a valid HLL representation.
|
||||
* Return C_OK if this is true, otherwise reply to the client
|
||||
* with an error and return C_ERR. */
|
||||
int isHLLObjectOrReply(client *c, robj *o) {
|
||||
int isHLLObjectOrReply(client *c, robj_roptr o) {
|
||||
struct hllhdr *hdr;
|
||||
|
||||
/* Key exists, check type */
|
||||
@@ -1157,7 +1166,7 @@ int isHLLObjectOrReply(client *c, robj *o) {
|
||||
|
||||
if (!sdsEncodedObject(o)) goto invalid;
|
||||
if (stringObjectLen(o) < sizeof(*hdr)) goto invalid;
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
|
||||
/* Magic should be "HYLL". */
|
||||
if (hdr->magic[0] != 'H' || hdr->magic[1] != 'Y' ||
|
||||
@@ -1199,7 +1208,7 @@ void pfaddCommand(client *c) {
|
||||
/* Perform the low level ADD operation for every element. */
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
int retval = hllAdd(o, (unsigned char*)ptrFromObj(c->argv[j]),
|
||||
sdslen(ptrFromObj(c->argv[j])));
|
||||
sdslen(szFromObj(c->argv[j])));
|
||||
switch(retval) {
|
||||
case 1:
|
||||
updated++;
|
||||
@@ -1209,11 +1218,11 @@ void pfaddCommand(client *c) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
if (updated) {
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
HLL_INVALIDATE_CACHE(hdr);
|
||||
}
|
||||
addReply(c, updated ? shared.cone : shared.czero);
|
||||
@@ -1240,8 +1249,8 @@ void pfcountCommand(client *c) {
|
||||
registers = max + HLL_HDR_SIZE;
|
||||
for (j = 1; j < c->argc; j++) {
|
||||
/* Check type and size. */
|
||||
robj *o = lookupKeyRead(c->db,c->argv[j]);
|
||||
if (o == NULL) continue; /* Assume empty HLL for non existing var.*/
|
||||
robj_roptr o = lookupKeyRead(c->db,c->argv[j]);
|
||||
if (o == nullptr) continue; /* Assume empty HLL for non existing var.*/
|
||||
if (isHLLObjectOrReply(c,o) != C_OK) return;
|
||||
|
||||
/* Merge with this HLL with our 'max' HHL by setting max[i]
|
||||
@@ -1271,7 +1280,7 @@ void pfcountCommand(client *c) {
|
||||
o = dbUnshareStringValue(c->db,c->argv[1],o);
|
||||
|
||||
/* Check if the cached cardinality is valid. */
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
if (HLL_VALID_CACHE(hdr)) {
|
||||
/* Just return the cached value. */
|
||||
card = (uint64_t)hdr->card[0];
|
||||
@@ -1303,7 +1312,7 @@ void pfcountCommand(client *c) {
|
||||
* may be modified and given that the HLL is a Redis string
|
||||
* we need to propagate the change. */
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
}
|
||||
addReplyLongLong(c,card);
|
||||
}
|
||||
@@ -1322,13 +1331,13 @@ void pfmergeCommand(client *c) {
|
||||
memset(max,0,sizeof(max));
|
||||
for (j = 1; j < c->argc; j++) {
|
||||
/* Check type and size. */
|
||||
robj *o = lookupKeyRead(c->db,c->argv[j]);
|
||||
if (o == NULL) continue; /* Assume empty HLL for non existing var. */
|
||||
robj_roptr o = lookupKeyRead(c->db,c->argv[j]);
|
||||
if (o == nullptr) continue; /* Assume empty HLL for non existing var. */
|
||||
if (isHLLObjectOrReply(c,o) != C_OK) return;
|
||||
|
||||
/* If at least one involved HLL is dense, use the dense representation
|
||||
* as target ASAP to save time and avoid the conversion step. */
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
if (hdr->encoding == HLL_DENSE) use_dense = 1;
|
||||
|
||||
/* Merge with this HLL with our 'max' HHL by setting max[i]
|
||||
@@ -1365,13 +1374,13 @@ void pfmergeCommand(client *c) {
|
||||
* invalidate the cached value. */
|
||||
for (j = 0; j < HLL_REGISTERS; j++) {
|
||||
if (max[j] == 0) continue;
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
switch(hdr->encoding) {
|
||||
case HLL_DENSE: hllDenseSet(hdr->registers,j,max[j]); break;
|
||||
case HLL_DENSE: hllDenseSet(hdr->registers(),j,max[j]); break;
|
||||
case HLL_SPARSE: hllSparseSet(o,j,max[j]); break;
|
||||
}
|
||||
}
|
||||
hdr = ptrFromObj(o); /* ptrFromObj(o) may be different now, as a side effect of
|
||||
hdr = (hllhdr*)ptrFromObj(o); /* ptrFromObj(o) may be different now, as a side effect of
|
||||
last hllSparseSet() call. */
|
||||
HLL_INVALIDATE_CACHE(hdr);
|
||||
|
||||
@@ -1379,7 +1388,7 @@ void pfmergeCommand(client *c) {
|
||||
/* We generate a PFADD event for PFMERGE for semantical simplicity
|
||||
* since in theory this is a mass-add of elements. */
|
||||
notifyKeyspaceEvent(NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
addReply(c,shared.ok);
|
||||
}
|
||||
|
||||
@@ -1395,6 +1404,10 @@ void pfselftestCommand(client *c) {
|
||||
struct hllhdr *hdr = (struct hllhdr*) bitcounters, *hdr2;
|
||||
robj *o = NULL;
|
||||
uint8_t bytecounters[HLL_REGISTERS];
|
||||
int64_t checkpoint = 1;
|
||||
uint64_t seed = 0;
|
||||
uint64_t ele;
|
||||
double relerr = 0;
|
||||
|
||||
/* Test 1: access registers.
|
||||
* The test is conceived to test that the different counters of our data
|
||||
@@ -1407,13 +1420,13 @@ void pfselftestCommand(client *c) {
|
||||
unsigned int r = rand() & HLL_REGISTER_MAX;
|
||||
|
||||
bytecounters[i] = r;
|
||||
HLL_DENSE_SET_REGISTER(hdr->registers,i,r);
|
||||
HLL_DENSE_SET_REGISTER(hdr->registers(),i,r);
|
||||
}
|
||||
/* Check that we are able to retrieve the same values. */
|
||||
for (i = 0; i < HLL_REGISTERS; i++) {
|
||||
unsigned int val;
|
||||
|
||||
HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
|
||||
HLL_DENSE_GET_REGISTER(val,hdr->registers(),i);
|
||||
if (val != bytecounters[i]) {
|
||||
addReplyErrorFormat(c,
|
||||
"TESTFAILED Register %d should be %d but is %d",
|
||||
@@ -1433,21 +1446,20 @@ void pfselftestCommand(client *c) {
|
||||
*
|
||||
* The test is performed with both dense and sparse HLLs at the same
|
||||
* time also verifying that the computed cardinality is the same. */
|
||||
memset(hdr->registers,0,HLL_DENSE_SIZE-HLL_HDR_SIZE);
|
||||
memset(hdr->registers(),0,HLL_DENSE_SIZE-HLL_HDR_SIZE);
|
||||
o = createHLLObject();
|
||||
double relerr = 1.04/sqrt(HLL_REGISTERS);
|
||||
int64_t checkpoint = 1;
|
||||
uint64_t seed = (uint64_t)rand() | (uint64_t)rand() << 32;
|
||||
uint64_t ele;
|
||||
relerr = 1.04/sqrt(HLL_REGISTERS);
|
||||
checkpoint = 1;
|
||||
seed = (uint64_t)rand() | (uint64_t)rand() << 32;
|
||||
for (j = 1; j <= 10000000; j++) {
|
||||
ele = j ^ seed;
|
||||
hllDenseAdd(hdr->registers,(unsigned char*)&ele,sizeof(ele));
|
||||
hllDenseAdd(hdr->registers(),(unsigned char*)&ele,sizeof(ele));
|
||||
hllAdd(o,(unsigned char*)&ele,sizeof(ele));
|
||||
|
||||
/* Make sure that for small cardinalities we use sparse
|
||||
* encoding. */
|
||||
if (j == checkpoint && j < server.hll_sparse_max_bytes/2) {
|
||||
hdr2 = ptrFromObj(o);
|
||||
if (j == checkpoint && j < g_pserver->hll_sparse_max_bytes/2) {
|
||||
hdr2 = (hllhdr*)ptrFromObj(o);
|
||||
if (hdr2->encoding != HLL_SPARSE) {
|
||||
addReplyError(c, "TESTFAILED sparse encoding not used");
|
||||
goto cleanup;
|
||||
@@ -1455,7 +1467,7 @@ void pfselftestCommand(client *c) {
|
||||
}
|
||||
|
||||
/* Check that dense and sparse representations agree. */
|
||||
if (j == checkpoint && hllCount(hdr,NULL) != hllCount(ptrFromObj(o),NULL)) {
|
||||
if (j == checkpoint && hllCount(hdr,NULL) != hllCount((hllhdr*)ptrFromObj(o),NULL)) {
|
||||
addReplyError(c, "TESTFAILED dense/sparse disagree");
|
||||
goto cleanup;
|
||||
}
|
||||
@@ -1494,7 +1506,7 @@ cleanup:
|
||||
/* PFDEBUG <subcommand> <key> ... args ...
|
||||
* Different debugging related operations about the HLL implementation. */
|
||||
void pfdebugCommand(client *c) {
|
||||
char *cmd = ptrFromObj(c->argv[1]);
|
||||
char *cmd = szFromObj(c->argv[1]);
|
||||
struct hllhdr *hdr;
|
||||
robj *o;
|
||||
int j;
|
||||
@@ -1506,7 +1518,7 @@ void pfdebugCommand(client *c) {
|
||||
}
|
||||
if (isHLLObjectOrReply(c,o) != C_OK) return;
|
||||
o = dbUnshareStringValue(c->db,c->argv[2],o);
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
|
||||
/* PFDEBUG GETREG <key> */
|
||||
if (!strcasecmp(cmd,"getreg")) {
|
||||
@@ -1517,15 +1529,15 @@ void pfdebugCommand(client *c) {
|
||||
addReplySds(c,sdsnew(invalid_hll_err));
|
||||
return;
|
||||
}
|
||||
server.dirty++; /* Force propagation on encoding change. */
|
||||
g_pserver->dirty++; /* Force propagation on encoding change. */
|
||||
}
|
||||
|
||||
hdr = ptrFromObj(o);
|
||||
hdr = (hllhdr*)ptrFromObj(o);
|
||||
addReplyArrayLen(c,HLL_REGISTERS);
|
||||
for (j = 0; j < HLL_REGISTERS; j++) {
|
||||
uint8_t val;
|
||||
|
||||
HLL_DENSE_GET_REGISTER(val,hdr->registers,j);
|
||||
HLL_DENSE_GET_REGISTER(val,hdr->registers(),j);
|
||||
addReplyLongLong(c,val);
|
||||
}
|
||||
}
|
||||
@@ -1533,7 +1545,7 @@ void pfdebugCommand(client *c) {
|
||||
else if (!strcasecmp(cmd,"decode")) {
|
||||
if (c->argc != 3) goto arityerr;
|
||||
|
||||
uint8_t *p = ptrFromObj(o), *end = p+sdslen(ptrFromObj(o));
|
||||
uint8_t *p = (uint8_t*)ptrFromObj(o), *end = p+sdslen(szFromObj(o));
|
||||
sds decoded = sdsempty();
|
||||
|
||||
if (hdr->encoding != HLL_SPARSE) {
|
||||
@@ -1566,7 +1578,7 @@ void pfdebugCommand(client *c) {
|
||||
}
|
||||
/* PFDEBUG ENCODING <key> */
|
||||
else if (!strcasecmp(cmd,"encoding")) {
|
||||
char *encodingstr[2] = {"dense","sparse"};
|
||||
const char *encodingstr[2] = {"dense","sparse"};
|
||||
if (c->argc != 3) goto arityerr;
|
||||
|
||||
addReplyStatus(c,encodingstr[hdr->encoding]);
|
||||
@@ -1582,7 +1594,7 @@ void pfdebugCommand(client *c) {
|
||||
return;
|
||||
}
|
||||
conv = 1;
|
||||
server.dirty++; /* Force propagation on encoding change. */
|
||||
g_pserver->dirty++; /* Force propagation on encoding change. */
|
||||
}
|
||||
addReply(c,conv ? shared.cone : shared.czero);
|
||||
} else {
|
||||
@@ -46,6 +46,10 @@ typedef struct intset {
|
||||
#endif
|
||||
} intset;
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
intset *intsetNew(void);
|
||||
intset *intsetAdd(intset *is, int64_t value, uint8_t *success);
|
||||
intset *intsetRemove(intset *is, int64_t value, int *success);
|
||||
@@ -59,4 +63,8 @@ size_t intsetBlobLen(intset *is);
|
||||
int intsetTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // __INTSET_H
|
||||
@@ -38,11 +38,11 @@
|
||||
/* Dictionary type for latency events. */
|
||||
int dictStringKeyCompare(void *privdata, const void *key1, const void *key2) {
|
||||
UNUSED(privdata);
|
||||
return strcmp(key1,key2) == 0;
|
||||
return strcmp((const char*)key1,(const char*)key2) == 0;
|
||||
}
|
||||
|
||||
uint64_t dictStringHash(const void *key) {
|
||||
return dictGenHashFunction(key, strlen(key));
|
||||
return dictGenHashFunction(key, strlen((const char*)key));
|
||||
}
|
||||
|
||||
void dictVanillaFree(void *privdata, void *val);
|
||||
@@ -88,25 +88,25 @@ int THPGetAnonHugePagesSize(void) {
|
||||
* of time series, each time serie is craeted on demand in order to avoid
|
||||
* having a fixed list to maintain. */
|
||||
void latencyMonitorInit(void) {
|
||||
server.latency_events = dictCreate(&latencyTimeSeriesDictType,NULL);
|
||||
g_pserver->latency_events = dictCreate(&latencyTimeSeriesDictType,NULL);
|
||||
}
|
||||
|
||||
/* Add the specified sample to the specified time series "event".
|
||||
* This function is usually called via latencyAddSampleIfNeeded(), that
|
||||
* is a macro that only adds the sample if the latency is higher than
|
||||
* server.latency_monitor_threshold. */
|
||||
* g_pserver->latency_monitor_threshold. */
|
||||
void latencyAddSample(const char *event, mstime_t latency) {
|
||||
struct latencyTimeSeries *ts = dictFetchValue(server.latency_events,event);
|
||||
struct latencyTimeSeries *ts = (latencyTimeSeries*)dictFetchValue(g_pserver->latency_events,event);
|
||||
time_t now = time(NULL);
|
||||
int prev;
|
||||
|
||||
/* Create the time series if it does not exist. */
|
||||
if (ts == NULL) {
|
||||
ts = zmalloc(sizeof(*ts), MALLOC_SHARED);
|
||||
ts = (latencyTimeSeries*)zmalloc(sizeof(*ts), MALLOC_SHARED);
|
||||
ts->idx = 0;
|
||||
ts->max = 0;
|
||||
memset(ts->samples,0,sizeof(ts->samples));
|
||||
dictAdd(server.latency_events,zstrdup(event),ts);
|
||||
dictAdd(g_pserver->latency_events,zstrdup(event),ts);
|
||||
}
|
||||
|
||||
if (latency > ts->max) ts->max = latency;
|
||||
@@ -137,12 +137,12 @@ int latencyResetEvent(char *event_to_reset) {
|
||||
dictEntry *de;
|
||||
int resets = 0;
|
||||
|
||||
di = dictGetSafeIterator(server.latency_events);
|
||||
di = dictGetSafeIterator(g_pserver->latency_events);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
char *event = dictGetKey(de);
|
||||
char *event = (char*)dictGetKey(de);
|
||||
|
||||
if (event_to_reset == NULL || strcasecmp(event,event_to_reset) == 0) {
|
||||
dictDelete(server.latency_events, event);
|
||||
dictDelete(g_pserver->latency_events, event);
|
||||
resets++;
|
||||
}
|
||||
}
|
||||
@@ -158,7 +158,7 @@ int latencyResetEvent(char *event_to_reset) {
|
||||
* If the specified event has no elements the structure is populate with
|
||||
* zero values. */
|
||||
void analyzeLatencyForEvent(char *event, struct latencyStats *ls) {
|
||||
struct latencyTimeSeries *ts = dictFetchValue(server.latency_events,event);
|
||||
struct latencyTimeSeries *ts = (latencyTimeSeries*)dictFetchValue(g_pserver->latency_events,event);
|
||||
int j;
|
||||
uint64_t sum;
|
||||
|
||||
@@ -236,8 +236,8 @@ sds createLatencyReport(void) {
|
||||
|
||||
/* Return ASAP if the latency engine is disabled and it looks like it
|
||||
* was never enabled so far. */
|
||||
if (dictSize(server.latency_events) == 0 &&
|
||||
server.latency_monitor_threshold == 0)
|
||||
if (dictSize(g_pserver->latency_events) == 0 &&
|
||||
g_pserver->latency_monitor_threshold == 0)
|
||||
{
|
||||
report = sdscat(report,"I'm sorry, Dave, I can't do that. Latency monitoring is disabled in this Redis instance. You may use \"CONFIG SET latency-monitor-threshold <milliseconds>.\" in order to enable it. If we weren't in a deep space mission I'd suggest to take a look at http://redis.io/topics/latency-monitor.\n");
|
||||
return report;
|
||||
@@ -249,10 +249,10 @@ sds createLatencyReport(void) {
|
||||
dictEntry *de;
|
||||
int eventnum = 0;
|
||||
|
||||
di = dictGetSafeIterator(server.latency_events);
|
||||
di = dictGetSafeIterator(g_pserver->latency_events);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
char *event = dictGetKey(de);
|
||||
struct latencyTimeSeries *ts = dictGetVal(de);
|
||||
char *event = (char*)dictGetKey(de);
|
||||
struct latencyTimeSeries *ts = (latencyTimeSeries*)dictGetVal(de);
|
||||
struct latencyStats ls;
|
||||
|
||||
if (ts == NULL) continue;
|
||||
@@ -273,32 +273,32 @@ sds createLatencyReport(void) {
|
||||
|
||||
/* Fork */
|
||||
if (!strcasecmp(event,"fork")) {
|
||||
char *fork_quality;
|
||||
if (server.stat_fork_rate < 10) {
|
||||
const char *fork_quality;
|
||||
if (g_pserver->stat_fork_rate < 10) {
|
||||
fork_quality = "terrible";
|
||||
advise_better_vm = 1;
|
||||
advices++;
|
||||
} else if (server.stat_fork_rate < 25) {
|
||||
} else if (g_pserver->stat_fork_rate < 25) {
|
||||
fork_quality = "poor";
|
||||
advise_better_vm = 1;
|
||||
advices++;
|
||||
} else if (server.stat_fork_rate < 100) {
|
||||
} else if (g_pserver->stat_fork_rate < 100) {
|
||||
fork_quality = "good";
|
||||
} else {
|
||||
fork_quality = "excellent";
|
||||
}
|
||||
report = sdscatprintf(report,
|
||||
" Fork rate is %.2f GB/sec (%s).", server.stat_fork_rate,
|
||||
" Fork rate is %.2f GB/sec (%s).", g_pserver->stat_fork_rate,
|
||||
fork_quality);
|
||||
}
|
||||
|
||||
/* Potentially commands. */
|
||||
if (!strcasecmp(event,"command")) {
|
||||
if (server.slowlog_log_slower_than < 0) {
|
||||
if (g_pserver->slowlog_log_slower_than < 0) {
|
||||
advise_slowlog_enabled = 1;
|
||||
advices++;
|
||||
} else if (server.slowlog_log_slower_than/1000 >
|
||||
server.latency_monitor_threshold)
|
||||
} else if (g_pserver->slowlog_log_slower_than/1000 >
|
||||
g_pserver->latency_monitor_threshold)
|
||||
{
|
||||
advise_slowlog_tuning = 1;
|
||||
advices++;
|
||||
@@ -401,11 +401,11 @@ sds createLatencyReport(void) {
|
||||
|
||||
/* Slow log. */
|
||||
if (advise_slowlog_enabled) {
|
||||
report = sdscatprintf(report,"- There are latency issues with potentially slow commands you are using. Try to enable the Slow Log Redis feature using the command 'CONFIG SET slowlog-log-slower-than %llu'. If the Slow log is disabled Redis is not able to log slow commands execution for you.\n", (unsigned long long)server.latency_monitor_threshold*1000);
|
||||
report = sdscatprintf(report,"- There are latency issues with potentially slow commands you are using. Try to enable the Slow Log Redis feature using the command 'CONFIG SET slowlog-log-slower-than %llu'. If the Slow log is disabled Redis is not able to log slow commands execution for you.\n", (unsigned long long)g_pserver->latency_monitor_threshold*1000);
|
||||
}
|
||||
|
||||
if (advise_slowlog_tuning) {
|
||||
report = sdscatprintf(report,"- Your current Slow Log configuration only logs events that are slower than your configured latency monitor threshold. Please use 'CONFIG SET slowlog-log-slower-than %llu'.\n", (unsigned long long)server.latency_monitor_threshold*1000);
|
||||
report = sdscatprintf(report,"- Your current Slow Log configuration only logs events that are slower than your configured latency monitor threshold. Please use 'CONFIG SET slowlog-log-slower-than %llu'.\n", (unsigned long long)g_pserver->latency_monitor_threshold*1000);
|
||||
}
|
||||
|
||||
if (advise_slowlog_inspect) {
|
||||
@@ -443,7 +443,7 @@ sds createLatencyReport(void) {
|
||||
report = sdscat(report,"- Assuming from the point of view of data safety this is viable in your environment, you could try to enable the 'no-appendfsync-on-rewrite' option, so that fsync will not be performed while there is a child rewriting the AOF file or producing an RDB file (the moment where there is high disk contention).\n");
|
||||
}
|
||||
|
||||
if (advise_relax_fsync_policy && server.aof_fsync == AOF_FSYNC_ALWAYS) {
|
||||
if (advise_relax_fsync_policy && g_pserver->aof_fsync == AOF_FSYNC_ALWAYS) {
|
||||
report = sdscat(report,"- Your fsync policy is set to 'always'. It is very hard to get good performances with such a setup, if possible try to relax the fsync policy to 'onesec'.\n");
|
||||
}
|
||||
|
||||
@@ -451,7 +451,7 @@ sds createLatencyReport(void) {
|
||||
report = sdscat(report,"- Latency during the AOF atomic rename operation or when the final difference is flushed to the AOF file at the end of the rewrite, sometimes is caused by very high write load, causing the AOF buffer to get very large. If possible try to send less commands to accomplish the same work, or use Lua scripts to group multiple operations into a single EVALSHA call.\n");
|
||||
}
|
||||
|
||||
if (advise_hz && server.hz < 100) {
|
||||
if (advise_hz && g_pserver->hz < 100) {
|
||||
report = sdscat(report,"- In order to make the Redis keys expiring process more incremental, try to set the 'hz' configuration parameter to 100 using 'CONFIG SET hz 100'.\n");
|
||||
}
|
||||
|
||||
@@ -497,11 +497,11 @@ void latencyCommandReplyWithLatestEvents(client *c) {
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
|
||||
addReplyArrayLen(c,dictSize(server.latency_events));
|
||||
di = dictGetIterator(server.latency_events);
|
||||
addReplyArrayLen(c,dictSize(g_pserver->latency_events));
|
||||
di = dictGetIterator(g_pserver->latency_events);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
char *event = dictGetKey(de);
|
||||
struct latencyTimeSeries *ts = dictGetVal(de);
|
||||
char *event = (char*)dictGetKey(de);
|
||||
struct latencyTimeSeries *ts = (latencyTimeSeries*)dictGetVal(de);
|
||||
int last = (ts->idx + LATENCY_TS_LEN - 1) % LATENCY_TS_LEN;
|
||||
|
||||
addReplyArrayLen(c,4);
|
||||
@@ -579,38 +579,38 @@ NULL
|
||||
};
|
||||
struct latencyTimeSeries *ts;
|
||||
|
||||
if (!strcasecmp(ptrFromObj(c->argv[1]),"history") && c->argc == 3) {
|
||||
if (!strcasecmp(szFromObj(c->argv[1]),"history") && c->argc == 3) {
|
||||
/* LATENCY HISTORY <event> */
|
||||
ts = dictFetchValue(server.latency_events,ptrFromObj(c->argv[2]));
|
||||
ts = (latencyTimeSeries*)dictFetchValue(g_pserver->latency_events,ptrFromObj(c->argv[2]));
|
||||
if (ts == NULL) {
|
||||
addReplyArrayLen(c,0);
|
||||
} else {
|
||||
latencyCommandReplyWithSamples(c,ts);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"graph") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"graph") && c->argc == 3) {
|
||||
/* LATENCY GRAPH <event> */
|
||||
sds graph;
|
||||
dictEntry *de;
|
||||
char *event;
|
||||
|
||||
de = dictFind(server.latency_events,ptrFromObj(c->argv[2]));
|
||||
de = dictFind(g_pserver->latency_events,ptrFromObj(c->argv[2]));
|
||||
if (de == NULL) goto nodataerr;
|
||||
ts = dictGetVal(de);
|
||||
event = dictGetKey(de);
|
||||
ts = (latencyTimeSeries*)dictGetVal(de);
|
||||
event = (char*)dictGetKey(de);
|
||||
|
||||
graph = latencyCommandGenSparkeline(event,ts);
|
||||
addReplyBulkCString(c,graph);
|
||||
sdsfree(graph);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"latest") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"latest") && c->argc == 2) {
|
||||
/* LATENCY LATEST */
|
||||
latencyCommandReplyWithLatestEvents(c);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"doctor") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"doctor") && c->argc == 2) {
|
||||
/* LATENCY DOCTOR */
|
||||
sds report = createLatencyReport();
|
||||
|
||||
addReplyBulkCBuffer(c,report,sdslen(report));
|
||||
sdsfree(report);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"reset") && c->argc >= 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"reset") && c->argc >= 2) {
|
||||
/* LATENCY RESET */
|
||||
if (c->argc == 2) {
|
||||
addReplyLongLong(c,latencyResetEvent(NULL));
|
||||
@@ -618,10 +618,10 @@ NULL
|
||||
int j, resets = 0;
|
||||
|
||||
for (j = 2; j < c->argc; j++)
|
||||
resets += latencyResetEvent(ptrFromObj(c->argv[j]));
|
||||
resets += latencyResetEvent(szFromObj(c->argv[j]));
|
||||
addReplyLongLong(c,resets);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"help") && c->argc >= 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"help") && c->argc >= 2) {
|
||||
addReplyHelp(c, help);
|
||||
} else {
|
||||
addReplySubcommandSyntaxError(c);
|
||||
+4
-4
@@ -72,7 +72,7 @@ int THPIsEnabled(void);
|
||||
/* Latency monitoring macros. */
|
||||
|
||||
/* Start monitoring an event. We just set the current time. */
|
||||
#define latencyStartMonitor(var) if (server.latency_monitor_threshold) { \
|
||||
#define latencyStartMonitor(var) if (g_pserver->latency_monitor_threshold) { \
|
||||
var = mstime(); \
|
||||
} else { \
|
||||
var = 0; \
|
||||
@@ -80,14 +80,14 @@ int THPIsEnabled(void);
|
||||
|
||||
/* End monitoring an event, compute the difference with the current time
|
||||
* to check the amount of time elapsed. */
|
||||
#define latencyEndMonitor(var) if (server.latency_monitor_threshold) { \
|
||||
#define latencyEndMonitor(var) if (g_pserver->latency_monitor_threshold) { \
|
||||
var = mstime() - var; \
|
||||
}
|
||||
|
||||
/* Add the sample only if the elapsed time is >= to the configured threshold. */
|
||||
#define latencyAddSampleIfNeeded(event,var) \
|
||||
if (server.latency_monitor_threshold && \
|
||||
(var) >= server.latency_monitor_threshold) \
|
||||
if (g_pserver->latency_monitor_threshold && \
|
||||
(var) >= g_pserver->latency_monitor_threshold) \
|
||||
latencyAddSample((event),(var));
|
||||
|
||||
/* Remove time from a nested event. */
|
||||
|
||||
@@ -30,16 +30,16 @@ size_t lazyfreeGetPendingObjectsCount(void) {
|
||||
* representing the list. */
|
||||
size_t lazyfreeGetFreeEffort(robj *obj) {
|
||||
if (obj->type == OBJ_LIST) {
|
||||
quicklist *ql = ptrFromObj(obj);
|
||||
quicklist *ql = (quicklist*)ptrFromObj(obj);
|
||||
return ql->len;
|
||||
} else if (obj->type == OBJ_SET && obj->encoding == OBJ_ENCODING_HT) {
|
||||
dict *ht = ptrFromObj(obj);
|
||||
dict *ht = (dict*)ptrFromObj(obj);
|
||||
return dictSize(ht);
|
||||
} else if (obj->type == OBJ_ZSET && obj->encoding == OBJ_ENCODING_SKIPLIST){
|
||||
zset *zs = ptrFromObj(obj);
|
||||
zset *zs = (zset*)ptrFromObj(obj);
|
||||
return zs->zsl->length;
|
||||
} else if (obj->type == OBJ_HASH && obj->encoding == OBJ_ENCODING_HT) {
|
||||
dict *ht = ptrFromObj(obj);
|
||||
dict *ht = (dict*)ptrFromObj(obj);
|
||||
return dictSize(ht);
|
||||
} else {
|
||||
return 1; /* Everything else is a single allocation. */
|
||||
@@ -52,16 +52,19 @@ size_t lazyfreeGetFreeEffort(robj *obj) {
|
||||
* will be reclaimed in a different bio.c thread. */
|
||||
#define LAZYFREE_THRESHOLD 64
|
||||
int dbAsyncDelete(redisDb *db, robj *key) {
|
||||
/* Deleting an entry from the expires dict will not free the sds of
|
||||
* the key, because it is shared with the main dictionary. */
|
||||
if (dictSize(db->expires) > 0) dictDelete(db->expires,ptrFromObj(key));
|
||||
|
||||
/* If the value is composed of a few allocations, to free in a lazy way
|
||||
* is actually just slower... So under a certain limit we just free
|
||||
* the object synchronously. */
|
||||
dictEntry *de = dictUnlink(db->pdict,ptrFromObj(key));
|
||||
if (de) {
|
||||
robj *val = dictGetVal(de);
|
||||
robj *val = (robj*)dictGetVal(de);
|
||||
if (val->FExpires())
|
||||
{
|
||||
/* Deleting an entry from the expires dict will not free the sds of
|
||||
* the key, because it is shared with the main dictionary. */
|
||||
removeExpireCore(db,key,de);
|
||||
}
|
||||
|
||||
size_t free_effort = lazyfreeGetFreeEffort(val);
|
||||
|
||||
/* If releasing the object is too much work, do it in the background
|
||||
@@ -72,7 +75,7 @@ int dbAsyncDelete(redisDb *db, robj *key) {
|
||||
* objects, and then call dbDelete(). In this case we'll fall
|
||||
* through and reach the dictFreeUnlinkedEntry() call, that will be
|
||||
* equivalent to just calling decrRefCount(). */
|
||||
if (free_effort > LAZYFREE_THRESHOLD && val->refcount == 1) {
|
||||
if (free_effort > LAZYFREE_THRESHOLD && val->getrefcount(std::memory_order_relaxed) == 1) {
|
||||
atomicIncr(lazyfree_objects,1);
|
||||
bioCreateBackgroundJob(BIO_LAZY_FREE,val,NULL,NULL);
|
||||
dictSetVal(db->pdict,de,NULL);
|
||||
@@ -83,7 +86,7 @@ int dbAsyncDelete(redisDb *db, robj *key) {
|
||||
* field to NULL in order to lazy free it later. */
|
||||
if (de) {
|
||||
dictFreeUnlinkedEntry(db->pdict,de);
|
||||
if (server.cluster_enabled) slotToKeyDel(key);
|
||||
if (g_pserver->cluster_enabled) slotToKeyDel(key);
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
@@ -93,7 +96,7 @@ int dbAsyncDelete(redisDb *db, robj *key) {
|
||||
/* Free an object, if the object is huge enough, free it in async way. */
|
||||
void freeObjAsync(robj *o) {
|
||||
size_t free_effort = lazyfreeGetFreeEffort(o);
|
||||
if (free_effort > LAZYFREE_THRESHOLD && o->refcount == 1) {
|
||||
if (free_effort > LAZYFREE_THRESHOLD && o->getrefcount(std::memory_order_relaxed) == 1) {
|
||||
atomicIncr(lazyfree_objects,1);
|
||||
bioCreateBackgroundJob(BIO_LAZY_FREE,o,NULL,NULL);
|
||||
} else {
|
||||
@@ -105,21 +108,23 @@ void freeObjAsync(robj *o) {
|
||||
* create a new empty set of hash tables and scheduling the old ones for
|
||||
* lazy freeing. */
|
||||
void emptyDbAsync(redisDb *db) {
|
||||
dict *oldht1 = db->pdict, *oldht2 = db->expires;
|
||||
dict *oldht1 = db->pdict;
|
||||
auto *set = db->setexpire;
|
||||
db->setexpire = new (MALLOC_LOCAL) expireset();
|
||||
db->expireitr = db->setexpire->end();
|
||||
db->pdict = dictCreate(&dbDictType,NULL);
|
||||
db->expires = dictCreate(&keyptrDictType,NULL);
|
||||
atomicIncr(lazyfree_objects,dictSize(oldht1));
|
||||
bioCreateBackgroundJob(BIO_LAZY_FREE,NULL,oldht1,oldht2);
|
||||
bioCreateBackgroundJob(BIO_LAZY_FREE,NULL,oldht1,set);
|
||||
}
|
||||
|
||||
/* Empty the slots-keys map of Redis CLuster by creating a new empty one
|
||||
* and scheduiling the old for lazy freeing. */
|
||||
void slotToKeyFlushAsync(void) {
|
||||
rax *old = server.cluster->slots_to_keys;
|
||||
rax *old = g_pserver->cluster->slots_to_keys;
|
||||
|
||||
server.cluster->slots_to_keys = raxNew();
|
||||
memset(server.cluster->slots_keys_count,0,
|
||||
sizeof(server.cluster->slots_keys_count));
|
||||
g_pserver->cluster->slots_to_keys = raxNew();
|
||||
memset(g_pserver->cluster->slots_keys_count,0,
|
||||
sizeof(g_pserver->cluster->slots_keys_count));
|
||||
atomicIncr(lazyfree_objects,old->numele);
|
||||
bioCreateBackgroundJob(BIO_LAZY_FREE,NULL,NULL,old);
|
||||
}
|
||||
@@ -136,10 +141,10 @@ void lazyfreeFreeObjectFromBioThread(robj *o) {
|
||||
* when the database was logically deleted. 'sl' is a skiplist used by
|
||||
* Redis Cluster in order to take the hash slots -> keys mapping. This
|
||||
* may be NULL if Redis Cluster is disabled. */
|
||||
void lazyfreeFreeDatabaseFromBioThread(dict *ht1, dict *ht2) {
|
||||
void lazyfreeFreeDatabaseFromBioThread(dict *ht1, expireset *set) {
|
||||
size_t numkeys = dictSize(ht1);
|
||||
dictRelease(ht1);
|
||||
dictRelease(ht2);
|
||||
delete set;
|
||||
atomicDecr(lazyfree_objects,numkeys);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,10 @@
|
||||
#define LP_AFTER 1
|
||||
#define LP_REPLACE 2
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
unsigned char *lpNew(void);
|
||||
void lpFree(unsigned char *lp);
|
||||
unsigned char *lpInsert(unsigned char *lp, unsigned char *ele, uint32_t size, unsigned char *p, int where, unsigned char **newp);
|
||||
@@ -58,4 +62,8 @@ unsigned char *lpPrev(unsigned char *lp, unsigned char *p);
|
||||
uint32_t lpBytes(unsigned char *lp);
|
||||
unsigned char *lpSeek(unsigned char *lp, long index);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -1,56 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Salvatore Sanfilippo <antirez at gmail dot com>
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* * 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.
|
||||
* * Neither the name of Redis 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 OWNER 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.
|
||||
*
|
||||
* ----------------------------------------------------------------------------
|
||||
*
|
||||
* This file implements the LOLWUT command. The command should do something
|
||||
* fun and interesting, and should be replaced by a new implementation at
|
||||
* each new version of Redis.
|
||||
*/
|
||||
|
||||
#include "server.h"
|
||||
|
||||
void lolwut5Command(client *c);
|
||||
|
||||
/* The default target for LOLWUT if no matching version was found.
|
||||
* This is what unstable versions of Redis will display. */
|
||||
void lolwutUnstableCommand(client *c) {
|
||||
sds rendered = sdsnew("Redis ver. ");
|
||||
rendered = sdscat(rendered,REDIS_VERSION);
|
||||
rendered = sdscatlen(rendered,"\n",1);
|
||||
addReplyBulkSds(c,rendered);
|
||||
}
|
||||
|
||||
void lolwutCommand(client *c) {
|
||||
char *v = REDIS_VERSION;
|
||||
if ((v[0] == '5' && v[1] == '.') ||
|
||||
(v[0] == '4' && v[1] == '.' && v[2] == '9'))
|
||||
lolwut5Command(c);
|
||||
else
|
||||
lolwutUnstableCommand(c);
|
||||
}
|
||||
-282
@@ -1,282 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Salvatore Sanfilippo <antirez at gmail dot com>
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice,
|
||||
* this list of conditions and the following disclaimer.
|
||||
* * 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.
|
||||
* * Neither the name of Redis 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 OWNER 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.
|
||||
*
|
||||
* ----------------------------------------------------------------------------
|
||||
*
|
||||
* This file implements the LOLWUT command. The command should do something
|
||||
* fun and interesting, and should be replaced by a new implementation at
|
||||
* each new version of Redis.
|
||||
*/
|
||||
|
||||
#include "server.h"
|
||||
#include <math.h>
|
||||
|
||||
/* This structure represents our canvas. Drawing functions will take a pointer
|
||||
* to a canvas to write to it. Later the canvas can be rendered to a string
|
||||
* suitable to be printed on the screen, using unicode Braille characters. */
|
||||
typedef struct lwCanvas {
|
||||
int width;
|
||||
int height;
|
||||
char *pixels;
|
||||
} lwCanvas;
|
||||
|
||||
/* Translate a group of 8 pixels (2x4 vertical rectangle) to the corresponding
|
||||
* braille character. The byte should correspond to the pixels arranged as
|
||||
* follows, where 0 is the least significant bit, and 7 the most significant
|
||||
* bit:
|
||||
*
|
||||
* 0 3
|
||||
* 1 4
|
||||
* 2 5
|
||||
* 6 7
|
||||
*
|
||||
* The corresponding utf8 encoded character is set into the three bytes
|
||||
* pointed by 'output'.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
void lwTranslatePixelsGroup(int byte, char *output) {
|
||||
int code = 0x2800 + byte;
|
||||
/* Convert to unicode. This is in the U0800-UFFFF range, so we need to
|
||||
* emit it like this in three bytes:
|
||||
* 1110xxxx 10xxxxxx 10xxxxxx. */
|
||||
output[0] = 0xE0 | (code >> 12); /* 1110-xxxx */
|
||||
output[1] = 0x80 | ((code >> 6) & 0x3F); /* 10-xxxxxx */
|
||||
output[2] = 0x80 | (code & 0x3F); /* 10-xxxxxx */
|
||||
}
|
||||
|
||||
/* Allocate and return a new canvas of the specified size. */
|
||||
lwCanvas *lwCreateCanvas(int width, int height) {
|
||||
lwCanvas *canvas = zmalloc(sizeof(*canvas), MALLOC_SHARED);
|
||||
canvas->width = width;
|
||||
canvas->height = height;
|
||||
canvas->pixels = zmalloc(width*height, MALLOC_SHARED);
|
||||
memset(canvas->pixels,0,width*height);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
/* Free the canvas created by lwCreateCanvas(). */
|
||||
void lwFreeCanvas(lwCanvas *canvas) {
|
||||
zfree(canvas->pixels);
|
||||
zfree(canvas);
|
||||
}
|
||||
|
||||
/* Set a pixel to the specified color. Color is 0 or 1, where zero means no
|
||||
* dot will be displyed, and 1 means dot will be displayed.
|
||||
* Coordinates are arranged so that left-top corner is 0,0. You can write
|
||||
* out of the size of the canvas without issues. */
|
||||
void lwDrawPixel(lwCanvas *canvas, int x, int y, int color) {
|
||||
if (x < 0 || x >= canvas->width ||
|
||||
y < 0 || y >= canvas->height) return;
|
||||
canvas->pixels[x+y*canvas->width] = color;
|
||||
}
|
||||
|
||||
/* Return the value of the specified pixel on the canvas. */
|
||||
int lwGetPixel(lwCanvas *canvas, int x, int y) {
|
||||
if (x < 0 || x >= canvas->width ||
|
||||
y < 0 || y >= canvas->height) return 0;
|
||||
return canvas->pixels[x+y*canvas->width];
|
||||
}
|
||||
|
||||
/* Draw a line from x1,y1 to x2,y2 using the Bresenham algorithm. */
|
||||
void lwDrawLine(lwCanvas *canvas, int x1, int y1, int x2, int y2, int color) {
|
||||
int dx = abs(x2-x1);
|
||||
int dy = abs(y2-y1);
|
||||
int sx = (x1 < x2) ? 1 : -1;
|
||||
int sy = (y1 < y2) ? 1 : -1;
|
||||
int err = dx-dy, e2;
|
||||
|
||||
while(1) {
|
||||
lwDrawPixel(canvas,x1,y1,color);
|
||||
if (x1 == x2 && y1 == y2) break;
|
||||
e2 = err*2;
|
||||
if (e2 > -dy) {
|
||||
err -= dy;
|
||||
x1 += sx;
|
||||
}
|
||||
if (e2 < dx) {
|
||||
err += dx;
|
||||
y1 += sy;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Draw a square centered at the specified x,y coordinates, with the specified
|
||||
* rotation angle and size. In order to write a rotated square, we use the
|
||||
* trivial fact that the parametric equation:
|
||||
*
|
||||
* x = sin(k)
|
||||
* y = cos(k)
|
||||
*
|
||||
* Describes a circle for values going from 0 to 2*PI. So basically if we start
|
||||
* at 45 degrees, that is k = PI/4, with the first point, and then we find
|
||||
* the other three points incrementing K by PI/2 (90 degrees), we'll have the
|
||||
* points of the square. In order to rotate the square, we just start with
|
||||
* k = PI/4 + rotation_angle, and we are done.
|
||||
*
|
||||
* Of course the vanilla equations above will describe the square inside a
|
||||
* circle of radius 1, so in order to draw larger squares we'll have to
|
||||
* multiply the obtained coordinates, and then translate them. However this
|
||||
* is much simpler than implementing the abstract concept of 2D shape and then
|
||||
* performing the rotation/translation transformation, so for LOLWUT it's
|
||||
* a good approach. */
|
||||
void lwDrawSquare(lwCanvas *canvas, int x, int y, float size, float angle) {
|
||||
int px[4], py[4];
|
||||
|
||||
/* Adjust the desired size according to the fact that the square inscribed
|
||||
* into a circle of radius 1 has the side of length SQRT(2). This way
|
||||
* size becomes a simple multiplication factor we can use with our
|
||||
* coordinates to magnify them. */
|
||||
size /= 1.4142135623;
|
||||
size = round(size);
|
||||
|
||||
/* Compute the four points. */
|
||||
float k = M_PI/4 + angle;
|
||||
for (int j = 0; j < 4; j++) {
|
||||
px[j] = round(sin(k) * size + x);
|
||||
py[j] = round(cos(k) * size + y);
|
||||
k += M_PI/2;
|
||||
}
|
||||
|
||||
/* Draw the square. */
|
||||
for (int j = 0; j < 4; j++)
|
||||
lwDrawLine(canvas,px[j],py[j],px[(j+1)%4],py[(j+1)%4],1);
|
||||
}
|
||||
|
||||
/* Schotter, the output of LOLWUT of Redis 5, is a computer graphic art piece
|
||||
* generated by Georg Nees in the 60s. It explores the relationship between
|
||||
* caos and order.
|
||||
*
|
||||
* The function creates the canvas itself, depending on the columns available
|
||||
* in the output display and the number of squares per row and per column
|
||||
* requested by the caller. */
|
||||
lwCanvas *lwDrawSchotter(int console_cols, int squares_per_row, int squares_per_col) {
|
||||
/* Calculate the canvas size. */
|
||||
int canvas_width = console_cols*2;
|
||||
int padding = canvas_width > 4 ? 2 : 0;
|
||||
float square_side = (float)(canvas_width-padding*2) / squares_per_row;
|
||||
int canvas_height = square_side * squares_per_col + padding*2;
|
||||
lwCanvas *canvas = lwCreateCanvas(canvas_width, canvas_height);
|
||||
|
||||
for (int y = 0; y < squares_per_col; y++) {
|
||||
for (int x = 0; x < squares_per_row; x++) {
|
||||
int sx = x * square_side + square_side/2 + padding;
|
||||
int sy = y * square_side + square_side/2 + padding;
|
||||
/* Rotate and translate randomly as we go down to lower
|
||||
* rows. */
|
||||
float angle = 0;
|
||||
if (y > 1) {
|
||||
float r1 = (float)rand() / RAND_MAX / squares_per_col * y;
|
||||
float r2 = (float)rand() / RAND_MAX / squares_per_col * y;
|
||||
float r3 = (float)rand() / RAND_MAX / squares_per_col * y;
|
||||
if (rand() % 2) r1 = -r1;
|
||||
if (rand() % 2) r2 = -r2;
|
||||
if (rand() % 2) r3 = -r3;
|
||||
angle = r1;
|
||||
sx += r2*square_side/3;
|
||||
sy += r3*square_side/3;
|
||||
}
|
||||
lwDrawSquare(canvas,sx,sy,square_side,angle);
|
||||
}
|
||||
}
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
/* Converts the canvas to an SDS string representing the UTF8 characters to
|
||||
* print to the terminal in order to obtain a graphical representaiton of the
|
||||
* logical canvas. The actual returned string will require a terminal that is
|
||||
* width/2 large and height/4 tall in order to hold the whole image without
|
||||
* overflowing or scrolling, since each Barille character is 2x4. */
|
||||
sds lwRenderCanvas(lwCanvas *canvas) {
|
||||
sds text = sdsempty();
|
||||
for (int y = 0; y < canvas->height; y += 4) {
|
||||
for (int x = 0; x < canvas->width; x += 2) {
|
||||
/* We need to emit groups of 8 bits according to a specific
|
||||
* arrangement. See lwTranslatePixelsGroup() for more info. */
|
||||
int byte = 0;
|
||||
if (lwGetPixel(canvas,x,y)) byte |= (1<<0);
|
||||
if (lwGetPixel(canvas,x,y+1)) byte |= (1<<1);
|
||||
if (lwGetPixel(canvas,x,y+2)) byte |= (1<<2);
|
||||
if (lwGetPixel(canvas,x+1,y)) byte |= (1<<3);
|
||||
if (lwGetPixel(canvas,x+1,y+1)) byte |= (1<<4);
|
||||
if (lwGetPixel(canvas,x+1,y+2)) byte |= (1<<5);
|
||||
if (lwGetPixel(canvas,x,y+3)) byte |= (1<<6);
|
||||
if (lwGetPixel(canvas,x+1,y+3)) byte |= (1<<7);
|
||||
char unicode[3];
|
||||
lwTranslatePixelsGroup(byte,unicode);
|
||||
text = sdscatlen(text,unicode,3);
|
||||
}
|
||||
if (y != canvas->height-1) text = sdscatlen(text,"\n",1);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/* The LOLWUT command:
|
||||
*
|
||||
* LOLWUT [terminal columns] [squares-per-row] [squares-per-col]
|
||||
*
|
||||
* By default the command uses 66 columns, 8 squares per row, 12 squares
|
||||
* per column.
|
||||
*/
|
||||
void lolwut5Command(client *c) {
|
||||
long cols = 66;
|
||||
long squares_per_row = 8;
|
||||
long squares_per_col = 12;
|
||||
|
||||
/* Parse the optional arguments if any. */
|
||||
if (c->argc > 1 &&
|
||||
getLongFromObjectOrReply(c,c->argv[1],&cols,NULL) != C_OK)
|
||||
return;
|
||||
|
||||
if (c->argc > 2 &&
|
||||
getLongFromObjectOrReply(c,c->argv[2],&squares_per_row,NULL) != C_OK)
|
||||
return;
|
||||
|
||||
if (c->argc > 3 &&
|
||||
getLongFromObjectOrReply(c,c->argv[3],&squares_per_col,NULL) != C_OK)
|
||||
return;
|
||||
|
||||
/* Limits. We want LOLWUT to be always reasonably fast and cheap to execute
|
||||
* so we have maximum number of columns, rows, and output resulution. */
|
||||
if (cols < 1) cols = 1;
|
||||
if (cols > 1000) cols = 1000;
|
||||
if (squares_per_row < 1) squares_per_row = 1;
|
||||
if (squares_per_row > 200) squares_per_row = 200;
|
||||
if (squares_per_col < 1) squares_per_col = 1;
|
||||
if (squares_per_col > 200) squares_per_col = 200;
|
||||
|
||||
/* Generate some computer art and reply. */
|
||||
lwCanvas *canvas = lwDrawSchotter(cols,squares_per_row,squares_per_col);
|
||||
sds rendered = lwRenderCanvas(canvas);
|
||||
rendered = sdscat(rendered,
|
||||
"\nGeorg Nees - schotter, plotter on paper, 1968. Redis ver. ");
|
||||
rendered = sdscat(rendered,REDIS_VERSION);
|
||||
rendered = sdscatlen(rendered,"\n",1);
|
||||
addReplyBulkSds(c,rendered);
|
||||
lwFreeCanvas(canvas);
|
||||
}
|
||||
@@ -48,6 +48,10 @@
|
||||
|
||||
#define LZF_VERSION 0x0105 /* 1.5, API version */
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Compress in_len bytes stored at the memory block starting at
|
||||
* in_data and write the result to out_data, up to a maximum length
|
||||
@@ -96,5 +100,9 @@ unsigned int
|
||||
lzf_decompress (const void *const in_data, unsigned int in_len,
|
||||
void *out_data, unsigned int out_len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+561
-245
File diff suppressed because it is too large.
Load diff
@@ -46,7 +46,6 @@ hellotimer.so: hellotimer.xo
|
||||
hellodict.xo: ../redismodule.h
|
||||
|
||||
hellodict.so: hellodict.xo
|
||||
$(LD) -o $@ $< $(SHOBJ_LDFLAGS) $(LIBS) -lc
|
||||
|
||||
testmodule.xo: ../redismodule.h
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
/* Timer callback. */
|
||||
void timerHandler(RedisModuleCtx *ctx, void *data) {
|
||||
REDISMODULE_NOT_USED(ctx);
|
||||
printf("Fired %s!\n", data);
|
||||
printf("Fired %s!\n", (const char *) data);
|
||||
RedisModule_Free(data);
|
||||
}
|
||||
|
||||
|
||||
@@ -109,9 +109,9 @@ int TestStringPrintf(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
|
||||
if (argc < 3) {
|
||||
return RedisModule_WrongArity(ctx);
|
||||
}
|
||||
RedisModuleString *s = RedisModule_CreateStringPrintf(ctx,
|
||||
"Got %d args. argv[1]: %s, argv[2]: %s",
|
||||
argc,
|
||||
RedisModuleString *s = RedisModule_CreateStringPrintf(ctx,
|
||||
"Got %d args. argv[1]: %s, argv[2]: %s",
|
||||
argc,
|
||||
RedisModule_StringPtrLen(argv[1], NULL),
|
||||
RedisModule_StringPtrLen(argv[2], NULL)
|
||||
);
|
||||
@@ -133,7 +133,7 @@ int TestUnlink(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
|
||||
|
||||
RedisModuleKey *k = RedisModule_OpenKey(ctx, RedisModule_CreateStringPrintf(ctx, "unlinked"), REDISMODULE_WRITE | REDISMODULE_READ);
|
||||
if (!k) return failTest(ctx, "Could not create key");
|
||||
|
||||
|
||||
if (REDISMODULE_ERR == RedisModule_StringSet(k, RedisModule_CreateStringPrintf(ctx, "Foobar"))) {
|
||||
return failTest(ctx, "Could not set string value");
|
||||
}
|
||||
@@ -152,7 +152,7 @@ int TestUnlink(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
|
||||
return failTest(ctx, "Could not verify key to be unlinked");
|
||||
}
|
||||
return RedisModule_ReplyWithSimpleString(ctx, "OK");
|
||||
|
||||
|
||||
}
|
||||
|
||||
int NotifyCallback(RedisModuleCtx *ctx, int type, const char *event,
|
||||
@@ -188,6 +188,10 @@ int TestNotifications(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
|
||||
RedisModule_Call(ctx, "LPUSH", "cc", "l", "y");
|
||||
RedisModule_Call(ctx, "LPUSH", "cc", "l", "y");
|
||||
|
||||
/* Miss some keys intentionally so we will get a "keymiss" notification. */
|
||||
RedisModule_Call(ctx, "GET", "c", "nosuchkey");
|
||||
RedisModule_Call(ctx, "SMEMBERS", "c", "nosuchkey");
|
||||
|
||||
size_t sz;
|
||||
const char *rep;
|
||||
RedisModuleCallReply *r = RedisModule_Call(ctx, "HGET", "cc", "notifications", "foo");
|
||||
@@ -225,6 +229,16 @@ int TestNotifications(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
|
||||
FAIL("Wrong reply for l");
|
||||
}
|
||||
|
||||
r = RedisModule_Call(ctx, "HGET", "cc", "notifications", "nosuchkey");
|
||||
if (r == NULL || RedisModule_CallReplyType(r) != REDISMODULE_REPLY_STRING) {
|
||||
FAIL("Wrong or no reply for nosuchkey");
|
||||
} else {
|
||||
rep = RedisModule_CallReplyStringPtr(r, &sz);
|
||||
if (sz != 1 || *rep != '2') {
|
||||
FAIL("Got reply '%.*s'. expected '2'", sz, rep);
|
||||
}
|
||||
}
|
||||
|
||||
RedisModule_Call(ctx, "FLUSHDB", "");
|
||||
|
||||
return RedisModule_ReplyWithSimpleString(ctx, "OK");
|
||||
@@ -423,7 +437,7 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
|
||||
if (RedisModule_CreateCommand(ctx,"test.ctxflags",
|
||||
TestCtxFlags,"readonly",1,1,1) == REDISMODULE_ERR)
|
||||
return REDISMODULE_ERR;
|
||||
|
||||
|
||||
if (RedisModule_CreateCommand(ctx,"test.unlink",
|
||||
TestUnlink,"write deny-oom",1,1,1) == REDISMODULE_ERR)
|
||||
return REDISMODULE_ERR;
|
||||
@@ -435,7 +449,8 @@ int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc)
|
||||
RedisModule_SubscribeToKeyspaceEvents(ctx,
|
||||
REDISMODULE_NOTIFY_HASH |
|
||||
REDISMODULE_NOTIFY_SET |
|
||||
REDISMODULE_NOTIFY_STRING,
|
||||
REDISMODULE_NOTIFY_STRING |
|
||||
REDISMODULE_NOTIFY_KEY_MISS,
|
||||
NotifyCallback);
|
||||
if (RedisModule_CreateCommand(ctx,"test.notify",
|
||||
TestNotifications,"write deny-oom",1,1,1) == REDISMODULE_ERR)
|
||||
|
||||
+24
-25
@@ -58,12 +58,12 @@ void queueMultiCommand(client *c) {
|
||||
multiCmd *mc;
|
||||
int j;
|
||||
|
||||
c->mstate.commands = zrealloc(c->mstate.commands,
|
||||
c->mstate.commands = (multiCmd*)zrealloc(c->mstate.commands,
|
||||
sizeof(multiCmd)*(c->mstate.count+1), MALLOC_LOCAL);
|
||||
mc = c->mstate.commands+c->mstate.count;
|
||||
mc->cmd = c->cmd;
|
||||
mc->argc = c->argc;
|
||||
mc->argv = zmalloc(sizeof(robj*)*c->argc, MALLOC_LOCAL);
|
||||
mc->argv = (robj**)zmalloc(sizeof(robj*)*c->argc, MALLOC_LOCAL);
|
||||
memcpy(mc->argv,c->argv,sizeof(robj*)*c->argc);
|
||||
for (j = 0; j < c->argc; j++)
|
||||
incrRefCount(mc->argv[j]);
|
||||
@@ -82,7 +82,6 @@ void discardTransaction(client *c) {
|
||||
/* Flag the transacation as DIRTY_EXEC so that EXEC will fail.
|
||||
* Should be called every time there is an error while queueing a command. */
|
||||
void flagTransaction(client *c) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
if (c->flags & CLIENT_MULTI)
|
||||
c->flags |= CLIENT_DIRTY_EXEC;
|
||||
}
|
||||
@@ -111,7 +110,7 @@ void discardCommand(client *c) {
|
||||
void execCommandPropagateMulti(client *c) {
|
||||
robj *multistring = createStringObject("MULTI",5);
|
||||
|
||||
propagate(server.multiCommand,c->db->id,&multistring,1,
|
||||
propagate(cserver.multiCommand,c->db->id,&multistring,1,
|
||||
PROPAGATE_AOF|PROPAGATE_REPL);
|
||||
decrRefCount(multistring);
|
||||
}
|
||||
@@ -122,7 +121,7 @@ void execCommand(client *c) {
|
||||
int orig_argc;
|
||||
struct redisCommand *orig_cmd;
|
||||
int must_propagate = 0; /* Need to propagate MULTI/EXEC to AOF / slaves? */
|
||||
int was_master = server.masterhost == NULL;
|
||||
int was_master = listLength(g_pserver->masters) == 0;
|
||||
|
||||
if (!(c->flags & CLIENT_MULTI)) {
|
||||
addReplyError(c,"EXEC without MULTI");
|
||||
@@ -143,11 +142,11 @@ void execCommand(client *c) {
|
||||
}
|
||||
|
||||
/* If there are write commands inside the transaction, and this is a read
|
||||
* only slave, we want to send an error. This happens when the transaction
|
||||
* only replica, we want to send an error. This happens when the transaction
|
||||
* was initiated when the instance was a master or a writable replica and
|
||||
* then the configuration changed (for example instance was turned into
|
||||
* a replica). */
|
||||
if (!server.loading && server.masterhost && server.repl_slave_ro &&
|
||||
if (!g_pserver->loading && listLength(g_pserver->masters) && g_pserver->repl_slave_ro &&
|
||||
!(c->flags & CLIENT_MASTER) && c->mstate.cmd_flags & CMD_WRITE)
|
||||
{
|
||||
addReplyError(c,
|
||||
@@ -178,7 +177,7 @@ void execCommand(client *c) {
|
||||
must_propagate = 1;
|
||||
}
|
||||
|
||||
call(c,server.loading ? CMD_CALL_NONE : CMD_CALL_FULL);
|
||||
call(c,g_pserver->loading ? CMD_CALL_NONE : CMD_CALL_FULL);
|
||||
|
||||
/* Commands may alter argc/argv, restore mstate. */
|
||||
c->mstate.commands[j].argc = c->argc;
|
||||
@@ -193,15 +192,15 @@ void execCommand(client *c) {
|
||||
/* Make sure the EXEC command will be propagated as well if MULTI
|
||||
* was already propagated. */
|
||||
if (must_propagate) {
|
||||
int is_master = server.masterhost == NULL;
|
||||
server.dirty++;
|
||||
int is_master = listLength(g_pserver->masters) == 0;
|
||||
g_pserver->dirty++;
|
||||
/* If inside the MULTI/EXEC block this instance was suddenly
|
||||
* switched from master to slave (using the SLAVEOF command), the
|
||||
* switched from master to replica (using the SLAVEOF command), the
|
||||
* initial MULTI was propagated into the replication backlog, but the
|
||||
* rest was not. We need to make sure to at least terminate the
|
||||
* backlog with the final EXEC. */
|
||||
if (server.repl_backlog && was_master && !is_master) {
|
||||
char *execcmd = "*1\r\n$4\r\nEXEC\r\n";
|
||||
if (g_pserver->repl_backlog && was_master && !is_master) {
|
||||
const char *execcmd = "*1\r\n$4\r\nEXEC\r\n";
|
||||
feedReplicationBacklog(execcmd,strlen(execcmd));
|
||||
}
|
||||
}
|
||||
@@ -212,8 +211,8 @@ handle_monitor:
|
||||
* MUTLI, EXEC, ... commands inside transaction ...
|
||||
* Instead EXEC is flagged as CMD_SKIP_MONITOR in the command
|
||||
* table, and we do it here with correct ordering. */
|
||||
if (listLength(server.monitors) && !server.loading)
|
||||
replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc);
|
||||
if (listLength(g_pserver->monitors) && !g_pserver->loading)
|
||||
replicationFeedMonitors(c,g_pserver->monitors,c->db->id,c->argv,c->argc);
|
||||
}
|
||||
|
||||
/* ===================== WATCH (CAS alike for MULTI/EXEC) ===================
|
||||
@@ -243,12 +242,12 @@ void watchForKey(client *c, robj *key) {
|
||||
/* Check if we are already watching for this key */
|
||||
listRewind(c->watched_keys,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
wk = listNodeValue(ln);
|
||||
wk = (watchedKey*)listNodeValue(ln);
|
||||
if (wk->db == c->db && equalStringObjects(key,wk->key))
|
||||
return; /* Key already watched */
|
||||
}
|
||||
/* This key is not already watched in this DB. Let's add it */
|
||||
clients = dictFetchValue(c->db->watched_keys,key);
|
||||
clients = (decltype(clients)) dictFetchValue(c->db->watched_keys,key);
|
||||
if (!clients) {
|
||||
clients = listCreate();
|
||||
dictAdd(c->db->watched_keys,key,clients);
|
||||
@@ -256,7 +255,7 @@ void watchForKey(client *c, robj *key) {
|
||||
}
|
||||
listAddNodeTail(clients,c);
|
||||
/* Add the new key to the list of keys watched by this client */
|
||||
wk = zmalloc(sizeof(*wk), MALLOC_SHARED);
|
||||
wk = (watchedKey*)zmalloc(sizeof(*wk), MALLOC_SHARED);
|
||||
wk->key = key;
|
||||
wk->db = c->db;
|
||||
incrRefCount(key);
|
||||
@@ -277,8 +276,8 @@ void unwatchAllKeys(client *c) {
|
||||
|
||||
/* Lookup the watched key -> clients list and remove the client
|
||||
* from the list */
|
||||
wk = listNodeValue(ln);
|
||||
clients = dictFetchValue(wk->db->watched_keys, wk->key);
|
||||
wk = (watchedKey*)listNodeValue(ln);
|
||||
clients = (decltype(clients))dictFetchValue(wk->db->watched_keys, wk->key);
|
||||
serverAssertWithInfo(c,NULL,clients != NULL);
|
||||
listDelNode(clients,listSearchKey(clients,c));
|
||||
/* Kill the entry at all if this was the only client */
|
||||
@@ -300,14 +299,14 @@ void touchWatchedKey(redisDb *db, robj *key) {
|
||||
listNode *ln;
|
||||
|
||||
if (dictSize(db->watched_keys) == 0) return;
|
||||
clients = dictFetchValue(db->watched_keys, key);
|
||||
clients = (list*)dictFetchValue(db->watched_keys, key);
|
||||
if (!clients) return;
|
||||
|
||||
/* Mark all the clients watching this key as CLIENT_DIRTY_CAS */
|
||||
/* Check if we are already watching for this key */
|
||||
listRewind(clients,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
client *c = listNodeValue(ln);
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
|
||||
c->flags |= CLIENT_DIRTY_CAS;
|
||||
}
|
||||
@@ -323,12 +322,12 @@ void touchWatchedKeysOnFlush(int dbid) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
|
||||
/* For every client, check all the waited keys */
|
||||
listRewind(server.clients,&li1);
|
||||
listRewind(g_pserver->clients,&li1);
|
||||
while((ln = listNext(&li1))) {
|
||||
client *c = listNodeValue(ln);
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
listRewind(c->watched_keys,&li2);
|
||||
while((ln = listNext(&li2))) {
|
||||
watchedKey *wk = listNodeValue(ln);
|
||||
watchedKey *wk = (watchedKey*)listNodeValue(ln);
|
||||
|
||||
/* For every watched key matching the specified DB, if the
|
||||
* key exists, mark the client as dirty, as the key will be
|
||||
+497
-341
File diff suppressed because it is too large.
Load diff
+34
@@ -0,0 +1,34 @@
|
||||
#include <cstddef> // std::size_t
|
||||
#include "server.h"
|
||||
#include "new.h"
|
||||
|
||||
#ifdef SANITIZE
|
||||
void *operator new(size_t size, enum MALLOC_CLASS mclass)
|
||||
{
|
||||
(void)mclass;
|
||||
return ::operator new(size);
|
||||
}
|
||||
|
||||
#else
|
||||
[[deprecated]]
|
||||
void *operator new(size_t size)
|
||||
{
|
||||
return zmalloc(size, MALLOC_LOCAL);
|
||||
}
|
||||
|
||||
void *operator new(size_t size, enum MALLOC_CLASS mclass)
|
||||
{
|
||||
return zmalloc(size, mclass);
|
||||
}
|
||||
|
||||
void operator delete(void * p) noexcept
|
||||
{
|
||||
zfree(p);
|
||||
}
|
||||
|
||||
void operator delete(void *p, std::size_t) noexcept
|
||||
{
|
||||
zfree(p);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
#include <cstddef> // std::size_t
|
||||
|
||||
void *operator new(size_t size, enum MALLOC_CLASS mclass);
|
||||
|
||||
#ifndef SANITIZE
|
||||
[[deprecated]]
|
||||
void *operator new(size_t size);
|
||||
|
||||
void operator delete(void * p) noexcept;
|
||||
void operator delete(void *p, std::size_t) noexcept;
|
||||
#endif
|
||||
@@ -55,6 +55,7 @@ int keyspaceEventsStringToFlags(char *classes) {
|
||||
case 'K': flags |= NOTIFY_KEYSPACE; break;
|
||||
case 'E': flags |= NOTIFY_KEYEVENT; break;
|
||||
case 't': flags |= NOTIFY_STREAM; break;
|
||||
case 'm': flags |= NOTIFY_KEY_MISS; break;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
@@ -81,6 +82,7 @@ sds keyspaceEventsFlagsToString(int flags) {
|
||||
if (flags & NOTIFY_EXPIRED) res = sdscatlen(res,"x",1);
|
||||
if (flags & NOTIFY_EVICTED) res = sdscatlen(res,"e",1);
|
||||
if (flags & NOTIFY_STREAM) res = sdscatlen(res,"t",1);
|
||||
if (flags & NOTIFY_KEY_MISS) res = sdscatlen(res,"m",1);
|
||||
}
|
||||
if (flags & NOTIFY_KEYSPACE) res = sdscatlen(res,"K",1);
|
||||
if (flags & NOTIFY_KEYEVENT) res = sdscatlen(res,"E",1);
|
||||
@@ -94,42 +96,42 @@ sds keyspaceEventsFlagsToString(int flags) {
|
||||
* 'event' is a C string representing the event name.
|
||||
* 'key' is a Redis object representing the key name.
|
||||
* 'dbid' is the database ID where the key lives. */
|
||||
void notifyKeyspaceEvent(int type, char *event, robj *key, int dbid) {
|
||||
void notifyKeyspaceEvent(int type, const char *event, robj *key, int dbid) {
|
||||
sds chan;
|
||||
robj *chanobj, *eventobj;
|
||||
int len = -1;
|
||||
char buf[24];
|
||||
|
||||
/* If any modules are interested in events, notify the module system now.
|
||||
/* If any modules are interested in events, notify the module system now.
|
||||
* This bypasses the notifications configuration, but the module engine
|
||||
* will only call event subscribers if the event type matches the types
|
||||
* they are interested in. */
|
||||
moduleNotifyKeyspaceEvent(type, event, key, dbid);
|
||||
|
||||
|
||||
/* If notifications for this class of events are off, return ASAP. */
|
||||
if (!(server.notify_keyspace_events & type)) return;
|
||||
if (!(g_pserver->notify_keyspace_events & type)) return;
|
||||
|
||||
eventobj = createStringObject(event,strlen(event));
|
||||
|
||||
/* __keyspace@<db>__:<key> <event> notifications. */
|
||||
if (server.notify_keyspace_events & NOTIFY_KEYSPACE) {
|
||||
if (g_pserver->notify_keyspace_events & NOTIFY_KEYSPACE) {
|
||||
chan = sdsnewlen("__keyspace@",11);
|
||||
len = ll2string(buf,sizeof(buf),dbid);
|
||||
chan = sdscatlen(chan, buf, len);
|
||||
chan = sdscatlen(chan, "__:", 3);
|
||||
chan = sdscatsds(chan, ptrFromObj(key));
|
||||
chan = sdscatsds(chan, szFromObj(key));
|
||||
chanobj = createObject(OBJ_STRING, chan);
|
||||
pubsubPublishMessage(chanobj, eventobj);
|
||||
decrRefCount(chanobj);
|
||||
}
|
||||
|
||||
/* __keyevent@<db>__:<event> <key> notifications. */
|
||||
if (server.notify_keyspace_events & NOTIFY_KEYEVENT) {
|
||||
if (g_pserver->notify_keyspace_events & NOTIFY_KEYEVENT) {
|
||||
chan = sdsnewlen("__keyevent@",11);
|
||||
if (len == -1) len = ll2string(buf,sizeof(buf),dbid);
|
||||
chan = sdscatlen(chan, buf, len);
|
||||
chan = sdscatlen(chan, "__:", 3);
|
||||
chan = sdscatsds(chan, ptrFromObj(eventobj));
|
||||
chan = sdscatsds(chan, szFromObj(eventobj));
|
||||
chanobj = createObject(OBJ_STRING, chan);
|
||||
pubsubPublishMessage(chanobj, key);
|
||||
decrRefCount(chanobj);
|
||||
+178
-150
@@ -39,15 +39,16 @@
|
||||
/* ===================== Creation and parsing of objects ==================== */
|
||||
|
||||
robj *createObject(int type, void *ptr) {
|
||||
robj *o = zmalloc(sizeof(*o), MALLOC_SHARED);
|
||||
robj *o = (robj*)zcalloc(sizeof(*o), MALLOC_SHARED);
|
||||
o->type = type;
|
||||
o->encoding = OBJ_ENCODING_RAW;
|
||||
o->m_ptr = ptr;
|
||||
o->refcount = 1;
|
||||
o->setrefcount(1);
|
||||
o->mvcc_tstamp = OBJ_MVCC_INVALID;
|
||||
|
||||
/* Set the LRU to the current lruclock (minutes resolution), or
|
||||
* alternatively the LFU counter. */
|
||||
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
o->lru = (LFUGetTimeInMinutes()<<8) | LFU_INIT_VAL;
|
||||
} else {
|
||||
o->lru = LRU_CLOCK();
|
||||
@@ -67,8 +68,9 @@ robj *createObject(int type, void *ptr) {
|
||||
*
|
||||
*/
|
||||
robj *makeObjectShared(robj *o) {
|
||||
serverAssert(o->refcount == 1);
|
||||
o->refcount = OBJ_SHARED_REFCOUNT;
|
||||
serverAssert(o->getrefcount(std::memory_order_relaxed) == 1);
|
||||
serverAssert(!o->FExpires());
|
||||
o->setrefcount(OBJ_SHARED_REFCOUNT);
|
||||
return o;
|
||||
}
|
||||
|
||||
@@ -85,13 +87,15 @@ robj *createEmbeddedStringObject(const char *ptr, size_t len) {
|
||||
size_t allocsize = sizeof(struct sdshdr8)+len+1;
|
||||
if (allocsize < sizeof(void*))
|
||||
allocsize = sizeof(void*);
|
||||
robj *o = zmalloc(sizeof(robj)+allocsize-sizeof(o->m_ptr), MALLOC_SHARED);
|
||||
struct sdshdr8 *sh = (void*)(&o->m_ptr);
|
||||
robj *o = (robj*)zcalloc(sizeof(robj)+allocsize-sizeof(o->m_ptr), MALLOC_SHARED);
|
||||
struct sdshdr8 *sh = (sdshdr8*)(&o->m_ptr);
|
||||
|
||||
o->type = OBJ_STRING;
|
||||
o->encoding = OBJ_ENCODING_EMBSTR;
|
||||
o->refcount = 1;
|
||||
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
o->setrefcount(1);
|
||||
o->mvcc_tstamp = OBJ_MVCC_INVALID;
|
||||
|
||||
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
o->lru = (LFUGetTimeInMinutes()<<8) | LFU_INIT_VAL;
|
||||
} else {
|
||||
o->lru = LRU_CLOCK();
|
||||
@@ -101,12 +105,12 @@ robj *createEmbeddedStringObject(const char *ptr, size_t len) {
|
||||
sh->alloc = len;
|
||||
sh->flags = SDS_TYPE_8;
|
||||
if (ptr == SDS_NOINIT)
|
||||
sh->buf[len] = '\0';
|
||||
sh->buf()[len] = '\0';
|
||||
else if (ptr) {
|
||||
memcpy(sh->buf,ptr,len);
|
||||
sh->buf[len] = '\0';
|
||||
memcpy(sh->buf(),ptr,len);
|
||||
sh->buf()[len] = '\0';
|
||||
} else {
|
||||
memset(sh->buf,0,len+1);
|
||||
memset(sh->buf(),0,len+1);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
@@ -135,8 +139,8 @@ robj *createStringObject(const char *ptr, size_t len) {
|
||||
robj *createStringObjectFromLongLongWithOptions(long long value, int valueobj) {
|
||||
robj *o;
|
||||
|
||||
if (server.maxmemory == 0 ||
|
||||
!(server.maxmemory_policy & MAXMEMORY_FLAG_NO_SHARED_INTEGERS))
|
||||
if (g_pserver->maxmemory == 0 ||
|
||||
!(g_pserver->maxmemory_policy & MAXMEMORY_FLAG_NO_SHARED_INTEGERS))
|
||||
{
|
||||
/* If the maxmemory policy permits, we can still return shared integers
|
||||
* even if valueobj is true. */
|
||||
@@ -199,9 +203,9 @@ robj *dupStringObject(const robj *o) {
|
||||
|
||||
switch(o->encoding) {
|
||||
case OBJ_ENCODING_RAW:
|
||||
return createRawStringObject(ptrFromObj(o),sdslen(ptrFromObj(o)));
|
||||
return createRawStringObject(szFromObj(o),sdslen(szFromObj(o)));
|
||||
case OBJ_ENCODING_EMBSTR:
|
||||
return createEmbeddedStringObject(ptrFromObj(o),sdslen(ptrFromObj(o)));
|
||||
return createEmbeddedStringObject(szFromObj(o),sdslen(szFromObj(o)));
|
||||
case OBJ_ENCODING_INT:
|
||||
d = createObject(OBJ_STRING, NULL);
|
||||
d->encoding = OBJ_ENCODING_INT;
|
||||
@@ -249,7 +253,7 @@ robj *createHashObject(void) {
|
||||
}
|
||||
|
||||
robj *createZsetObject(void) {
|
||||
zset *zs = zmalloc(sizeof(*zs), MALLOC_SHARED);
|
||||
zset *zs = (zset*)zmalloc(sizeof(*zs), MALLOC_SHARED);
|
||||
robj *o;
|
||||
|
||||
zs->pdict = dictCreate(&zsetDictType,NULL);
|
||||
@@ -274,27 +278,27 @@ robj *createStreamObject(void) {
|
||||
}
|
||||
|
||||
robj *createModuleObject(moduleType *mt, void *value) {
|
||||
moduleValue *mv = zmalloc(sizeof(*mv), MALLOC_SHARED);
|
||||
moduleValue *mv = (moduleValue*)zmalloc(sizeof(*mv), MALLOC_SHARED);
|
||||
mv->type = mt;
|
||||
mv->value = value;
|
||||
return createObject(OBJ_MODULE,mv);
|
||||
}
|
||||
|
||||
void freeStringObject(robj *o) {
|
||||
void freeStringObject(robj_roptr o) {
|
||||
if (o->encoding == OBJ_ENCODING_RAW) {
|
||||
sdsfree(ptrFromObj(o));
|
||||
sdsfree(szFromObj(o));
|
||||
}
|
||||
}
|
||||
|
||||
void freeListObject(robj *o) {
|
||||
void freeListObject(robj_roptr o) {
|
||||
if (o->encoding == OBJ_ENCODING_QUICKLIST) {
|
||||
quicklistRelease(ptrFromObj(o));
|
||||
quicklistRelease((quicklist*)ptrFromObj(o));
|
||||
} else {
|
||||
serverPanic("Unknown list encoding type");
|
||||
}
|
||||
}
|
||||
|
||||
void freeSetObject(robj *o) {
|
||||
void freeSetObject(robj_roptr o) {
|
||||
switch (o->encoding) {
|
||||
case OBJ_ENCODING_HT:
|
||||
dictRelease((dict*) ptrFromObj(o));
|
||||
@@ -307,11 +311,11 @@ void freeSetObject(robj *o) {
|
||||
}
|
||||
}
|
||||
|
||||
void freeZsetObject(robj *o) {
|
||||
void freeZsetObject(robj_roptr o) {
|
||||
zset *zs;
|
||||
switch (o->encoding) {
|
||||
case OBJ_ENCODING_SKIPLIST:
|
||||
zs = ptrFromObj(o);
|
||||
zs = (zset*)ptrFromObj(o);
|
||||
dictRelease(zs->pdict);
|
||||
zslFree(zs->zsl);
|
||||
zfree(zs);
|
||||
@@ -324,7 +328,7 @@ void freeZsetObject(robj *o) {
|
||||
}
|
||||
}
|
||||
|
||||
void freeHashObject(robj *o) {
|
||||
void freeHashObject(robj_roptr o) {
|
||||
switch (o->encoding) {
|
||||
case OBJ_ENCODING_HT:
|
||||
dictRelease((dict*) ptrFromObj(o));
|
||||
@@ -338,22 +342,25 @@ void freeHashObject(robj *o) {
|
||||
}
|
||||
}
|
||||
|
||||
void freeModuleObject(robj *o) {
|
||||
moduleValue *mv = ptrFromObj(o);
|
||||
void freeModuleObject(robj_roptr o) {
|
||||
moduleValue *mv = (moduleValue*)ptrFromObj(o);
|
||||
mv->type->free(mv->value);
|
||||
zfree(mv);
|
||||
}
|
||||
|
||||
void freeStreamObject(robj *o) {
|
||||
freeStream(ptrFromObj(o));
|
||||
void freeStreamObject(robj_roptr o) {
|
||||
freeStream((stream*)ptrFromObj(o));
|
||||
}
|
||||
|
||||
void incrRefCount(robj *o) {
|
||||
if (o->refcount != OBJ_SHARED_REFCOUNT) o->refcount++;
|
||||
void incrRefCount(robj_roptr o) {
|
||||
if (o->getrefcount(std::memory_order_relaxed) != OBJ_SHARED_REFCOUNT) o->addref();
|
||||
}
|
||||
|
||||
void decrRefCount(robj *o) {
|
||||
if (o->refcount == 1) {
|
||||
void decrRefCount(robj_roptr o) {
|
||||
if (o->getrefcount(std::memory_order_relaxed) == OBJ_SHARED_REFCOUNT)
|
||||
return;
|
||||
unsigned prev = o->release();
|
||||
if (prev == 1) {
|
||||
switch(o->type) {
|
||||
case OBJ_STRING: freeStringObject(o); break;
|
||||
case OBJ_LIST: freeListObject(o); break;
|
||||
@@ -364,18 +371,17 @@ void decrRefCount(robj *o) {
|
||||
case OBJ_STREAM: freeStreamObject(o); break;
|
||||
default: serverPanic("Unknown object type"); break;
|
||||
}
|
||||
zfree(o);
|
||||
zfree(o.unsafe_robjcast());
|
||||
} else {
|
||||
if (o->refcount <= 0) serverPanic("decrRefCount against refcount <= 0");
|
||||
if (o->refcount != OBJ_SHARED_REFCOUNT) o->refcount--;
|
||||
if (prev <= 0) serverPanic("decrRefCount against refcount <= 0");
|
||||
}
|
||||
}
|
||||
|
||||
/* This variant of decrRefCount() gets its argument as void, and is useful
|
||||
* as free method in data structures that expect a 'void free_object(void*)'
|
||||
* prototype for the free method. */
|
||||
void decrRefCountVoid(void *o) {
|
||||
decrRefCount(o);
|
||||
void decrRefCountVoid(const void *o) {
|
||||
decrRefCount((robj*)o);
|
||||
}
|
||||
|
||||
/* This function set the ref count to zero without freeing the object.
|
||||
@@ -391,11 +397,11 @@ void decrRefCountVoid(void *o) {
|
||||
* decrRefCount(obj);
|
||||
*/
|
||||
robj *resetRefCount(robj *obj) {
|
||||
obj->refcount = 0;
|
||||
obj->setrefcount(0);
|
||||
return obj;
|
||||
}
|
||||
|
||||
int checkType(client *c, robj *o, int type) {
|
||||
int checkType(client *c, robj_roptr o, int type) {
|
||||
if (o->type != type) {
|
||||
addReplyAsync(c,shared.wrongtypeerr);
|
||||
return 1;
|
||||
@@ -403,7 +409,7 @@ int checkType(client *c, robj *o, int type) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int isSdsRepresentableAsLongLong(sds s, long long *llval) {
|
||||
int isSdsRepresentableAsLongLong(const char *s, long long *llval) {
|
||||
return string2ll(s,sdslen(s),llval) ? C_OK : C_ERR;
|
||||
}
|
||||
|
||||
@@ -413,7 +419,7 @@ int isObjectRepresentableAsLongLong(robj *o, long long *llval) {
|
||||
if (llval) *llval = (long) ptrFromObj(o);
|
||||
return C_OK;
|
||||
} else {
|
||||
return isSdsRepresentableAsLongLong(ptrFromObj(o),llval);
|
||||
return isSdsRepresentableAsLongLong(szFromObj(o),llval);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,16 +429,16 @@ int isObjectRepresentableAsLongLong(robj *o, long long *llval) {
|
||||
* wasting too much time in allocations when appending to the string. */
|
||||
void trimStringObjectIfNeeded(robj *o) {
|
||||
if (o->encoding == OBJ_ENCODING_RAW &&
|
||||
sdsavail(ptrFromObj(o)) > sdslen(ptrFromObj(o))/10)
|
||||
sdsavail(szFromObj(o)) > sdslen(szFromObj(o))/10)
|
||||
{
|
||||
o->m_ptr = sdsRemoveFreeSpace(ptrFromObj(o));
|
||||
o->m_ptr = sdsRemoveFreeSpace(szFromObj(o));
|
||||
}
|
||||
}
|
||||
|
||||
/* Try to encode a string object in order to save space */
|
||||
robj *tryObjectEncoding(robj *o) {
|
||||
long value;
|
||||
sds s = ptrFromObj(o);
|
||||
sds s = szFromObj(o);
|
||||
size_t len;
|
||||
|
||||
/* Make sure this is a string object, the only type we encode
|
||||
@@ -449,7 +455,7 @@ robj *tryObjectEncoding(robj *o) {
|
||||
/* It's not safe to encode shared objects: shared objects can be shared
|
||||
* everywhere in the "object space" of Redis and may end in places where
|
||||
* they are not handled. We handle them only as values in the keyspace. */
|
||||
if (o->refcount > 1) return o;
|
||||
if (o->getrefcount(std::memory_order_relaxed) > 1) return o;
|
||||
|
||||
/* Check if we can represent this string as a long integer.
|
||||
* Note that we are sure that a string larger than 20 chars is not
|
||||
@@ -460,8 +466,8 @@ robj *tryObjectEncoding(robj *o) {
|
||||
* Note that we avoid using shared integers when maxmemory is used
|
||||
* because every object needs to have a private LRU field for the LRU
|
||||
* algorithm to work well. */
|
||||
if ((server.maxmemory == 0 ||
|
||||
!(server.maxmemory_policy & MAXMEMORY_FLAG_NO_SHARED_INTEGERS)) &&
|
||||
if ((g_pserver->maxmemory == 0 ||
|
||||
!(g_pserver->maxmemory_policy & MAXMEMORY_FLAG_NO_SHARED_INTEGERS)) &&
|
||||
value >= 0 &&
|
||||
value < OBJ_SHARED_INTEGERS)
|
||||
{
|
||||
@@ -469,7 +475,7 @@ robj *tryObjectEncoding(robj *o) {
|
||||
incrRefCount(shared.integers[value]);
|
||||
return shared.integers[value];
|
||||
} else {
|
||||
if (o->encoding == OBJ_ENCODING_RAW) sdsfree(ptrFromObj(o));
|
||||
if (o->encoding == OBJ_ENCODING_RAW) sdsfree(szFromObj(o));
|
||||
o->encoding = OBJ_ENCODING_INT;
|
||||
o->m_ptr = (void*) value;
|
||||
return o;
|
||||
@@ -524,6 +530,10 @@ robj *getDecodedObject(robj *o) {
|
||||
}
|
||||
}
|
||||
|
||||
robj_roptr getDecodedObject(robj_roptr o) {
|
||||
return getDecodedObject(o.unsafe_robjcast());
|
||||
}
|
||||
|
||||
/* Compare two string objects via strcmp() or strcoll() depending on flags.
|
||||
* Note that the objects may be integer-encoded. In such a case we
|
||||
* use ll2string() to get a string representation of the numbers on the stack
|
||||
@@ -542,14 +552,14 @@ int compareStringObjectsWithFlags(robj *a, robj *b, int flags) {
|
||||
|
||||
if (a == b) return 0;
|
||||
if (sdsEncodedObject(a)) {
|
||||
astr = ptrFromObj(a);
|
||||
astr = szFromObj(a);
|
||||
alen = sdslen(astr);
|
||||
} else {
|
||||
alen = ll2string(bufa,sizeof(bufa),(long) ptrFromObj(a));
|
||||
astr = bufa;
|
||||
}
|
||||
if (sdsEncodedObject(b)) {
|
||||
bstr = ptrFromObj(b);
|
||||
bstr = szFromObj(b);
|
||||
blen = sdslen(bstr);
|
||||
} else {
|
||||
blen = ll2string(bufb,sizeof(bufb),(long) ptrFromObj(b));
|
||||
@@ -592,10 +602,10 @@ int equalStringObjects(robj *a, robj *b) {
|
||||
}
|
||||
}
|
||||
|
||||
size_t stringObjectLen(robj *o) {
|
||||
size_t stringObjectLen(robj_roptr o) {
|
||||
serverAssertWithInfo(NULL,o,o->type == OBJ_STRING);
|
||||
if (sdsEncodedObject(o)) {
|
||||
return sdslen(ptrFromObj(o));
|
||||
return sdslen(szFromObj(o));
|
||||
} else {
|
||||
return sdigits10((long)ptrFromObj(o));
|
||||
}
|
||||
@@ -611,13 +621,13 @@ int getDoubleFromObject(const robj *o, double *target) {
|
||||
serverAssertWithInfo(NULL,o,o->type == OBJ_STRING);
|
||||
if (sdsEncodedObject(o)) {
|
||||
errno = 0;
|
||||
value = strtod(ptrFromObj(o), &eptr);
|
||||
if (sdslen(ptrFromObj(o)) == 0 ||
|
||||
isspace(((const char*)ptrFromObj(o))[0]) ||
|
||||
(size_t)(eptr-(char*)ptrFromObj(o)) != sdslen(ptrFromObj(o)) ||
|
||||
value = strtod(szFromObj(o), &eptr);
|
||||
if (sdslen(szFromObj(o)) == 0 ||
|
||||
isspace(((const char*)szFromObj(o))[0]) ||
|
||||
(size_t)(eptr-(char*)szFromObj(o)) != sdslen(szFromObj(o)) ||
|
||||
(errno == ERANGE &&
|
||||
(value == HUGE_VAL || value == -HUGE_VAL || value == 0)) ||
|
||||
isnan(value))
|
||||
std::isnan(value))
|
||||
return C_ERR;
|
||||
} else if (o->encoding == OBJ_ENCODING_INT) {
|
||||
value = (long)ptrFromObj(o);
|
||||
@@ -653,16 +663,16 @@ int getLongDoubleFromObject(robj *o, long double *target) {
|
||||
serverAssertWithInfo(NULL,o,o->type == OBJ_STRING);
|
||||
if (sdsEncodedObject(o)) {
|
||||
errno = 0;
|
||||
value = strtold(ptrFromObj(o), &eptr);
|
||||
if (sdslen(ptrFromObj(o)) == 0 ||
|
||||
isspace(((const char*)ptrFromObj(o))[0]) ||
|
||||
(size_t)(eptr-(char*)ptrFromObj(o)) != sdslen(ptrFromObj(o)) ||
|
||||
value = strtold(szFromObj(o), &eptr);
|
||||
if (sdslen(szFromObj(o)) == 0 ||
|
||||
isspace(((const char*)szFromObj(o))[0]) ||
|
||||
(size_t)(eptr-(char*)szFromObj(o)) != sdslen(szFromObj(o)) ||
|
||||
(errno == ERANGE &&
|
||||
(value == HUGE_VAL || value == -HUGE_VAL || value == 0)) ||
|
||||
isnan(value))
|
||||
std::isnan(value))
|
||||
return C_ERR;
|
||||
} else if (o->encoding == OBJ_ENCODING_INT) {
|
||||
value = (long)ptrFromObj(o);
|
||||
value = (long)szFromObj(o);
|
||||
} else {
|
||||
serverPanic("Unknown string encoding");
|
||||
}
|
||||
@@ -693,7 +703,7 @@ int getLongLongFromObject(robj *o, long long *target) {
|
||||
} else {
|
||||
serverAssertWithInfo(NULL,o,o->type == OBJ_STRING);
|
||||
if (sdsEncodedObject(o)) {
|
||||
if (string2ll(ptrFromObj(o),sdslen(ptrFromObj(o)),&value) == 0) return C_ERR;
|
||||
if (string2ll(szFromObj(o),sdslen(szFromObj(o)),&value) == 0) return C_ERR;
|
||||
} else if (o->encoding == OBJ_ENCODING_INT) {
|
||||
value = (long)ptrFromObj(o);
|
||||
} else {
|
||||
@@ -734,7 +744,7 @@ int getLongFromObjectOrReply(client *c, robj *o, long *target, const char *msg)
|
||||
return C_OK;
|
||||
}
|
||||
|
||||
char *strEncoding(int encoding) {
|
||||
const char *strEncoding(int encoding) {
|
||||
switch(encoding) {
|
||||
case OBJ_ENCODING_RAW: return "raw";
|
||||
case OBJ_ENCODING_INT: return "int";
|
||||
@@ -790,15 +800,15 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
if(o->encoding == OBJ_ENCODING_INT) {
|
||||
asize = sizeof(*o);
|
||||
} else if(o->encoding == OBJ_ENCODING_RAW) {
|
||||
asize = sdsAllocSize(ptrFromObj(o))+sizeof(*o);
|
||||
asize = sdsAllocSize(szFromObj(o))+sizeof(*o);
|
||||
} else if(o->encoding == OBJ_ENCODING_EMBSTR) {
|
||||
asize = sdslen(ptrFromObj(o))+2+sizeof(*o);
|
||||
asize = sdslen(szFromObj(o))+2+sizeof(*o);
|
||||
} else {
|
||||
serverPanic("Unknown string encoding");
|
||||
}
|
||||
} else if (o->type == OBJ_LIST) {
|
||||
if (o->encoding == OBJ_ENCODING_QUICKLIST) {
|
||||
quicklist *ql = ptrFromObj(o);
|
||||
quicklist *ql = (quicklist*)ptrFromObj(o);
|
||||
quicklistNode *node = ql->head;
|
||||
asize = sizeof(*o)+sizeof(quicklist);
|
||||
do {
|
||||
@@ -807,41 +817,41 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
} while ((node = node->next) && samples < sample_size);
|
||||
asize += (double)elesize/samples*ql->len;
|
||||
} else if (o->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
asize = sizeof(*o)+ziplistBlobLen(ptrFromObj(o));
|
||||
asize = sizeof(*o)+ziplistBlobLen((unsigned char*)ptrFromObj(o));
|
||||
} else {
|
||||
serverPanic("Unknown list encoding");
|
||||
}
|
||||
} else if (o->type == OBJ_SET) {
|
||||
if (o->encoding == OBJ_ENCODING_HT) {
|
||||
d = ptrFromObj(o);
|
||||
d = (dict*)ptrFromObj(o);
|
||||
di = dictGetIterator(d);
|
||||
asize = sizeof(*o)+sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
|
||||
while((de = dictNext(di)) != NULL && samples < sample_size) {
|
||||
ele = dictGetKey(de);
|
||||
ele = (sds)dictGetKey(de);
|
||||
elesize += sizeof(struct dictEntry) + sdsAllocSize(ele);
|
||||
samples++;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
if (samples) asize += (double)elesize/samples*dictSize(d);
|
||||
} else if (o->encoding == OBJ_ENCODING_INTSET) {
|
||||
intset *is = ptrFromObj(o);
|
||||
intset *is = (intset*)ptrFromObj(o);
|
||||
asize = sizeof(*o)+sizeof(*is)+is->encoding*is->length;
|
||||
} else {
|
||||
serverPanic("Unknown set encoding");
|
||||
}
|
||||
} else if (o->type == OBJ_ZSET) {
|
||||
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
asize = sizeof(*o)+(ziplistBlobLen(ptrFromObj(o)));
|
||||
asize = sizeof(*o)+(ziplistBlobLen((unsigned char*)ptrFromObj(o)));
|
||||
} else if (o->encoding == OBJ_ENCODING_SKIPLIST) {
|
||||
d = ((zset*)ptrFromObj(o))->pdict;
|
||||
zskiplist *zsl = ((zset*)ptrFromObj(o))->zsl;
|
||||
zskiplistNode *znode = zsl->header->level[0].forward;
|
||||
zskiplistNode *znode = zsl->header->level(0)->forward;
|
||||
asize = sizeof(*o)+sizeof(zset)+(sizeof(struct dictEntry*)*dictSlots(d));
|
||||
while(znode != NULL && samples < sample_size) {
|
||||
elesize += sdsAllocSize(znode->ele);
|
||||
elesize += sizeof(struct dictEntry) + zmalloc_size(znode);
|
||||
samples++;
|
||||
znode = znode->level[0].forward;
|
||||
znode = znode->level(0)->forward;
|
||||
}
|
||||
if (samples) asize += (double)elesize/samples*dictSize(d);
|
||||
} else {
|
||||
@@ -849,14 +859,14 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
}
|
||||
} else if (o->type == OBJ_HASH) {
|
||||
if (o->encoding == OBJ_ENCODING_ZIPLIST) {
|
||||
asize = sizeof(*o)+(ziplistBlobLen(ptrFromObj(o)));
|
||||
asize = sizeof(*o)+(ziplistBlobLen((unsigned char*)ptrFromObj(o)));
|
||||
} else if (o->encoding == OBJ_ENCODING_HT) {
|
||||
d = ptrFromObj(o);
|
||||
d = (dict*)ptrFromObj(o);
|
||||
di = dictGetIterator(d);
|
||||
asize = sizeof(*o)+sizeof(dict)+(sizeof(struct dictEntry*)*dictSlots(d));
|
||||
while((de = dictNext(di)) != NULL && samples < sample_size) {
|
||||
ele = dictGetKey(de);
|
||||
ele2 = dictGetVal(de);
|
||||
ele = (sds)dictGetKey(de);
|
||||
ele2 = (sds)dictGetVal(de);
|
||||
elesize += sdsAllocSize(ele) + sdsAllocSize(ele2);
|
||||
elesize += sizeof(struct dictEntry);
|
||||
samples++;
|
||||
@@ -867,7 +877,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
serverPanic("Unknown hash encoding");
|
||||
}
|
||||
} else if (o->type == OBJ_STREAM) {
|
||||
stream *s = ptrFromObj(o);
|
||||
stream *s = (stream*)ptrFromObj(o);
|
||||
asize = sizeof(*o);
|
||||
asize += streamRadixTreeMemoryUsage(s->prax);
|
||||
|
||||
@@ -880,7 +890,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
raxSeek(&ri,"^",NULL,0);
|
||||
size_t lpsize = 0, samples = 0;
|
||||
while(samples < sample_size && raxNext(&ri)) {
|
||||
unsigned char *lp = ri.data;
|
||||
unsigned char *lp = (unsigned char*)ri.data;
|
||||
lpsize += lpBytes(lp);
|
||||
samples++;
|
||||
}
|
||||
@@ -893,7 +903,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
* if there are a few elements in the radix tree. */
|
||||
raxSeek(&ri,"$",NULL,0);
|
||||
raxNext(&ri);
|
||||
asize += lpBytes(ri.data);
|
||||
asize += lpBytes((unsigned char*)ri.data);
|
||||
}
|
||||
raxStop(&ri);
|
||||
|
||||
@@ -905,7 +915,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
raxStart(&ri,s->cgroups);
|
||||
raxSeek(&ri,"^",NULL,0);
|
||||
while(raxNext(&ri)) {
|
||||
streamCG *cg = ri.data;
|
||||
streamCG *cg = (streamCG*)ri.data;
|
||||
asize += sizeof(*cg);
|
||||
asize += streamRadixTreeMemoryUsage(cg->pel);
|
||||
asize += sizeof(streamNACK)*raxSize(cg->pel);
|
||||
@@ -916,7 +926,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
raxStart(&cri,cg->consumers);
|
||||
raxSeek(&cri,"^",NULL,0);
|
||||
while(raxNext(&cri)) {
|
||||
streamConsumer *consumer = cri.data;
|
||||
streamConsumer *consumer = (streamConsumer*)cri.data;
|
||||
asize += sizeof(*consumer);
|
||||
asize += sdslen(consumer->name);
|
||||
asize += streamRadixTreeMemoryUsage(consumer->pel);
|
||||
@@ -928,7 +938,7 @@ size_t objectComputeSize(robj *o, size_t sample_size) {
|
||||
raxStop(&ri);
|
||||
}
|
||||
} else if (o->type == OBJ_MODULE) {
|
||||
moduleValue *mv = ptrFromObj(o);
|
||||
moduleValue *mv = (moduleValue*)ptrFromObj(o);
|
||||
moduleType *mt = mv->type;
|
||||
if (mt->mem_usage != NULL) {
|
||||
asize = mt->mem_usage(mv->value);
|
||||
@@ -956,44 +966,44 @@ struct redisMemOverhead *getMemoryOverheadData(void) {
|
||||
size_t mem_total = 0;
|
||||
size_t mem = 0;
|
||||
size_t zmalloc_used = zmalloc_used_memory();
|
||||
struct redisMemOverhead *mh = zcalloc(sizeof(*mh), MALLOC_LOCAL);
|
||||
struct redisMemOverhead *mh = (redisMemOverhead*)zcalloc(sizeof(*mh), MALLOC_LOCAL);
|
||||
|
||||
mh->total_allocated = zmalloc_used;
|
||||
mh->startup_allocated = server.initial_memory_usage;
|
||||
mh->peak_allocated = server.stat_peak_memory;
|
||||
mh->startup_allocated = g_pserver->initial_memory_usage;
|
||||
mh->peak_allocated = g_pserver->stat_peak_memory;
|
||||
mh->total_frag =
|
||||
(float)server.cron_malloc_stats.process_rss / server.cron_malloc_stats.zmalloc_used;
|
||||
(float)g_pserver->cron_malloc_stats.process_rss / g_pserver->cron_malloc_stats.zmalloc_used;
|
||||
mh->total_frag_bytes =
|
||||
server.cron_malloc_stats.process_rss - server.cron_malloc_stats.zmalloc_used;
|
||||
g_pserver->cron_malloc_stats.process_rss - g_pserver->cron_malloc_stats.zmalloc_used;
|
||||
mh->allocator_frag =
|
||||
(float)server.cron_malloc_stats.allocator_active / server.cron_malloc_stats.allocator_allocated;
|
||||
(float)g_pserver->cron_malloc_stats.allocator_active / g_pserver->cron_malloc_stats.allocator_allocated;
|
||||
mh->allocator_frag_bytes =
|
||||
server.cron_malloc_stats.allocator_active - server.cron_malloc_stats.allocator_allocated;
|
||||
g_pserver->cron_malloc_stats.allocator_active - g_pserver->cron_malloc_stats.allocator_allocated;
|
||||
mh->allocator_rss =
|
||||
(float)server.cron_malloc_stats.allocator_resident / server.cron_malloc_stats.allocator_active;
|
||||
(float)g_pserver->cron_malloc_stats.allocator_resident / g_pserver->cron_malloc_stats.allocator_active;
|
||||
mh->allocator_rss_bytes =
|
||||
server.cron_malloc_stats.allocator_resident - server.cron_malloc_stats.allocator_active;
|
||||
g_pserver->cron_malloc_stats.allocator_resident - g_pserver->cron_malloc_stats.allocator_active;
|
||||
mh->rss_extra =
|
||||
(float)server.cron_malloc_stats.process_rss / server.cron_malloc_stats.allocator_resident;
|
||||
(float)g_pserver->cron_malloc_stats.process_rss / g_pserver->cron_malloc_stats.allocator_resident;
|
||||
mh->rss_extra_bytes =
|
||||
server.cron_malloc_stats.process_rss - server.cron_malloc_stats.allocator_resident;
|
||||
g_pserver->cron_malloc_stats.process_rss - g_pserver->cron_malloc_stats.allocator_resident;
|
||||
|
||||
mem_total += server.initial_memory_usage;
|
||||
mem_total += g_pserver->initial_memory_usage;
|
||||
|
||||
mem = 0;
|
||||
if (server.repl_backlog)
|
||||
mem += zmalloc_size(server.repl_backlog);
|
||||
if (g_pserver->repl_backlog)
|
||||
mem += zmalloc_size(g_pserver->repl_backlog);
|
||||
mh->repl_backlog = mem;
|
||||
mem_total += mem;
|
||||
|
||||
mem = 0;
|
||||
if (listLength(server.slaves)) {
|
||||
if (listLength(g_pserver->slaves)) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
|
||||
listRewind(server.slaves,&li);
|
||||
listRewind(g_pserver->slaves,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
client *c = listNodeValue(ln);
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
if (c->flags & CLIENT_CLOSE_ASAP)
|
||||
continue;
|
||||
mem += getClientOutputBufferMemoryUsage(c);
|
||||
@@ -1005,13 +1015,13 @@ struct redisMemOverhead *getMemoryOverheadData(void) {
|
||||
mem_total+=mem;
|
||||
|
||||
mem = 0;
|
||||
if (listLength(server.clients)) {
|
||||
if (listLength(g_pserver->clients)) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
|
||||
listRewind(server.clients,&li);
|
||||
listRewind(g_pserver->clients,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
client *c = listNodeValue(ln);
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
if (c->flags & CLIENT_SLAVE && !(c->flags & CLIENT_MONITOR))
|
||||
continue;
|
||||
mem += getClientOutputBufferMemoryUsage(c);
|
||||
@@ -1023,32 +1033,32 @@ struct redisMemOverhead *getMemoryOverheadData(void) {
|
||||
mem_total+=mem;
|
||||
|
||||
mem = 0;
|
||||
if (server.aof_state != AOF_OFF) {
|
||||
mem += sdsalloc(server.aof_buf);
|
||||
if (g_pserver->aof_state != AOF_OFF) {
|
||||
mem += sdsalloc(g_pserver->aof_buf);
|
||||
mem += aofRewriteBufferSize();
|
||||
}
|
||||
mh->aof_buffer = mem;
|
||||
mem_total+=mem;
|
||||
|
||||
mem = server.lua_scripts_mem;
|
||||
mem += dictSize(server.lua_scripts) * sizeof(dictEntry) +
|
||||
dictSlots(server.lua_scripts) * sizeof(dictEntry*);
|
||||
mem += dictSize(server.repl_scriptcache_dict) * sizeof(dictEntry) +
|
||||
dictSlots(server.repl_scriptcache_dict) * sizeof(dictEntry*);
|
||||
if (listLength(server.repl_scriptcache_fifo) > 0) {
|
||||
mem += listLength(server.repl_scriptcache_fifo) * (sizeof(listNode) +
|
||||
sdsZmallocSize(listNodeValue(listFirst(server.repl_scriptcache_fifo))));
|
||||
mem = g_pserver->lua_scripts_mem;
|
||||
mem += dictSize(g_pserver->lua_scripts) * sizeof(dictEntry) +
|
||||
dictSlots(g_pserver->lua_scripts) * sizeof(dictEntry*);
|
||||
mem += dictSize(g_pserver->repl_scriptcache_dict) * sizeof(dictEntry) +
|
||||
dictSlots(g_pserver->repl_scriptcache_dict) * sizeof(dictEntry*);
|
||||
if (listLength(g_pserver->repl_scriptcache_fifo) > 0) {
|
||||
mem += listLength(g_pserver->repl_scriptcache_fifo) * (sizeof(listNode) +
|
||||
sdsZmallocSize((sds)listNodeValue(listFirst(g_pserver->repl_scriptcache_fifo))));
|
||||
}
|
||||
mh->lua_caches = mem;
|
||||
mem_total+=mem;
|
||||
|
||||
for (j = 0; j < server.dbnum; j++) {
|
||||
redisDb *db = server.db+j;
|
||||
for (j = 0; j < cserver.dbnum; j++) {
|
||||
redisDb *db = g_pserver->db+j;
|
||||
long long keyscount = dictSize(db->pdict);
|
||||
if (keyscount==0) continue;
|
||||
|
||||
mh->total_keys += keyscount;
|
||||
mh->db = zrealloc(mh->db,sizeof(mh->db[0])*(mh->num_dbs+1), MALLOC_LOCAL);
|
||||
mh->db = (decltype(mh->db))zrealloc(mh->db,sizeof(mh->db[0])*(mh->num_dbs+1), MALLOC_LOCAL);
|
||||
mh->db[mh->num_dbs].dbid = j;
|
||||
|
||||
mem = dictSize(db->pdict) * sizeof(dictEntry) +
|
||||
@@ -1057,8 +1067,7 @@ struct redisMemOverhead *getMemoryOverheadData(void) {
|
||||
mh->db[mh->num_dbs].overhead_ht_main = mem;
|
||||
mem_total+=mem;
|
||||
|
||||
mem = dictSize(db->expires) * sizeof(dictEntry) +
|
||||
dictSlots(db->expires) * sizeof(dictEntry*);
|
||||
mem = db->setexpire->bytes_used();
|
||||
mh->db[mh->num_dbs].overhead_ht_expires = mem;
|
||||
mem_total+=mem;
|
||||
|
||||
@@ -1139,8 +1148,8 @@ sds getMemoryDoctorReport(void) {
|
||||
}
|
||||
|
||||
/* Clients using more than 200k each average? */
|
||||
long numslaves = listLength(server.slaves);
|
||||
long numclients = listLength(server.clients)-numslaves;
|
||||
long numslaves = listLength(g_pserver->slaves);
|
||||
long numclients = listLength(g_pserver->clients)-numslaves;
|
||||
if ((numclients > 0) && mh->clients_normal / numclients > (1024*200)) {
|
||||
big_client_buf = 1;
|
||||
num_reports++;
|
||||
@@ -1153,7 +1162,7 @@ sds getMemoryDoctorReport(void) {
|
||||
}
|
||||
|
||||
/* Too many scripts are cached? */
|
||||
if (dictSize(server.lua_scripts) > 1000) {
|
||||
if (dictSize(g_pserver->lua_scripts) > 1000) {
|
||||
many_scripts = 1;
|
||||
num_reports++;
|
||||
}
|
||||
@@ -1203,14 +1212,14 @@ sds getMemoryDoctorReport(void) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Set the object LRU/LFU depending on server.maxmemory_policy.
|
||||
/* Set the object LRU/LFU depending on g_pserver->maxmemory_policy.
|
||||
* The lfu_freq arg is only relevant if policy is MAXMEMORY_FLAG_LFU.
|
||||
* The lru_idle and lru_clock args are only relevant if policy
|
||||
* is MAXMEMORY_FLAG_LRU.
|
||||
* Either or both of them may be <0, in that case, nothing is set. */
|
||||
void objectSetLRUOrLFU(robj *val, long long lfu_freq, long long lru_idle,
|
||||
long long lru_clock) {
|
||||
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
if (lfu_freq >= 0) {
|
||||
serverAssert(lfu_freq <= 255);
|
||||
val->lru = (LFUGetTimeInMinutes()<<8) | lfu_freq;
|
||||
@@ -1256,7 +1265,7 @@ robj *objectCommandLookupOrReply(client *c, robj *key, robj *reply) {
|
||||
void objectCommand(client *c) {
|
||||
robj *o;
|
||||
|
||||
if (c->argc == 2 && !strcasecmp(ptrFromObj(c->argv[1]),"help")) {
|
||||
if (c->argc == 2 && !strcasecmp(szFromObj(c->argv[1]),"help")) {
|
||||
const char *help[] = {
|
||||
"ENCODING <key> -- Return the kind of internal representation used in order to store the value associated with a key.",
|
||||
"FREQ <key> -- Return the access frequency index of the key. The returned integer is proportional to the logarithm of the recent access frequency of the key.",
|
||||
@@ -1265,26 +1274,26 @@ void objectCommand(client *c) {
|
||||
NULL
|
||||
};
|
||||
addReplyHelp(c, help);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"refcount") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"refcount") && c->argc == 3) {
|
||||
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
|
||||
== NULL) return;
|
||||
addReplyLongLong(c,o->refcount);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"encoding") && c->argc == 3) {
|
||||
addReplyLongLong(c,o->getrefcount(std::memory_order_relaxed));
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"encoding") && c->argc == 3) {
|
||||
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
|
||||
== NULL) return;
|
||||
addReplyBulkCString(c,strEncoding(o->encoding));
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"idletime") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"idletime") && c->argc == 3) {
|
||||
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
|
||||
== NULL) return;
|
||||
if (server.maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
if (g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU) {
|
||||
addReplyError(c,"An LFU maxmemory policy is selected, idle time not tracked. Please note that when switching between policies at runtime LRU and LFU data will take some time to adjust.");
|
||||
return;
|
||||
}
|
||||
addReplyLongLong(c,estimateObjectIdleTime(o)/1000);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"freq") && c->argc == 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"freq") && c->argc == 3) {
|
||||
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
|
||||
== NULL) return;
|
||||
if (!(server.maxmemory_policy & MAXMEMORY_FLAG_LFU)) {
|
||||
if (!(g_pserver->maxmemory_policy & MAXMEMORY_FLAG_LFU)) {
|
||||
addReplyError(c,"An LFU maxmemory policy is not selected, access frequency not tracked. Please note that when switching between policies at runtime LRU and LFU data will take some time to adjust.");
|
||||
return;
|
||||
}
|
||||
@@ -1293,6 +1302,10 @@ NULL
|
||||
* because we update the access time only
|
||||
* when the key is read or overwritten. */
|
||||
addReplyLongLong(c,LFUDecrAndReturn(o));
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]), "lastmodified") && c->argc == 3) {
|
||||
if ((o = objectCommandLookupOrReply(c,c->argv[2],shared.null[c->resp]))
|
||||
== NULL) return;
|
||||
addReplyLongLong(c, (g_pserver->mstime - (o->mvcc_tstamp >> MVCC_MS_SHIFT)) / 1000);
|
||||
} else {
|
||||
addReplySubcommandSyntaxError(c);
|
||||
}
|
||||
@@ -1303,21 +1316,21 @@ NULL
|
||||
*
|
||||
* Usage: MEMORY usage <key> */
|
||||
void memoryCommand(client *c) {
|
||||
if (!strcasecmp(ptrFromObj(c->argv[1]),"help") && c->argc == 2) {
|
||||
if (!strcasecmp(szFromObj(c->argv[1]),"help") && c->argc == 2) {
|
||||
const char *help[] = {
|
||||
"DOCTOR - Return memory problems reports.",
|
||||
"MALLOC-STATS -- Return internal statistics report from the memory allocator.",
|
||||
"PURGE -- Attempt to purge dirty pages for reclamation by the allocator.",
|
||||
"STATS -- Return information about the memory usage of the server.",
|
||||
"STATS -- Return information about the memory usage of the g_pserver->",
|
||||
"USAGE <key> [SAMPLES <count>] -- Return memory in bytes used by <key> and its value. Nested values are sampled up to <count> times (default: 5).",
|
||||
NULL
|
||||
};
|
||||
addReplyHelp(c, help);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"usage") && c->argc >= 3) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"usage") && c->argc >= 3) {
|
||||
dictEntry *de;
|
||||
long long samples = OBJ_COMPUTE_SIZE_DEF_SAMPLES;
|
||||
for (int j = 3; j < c->argc; j++) {
|
||||
if (!strcasecmp(ptrFromObj(c->argv[j]),"samples") &&
|
||||
if (!strcasecmp(szFromObj(c->argv[j]),"samples") &&
|
||||
j+1 < c->argc)
|
||||
{
|
||||
if (getLongLongFromObjectOrReply(c,c->argv[j+1],&samples,NULL)
|
||||
@@ -1334,14 +1347,14 @@ NULL
|
||||
}
|
||||
}
|
||||
if ((de = dictFind(c->db->pdict,ptrFromObj(c->argv[2]))) == NULL) {
|
||||
addReplyNull(c);
|
||||
addReplyNull(c, shared.nullbulk);
|
||||
return;
|
||||
}
|
||||
size_t usage = objectComputeSize(dictGetVal(de),samples);
|
||||
usage += sdsAllocSize(dictGetKey(de));
|
||||
size_t usage = objectComputeSize((robj*)dictGetVal(de),samples);
|
||||
usage += sdsAllocSize((sds)dictGetKey(de));
|
||||
usage += sizeof(dictEntry);
|
||||
addReplyLongLong(c,usage);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"stats") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"stats") && c->argc == 2) {
|
||||
struct redisMemOverhead *mh = getMemoryOverheadData();
|
||||
|
||||
addReplyMapLen(c,25+mh->num_dbs);
|
||||
@@ -1402,13 +1415,13 @@ NULL
|
||||
addReplyDouble(c,mh->peak_perc);
|
||||
|
||||
addReplyBulkCString(c,"allocator.allocated");
|
||||
addReplyLongLong(c,server.cron_malloc_stats.allocator_allocated);
|
||||
addReplyLongLong(c,g_pserver->cron_malloc_stats.allocator_allocated);
|
||||
|
||||
addReplyBulkCString(c,"allocator.active");
|
||||
addReplyLongLong(c,server.cron_malloc_stats.allocator_active);
|
||||
addReplyLongLong(c,g_pserver->cron_malloc_stats.allocator_active);
|
||||
|
||||
addReplyBulkCString(c,"allocator.resident");
|
||||
addReplyLongLong(c,server.cron_malloc_stats.allocator_resident);
|
||||
addReplyLongLong(c,g_pserver->cron_malloc_stats.allocator_resident);
|
||||
|
||||
addReplyBulkCString(c,"allocator-fragmentation.ratio");
|
||||
addReplyDouble(c,mh->allocator_frag);
|
||||
@@ -1435,7 +1448,7 @@ NULL
|
||||
addReplyLongLong(c,mh->total_frag_bytes);
|
||||
|
||||
freeMemoryOverheadData(mh);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"malloc-stats") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"malloc-stats") && c->argc == 2) {
|
||||
#if defined(USE_JEMALLOC)
|
||||
sds info = sdsempty();
|
||||
je_malloc_stats_print(inputCatSds, &info, NULL);
|
||||
@@ -1443,10 +1456,10 @@ NULL
|
||||
#else
|
||||
addReplyBulkCString(c,"Stats not supported for the current allocator");
|
||||
#endif
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"doctor") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"doctor") && c->argc == 2) {
|
||||
sds report = getMemoryDoctorReport();
|
||||
addReplyBulkSds(c,report);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"purge") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"purge") && c->argc == 2) {
|
||||
#if defined(USE_JEMALLOC)
|
||||
char tmp[32];
|
||||
unsigned narenas = 0;
|
||||
@@ -1467,3 +1480,18 @@ NULL
|
||||
addReplyErrorFormat(c, "Unknown subcommand or wrong number of arguments for '%s'. Try MEMORY HELP", (char*)ptrFromObj(c->argv[1]));
|
||||
}
|
||||
}
|
||||
|
||||
void redisObject::SetFExpires(bool fExpire)
|
||||
{
|
||||
serverAssert(this->refcount != OBJ_SHARED_REFCOUNT);
|
||||
if (fExpire)
|
||||
this->refcount.fetch_or(1U << 31, std::memory_order_relaxed);
|
||||
else
|
||||
this->refcount.fetch_and(~(1U << 31), std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void redisObject::setrefcount(unsigned ref)
|
||||
{
|
||||
serverAssert(!FExpires());
|
||||
refcount.store(ref, std::memory_order_relaxed);
|
||||
}
|
||||
+1
-1
@@ -33,7 +33,7 @@
|
||||
#ifndef __PQSORT_H
|
||||
#define __PQSORT_H
|
||||
|
||||
void
|
||||
extern "C" void
|
||||
pqsort(void *a, size_t n, size_t es,
|
||||
int (*cmp) (const void *, const void *), size_t lrange, size_t rrange);
|
||||
|
||||
|
||||
@@ -84,7 +84,7 @@ void addReplyPubsubUnsubscribed(client *c, robj *channel) {
|
||||
if (channel)
|
||||
addReplyBulk(c,channel);
|
||||
else
|
||||
addReplyNull(c);
|
||||
addReplyNull(c, shared.nullbulk);
|
||||
addReplyLongLong(c,clientSubscriptionsCount(c));
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ void addReplyPubsubPatUnsubscribed(client *c, robj *pattern) {
|
||||
if (pattern)
|
||||
addReplyBulk(c,pattern);
|
||||
else
|
||||
addReplyNull(c);
|
||||
addReplyNull(c, shared.nullbulk);
|
||||
addReplyLongLong(c,clientSubscriptionsCount(c));
|
||||
}
|
||||
|
||||
@@ -120,15 +120,15 @@ void addReplyPubsubPatUnsubscribed(client *c, robj *pattern) {
|
||||
* Pubsub low level API
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
void freePubsubPattern(void *p) {
|
||||
pubsubPattern *pat = p;
|
||||
void freePubsubPattern(const void *p) {
|
||||
pubsubPattern *pat = (pubsubPattern *)p;
|
||||
|
||||
decrRefCount(pat->pattern);
|
||||
zfree(pat);
|
||||
}
|
||||
|
||||
int listMatchPubsubPattern(void *a, void *b) {
|
||||
pubsubPattern *pa = a, *pb = b;
|
||||
pubsubPattern *pa = (pubsubPattern*)a, *pb = (pubsubPattern*)b;
|
||||
|
||||
return (pa->pclient == pb->pclient) &&
|
||||
(equalStringObjects(pa->pattern,pb->pattern));
|
||||
@@ -143,6 +143,8 @@ int clientSubscriptionsCount(client *c) {
|
||||
/* Subscribe a client to a channel. Returns 1 if the operation succeeded, or
|
||||
* 0 if the client was already subscribed to that channel. */
|
||||
int pubsubSubscribeChannel(client *c, robj *channel) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
serverAssert(c->lock.fOwnLock());
|
||||
dictEntry *de;
|
||||
list *clients = NULL;
|
||||
int retval = 0;
|
||||
@@ -152,13 +154,13 @@ int pubsubSubscribeChannel(client *c, robj *channel) {
|
||||
retval = 1;
|
||||
incrRefCount(channel);
|
||||
/* Add the client to the channel -> list of clients hash table */
|
||||
de = dictFind(server.pubsub_channels,channel);
|
||||
de = dictFind(g_pserver->pubsub_channels,channel);
|
||||
if (de == NULL) {
|
||||
clients = listCreate();
|
||||
dictAdd(server.pubsub_channels,channel,clients);
|
||||
dictAdd(g_pserver->pubsub_channels,channel,clients);
|
||||
incrRefCount(channel);
|
||||
} else {
|
||||
clients = dictGetVal(de);
|
||||
clients = (list*)dictGetVal(de);
|
||||
}
|
||||
listAddNodeTail(clients,c);
|
||||
}
|
||||
@@ -181,9 +183,9 @@ int pubsubUnsubscribeChannel(client *c, robj *channel, int notify) {
|
||||
if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
|
||||
retval = 1;
|
||||
/* Remove the client from the channel -> clients list hash table */
|
||||
de = dictFind(server.pubsub_channels,channel);
|
||||
de = dictFind(g_pserver->pubsub_channels,channel);
|
||||
serverAssertWithInfo(c,NULL,de != NULL);
|
||||
clients = dictGetVal(de);
|
||||
clients = (list*)dictGetVal(de);
|
||||
ln = listSearchKey(clients,c);
|
||||
serverAssertWithInfo(c,NULL,ln != NULL);
|
||||
listDelNode(clients,ln);
|
||||
@@ -191,7 +193,7 @@ int pubsubUnsubscribeChannel(client *c, robj *channel, int notify) {
|
||||
/* Free the list and associated hash entry at all if this was
|
||||
* the latest client, so that it will be possible to abuse
|
||||
* Redis PUBSUB creating millions of channels. */
|
||||
dictDelete(server.pubsub_channels,channel);
|
||||
dictDelete(g_pserver->pubsub_channels,channel);
|
||||
}
|
||||
}
|
||||
/* Notify the client */
|
||||
@@ -202,6 +204,7 @@ int pubsubUnsubscribeChannel(client *c, robj *channel, int notify) {
|
||||
|
||||
/* Subscribe a client to a pattern. Returns 1 if the operation succeeded, or 0 if the client was already subscribed to that pattern. */
|
||||
int pubsubSubscribePattern(client *c, robj *pattern) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
int retval = 0;
|
||||
|
||||
if (listSearchKey(c->pubsub_patterns,pattern) == NULL) {
|
||||
@@ -209,10 +212,10 @@ int pubsubSubscribePattern(client *c, robj *pattern) {
|
||||
pubsubPattern *pat;
|
||||
listAddNodeTail(c->pubsub_patterns,pattern);
|
||||
incrRefCount(pattern);
|
||||
pat = zmalloc(sizeof(*pat), MALLOC_LOCAL);
|
||||
pat = (pubsubPattern*)zmalloc(sizeof(*pat), MALLOC_LOCAL);
|
||||
pat->pattern = getDecodedObject(pattern);
|
||||
pat->pclient = c;
|
||||
listAddNodeTail(server.pubsub_patterns,pat);
|
||||
listAddNodeTail(g_pserver->pubsub_patterns,pat);
|
||||
}
|
||||
/* Notify the client */
|
||||
addReplyPubsubPatSubscribed(c,pattern);
|
||||
@@ -232,8 +235,8 @@ int pubsubUnsubscribePattern(client *c, robj *pattern, int notify) {
|
||||
listDelNode(c->pubsub_patterns,ln);
|
||||
pat.pclient = c;
|
||||
pat.pattern = pattern;
|
||||
ln = listSearchKey(server.pubsub_patterns,&pat);
|
||||
listDelNode(server.pubsub_patterns,ln);
|
||||
ln = listSearchKey(g_pserver->pubsub_patterns,&pat);
|
||||
listDelNode(g_pserver->pubsub_patterns,ln);
|
||||
}
|
||||
/* Notify the client */
|
||||
if (notify) addReplyPubsubPatUnsubscribed(c,pattern);
|
||||
@@ -244,12 +247,13 @@ int pubsubUnsubscribePattern(client *c, robj *pattern, int notify) {
|
||||
/* Unsubscribe from all the channels. Return the number of channels the
|
||||
* client was subscribed to. */
|
||||
int pubsubUnsubscribeAllChannels(client *c, int notify) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
dictIterator *di = dictGetSafeIterator(c->pubsub_channels);
|
||||
dictEntry *de;
|
||||
int count = 0;
|
||||
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
robj *channel = dictGetKey(de);
|
||||
robj *channel = (robj*)dictGetKey(de);
|
||||
|
||||
count += pubsubUnsubscribeChannel(c,channel,notify);
|
||||
}
|
||||
@@ -262,13 +266,14 @@ int pubsubUnsubscribeAllChannels(client *c, int notify) {
|
||||
/* Unsubscribe from all the patterns. Return the number of patterns the
|
||||
* client was subscribed from. */
|
||||
int pubsubUnsubscribeAllPatterns(client *c, int notify) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
int count = 0;
|
||||
|
||||
listRewind(c->pubsub_patterns,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
robj *pattern = ln->value;
|
||||
robj *pattern = (robj*)ln->value;
|
||||
|
||||
count += pubsubUnsubscribePattern(c,pattern,notify);
|
||||
}
|
||||
@@ -278,43 +283,52 @@ int pubsubUnsubscribeAllPatterns(client *c, int notify) {
|
||||
|
||||
/* Publish a message */
|
||||
int pubsubPublishMessage(robj *channel, robj *message) {
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
int receivers = 0;
|
||||
dictEntry *de;
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
|
||||
/* Send to clients listening for that channel */
|
||||
de = dictFind(server.pubsub_channels,channel);
|
||||
de = dictFind(g_pserver->pubsub_channels,channel);
|
||||
if (de) {
|
||||
list *list = dictGetVal(de);
|
||||
list *list = reinterpret_cast<::list*>(dictGetVal(de));
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
|
||||
listRewind(list,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
client *c = ln->value;
|
||||
fastlock_lock(&c->lock);
|
||||
client *c = reinterpret_cast<client*>(ln->value);
|
||||
if (c->flags & CLIENT_CLOSE_ASAP) // avoid blocking if the write will be ignored
|
||||
continue;
|
||||
if (FCorrectThread(c))
|
||||
fastlock_lock(&c->lock);
|
||||
addReplyPubsubMessage(c,channel,message);
|
||||
fastlock_unlock(&c->lock);
|
||||
if (FCorrectThread(c))
|
||||
fastlock_unlock(&c->lock);
|
||||
receivers++;
|
||||
}
|
||||
}
|
||||
/* Send to clients listening to matching channels */
|
||||
if (listLength(server.pubsub_patterns)) {
|
||||
listRewind(server.pubsub_patterns,&li);
|
||||
if (listLength(g_pserver->pubsub_patterns)) {
|
||||
listRewind(g_pserver->pubsub_patterns,&li);
|
||||
channel = getDecodedObject(channel);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
pubsubPattern *pat = ln->value;
|
||||
pubsubPattern *pat = (pubsubPattern*)ln->value;
|
||||
|
||||
if (stringmatchlen((char*)ptrFromObj(pat->pattern),
|
||||
sdslen(ptrFromObj(pat->pattern)),
|
||||
sdslen(szFromObj(pat->pattern)),
|
||||
(char*)ptrFromObj(channel),
|
||||
sdslen(ptrFromObj(channel)),0))
|
||||
sdslen(szFromObj(channel)),0))
|
||||
{
|
||||
fastlock_lock(&pat->pclient->lock);
|
||||
if (pat->pclient->flags & CLIENT_CLOSE_ASAP)
|
||||
continue;
|
||||
if (FCorrectThread(pat->pclient))
|
||||
fastlock_lock(&pat->pclient->lock);
|
||||
addReplyPubsubPatMessage(pat->pclient,
|
||||
pat->pattern,channel,message);
|
||||
fastlock_unlock(&pat->pclient->lock);
|
||||
if (FCorrectThread(pat->pclient))
|
||||
fastlock_unlock(&pat->pclient->lock);
|
||||
receivers++;
|
||||
}
|
||||
}
|
||||
@@ -371,7 +385,7 @@ void punsubscribeCommand(client *c) {
|
||||
|
||||
void publishCommand(client *c) {
|
||||
int receivers = pubsubPublishMessage(c->argv[1],c->argv[2]);
|
||||
if (server.cluster_enabled)
|
||||
if (g_pserver->cluster_enabled)
|
||||
clusterPropagatePublish(c->argv[1],c->argv[2]);
|
||||
else
|
||||
forceCommandPropagation(c,PROPAGATE_REPL);
|
||||
@@ -380,7 +394,7 @@ void publishCommand(client *c) {
|
||||
|
||||
/* PUBSUB command for Pub/Sub introspection. */
|
||||
void pubsubCommand(client *c) {
|
||||
if (c->argc == 2 && !strcasecmp(ptrFromObj(c->argv[1]),"help")) {
|
||||
if (c->argc == 2 && !strcasecmp(szFromObj(c->argv[1]),"help")) {
|
||||
const char *help[] = {
|
||||
"CHANNELS [<pattern>] -- Return the currently active channels matching a pattern (default: all).",
|
||||
"NUMPAT -- Return number of subscriptions to patterns.",
|
||||
@@ -388,20 +402,20 @@ void pubsubCommand(client *c) {
|
||||
NULL
|
||||
};
|
||||
addReplyHelp(c, help);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"channels") &&
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"channels") &&
|
||||
(c->argc == 2 || c->argc == 3))
|
||||
{
|
||||
/* PUBSUB CHANNELS [<pattern>] */
|
||||
sds pat = (c->argc == 2) ? NULL : ptrFromObj(c->argv[2]);
|
||||
dictIterator *di = dictGetIterator(server.pubsub_channels);
|
||||
sds pat = (c->argc == 2) ? NULL : szFromObj(c->argv[2]);
|
||||
dictIterator *di = dictGetIterator(g_pserver->pubsub_channels);
|
||||
dictEntry *de;
|
||||
long mblen = 0;
|
||||
void *replylen;
|
||||
|
||||
replylen = addReplyDeferredLen(c);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
robj *cobj = dictGetKey(de);
|
||||
sds channel = ptrFromObj(cobj);
|
||||
robj *cobj = (robj*)dictGetKey(de);
|
||||
sds channel = szFromObj(cobj);
|
||||
|
||||
if (!pat || stringmatchlen(pat, sdslen(pat),
|
||||
channel, sdslen(channel),0))
|
||||
@@ -412,20 +426,20 @@ NULL
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
setDeferredArrayLen(c,replylen,mblen);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"numsub") && c->argc >= 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"numsub") && c->argc >= 2) {
|
||||
/* PUBSUB NUMSUB [Channel_1 ... Channel_N] */
|
||||
int j;
|
||||
|
||||
addReplyArrayLen(c,(c->argc-2)*2);
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
list *l = dictFetchValue(server.pubsub_channels,c->argv[j]);
|
||||
list *l = (list*)dictFetchValue(g_pserver->pubsub_channels,c->argv[j]);
|
||||
|
||||
addReplyBulk(c,c->argv[j]);
|
||||
addReplyLongLong(c,l ? listLength(l) : 0);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"numpat") && c->argc == 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"numpat") && c->argc == 2) {
|
||||
/* PUBSUB NUMPAT */
|
||||
addReplyLongLong(c,listLength(server.pubsub_patterns));
|
||||
addReplyLongLong(c,listLength(g_pserver->pubsub_patterns));
|
||||
} else {
|
||||
addReplySubcommandSyntaxError(c);
|
||||
}
|
||||
@@ -122,6 +122,10 @@ typedef struct quicklistEntry {
|
||||
#define quicklistNodeIsCompressed(node) \
|
||||
((node)->encoding == QUICKLIST_NODE_ENCODING_LZF)
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Prototypes */
|
||||
quicklist *quicklistCreate(void);
|
||||
quicklist *quicklistNew(int fill, int compress);
|
||||
@@ -174,4 +178,8 @@ int quicklistTest(int argc, char *argv[]);
|
||||
#define AL_START_HEAD 0
|
||||
#define AL_START_TAIL 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* __QUICKLIST_H__ */
|
||||
+12
-5
@@ -6,7 +6,7 @@ extern "C" {
|
||||
#include <sys/wait.h>
|
||||
|
||||
/* Save the DB on disk. Return C_ERR on error, C_OK on success. */
|
||||
extern "C" int rdbSaveS3(char *s3bucket, rdbSaveInfo *rsi)
|
||||
int rdbSaveS3(char *s3bucket, rdbSaveInfo *rsi)
|
||||
{
|
||||
int status = EXIT_FAILURE;
|
||||
int fd[2];
|
||||
@@ -33,12 +33,19 @@ extern "C" int rdbSaveS3(char *s3bucket, rdbSaveInfo *rsi)
|
||||
else
|
||||
{
|
||||
close(fd[0]);
|
||||
if (rdbSaveFd(fd[1], rsi) != C_OK)
|
||||
FILE *fp = fdopen(fd[1], "w");
|
||||
if (fp == NULL)
|
||||
{
|
||||
close(fd[1]);
|
||||
close (fd[1]);
|
||||
return C_ERR;
|
||||
}
|
||||
close(fd[1]);
|
||||
|
||||
if (rdbSaveFp(fp, rsi) != C_OK)
|
||||
{
|
||||
fclose(fp);
|
||||
return C_ERR;
|
||||
}
|
||||
fclose(fp);
|
||||
waitpid(pid, &status, 0);
|
||||
}
|
||||
|
||||
@@ -59,7 +66,7 @@ int rdbLoadS3Core(int fd, rdbSaveInfo *rsi)
|
||||
|
||||
if ((fp = fdopen(fd, "rb")) == NULL) return C_ERR;
|
||||
startLoading(fp);
|
||||
rioInitWithFile(&rdb,fileno(fp));
|
||||
rioInitWithFile(&rdb,fp);
|
||||
retval = rdbLoadRio(&rdb,rsi,0);
|
||||
fclose(fp);
|
||||
stopLoading();
|
||||
|
||||
+396
-302
File diff suppressed because it is too large.
Load diff
@@ -133,25 +133,26 @@ int rdbSaveMillisecondTime(rio *rdb, long long t);
|
||||
long long rdbLoadMillisecondTime(rio *rdb, int rdbver);
|
||||
uint64_t rdbLoadLen(rio *rdb, int *isencoded);
|
||||
int rdbLoadLenByRef(rio *rdb, int *isencoded, uint64_t *lenptr);
|
||||
int rdbSaveObjectType(rio *rdb, robj *o);
|
||||
int rdbSaveObjectType(rio *rdb, robj_roptr o);
|
||||
int rdbLoadObjectType(rio *rdb);
|
||||
int rdbLoad(rdbSaveInfo *rsi);
|
||||
int rdbLoadFile(const char *filename, rdbSaveInfo *rsi);
|
||||
int rdbSaveBackground(rdbSaveInfo *rsi);
|
||||
int rdbSaveToSlavesSockets(rdbSaveInfo *rsi);
|
||||
void rdbRemoveTempFile(pid_t childpid);
|
||||
int rdbSave(rdbSaveInfo *rsi);
|
||||
int rdbSaveFile(char *filename, rdbSaveInfo *rsi);
|
||||
int rdbSaveFd(int fd, rdbSaveInfo *rsi);
|
||||
int rdbSaveFp(FILE *pf, rdbSaveInfo *rsi);
|
||||
int rdbSaveS3(char *path, rdbSaveInfo *rsi);
|
||||
int rdbLoadS3(char *path, rdbSaveInfo *rsi);
|
||||
ssize_t rdbSaveObject(rio *rdb, robj *o, robj *key);
|
||||
ssize_t rdbSaveObject(rio *rdb, robj_roptr o, robj *key);
|
||||
size_t rdbSavedObjectLen(robj *o);
|
||||
robj *rdbLoadObject(int type, rio *rdb, robj *key);
|
||||
robj *rdbLoadObject(int type, rio *rdb, robj *key, uint64_t mvcc_tstamp);
|
||||
void backgroundSaveDoneHandler(int exitcode, int bysignal);
|
||||
int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val, long long expiretime);
|
||||
robj *rdbLoadStringObject(rio *rdb);
|
||||
ssize_t rdbSaveStringObject(rio *rdb, robj *obj);
|
||||
ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len);
|
||||
ssize_t rdbSaveStringObject(rio *rdb, robj_roptr obj);
|
||||
ssize_t rdbSaveRawString(rio *rdb, const unsigned char *s, size_t len);
|
||||
void *rdbGenericLoadStringObject(rio *rdb, int flags, size_t *lenptr);
|
||||
int rdbSaveBinaryDoubleValue(rio *rdb, double val);
|
||||
int rdbLoadBinaryDoubleValue(rio *rdb, double *val);
|
||||
|
||||
@@ -41,10 +41,11 @@
|
||||
#include <assert.h>
|
||||
#include <math.h>
|
||||
#include <pthread.h>
|
||||
|
||||
extern "C" {
|
||||
#include <sds.h> /* Use hiredis sds. */
|
||||
#include "ae.h"
|
||||
#include "hiredis.h"
|
||||
}
|
||||
#include "ae.h"
|
||||
#include "adlist.h"
|
||||
#include "dict.h"
|
||||
#include "zmalloc.h"
|
||||
@@ -151,7 +152,7 @@ typedef struct clusterNode {
|
||||
int port;
|
||||
sds name;
|
||||
int flags;
|
||||
sds replicate; /* Master ID if node is a slave */
|
||||
sds replicate; /* Master ID if node is a replica */
|
||||
int *slots;
|
||||
int slots_count;
|
||||
int current_slot_index;
|
||||
@@ -172,6 +173,8 @@ typedef struct redisConfig {
|
||||
sds appendonly;
|
||||
} redisConfig;
|
||||
|
||||
int g_fInCrash = false;
|
||||
|
||||
/* Prototypes */
|
||||
static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
static void createMissingClients(client c);
|
||||
@@ -231,7 +234,7 @@ static int dictSdsKeyCompare(void *privdata, const void *key1,
|
||||
}
|
||||
|
||||
/* _serverAssert is needed by dict */
|
||||
void _serverAssert(const char *estr, const char *file, int line) {
|
||||
extern "C" void _serverAssert(const char *estr, const char *file, int line) {
|
||||
fprintf(stderr, "=== ASSERTION FAILED ===");
|
||||
fprintf(stderr, "==> %s:%d '%s' is not true",file,line,estr);
|
||||
*((char*)-1) = 'x';
|
||||
@@ -240,7 +243,9 @@ void _serverAssert(const char *estr, const char *file, int line) {
|
||||
static redisConfig *getRedisConfig(const char *ip, int port,
|
||||
const char *hostsocket)
|
||||
{
|
||||
redisConfig *cfg = zcalloc(sizeof(*cfg), MALLOC_LOCAL);
|
||||
redisConfig *cfg = (redisConfig*)zcalloc(sizeof(*cfg), MALLOC_LOCAL);
|
||||
int i = 0;
|
||||
void *r = NULL;
|
||||
if (!cfg) return NULL;
|
||||
redisContext *c = NULL;
|
||||
redisReply *reply = NULL, *sub_reply = NULL;
|
||||
@@ -250,15 +255,27 @@ static redisConfig *getRedisConfig(const char *ip, int port,
|
||||
c = redisConnectUnix(hostsocket);
|
||||
if (c == NULL || c->err) {
|
||||
fprintf(stderr,"Could not connect to Redis at ");
|
||||
char *err = (c != NULL ? c->errstr : "");
|
||||
const char *err = (c != NULL ? c->errstr : "");
|
||||
if (hostsocket == NULL) fprintf(stderr,"%s:%d: %s\n",ip,port,err);
|
||||
else fprintf(stderr,"%s: %s\n",hostsocket,err);
|
||||
goto fail;
|
||||
}
|
||||
|
||||
if(config.auth){
|
||||
void *authReply = NULL;
|
||||
redisAppendCommand(c, "AUTH %s", config.auth);
|
||||
if (REDIS_OK != redisGetReply(c, &authReply)) goto fail;
|
||||
if (reply) freeReplyObject(reply);
|
||||
reply = ((redisReply *) authReply);
|
||||
if (reply->type == REDIS_REPLY_ERROR) {
|
||||
fprintf(stderr, "ERROR: %s\n", reply->str);
|
||||
goto fail;
|
||||
}
|
||||
}
|
||||
|
||||
redisAppendCommand(c, "CONFIG GET %s", "save");
|
||||
redisAppendCommand(c, "CONFIG GET %s", "appendonly");
|
||||
int i = 0;
|
||||
void *r = NULL;
|
||||
|
||||
for (; i < 2; i++) {
|
||||
int res = redisGetReply(c, &r);
|
||||
if (reply) freeReplyObject(reply);
|
||||
@@ -270,7 +287,7 @@ static redisConfig *getRedisConfig(const char *ip, int port,
|
||||
}
|
||||
if (reply->type != REDIS_REPLY_ARRAY || reply->elements < 2) goto fail;
|
||||
sub_reply = reply->element[1];
|
||||
char *value = sub_reply->str;
|
||||
const char *value = sub_reply->str;
|
||||
if (!value) value = "";
|
||||
switch (i) {
|
||||
case 0: cfg->save = sdsnew(value); break;
|
||||
@@ -325,7 +342,7 @@ static void freeAllClients(void) {
|
||||
|
||||
while(ln) {
|
||||
next = ln->next;
|
||||
freeClient(ln->value);
|
||||
freeClient((client)ln->value);
|
||||
ln = next;
|
||||
}
|
||||
}
|
||||
@@ -405,7 +422,7 @@ static void clientDone(client c) {
|
||||
}
|
||||
|
||||
static void readHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
client c = privdata;
|
||||
client c = (client)privdata;
|
||||
void *reply = NULL;
|
||||
UNUSED(el);
|
||||
UNUSED(fd);
|
||||
@@ -430,7 +447,7 @@ static void readHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
fprintf(stderr,"Unexpected error reply, exiting...\n");
|
||||
exit(1);
|
||||
}
|
||||
redisReply *r = reply;
|
||||
redisReply *r = (redisReply*)reply;
|
||||
int is_err = (r->type == REDIS_REPLY_ERROR);
|
||||
|
||||
if (is_err && config.showerrors) {
|
||||
@@ -505,7 +522,7 @@ static void readHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
}
|
||||
|
||||
static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
client c = privdata;
|
||||
client c = (client)privdata;
|
||||
UNUSED(el);
|
||||
UNUSED(fd);
|
||||
UNUSED(mask);
|
||||
@@ -565,10 +582,10 @@ static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
* for arguments randomization.
|
||||
*
|
||||
* Even when cloning another client, prefix commands are applied if needed.*/
|
||||
static client createClient(char *cmd, size_t len, client from, int thread_id) {
|
||||
static client createClient(const char *cmd, size_t len, client from, int thread_id) {
|
||||
int j;
|
||||
int is_cluster_client = (config.cluster_mode && thread_id >= 0);
|
||||
client c = zmalloc(sizeof(struct _client), MALLOC_LOCAL);
|
||||
client c = (client)zmalloc(sizeof(struct _client), MALLOC_LOCAL);
|
||||
|
||||
const char *ip = NULL;
|
||||
int port = 0;
|
||||
@@ -653,7 +670,7 @@ static client createClient(char *cmd, size_t len, client from, int thread_id) {
|
||||
if (from) {
|
||||
c->randlen = from->randlen;
|
||||
c->randfree = 0;
|
||||
c->randptr = zmalloc(sizeof(char*)*c->randlen, MALLOC_LOCAL);
|
||||
c->randptr = (char**)zmalloc(sizeof(char*)*c->randlen, MALLOC_LOCAL);
|
||||
/* copy the offsets. */
|
||||
for (j = 0; j < (int)c->randlen; j++) {
|
||||
c->randptr[j] = c->obuf + (from->randptr[j]-from->obuf);
|
||||
@@ -665,10 +682,10 @@ static client createClient(char *cmd, size_t len, client from, int thread_id) {
|
||||
|
||||
c->randlen = 0;
|
||||
c->randfree = RANDPTR_INITIAL_SIZE;
|
||||
c->randptr = zmalloc(sizeof(char*)*c->randfree, MALLOC_LOCAL);
|
||||
c->randptr = (char**)zmalloc(sizeof(char*)*c->randfree, MALLOC_LOCAL);
|
||||
while ((p = strstr(p,"__rand_int__")) != NULL) {
|
||||
if (c->randfree == 0) {
|
||||
c->randptr = zrealloc(c->randptr,sizeof(char*)*c->randlen*2, MALLOC_LOCAL);
|
||||
c->randptr = (char**)zrealloc(c->randptr,sizeof(char*)*c->randlen*2, MALLOC_LOCAL);
|
||||
c->randfree += c->randlen;
|
||||
}
|
||||
c->randptr[c->randlen++] = p;
|
||||
@@ -682,7 +699,7 @@ static client createClient(char *cmd, size_t len, client from, int thread_id) {
|
||||
if (from) {
|
||||
c->staglen = from->staglen;
|
||||
c->stagfree = 0;
|
||||
c->stagptr = zmalloc(sizeof(char*)*c->staglen, MALLOC_LOCAL);
|
||||
c->stagptr = (char**)zmalloc(sizeof(char*)*c->staglen, MALLOC_LOCAL);
|
||||
/* copy the offsets. */
|
||||
for (j = 0; j < (int)c->staglen; j++) {
|
||||
c->stagptr[j] = c->obuf + (from->stagptr[j]-from->obuf);
|
||||
@@ -694,10 +711,10 @@ static client createClient(char *cmd, size_t len, client from, int thread_id) {
|
||||
|
||||
c->staglen = 0;
|
||||
c->stagfree = RANDPTR_INITIAL_SIZE;
|
||||
c->stagptr = zmalloc(sizeof(char*)*c->stagfree, MALLOC_LOCAL);
|
||||
c->stagptr = (char**)zmalloc(sizeof(char*)*c->stagfree, MALLOC_LOCAL);
|
||||
while ((p = strstr(p,"{tag}")) != NULL) {
|
||||
if (c->stagfree == 0) {
|
||||
c->stagptr = zrealloc(c->stagptr,
|
||||
c->stagptr = (char**)zrealloc(c->stagptr,
|
||||
sizeof(char*) * c->staglen*2, MALLOC_LOCAL);
|
||||
c->stagfree += c->staglen;
|
||||
}
|
||||
@@ -821,7 +838,7 @@ static void showLatencyReport(void) {
|
||||
static void initBenchmarkThreads() {
|
||||
int i;
|
||||
if (config.threads) freeBenchmarkThreads();
|
||||
config.threads = zmalloc(config.num_threads * sizeof(benchmarkThread*), MALLOC_LOCAL);
|
||||
config.threads = (benchmarkThread**)zmalloc(config.num_threads * sizeof(benchmarkThread*), MALLOC_LOCAL);
|
||||
for (i = 0; i < config.num_threads; i++) {
|
||||
benchmarkThread *thread = createBenchmarkThread(i);
|
||||
config.threads[i] = thread;
|
||||
@@ -841,7 +858,7 @@ static void startBenchmarkThreads() {
|
||||
pthread_join(config.threads[i]->thread, NULL);
|
||||
}
|
||||
|
||||
static void benchmark(char *title, char *cmd, int len) {
|
||||
static void benchmark(const char *title, const char *cmd, int len) {
|
||||
client c;
|
||||
|
||||
config.title = title;
|
||||
@@ -867,7 +884,7 @@ static void benchmark(char *title, char *cmd, int len) {
|
||||
/* Thread functions. */
|
||||
|
||||
static benchmarkThread *createBenchmarkThread(int index) {
|
||||
benchmarkThread *thread = zmalloc(sizeof(*thread), MALLOC_LOCAL);
|
||||
benchmarkThread *thread = (benchmarkThread*)zmalloc(sizeof(*thread), MALLOC_LOCAL);
|
||||
if (thread == NULL) return NULL;
|
||||
thread->index = index;
|
||||
thread->el = aeCreateEventLoop(1024*10);
|
||||
@@ -899,7 +916,7 @@ static void *execBenchmarkThread(void *ptr) {
|
||||
/* Cluster helper functions. */
|
||||
|
||||
static clusterNode *createClusterNode(char *ip, int port) {
|
||||
clusterNode *node = zmalloc(sizeof(*node), MALLOC_LOCAL);
|
||||
clusterNode *node = (clusterNode*)zmalloc(sizeof(*node), MALLOC_LOCAL);
|
||||
if (!node) return NULL;
|
||||
node->ip = ip;
|
||||
node->port = port;
|
||||
@@ -907,7 +924,7 @@ static clusterNode *createClusterNode(char *ip, int port) {
|
||||
node->flags = 0;
|
||||
node->replicate = NULL;
|
||||
node->replicas_count = 0;
|
||||
node->slots = zmalloc(CLUSTER_SLOTS * sizeof(int), MALLOC_LOCAL);
|
||||
node->slots = (int*)zmalloc(CLUSTER_SLOTS * sizeof(int), MALLOC_LOCAL);
|
||||
node->slots_count = 0;
|
||||
node->current_slot_index = 0;
|
||||
node->updated_slots = NULL;
|
||||
@@ -953,7 +970,7 @@ static void freeClusterNodes() {
|
||||
|
||||
static clusterNode **addClusterNode(clusterNode *node) {
|
||||
int count = config.cluster_node_count + 1;
|
||||
config.cluster_nodes = zrealloc(config.cluster_nodes,
|
||||
config.cluster_nodes = (clusterNode**)zrealloc(config.cluster_nodes,
|
||||
count * sizeof(*node), MALLOC_LOCAL);
|
||||
if (!config.cluster_nodes) return NULL;
|
||||
config.cluster_nodes[config.cluster_node_count++] = node;
|
||||
@@ -964,6 +981,7 @@ static int fetchClusterConfiguration() {
|
||||
int success = 1;
|
||||
redisContext *ctx = NULL;
|
||||
redisReply *reply = NULL;
|
||||
char *lines = reply->str, *p, *line;
|
||||
if (config.hostsocket == NULL)
|
||||
ctx = redisConnect(config.hostip,config.hostport);
|
||||
else
|
||||
@@ -979,7 +997,7 @@ static int fetchClusterConfiguration() {
|
||||
clusterNode *firstNode = createClusterNode((char *) config.hostip,
|
||||
config.hostport);
|
||||
if (!firstNode) {success = 0; goto cleanup;}
|
||||
reply = redisCommand(ctx, "CLUSTER NODES");
|
||||
reply = (redisReply*)redisCommand(ctx, "CLUSTER NODES");
|
||||
success = (reply != NULL);
|
||||
if (!success) goto cleanup;
|
||||
success = (reply->type != REDIS_REPLY_ERROR);
|
||||
@@ -993,7 +1011,7 @@ static int fetchClusterConfiguration() {
|
||||
}
|
||||
goto cleanup;
|
||||
}
|
||||
char *lines = reply->str, *p, *line;
|
||||
lines = reply->str;
|
||||
while ((p = strstr(lines, "\n")) != NULL) {
|
||||
*p = '\0';
|
||||
line = lines;
|
||||
@@ -1077,7 +1095,7 @@ static int fetchClusterConfiguration() {
|
||||
sds dst = sdsnew(p);
|
||||
node->migrating_count += 2;
|
||||
node->migrating =
|
||||
zrealloc(node->migrating,
|
||||
(char**)zrealloc(node->migrating,
|
||||
(node->migrating_count * sizeof(sds)), MALLOC_LOCAL);
|
||||
node->migrating[node->migrating_count - 2] =
|
||||
slot;
|
||||
@@ -1091,7 +1109,7 @@ static int fetchClusterConfiguration() {
|
||||
sds slot = sdsnew(slotsdef);
|
||||
sds src = sdsnew(p);
|
||||
node->importing_count += 2;
|
||||
node->importing = zrealloc(node->importing,
|
||||
node->importing = (char**)zrealloc(node->importing,
|
||||
(node->importing_count * sizeof(sds)), MALLOC_LOCAL);
|
||||
node->importing[node->importing_count - 2] =
|
||||
slot;
|
||||
@@ -1183,7 +1201,7 @@ static int fetchClusterSlotsConfiguration(client c) {
|
||||
node->updated_slots_count = 0;
|
||||
dictReplace(masters, node->name, node) ;
|
||||
}
|
||||
reply = redisCommand(ctx, "CLUSTER SLOTS");
|
||||
reply = (redisReply*)redisCommand(ctx, "CLUSTER SLOTS");
|
||||
if (reply == NULL || reply->type == REDIS_REPLY_ERROR) {
|
||||
success = 0;
|
||||
if (reply)
|
||||
@@ -1193,7 +1211,7 @@ static int fetchClusterSlotsConfiguration(client c) {
|
||||
assert(reply->type == REDIS_REPLY_ARRAY);
|
||||
for (i = 0; i < reply->elements; i++) {
|
||||
redisReply *r = reply->element[i];
|
||||
assert(r->type = REDIS_REPLY_ARRAY);
|
||||
assert(r->type == REDIS_REPLY_ARRAY);
|
||||
assert(r->elements >= 3);
|
||||
int from, to, slot;
|
||||
from = r->element[0]->integer;
|
||||
@@ -1211,9 +1229,9 @@ static int fetchClusterSlotsConfiguration(client c) {
|
||||
goto cleanup;
|
||||
}
|
||||
sdsfree(name);
|
||||
clusterNode *node = dictGetVal(entry);
|
||||
clusterNode *node = (clusterNode*)dictGetVal(entry);
|
||||
if (node->updated_slots == NULL)
|
||||
node->updated_slots = zcalloc(CLUSTER_SLOTS * sizeof(int), MALLOC_LOCAL);
|
||||
node->updated_slots = (int*)zcalloc(CLUSTER_SLOTS * sizeof(int), MALLOC_LOCAL);
|
||||
for (slot = from; slot <= to; slot++)
|
||||
node->updated_slots[node->updated_slots_count++] = slot;
|
||||
}
|
||||
@@ -1295,7 +1313,7 @@ int parseOptions(int argc, const char **argv) {
|
||||
if (*p < '0' || *p > '9') goto invalid;
|
||||
}
|
||||
config.randomkeys = 1;
|
||||
config.randomkeys_keyspacelen = atoi(argv[++i]);
|
||||
config.randomkeys_keyspacelen = atoi(next);
|
||||
if (config.randomkeys_keyspacelen < 0)
|
||||
config.randomkeys_keyspacelen = 0;
|
||||
} else if (!strcmp(argv[i],"-q")) {
|
||||
@@ -1436,7 +1454,7 @@ int showThroughput(struct aeEventLoop *eventLoop, long long id, void *clientData
|
||||
|
||||
/* Return true if the named test was selected using the -t command line
|
||||
* switch, or if all the tests are selected (no -t passed by user). */
|
||||
int test_is_selected(char *name) {
|
||||
int test_is_selected(const char *name) {
|
||||
char buf[256];
|
||||
int l = strlen(name);
|
||||
|
||||
@@ -1499,7 +1517,7 @@ int main(int argc, const char **argv) {
|
||||
argc -= i;
|
||||
argv += i;
|
||||
|
||||
config.latency = zmalloc(sizeof(long long)*config.requests, MALLOC_LOCAL);
|
||||
config.latency = (long long*)zmalloc(sizeof(long long)*config.requests, MALLOC_LOCAL);
|
||||
|
||||
if (config.cluster_mode) {
|
||||
/* Fetch cluster configuration. */
|
||||
@@ -1530,7 +1548,10 @@ int main(int argc, const char **argv) {
|
||||
if (node->name) printf("%s ", node->name);
|
||||
printf("%s:%d\n", node->ip, node->port);
|
||||
node->redis_config = getRedisConfig(node->ip, node->port, NULL);
|
||||
if (node->redis_config == NULL) exit(1);
|
||||
if (node->redis_config == NULL) {
|
||||
fprintf(stderr, "WARN: could not fetch node CONFIG %s:%d\n",
|
||||
node->ip, node->port);
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
/* Automatically set thread number to node count if not specified
|
||||
@@ -1540,7 +1561,8 @@ int main(int argc, const char **argv) {
|
||||
} else {
|
||||
config.redis_config =
|
||||
getRedisConfig(config.hostip, config.hostport, config.hostsocket);
|
||||
if (config.redis_config == NULL) exit(1);
|
||||
if (config.redis_config == NULL)
|
||||
fprintf(stderr, "WARN: could not fetch server CONFIG\n");
|
||||
}
|
||||
|
||||
if (config.num_threads > 0) {
|
||||
@@ -1596,7 +1618,7 @@ int main(int argc, const char **argv) {
|
||||
}
|
||||
|
||||
/* Run default benchmark suite. */
|
||||
data = zmalloc(config.datasize+1, MALLOC_LOCAL);
|
||||
data = (char*)zmalloc(config.datasize+1, MALLOC_LOCAL);
|
||||
do {
|
||||
memset(data,'x',config.datasize);
|
||||
data[config.datasize] = '\0';
|
||||
@@ -37,7 +37,7 @@
|
||||
snprintf(error, sizeof(error), "0x%16llx: %s", (long long)epos, __buf); \
|
||||
}
|
||||
|
||||
static char error[1024];
|
||||
static char error[1044];
|
||||
static off_t epos;
|
||||
|
||||
int consumeNewline(char *buf) {
|
||||
@@ -190,7 +190,7 @@ int redis_check_aof_main(int argc, char **argv) {
|
||||
if (has_preamble) {
|
||||
printf("The AOF appears to start with an RDB preamble.\n"
|
||||
"Checking the RDB preamble to start:\n");
|
||||
if (redis_check_rdb_main(argc,argv,fp) == C_ERR) {
|
||||
if (redis_check_rdb_main(argc,(const char**)argv,fp) == C_ERR) {
|
||||
printf("RDB preamble of AOF file is not sane, aborting.\n");
|
||||
exit(1);
|
||||
} else {
|
||||
@@ -37,7 +37,7 @@ void rdbLoadProgressCallback(rio *r, const void *buf, size_t len);
|
||||
int rdbCheckMode = 0;
|
||||
|
||||
struct {
|
||||
rio *rio;
|
||||
::rio *rio;
|
||||
robj *key; /* Current key we are reading. */
|
||||
int key_type; /* Current key type if != -1. */
|
||||
unsigned long keys; /* Number of keys processed. */
|
||||
@@ -59,7 +59,7 @@ struct {
|
||||
#define RDB_CHECK_DOING_READ_LEN 6
|
||||
#define RDB_CHECK_DOING_READ_AUX 7
|
||||
|
||||
char *rdb_check_doing_string[] = {
|
||||
const char *rdb_check_doing_string[] = {
|
||||
"start",
|
||||
"read-type",
|
||||
"read-expire",
|
||||
@@ -70,7 +70,7 @@ char *rdb_check_doing_string[] = {
|
||||
"read-aux"
|
||||
};
|
||||
|
||||
char *rdb_type_string[] = {
|
||||
const char *rdb_type_string[] = {
|
||||
"string",
|
||||
"list-linked",
|
||||
"set-hashtable",
|
||||
@@ -176,7 +176,7 @@ void rdbCheckSetupSignals(void) {
|
||||
* 1 is returned.
|
||||
* The file is specified as a filename in 'rdbfilename' if 'fp' is not NULL,
|
||||
* otherwise the already open file 'fp' is checked. */
|
||||
int redis_check_rdb(char *rdbfilename, FILE *fp) {
|
||||
int redis_check_rdb(const char *rdbfilename, FILE *fp) {
|
||||
uint64_t dbid;
|
||||
int type, rdbver;
|
||||
char buf[1024];
|
||||
@@ -186,7 +186,7 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) {
|
||||
int closefile = (fp == NULL);
|
||||
if (fp == NULL && (fp = fopen(rdbfilename,"r")) == NULL) return 1;
|
||||
|
||||
rioInitWithFile(&rdb,fileno(fp));
|
||||
rioInitWithFile(&rdb,fp);
|
||||
rdbstate.rio = &rdb;
|
||||
rdb.update_cksum = rdbLoadProgressCallback;
|
||||
if (rioRead(&rdb,buf,9) == 0) goto eoferr;
|
||||
@@ -285,7 +285,7 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) {
|
||||
rdbstate.keys++;
|
||||
/* Read value */
|
||||
rdbstate.doing = RDB_CHECK_DOING_READ_OBJECT_VALUE;
|
||||
if ((val = rdbLoadObject(type,&rdb,key)) == NULL) goto eoferr;
|
||||
if ((val = rdbLoadObject(type,&rdb,key,OBJ_MVCC_INVALID)) == NULL) goto eoferr;
|
||||
/* Check if the key already expired. */
|
||||
if (expiretime != -1 && expiretime < now)
|
||||
rdbstate.already_expired++;
|
||||
@@ -297,7 +297,7 @@ int redis_check_rdb(char *rdbfilename, FILE *fp) {
|
||||
expiretime = -1;
|
||||
}
|
||||
/* Verify the checksum if RDB version is >= 5 */
|
||||
if (rdbver >= 5 && server.rdb_checksum) {
|
||||
if (rdbver >= 5 && g_pserver->rdb_checksum) {
|
||||
uint64_t cksum, expected = rdb.cksum;
|
||||
|
||||
rdbstate.doing = RDB_CHECK_DOING_CHECK_SUM;
|
||||
@@ -339,7 +339,7 @@ err:
|
||||
* status code according to success (RDB is sane) or error (RDB is corrupted).
|
||||
* Otherwise if called with a non NULL fp, the function returns C_OK or
|
||||
* C_ERR depending on the success or failure. */
|
||||
int redis_check_rdb_main(int argc, char **argv, FILE *fp) {
|
||||
int redis_check_rdb_main(int argc, const char **argv, FILE *fp) {
|
||||
if (argc != 2 && fp == NULL) {
|
||||
fprintf(stderr, "Usage: %s <rdb-file-name>\n", argv[0]);
|
||||
exit(1);
|
||||
@@ -349,7 +349,7 @@ int redis_check_rdb_main(int argc, char **argv, FILE *fp) {
|
||||
* an already initialized Redis instance, check if we really need to. */
|
||||
if (shared.integers[0] == NULL)
|
||||
createSharedObjects();
|
||||
server.loading_process_events_interval_bytes = 0;
|
||||
g_pserver->loading_process_events_interval_bytes = 0;
|
||||
rdbCheckMode = 1;
|
||||
rdbCheckInfo("Checking RDB file %s", argv[1]);
|
||||
rdbCheckSetupSignals();
|
||||
@@ -0,0 +1,933 @@
|
||||
#include "fmacros.h"
|
||||
#include "version.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <signal.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
#include <ctype.h>
|
||||
#include <errno.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/time.h>
|
||||
#include <assert.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
extern "C" {
|
||||
#include <hiredis.h>
|
||||
#include <sds.h> /* use sds.h from hiredis, so that only one set of sds functions will be present in the binary */
|
||||
}
|
||||
#include "dict.h"
|
||||
#include "adlist.h"
|
||||
#include "zmalloc.h"
|
||||
#include "storage.h"
|
||||
|
||||
#include "redis-cli.h"
|
||||
|
||||
static dict *clusterManagerGetLinkStatus(void);
|
||||
|
||||
/* The Cluster Manager global structure */
|
||||
struct clusterManager cluster_manager;
|
||||
|
||||
extern "C" uint64_t dictSdsHash(const void *key) {
|
||||
return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
|
||||
}
|
||||
|
||||
extern "C" int dictSdsKeyCompare(void *privdata, const void *key1,
|
||||
const void *key2)
|
||||
{
|
||||
int l1,l2;
|
||||
DICT_NOTUSED(privdata);
|
||||
|
||||
l1 = sdslen((sds)key1);
|
||||
l2 = sdslen((sds)key2);
|
||||
if (l1 != l2) return 0;
|
||||
return memcmp(key1, key2, l1) == 0;
|
||||
}
|
||||
|
||||
extern "C" void dictSdsDestructor(void *privdata, void *val)
|
||||
{
|
||||
DICT_NOTUSED(privdata);
|
||||
sdsfree((sds)val);
|
||||
}
|
||||
|
||||
extern "C" void dictListDestructor(void *privdata, void *val)
|
||||
{
|
||||
DICT_NOTUSED(privdata);
|
||||
listRelease((list*)val);
|
||||
}
|
||||
|
||||
/* Used by clusterManagerFixSlotsCoverage */
|
||||
dict *clusterManagerUncoveredSlots = NULL;
|
||||
|
||||
/* Info about a cluster internal link. */
|
||||
|
||||
typedef struct clusterManagerLink {
|
||||
sds node_name;
|
||||
sds node_addr;
|
||||
int connected;
|
||||
int handshaking;
|
||||
} clusterManagerLink;
|
||||
|
||||
static dictType clusterManagerDictType = {
|
||||
dictSdsHash, /* hash function */
|
||||
NULL, /* key dup */
|
||||
NULL, /* val dup */
|
||||
dictSdsKeyCompare, /* key compare */
|
||||
NULL, /* key destructor */
|
||||
dictSdsDestructor /* val destructor */
|
||||
};
|
||||
|
||||
static dictType clusterManagerLinkDictType = {
|
||||
dictSdsHash, /* hash function */
|
||||
NULL, /* key dup */
|
||||
NULL, /* val dup */
|
||||
dictSdsKeyCompare, /* key compare */
|
||||
dictSdsDestructor, /* key destructor */
|
||||
dictListDestructor /* val destructor */
|
||||
};
|
||||
|
||||
|
||||
extern "C" void freeClusterManager(void) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
if (cluster_manager.nodes != NULL) {
|
||||
listRewind(cluster_manager.nodes,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
freeClusterManagerNode(n);
|
||||
}
|
||||
listRelease(cluster_manager.nodes);
|
||||
cluster_manager.nodes = NULL;
|
||||
}
|
||||
if (cluster_manager.errors != NULL) {
|
||||
listRewind(cluster_manager.errors,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sds err = (sds)ln->value;
|
||||
sdsfree(err);
|
||||
}
|
||||
listRelease(cluster_manager.errors);
|
||||
cluster_manager.errors = NULL;
|
||||
}
|
||||
if (clusterManagerUncoveredSlots != NULL)
|
||||
dictRelease(clusterManagerUncoveredSlots);
|
||||
}
|
||||
|
||||
/* Return the anti-affinity score, which is a measure of the amount of
|
||||
* violations of anti-affinity in the current cluster layout, that is, how
|
||||
* badly the masters and slaves are distributed in the different IP
|
||||
* addresses so that slaves of the same master are not in the master
|
||||
* host and are also in different hosts.
|
||||
*
|
||||
* The score is calculated as follows:
|
||||
*
|
||||
* SAME_AS_MASTER = 10000 * each replica in the same IP of its master.
|
||||
* SAME_AS_SLAVE = 1 * each replica having the same IP as another replica
|
||||
of the same master.
|
||||
* FINAL_SCORE = SAME_AS_MASTER + SAME_AS_SLAVE
|
||||
*
|
||||
* So a greater score means a worse anti-affinity level, while zero
|
||||
* means perfect anti-affinity.
|
||||
*
|
||||
* The anti affinity optimizator will try to get a score as low as
|
||||
* possible. Since we do not want to sacrifice the fact that slaves should
|
||||
* not be in the same host as the master, we assign 10000 times the score
|
||||
* to this violation, so that we'll optimize for the second factor only
|
||||
* if it does not impact the first one.
|
||||
*
|
||||
* The ipnodes argument is an array of clusterManagerNodeArray, one for
|
||||
* each IP, while ip_count is the total number of IPs in the configuration.
|
||||
*
|
||||
* The function returns the above score, and the list of
|
||||
* offending slaves can be stored into the 'offending' argument,
|
||||
* so that the optimizer can try changing the configuration of the
|
||||
* slaves violating the anti-affinity goals. */
|
||||
int clusterManagerGetAntiAffinityScore(clusterManagerNodeArray *ipnodes,
|
||||
int ip_count, clusterManagerNode ***offending, int *offending_len)
|
||||
{
|
||||
int score = 0, i, j;
|
||||
int node_len = cluster_manager.nodes->len;
|
||||
clusterManagerNode **offending_p = NULL;
|
||||
if (offending != NULL) {
|
||||
*offending = (clusterManagerNode**)zcalloc(node_len * sizeof(clusterManagerNode*), MALLOC_LOCAL);
|
||||
offending_p = *offending;
|
||||
}
|
||||
/* For each set of nodes in the same host, split by
|
||||
* related nodes (masters and slaves which are involved in
|
||||
* replication of each other) */
|
||||
for (i = 0; i < ip_count; i++) {
|
||||
clusterManagerNodeArray *node_array = &(ipnodes[i]);
|
||||
dict *related = dictCreate(&clusterManagerDictType, NULL);
|
||||
char *ip = NULL;
|
||||
for (j = 0; j < node_array->len; j++) {
|
||||
clusterManagerNode *node = node_array->nodes[j];
|
||||
if (node == NULL) continue;
|
||||
if (!ip) ip = node->ip;
|
||||
sds types;
|
||||
/* We always use the Master ID as key. */
|
||||
sds key = (!node->replicate ? node->name : node->replicate);
|
||||
assert(key != NULL);
|
||||
dictEntry *entry = dictFind(related, key);
|
||||
if (entry) types = sdsdup((sds) dictGetVal(entry));
|
||||
else types = sdsempty();
|
||||
/* Master type 'm' is always set as the first character of the
|
||||
* types string. */
|
||||
if (!node->replicate) types = sdscatprintf(types, "m%s", types);
|
||||
else types = sdscat(types, "s");
|
||||
dictReplace(related, key, types);
|
||||
}
|
||||
/* Now it's trivial to check, for each related group having the
|
||||
* same host, what is their local score. */
|
||||
dictIterator *iter = dictGetIterator(related);
|
||||
dictEntry *entry;
|
||||
while ((entry = dictNext(iter)) != NULL) {
|
||||
sds types = (sds) dictGetVal(entry);
|
||||
sds name = (sds) dictGetKey(entry);
|
||||
int typeslen = sdslen(types);
|
||||
if (typeslen < 2) continue;
|
||||
if (types[0] == 'm') score += (10000 * (typeslen - 1));
|
||||
else score += (1 * typeslen);
|
||||
if (offending == NULL) continue;
|
||||
/* Populate the list of offending nodes. */
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
if (n->replicate == NULL) continue;
|
||||
if (!strcmp(n->replicate, name) && !strcmp(n->ip, ip)) {
|
||||
*(offending_p++) = n;
|
||||
if (offending_len != NULL) (*offending_len)++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//if (offending_len != NULL) *offending_len = offending_p - *offending;
|
||||
dictReleaseIterator(iter);
|
||||
dictRelease(related);
|
||||
}
|
||||
return score;
|
||||
}
|
||||
|
||||
|
||||
/* Wait until the cluster configuration is consistent. */
|
||||
extern "C" void clusterManagerWaitForClusterJoin(void) {
|
||||
printf("Waiting for the cluster to join\n");
|
||||
int counter = 0,
|
||||
check_after = CLUSTER_JOIN_CHECK_AFTER +
|
||||
(int)(listLength(cluster_manager.nodes) * 0.15f);
|
||||
while(!clusterManagerIsConfigConsistent()) {
|
||||
printf(".");
|
||||
fflush(stdout);
|
||||
sleep(1);
|
||||
if (++counter > check_after) {
|
||||
dict *status = clusterManagerGetLinkStatus();
|
||||
dictIterator *iter = NULL;
|
||||
if (status != NULL && dictSize(status) > 0) {
|
||||
printf("\n");
|
||||
clusterManagerLogErr("Warning: %d node(s) may "
|
||||
"be unreachable\n", dictSize(status));
|
||||
iter = dictGetIterator(status);
|
||||
dictEntry *entry;
|
||||
while ((entry = dictNext(iter)) != NULL) {
|
||||
sds nodeaddr = (sds) dictGetKey(entry);
|
||||
char *node_ip = NULL;
|
||||
int node_port = 0, node_bus_port = 0;
|
||||
list *from = (list *) dictGetVal(entry);
|
||||
if (parseClusterNodeAddress(nodeaddr, &node_ip,
|
||||
&node_port, &node_bus_port) && node_bus_port) {
|
||||
clusterManagerLogErr(" - The port %d of node %s may "
|
||||
"be unreachable from:\n",
|
||||
node_bus_port, node_ip);
|
||||
} else {
|
||||
clusterManagerLogErr(" - Node %s may be unreachable "
|
||||
"from:\n", nodeaddr);
|
||||
}
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(from, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sds from_addr = (sds)ln->value;
|
||||
clusterManagerLogErr(" %s\n", from_addr);
|
||||
sdsfree(from_addr);
|
||||
}
|
||||
clusterManagerLogErr("Cluster bus ports must be reachable "
|
||||
"by every node.\nRemember that "
|
||||
"cluster bus ports are different "
|
||||
"from standard instance ports.\n");
|
||||
listEmpty(from);
|
||||
}
|
||||
}
|
||||
if (iter != NULL) dictReleaseIterator(iter);
|
||||
if (status != NULL) dictRelease(status);
|
||||
counter = 0;
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
list *clusterManagerGetDisconnectedLinks(clusterManagerNode *node) {
|
||||
list *links = NULL;
|
||||
char *lines = NULL, *p, *line;
|
||||
redisReply *reply = (redisReply*)CLUSTER_MANAGER_COMMAND(node, "CLUSTER NODES");
|
||||
if (!clusterManagerCheckRedisReply(node, reply, NULL)) goto cleanup;
|
||||
links = listCreate();
|
||||
lines = reply->str;
|
||||
while ((p = strstr(lines, "\n")) != NULL) {
|
||||
int i = 0;
|
||||
*p = '\0';
|
||||
line = lines;
|
||||
lines = p + 1;
|
||||
char *nodename = NULL, *addr = NULL, *flags = NULL, *link_status = NULL;
|
||||
while ((p = strchr(line, ' ')) != NULL) {
|
||||
*p = '\0';
|
||||
char *token = line;
|
||||
line = p + 1;
|
||||
if (i == 0) nodename = token;
|
||||
else if (i == 1) addr = token;
|
||||
else if (i == 2) flags = token;
|
||||
else if (i == 7) link_status = token;
|
||||
else if (i == 8) break;
|
||||
i++;
|
||||
}
|
||||
if (i == 7) link_status = line;
|
||||
if (nodename == NULL || addr == NULL || flags == NULL ||
|
||||
link_status == NULL) continue;
|
||||
if (strstr(flags, "myself") != NULL) continue;
|
||||
int disconnected = ((strstr(flags, "disconnected") != NULL) ||
|
||||
(strstr(link_status, "disconnected")));
|
||||
int handshaking = (strstr(flags, "handshake") != NULL);
|
||||
if (disconnected || handshaking) {
|
||||
clusterManagerLink *link = (clusterManagerLink*)zmalloc(sizeof(*link), MALLOC_LOCAL);
|
||||
link->node_name = sdsnew(nodename);
|
||||
link->node_addr = sdsnew(addr);
|
||||
link->connected = 0;
|
||||
link->handshaking = handshaking;
|
||||
listAddNodeTail(links, link);
|
||||
}
|
||||
}
|
||||
cleanup:
|
||||
if (reply != NULL) freeReplyObject(reply);
|
||||
return links;
|
||||
}
|
||||
|
||||
/* Check for disconnected cluster links. It returns a dict whose keys
|
||||
* are the unreachable node addresses and the values are lists of
|
||||
* node addresses that cannot reach the unreachable node. */
|
||||
dict *clusterManagerGetLinkStatus(void) {
|
||||
if (cluster_manager.nodes == NULL) return NULL;
|
||||
dict *status = dictCreate(&clusterManagerLinkDictType, NULL);
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *node = (clusterManagerNode*)ln->value;
|
||||
list *links = clusterManagerGetDisconnectedLinks(node);
|
||||
if (links) {
|
||||
listIter lli;
|
||||
listNode *lln;
|
||||
listRewind(links, &lli);
|
||||
while ((lln = listNext(&lli)) != NULL) {
|
||||
clusterManagerLink *link = (clusterManagerLink*)lln->value;
|
||||
list *from = NULL;
|
||||
dictEntry *entry = dictFind(status, link->node_addr);
|
||||
if (entry) from = (list*)dictGetVal(entry);
|
||||
else {
|
||||
from = listCreate();
|
||||
dictAdd(status, sdsdup(link->node_addr), from);
|
||||
}
|
||||
sds myaddr = sdsempty();
|
||||
myaddr = sdscatfmt(myaddr, "%s:%u", node->ip, node->port);
|
||||
listAddNodeTail(from, myaddr);
|
||||
sdsfree(link->node_name);
|
||||
sdsfree(link->node_addr);
|
||||
zfree(link);
|
||||
}
|
||||
listRelease(links);
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
/* This function returns a random master node, return NULL if none */
|
||||
|
||||
static clusterManagerNode *clusterManagerNodeMasterRandom() {
|
||||
int master_count = 0;
|
||||
int idx;
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
if (n->flags & CLUSTER_MANAGER_FLAG_SLAVE) continue;
|
||||
master_count++;
|
||||
}
|
||||
|
||||
srand(time(NULL));
|
||||
idx = rand() % master_count;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
if (n->flags & CLUSTER_MANAGER_FLAG_SLAVE) continue;
|
||||
if (!idx--) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
/* Can not be reached */
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int clusterManagerFixSlotsCoverage(char *all_slots) {
|
||||
int i, fixed = 0;
|
||||
dictIterator *iter = nullptr;
|
||||
dictEntry *entry = nullptr;
|
||||
list *none = NULL, *single = NULL, *multi = NULL;
|
||||
clusterManagerLogInfo(">>> Fixing slots coverage...\n");
|
||||
printf("List of not covered slots: \n");
|
||||
int uncovered_count = 0;
|
||||
sds log = sdsempty();
|
||||
for (i = 0; i < CLUSTER_MANAGER_SLOTS; i++) {
|
||||
int covered = all_slots[i];
|
||||
if (!covered) {
|
||||
sds key = sdsfromlonglong((long long) i);
|
||||
if (uncovered_count++ > 0) printf(",");
|
||||
printf("%s", (char *) key);
|
||||
list *slot_nodes = listCreate();
|
||||
sds slot_nodes_str = sdsempty();
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
if (n->flags & CLUSTER_MANAGER_FLAG_SLAVE || n->replicate)
|
||||
continue;
|
||||
redisReply *reply = (redisReply*)CLUSTER_MANAGER_COMMAND(n,
|
||||
"CLUSTER GETKEYSINSLOT %d %d", i, 1);
|
||||
if (!clusterManagerCheckRedisReply(n, reply, NULL)) {
|
||||
fixed = -1;
|
||||
if (reply) freeReplyObject(reply);
|
||||
goto cleanup;
|
||||
}
|
||||
assert(reply->type == REDIS_REPLY_ARRAY);
|
||||
if (reply->elements > 0) {
|
||||
listAddNodeTail(slot_nodes, n);
|
||||
if (listLength(slot_nodes) > 1)
|
||||
slot_nodes_str = sdscat(slot_nodes_str, ", ");
|
||||
slot_nodes_str = sdscatfmt(slot_nodes_str,
|
||||
"%s:%u", n->ip, n->port);
|
||||
}
|
||||
freeReplyObject(reply);
|
||||
}
|
||||
log = sdscatfmt(log, "\nSlot %S has keys in %u nodes: %S",
|
||||
key, listLength(slot_nodes), slot_nodes_str);
|
||||
sdsfree(slot_nodes_str);
|
||||
dictAdd(clusterManagerUncoveredSlots, key, slot_nodes);
|
||||
}
|
||||
}
|
||||
printf("\n%s\n", log);
|
||||
/* For every slot, take action depending on the actual condition:
|
||||
* 1) No node has keys for this slot.
|
||||
* 2) A single node has keys for this slot.
|
||||
* 3) Multiple nodes have keys for this slot. */
|
||||
none = listCreate();
|
||||
single = listCreate();
|
||||
multi = listCreate();
|
||||
iter = dictGetIterator(clusterManagerUncoveredSlots);
|
||||
while ((entry = dictNext(iter)) != NULL) {
|
||||
sds slot = (sds) dictGetKey(entry);
|
||||
list *nodes = (list *) dictGetVal(entry);
|
||||
switch (listLength(nodes)){
|
||||
case 0: listAddNodeTail(none, slot); break;
|
||||
case 1: listAddNodeTail(single, slot); break;
|
||||
default: listAddNodeTail(multi, slot); break;
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(iter);
|
||||
|
||||
/* Handle case "1": keys in no node. */
|
||||
if (listLength(none) > 0) {
|
||||
printf("The following uncovered slots have no keys "
|
||||
"across the cluster:\n");
|
||||
clusterManagerPrintSlotsList(none);
|
||||
if (confirmWithYes("Fix these slots by covering with a random node?")){
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(none, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sds slot = (sds)ln->value;
|
||||
int s = atoi(slot);
|
||||
clusterManagerNode *n = clusterManagerNodeMasterRandom();
|
||||
clusterManagerLogInfo(">>> Covering slot %s with %s:%d\n",
|
||||
slot, n->ip, n->port);
|
||||
if (!clusterManagerSetSlotOwner(n, s, 0)) {
|
||||
fixed = -1;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Since CLUSTER ADDSLOTS succeeded, we also update the slot
|
||||
* info into the node struct, in order to keep it synced */
|
||||
n->slots[s] = 1;
|
||||
fixed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Handle case "2": keys only in one node. */
|
||||
if (listLength(single) > 0) {
|
||||
printf("The following uncovered slots have keys in just one node:\n");
|
||||
clusterManagerPrintSlotsList(single);
|
||||
if (confirmWithYes("Fix these slots by covering with those nodes?")){
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(single, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sds slot = (sds)ln->value;
|
||||
int s = atoi(slot);
|
||||
dictEntry *entry = dictFind(clusterManagerUncoveredSlots, slot);
|
||||
assert(entry != NULL);
|
||||
list *nodes = (list *) dictGetVal(entry);
|
||||
listNode *fn = listFirst(nodes);
|
||||
assert(fn != NULL);
|
||||
clusterManagerNode *n = (clusterManagerNode*)fn->value;
|
||||
clusterManagerLogInfo(">>> Covering slot %s with %s:%d\n",
|
||||
slot, n->ip, n->port);
|
||||
if (!clusterManagerSetSlotOwner(n, s, 0)) {
|
||||
fixed = -1;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Since CLUSTER ADDSLOTS succeeded, we also update the slot
|
||||
* info into the node struct, in order to keep it synced */
|
||||
n->slots[atoi(slot)] = 1;
|
||||
fixed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Handle case "3": keys in multiple nodes. */
|
||||
if (listLength(multi) > 0) {
|
||||
printf("The following uncovered slots have keys in multiple nodes:\n");
|
||||
clusterManagerPrintSlotsList(multi);
|
||||
if (confirmWithYes("Fix these slots by moving keys "
|
||||
"into a single node?")) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(multi, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sds slot = (sds)ln->value;
|
||||
dictEntry *entry = dictFind(clusterManagerUncoveredSlots, slot);
|
||||
assert(entry != NULL);
|
||||
list *nodes = (list *) dictGetVal(entry);
|
||||
int s = atoi(slot);
|
||||
clusterManagerNode *target =
|
||||
clusterManagerGetNodeWithMostKeysInSlot(nodes, s, NULL);
|
||||
if (target == NULL) {
|
||||
fixed = -1;
|
||||
goto cleanup;
|
||||
}
|
||||
clusterManagerLogInfo(">>> Covering slot %s moving keys "
|
||||
"to %s:%d\n", slot,
|
||||
target->ip, target->port);
|
||||
if (!clusterManagerSetSlotOwner(target, s, 1)) {
|
||||
fixed = -1;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Since CLUSTER ADDSLOTS succeeded, we also update the slot
|
||||
* info into the node struct, in order to keep it synced */
|
||||
target->slots[atoi(slot)] = 1;
|
||||
listIter nli;
|
||||
listNode *nln;
|
||||
listRewind(nodes, &nli);
|
||||
while ((nln = listNext(&nli)) != NULL) {
|
||||
clusterManagerNode *src = (clusterManagerNode*)nln->value;
|
||||
if (src == target) continue;
|
||||
/* Assign the slot to target node in the source node. */
|
||||
if (!clusterManagerSetSlot(src, target, s, "NODE", NULL))
|
||||
fixed = -1;
|
||||
if (fixed < 0) goto cleanup;
|
||||
/* Set the source node in 'importing' state
|
||||
* (even if we will actually migrate keys away)
|
||||
* in order to avoid receiving redirections
|
||||
* for MIGRATE. */
|
||||
if (!clusterManagerSetSlot(src, target, s,
|
||||
"IMPORTING", NULL)) fixed = -1;
|
||||
if (fixed < 0) goto cleanup;
|
||||
int opts = CLUSTER_MANAGER_OPT_VERBOSE |
|
||||
CLUSTER_MANAGER_OPT_COLD;
|
||||
if (!clusterManagerMoveSlot(src, target, s, opts, NULL)) {
|
||||
fixed = -1;
|
||||
goto cleanup;
|
||||
}
|
||||
if (!clusterManagerClearSlotStatus(src, s))
|
||||
fixed = -1;
|
||||
if (fixed < 0) goto cleanup;
|
||||
}
|
||||
fixed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
cleanup:
|
||||
sdsfree(log);
|
||||
if (none) listRelease(none);
|
||||
if (single) listRelease(single);
|
||||
if (multi) listRelease(multi);
|
||||
return fixed;
|
||||
}
|
||||
|
||||
|
||||
extern "C" int clusterManagerCheckCluster(int quiet) {
|
||||
listNode *ln = listFirst(cluster_manager.nodes);
|
||||
if (!ln) return 0;
|
||||
clusterManagerNode *node = (clusterManagerNode*)ln->value;
|
||||
clusterManagerLogInfo(">>> Performing Cluster Check (using node %s:%d)\n",
|
||||
node->ip, node->port);
|
||||
int result = 1, consistent = 0;
|
||||
int do_fix = config.cluster_manager_command.flags &
|
||||
CLUSTER_MANAGER_CMD_FLAG_FIX;
|
||||
if (!quiet) clusterManagerShowNodes();
|
||||
consistent = clusterManagerIsConfigConsistent();
|
||||
if (!consistent) {
|
||||
sds err = sdsnew("[ERR] Nodes don't agree about configuration!");
|
||||
clusterManagerOnError(err);
|
||||
result = 0;
|
||||
} else {
|
||||
clusterManagerLogOk("[OK] All nodes agree about slots "
|
||||
"configuration.\n");
|
||||
}
|
||||
/* Check open slots */
|
||||
clusterManagerLogInfo(">>> Check for open slots...\n");
|
||||
listIter li;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
int i;
|
||||
dict *open_slots = NULL;
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
if (n->migrating != NULL) {
|
||||
if (open_slots == NULL)
|
||||
open_slots = dictCreate(&clusterManagerDictType, NULL);
|
||||
sds errstr = sdsempty();
|
||||
errstr = sdscatprintf(errstr,
|
||||
"[WARNING] Node %s:%d has slots in "
|
||||
"migrating state ",
|
||||
n->ip,
|
||||
n->port);
|
||||
for (i = 0; i < n->migrating_count; i += 2) {
|
||||
sds slot = n->migrating[i];
|
||||
dictReplace(open_slots, slot, sdsdup(n->migrating[i + 1]));
|
||||
const char *fmt = (i > 0 ? ",%S" : "%S");
|
||||
errstr = sdscatfmt(errstr, fmt, slot);
|
||||
}
|
||||
errstr = sdscat(errstr, ".");
|
||||
clusterManagerOnError(errstr);
|
||||
}
|
||||
if (n->importing != NULL) {
|
||||
if (open_slots == NULL)
|
||||
open_slots = dictCreate(&clusterManagerDictType, NULL);
|
||||
sds errstr = sdsempty();
|
||||
errstr = sdscatprintf(errstr,
|
||||
"[WARNING] Node %s:%d has slots in "
|
||||
"importing state ",
|
||||
n->ip,
|
||||
n->port);
|
||||
for (i = 0; i < n->importing_count; i += 2) {
|
||||
sds slot = n->importing[i];
|
||||
dictReplace(open_slots, slot, sdsdup(n->importing[i + 1]));
|
||||
const char *fmt = (i > 0 ? ",%S" : "%S");
|
||||
errstr = sdscatfmt(errstr, fmt, slot);
|
||||
}
|
||||
errstr = sdscat(errstr, ".");
|
||||
clusterManagerOnError(errstr);
|
||||
}
|
||||
}
|
||||
if (open_slots != NULL) {
|
||||
result = 0;
|
||||
dictIterator *iter = dictGetIterator(open_slots);
|
||||
dictEntry *entry;
|
||||
sds errstr = sdsnew("[WARNING] The following slots are open: ");
|
||||
i = 0;
|
||||
while ((entry = dictNext(iter)) != NULL) {
|
||||
sds slot = (sds) dictGetKey(entry);
|
||||
const char *fmt = (i++ > 0 ? ",%S" : "%S");
|
||||
errstr = sdscatfmt(errstr, fmt, slot);
|
||||
}
|
||||
clusterManagerLogErr("%s.\n", (char *) errstr);
|
||||
sdsfree(errstr);
|
||||
if (do_fix) {
|
||||
/* Fix open slots. */
|
||||
dictReleaseIterator(iter);
|
||||
iter = dictGetIterator(open_slots);
|
||||
while ((entry = dictNext(iter)) != NULL) {
|
||||
sds slot = (sds) dictGetKey(entry);
|
||||
result = clusterManagerFixOpenSlot(atoi(slot));
|
||||
if (!result) break;
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(iter);
|
||||
dictRelease(open_slots);
|
||||
}
|
||||
clusterManagerLogInfo(">>> Check slots coverage...\n");
|
||||
char slots[CLUSTER_MANAGER_SLOTS];
|
||||
memset(slots, 0, CLUSTER_MANAGER_SLOTS);
|
||||
int coverage = clusterManagerGetCoveredSlots(slots);
|
||||
if (coverage == CLUSTER_MANAGER_SLOTS) {
|
||||
clusterManagerLogOk("[OK] All %d slots covered.\n",
|
||||
CLUSTER_MANAGER_SLOTS);
|
||||
} else {
|
||||
sds err = sdsempty();
|
||||
err = sdscatprintf(err, "[ERR] Not all %d slots are "
|
||||
"covered by nodes.\n",
|
||||
CLUSTER_MANAGER_SLOTS);
|
||||
clusterManagerOnError(err);
|
||||
result = 0;
|
||||
if (do_fix/* && result*/) {
|
||||
dictType dtype = clusterManagerDictType;
|
||||
dtype.keyDestructor = dictSdsDestructor;
|
||||
dtype.valDestructor = dictListDestructor;
|
||||
clusterManagerUncoveredSlots = dictCreate(&dtype, NULL);
|
||||
int fixed = clusterManagerFixSlotsCoverage(slots);
|
||||
if (fixed > 0) result = 1;
|
||||
}
|
||||
}
|
||||
int search_multiple_owners = config.cluster_manager_command.flags &
|
||||
CLUSTER_MANAGER_CMD_FLAG_CHECK_OWNERS;
|
||||
if (search_multiple_owners) {
|
||||
/* Check whether there are multiple owners, even when slots are
|
||||
* fully covered and there are no open slots. */
|
||||
clusterManagerLogInfo(">>> Check for multiple slot owners...\n");
|
||||
int slot = 0, slots_with_multiple_owners = 0;
|
||||
for (; slot < CLUSTER_MANAGER_SLOTS; slot++) {
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(cluster_manager.nodes, &li);
|
||||
list *owners = listCreate();
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
if (n->flags & CLUSTER_MANAGER_FLAG_SLAVE) continue;
|
||||
if (n->slots[slot]) listAddNodeTail(owners, n);
|
||||
else {
|
||||
/* Nodes having keys for the slot will be considered
|
||||
* owners too. */
|
||||
int count = clusterManagerCountKeysInSlot(n, slot);
|
||||
if (count > 0) listAddNodeTail(owners, n);
|
||||
}
|
||||
}
|
||||
if (listLength(owners) > 1) {
|
||||
result = 0;
|
||||
clusterManagerLogErr("[WARNING] Slot %d has %d owners:\n",
|
||||
slot, listLength(owners));
|
||||
listRewind(owners, &li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
clusterManagerNode *n = (clusterManagerNode*)ln->value;
|
||||
clusterManagerLogErr(" %s:%d\n", n->ip, n->port);
|
||||
}
|
||||
slots_with_multiple_owners++;
|
||||
if (do_fix) {
|
||||
result = clusterManagerFixMultipleSlotOwners(slot, owners);
|
||||
if (!result) {
|
||||
clusterManagerLogErr("Failed to fix multiple owners "
|
||||
"for slot %d\n", slot);
|
||||
listRelease(owners);
|
||||
break;
|
||||
} else slots_with_multiple_owners--;
|
||||
}
|
||||
}
|
||||
listRelease(owners);
|
||||
}
|
||||
if (slots_with_multiple_owners == 0)
|
||||
clusterManagerLogOk("[OK] No multiple owners found.\n");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static typeinfo* typeinfo_add(dict *types, const char* name, typeinfo* type_template) {
|
||||
typeinfo *info = (typeinfo*)zmalloc(sizeof(typeinfo), MALLOC_LOCAL);
|
||||
*info = *type_template;
|
||||
info->name = sdsnew(name);
|
||||
dictAdd(types, info->name, info);
|
||||
return info;
|
||||
}
|
||||
|
||||
static dictType typeinfoDictType = {
|
||||
dictSdsHash, /* hash function */
|
||||
NULL, /* key dup */
|
||||
NULL, /* val dup */
|
||||
dictSdsKeyCompare, /* key compare */
|
||||
NULL, /* key destructor (owned by the value)*/
|
||||
type_free /* val destructor */
|
||||
};
|
||||
|
||||
static void getKeyTypes(dict *types_dict, redisReply *keys, typeinfo **types) {
|
||||
redisReply *reply;
|
||||
unsigned int i;
|
||||
|
||||
/* Pipeline TYPE commands */
|
||||
for(i=0;i<keys->elements;i++) {
|
||||
redisAppendCommand(context, "TYPE %s", keys->element[i]->str);
|
||||
}
|
||||
|
||||
/* Retrieve types */
|
||||
for(i=0;i<keys->elements;i++) {
|
||||
if(redisGetReply(context, (void**)&reply)!=REDIS_OK) {
|
||||
fprintf(stderr, "Error getting type for key '%s' (%d: %s)\n",
|
||||
keys->element[i]->str, context->err, context->errstr);
|
||||
exit(1);
|
||||
} else if(reply->type != REDIS_REPLY_STATUS) {
|
||||
if(reply->type == REDIS_REPLY_ERROR) {
|
||||
fprintf(stderr, "TYPE returned an error: %s\n", reply->str);
|
||||
} else {
|
||||
fprintf(stderr,
|
||||
"Invalid reply type (%d) for TYPE on key '%s'!\n",
|
||||
reply->type, keys->element[i]->str);
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
sds typereply = sdsnew(reply->str);
|
||||
dictEntry *de = dictFind(types_dict, typereply);
|
||||
sdsfree(typereply);
|
||||
typeinfo *type = NULL;
|
||||
if (de)
|
||||
type = (typeinfo*)dictGetVal(de);
|
||||
else if (strcmp(reply->str, "none")) /* create new types for modules, (but not for deleted keys) */
|
||||
type = typeinfo_add(types_dict, reply->str, &type_other);
|
||||
types[i] = type;
|
||||
freeReplyObject(reply);
|
||||
}
|
||||
}
|
||||
|
||||
void findBigKeys(int memkeys, unsigned memkeys_samples) {
|
||||
unsigned long long sampled = 0, total_keys, totlen=0, *sizes=NULL, it=0;
|
||||
redisReply *reply, *keys;
|
||||
unsigned int arrsize=0, i;
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
typeinfo **types = NULL;
|
||||
double pct;
|
||||
|
||||
dict *types_dict = dictCreate(&typeinfoDictType, NULL);
|
||||
typeinfo_add(types_dict, "string", &type_string);
|
||||
typeinfo_add(types_dict, "list", &type_list);
|
||||
typeinfo_add(types_dict, "set", &type_set);
|
||||
typeinfo_add(types_dict, "hash", &type_hash);
|
||||
typeinfo_add(types_dict, "zset", &type_zset);
|
||||
typeinfo_add(types_dict, "stream", &type_stream);
|
||||
|
||||
/* Total keys pre scanning */
|
||||
total_keys = getDbSize();
|
||||
|
||||
/* Status message */
|
||||
printf("\n# Scanning the entire keyspace to find biggest keys as well as\n");
|
||||
printf("# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec\n");
|
||||
printf("# per 100 SCAN commands (not usually needed).\n\n");
|
||||
|
||||
/* SCAN loop */
|
||||
do {
|
||||
/* Calculate approximate percentage completion */
|
||||
pct = 100 * (double)sampled/total_keys;
|
||||
|
||||
/* Grab some keys and point to the keys array */
|
||||
reply = sendScan(&it);
|
||||
keys = reply->element[1];
|
||||
|
||||
/* Reallocate our type and size array if we need to */
|
||||
if(keys->elements > arrsize) {
|
||||
types = (typeinfo**)zrealloc(types, sizeof(int)*keys->elements, MALLOC_LOCAL);
|
||||
sizes = (unsigned long long*)zrealloc(sizes, sizeof(unsigned long long)*keys->elements, MALLOC_LOCAL);
|
||||
|
||||
if(!types || !sizes) {
|
||||
fprintf(stderr, "Failed to allocate storage for keys!\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
arrsize = keys->elements;
|
||||
}
|
||||
|
||||
/* Retrieve types and then sizes */
|
||||
getKeyTypes(types_dict, keys, types);
|
||||
getKeySizes(keys, types, sizes, memkeys, memkeys_samples);
|
||||
|
||||
/* Now update our stats */
|
||||
for(i=0;i<keys->elements;i++) {
|
||||
typeinfo *type = types[i];
|
||||
/* Skip keys that disappeared between SCAN and TYPE */
|
||||
if(!type)
|
||||
continue;
|
||||
|
||||
type->totalsize += sizes[i];
|
||||
type->count++;
|
||||
totlen += keys->element[i]->len;
|
||||
sampled++;
|
||||
|
||||
if(type->biggest<sizes[i]) {
|
||||
printf(
|
||||
"[%05.2f%%] Biggest %-6s found so far '%s' with %llu %s\n",
|
||||
pct, type->name, keys->element[i]->str, sizes[i],
|
||||
!memkeys? type->sizeunit: "bytes");
|
||||
|
||||
/* Keep track of biggest key name for this type */
|
||||
if (type->biggest_key)
|
||||
sdsfree(type->biggest_key);
|
||||
type->biggest_key = sdsnew(keys->element[i]->str);
|
||||
if(!type->biggest_key) {
|
||||
fprintf(stderr, "Failed to allocate memory for key!\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* Keep track of the biggest size for this type */
|
||||
type->biggest = sizes[i];
|
||||
}
|
||||
|
||||
/* Update overall progress */
|
||||
if(sampled % 1000000 == 0) {
|
||||
printf("[%05.2f%%] Sampled %llu keys so far\n", pct, sampled);
|
||||
}
|
||||
}
|
||||
|
||||
/* Sleep if we've been directed to do so */
|
||||
if(sampled && (sampled %100) == 0 && config.interval) {
|
||||
usleep(config.interval);
|
||||
}
|
||||
|
||||
freeReplyObject(reply);
|
||||
} while(it != 0);
|
||||
|
||||
if(types) zfree(types);
|
||||
if(sizes) zfree(sizes);
|
||||
|
||||
/* We're done */
|
||||
printf("\n-------- summary -------\n\n");
|
||||
|
||||
printf("Sampled %llu keys in the keyspace!\n", sampled);
|
||||
printf("Total key length in bytes is %llu (avg len %.2f)\n\n",
|
||||
totlen, totlen ? (double)totlen/sampled : 0);
|
||||
|
||||
/* Output the biggest keys we found, for types we did find */
|
||||
di = dictGetIterator(types_dict);
|
||||
while ((de = dictNext(di))) {
|
||||
typeinfo *type = (typeinfo*)dictGetVal(de);
|
||||
if(type->biggest_key) {
|
||||
printf("Biggest %6s found '%s' has %llu %s\n", type->name, type->biggest_key,
|
||||
type->biggest, !memkeys? type->sizeunit: "bytes");
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
printf("\n");
|
||||
|
||||
di = dictGetIterator(types_dict);
|
||||
while ((de = dictNext(di))) {
|
||||
typeinfo *type = (typeinfo*)dictGetVal(de);
|
||||
printf("%llu %ss with %llu %s (%05.2f%% of keys, avg size %.2f)\n",
|
||||
type->count, type->name, type->totalsize, !memkeys? type->sizeunit: "bytes",
|
||||
sampled ? 100 * (double)type->count/sampled : 0,
|
||||
type->count ? (double)type->totalsize/type->count : 0);
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
dictRelease(types_dict);
|
||||
|
||||
/* Success! */
|
||||
exit(0);
|
||||
}
|
||||
+172
-1152
File diff suppressed because it is too large.
Load diff
+280
@@ -0,0 +1,280 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define UNUSED(V) ((void) V)
|
||||
|
||||
#define OUTPUT_STANDARD 0
|
||||
#define OUTPUT_RAW 1
|
||||
#define OUTPUT_CSV 2
|
||||
#define REDIS_CLI_KEEPALIVE_INTERVAL 15 /* seconds */
|
||||
#define REDIS_CLI_DEFAULT_PIPE_TIMEOUT 30 /* seconds */
|
||||
#define REDIS_CLI_HISTFILE_ENV "REDISCLI_HISTFILE"
|
||||
#define REDIS_CLI_HISTFILE_DEFAULT ".rediscli_history"
|
||||
#define REDIS_CLI_RCFILE_ENV "REDISCLI_RCFILE"
|
||||
#define REDIS_CLI_RCFILE_DEFAULT ".redisclirc"
|
||||
#define REDIS_CLI_AUTH_ENV "REDISCLI_AUTH"
|
||||
|
||||
#define CLUSTER_MANAGER_SLOTS 16384
|
||||
#define CLUSTER_MANAGER_MIGRATE_TIMEOUT 60000
|
||||
#define CLUSTER_MANAGER_MIGRATE_PIPELINE 10
|
||||
#define CLUSTER_MANAGER_REBALANCE_THRESHOLD 2
|
||||
|
||||
#define CLUSTER_MANAGER_INVALID_HOST_ARG \
|
||||
"[ERR] Invalid arguments: you need to pass either a valid " \
|
||||
"address (ie. 120.0.0.1:7000) or space separated IP " \
|
||||
"and port (ie. 120.0.0.1 7000)\n"
|
||||
#define CLUSTER_MANAGER_MODE() (config.cluster_manager_command.name != NULL)
|
||||
#define CLUSTER_MANAGER_MASTERS_COUNT(nodes, replicas) (nodes/(replicas + 1))
|
||||
#define CLUSTER_MANAGER_COMMAND(n,...) \
|
||||
(redisCommand(n->context, __VA_ARGS__))
|
||||
|
||||
#define CLUSTER_MANAGER_NODE_ARRAY_FREE(array) zfree(array->alloc)
|
||||
|
||||
#define CLUSTER_MANAGER_PRINT_REPLY_ERROR(n, err) \
|
||||
clusterManagerLogErr("Node %s:%d replied with error:\n%s\n", \
|
||||
n->ip, n->port, err);
|
||||
|
||||
#define clusterManagerLogInfo(...) \
|
||||
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_INFO,__VA_ARGS__)
|
||||
|
||||
#define clusterManagerLogErr(...) \
|
||||
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_ERR,__VA_ARGS__)
|
||||
|
||||
#define clusterManagerLogWarn(...) \
|
||||
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_WARN,__VA_ARGS__)
|
||||
|
||||
#define clusterManagerLogOk(...) \
|
||||
clusterManagerLog(CLUSTER_MANAGER_LOG_LVL_SUCCESS,__VA_ARGS__)
|
||||
|
||||
#define CLUSTER_MANAGER_FLAG_MYSELF 1 << 0
|
||||
#define CLUSTER_MANAGER_FLAG_SLAVE 1 << 1
|
||||
#define CLUSTER_MANAGER_FLAG_FRIEND 1 << 2
|
||||
#define CLUSTER_MANAGER_FLAG_NOADDR 1 << 3
|
||||
#define CLUSTER_MANAGER_FLAG_DISCONNECT 1 << 4
|
||||
#define CLUSTER_MANAGER_FLAG_FAIL 1 << 5
|
||||
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_FIX 1 << 0
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_SLAVE 1 << 1
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_YES 1 << 2
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_AUTOWEIGHTS 1 << 3
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_EMPTYMASTER 1 << 4
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_SIMULATE 1 << 5
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_REPLACE 1 << 6
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_COPY 1 << 7
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_COLOR 1 << 8
|
||||
#define CLUSTER_MANAGER_CMD_FLAG_CHECK_OWNERS 1 << 9
|
||||
|
||||
#define CLUSTER_MANAGER_OPT_GETFRIENDS 1 << 0
|
||||
#define CLUSTER_MANAGER_OPT_COLD 1 << 1
|
||||
#define CLUSTER_MANAGER_OPT_UPDATE 1 << 2
|
||||
#define CLUSTER_MANAGER_OPT_QUIET 1 << 6
|
||||
#define CLUSTER_MANAGER_OPT_VERBOSE 1 << 7
|
||||
|
||||
#define CLUSTER_MANAGER_LOG_LVL_INFO 1
|
||||
#define CLUSTER_MANAGER_LOG_LVL_WARN 2
|
||||
#define CLUSTER_MANAGER_LOG_LVL_ERR 3
|
||||
#define CLUSTER_MANAGER_LOG_LVL_SUCCESS 4
|
||||
|
||||
#define CLUSTER_JOIN_CHECK_AFTER 20
|
||||
|
||||
#define LOG_COLOR_BOLD "29;1m"
|
||||
#define LOG_COLOR_RED "31;1m"
|
||||
#define LOG_COLOR_GREEN "32;1m"
|
||||
#define LOG_COLOR_YELLOW "33;1m"
|
||||
#define LOG_COLOR_RESET "0m"
|
||||
|
||||
/* cliConnect() flags. */
|
||||
#define CC_FORCE (1<<0) /* Re-connect if already connected. */
|
||||
#define CC_QUIET (1<<1) /* Don't log connecting errors. */
|
||||
|
||||
struct clusterManagerLink;
|
||||
typedef struct clusterManagerLink clusterManagerLink;
|
||||
|
||||
/* Dict Helpers */
|
||||
|
||||
uint64_t dictSdsHash(const void *key);
|
||||
int dictSdsKeyCompare(void *privdata, const void *key1,
|
||||
const void *key2);
|
||||
void dictSdsDestructor(void *privdata, void *val);
|
||||
void dictListDestructor(void *privdata, void *val);
|
||||
|
||||
/* Cluster Manager Command Info */
|
||||
typedef struct clusterManagerCommand {
|
||||
char *name;
|
||||
int argc;
|
||||
char **argv;
|
||||
int flags;
|
||||
int replicas;
|
||||
char *from;
|
||||
char *to;
|
||||
char **weight;
|
||||
int weight_argc;
|
||||
char *master_id;
|
||||
int slots;
|
||||
int timeout;
|
||||
int pipeline;
|
||||
float threshold;
|
||||
char *backup_dir;
|
||||
} clusterManagerCommand;
|
||||
|
||||
void createClusterManagerCommand(char *cmdname, int argc, char **argv);
|
||||
|
||||
extern redisContext *context;
|
||||
extern struct config {
|
||||
char *hostip;
|
||||
int hostport;
|
||||
char *hostsocket;
|
||||
long repeat;
|
||||
long interval;
|
||||
int dbnum;
|
||||
int interactive;
|
||||
int shutdown;
|
||||
int monitor_mode;
|
||||
int pubsub_mode;
|
||||
int latency_mode;
|
||||
int latency_dist_mode;
|
||||
int latency_history;
|
||||
int lru_test_mode;
|
||||
long long lru_test_sample_size;
|
||||
int cluster_mode;
|
||||
int cluster_reissue_command;
|
||||
int slave_mode;
|
||||
int pipe_mode;
|
||||
int pipe_timeout;
|
||||
int getrdb_mode;
|
||||
int stat_mode;
|
||||
int scan_mode;
|
||||
int intrinsic_latency_mode;
|
||||
int intrinsic_latency_duration;
|
||||
char *pattern;
|
||||
char *rdb_filename;
|
||||
int bigkeys;
|
||||
int memkeys;
|
||||
unsigned memkeys_samples;
|
||||
int hotkeys;
|
||||
int stdinarg; /* get last arg from stdin. (-x option) */
|
||||
char *auth;
|
||||
int output; /* output mode, see OUTPUT_* defines */
|
||||
sds mb_delim;
|
||||
char prompt[128];
|
||||
char *eval;
|
||||
int eval_ldb;
|
||||
int eval_ldb_sync; /* Ask for synchronous mode of the Lua debugger. */
|
||||
int eval_ldb_end; /* Lua debugging session ended. */
|
||||
int enable_ldb_on_eval; /* Handle manual SCRIPT DEBUG + EVAL commands. */
|
||||
int last_cmd_type;
|
||||
int verbose;
|
||||
clusterManagerCommand cluster_manager_command;
|
||||
int no_auth_warning;
|
||||
} config;
|
||||
|
||||
/* The Cluster Manager global structure */
|
||||
extern struct clusterManager {
|
||||
list *nodes; /* List of nodes in the configuration. */
|
||||
list *errors;
|
||||
} cluster_manager;
|
||||
|
||||
typedef struct clusterManagerNode {
|
||||
redisContext *context;
|
||||
sds name;
|
||||
char *ip;
|
||||
int port;
|
||||
uint64_t current_epoch;
|
||||
time_t ping_sent;
|
||||
time_t ping_recv;
|
||||
int flags;
|
||||
list *flags_str; /* Flags string representations */
|
||||
sds replicate; /* Master ID if node is a replica */
|
||||
int dirty; /* Node has changes that can be flushed */
|
||||
uint8_t slots[CLUSTER_MANAGER_SLOTS];
|
||||
int slots_count;
|
||||
int replicas_count;
|
||||
list *friends;
|
||||
sds *migrating; /* An array of sds where even strings are slots and odd
|
||||
* strings are the destination node IDs. */
|
||||
sds *importing; /* An array of sds where even strings are slots and odd
|
||||
* strings are the source node IDs. */
|
||||
int migrating_count; /* Length of the migrating array (migrating slots*2) */
|
||||
int importing_count; /* Length of the importing array (importing slots*2) */
|
||||
float weight; /* Weight used by rebalance */
|
||||
int balance; /* Used by rebalance */
|
||||
} clusterManagerNode;
|
||||
|
||||
/* Data structure used to represent a sequence of cluster nodes. */
|
||||
typedef struct clusterManagerNodeArray {
|
||||
clusterManagerNode **nodes; /* Actual nodes array */
|
||||
clusterManagerNode **alloc; /* Pointer to the allocated memory */
|
||||
int len; /* Actual length of the array */
|
||||
int count; /* Non-NULL nodes count */
|
||||
} clusterManagerNodeArray;
|
||||
|
||||
/* Used for the reshard table. */
|
||||
typedef struct clusterManagerReshardTableItem {
|
||||
clusterManagerNode *source;
|
||||
int slot;
|
||||
} clusterManagerReshardTableItem;
|
||||
|
||||
typedef struct typeinfo {
|
||||
char *name;
|
||||
char *sizecmd;
|
||||
char *sizeunit;
|
||||
unsigned long long biggest;
|
||||
unsigned long long count;
|
||||
unsigned long long totalsize;
|
||||
sds biggest_key;
|
||||
} typeinfo;
|
||||
|
||||
extern typeinfo type_string;
|
||||
extern typeinfo type_list;
|
||||
extern typeinfo type_set;
|
||||
extern typeinfo type_hash;
|
||||
extern typeinfo type_zset;
|
||||
extern typeinfo type_stream;
|
||||
extern typeinfo type_other;
|
||||
|
||||
void findBigKeys(int memkeys, unsigned memkeys_samples);
|
||||
int clusterManagerGetAntiAffinityScore(clusterManagerNodeArray *ipnodes,
|
||||
int ip_count, clusterManagerNode ***offending, int *offending_len);
|
||||
int clusterManagerFixMultipleSlotOwners(int slot, list *owners);
|
||||
void getKeySizes(redisReply *keys, struct typeinfo **types,
|
||||
unsigned long long *sizes, int memkeys,
|
||||
unsigned memkeys_samples);
|
||||
int clusterManagerFixOpenSlot(int slot);
|
||||
void clusterManagerPrintSlotsList(list *slots);
|
||||
int clusterManagerGetCoveredSlots(char *all_slots);
|
||||
void clusterManagerOnError(sds err);
|
||||
int clusterManagerIsConfigConsistent(void);
|
||||
void freeClusterManagerNode(clusterManagerNode *node);
|
||||
void clusterManagerLog(int level, const char* fmt, ...);
|
||||
int parseClusterNodeAddress(char *addr, char **ip_ptr, int *port_ptr,
|
||||
int *bus_port_ptr);
|
||||
int clusterManagerCheckRedisReply(clusterManagerNode *n,
|
||||
redisReply *r, char **err);
|
||||
int confirmWithYes(const char *msg);
|
||||
int clusterManagerSetSlotOwner(clusterManagerNode *owner,
|
||||
int slot,
|
||||
int do_clear);
|
||||
clusterManagerNode * clusterManagerGetNodeWithMostKeysInSlot(list *nodes,
|
||||
int slot,
|
||||
char **err);
|
||||
int clusterManagerSetSlot(clusterManagerNode *node1,
|
||||
clusterManagerNode *node2,
|
||||
int slot, const char *status, char **err);
|
||||
int clusterManagerMoveSlot(clusterManagerNode *source,
|
||||
clusterManagerNode *target,
|
||||
int slot, int opts, char**err);
|
||||
int clusterManagerClearSlotStatus(clusterManagerNode *node, int slot);
|
||||
void clusterManagerShowNodes(void);
|
||||
signed int clusterManagerCountKeysInSlot(clusterManagerNode *node,
|
||||
int slot);
|
||||
void type_free(void* priv_data, void* val);
|
||||
int getDbSize(void);
|
||||
redisReply *sendScan(unsigned long long *it);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+9
-1
@@ -40,10 +40,18 @@
|
||||
|
||||
#include <unistd.h> /* for _exit() */
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define assert(_e) ((_e)?(void)0 : (_serverAssert(#_e,__FILE__,__LINE__),_exit(1)))
|
||||
#define panic(...) _serverPanic(__FILE__,__LINE__,__VA_ARGS__),_exit(1)
|
||||
|
||||
void _serverAssert(char *estr, char *file, int line);
|
||||
void _serverAssert(const char *estr, const char *file, int line);
|
||||
void _serverPanic(const char *file, int line, const char *msg, ...);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+39
-3
@@ -5,6 +5,10 @@
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* ---------------- Defines common between core and modules --------------- */
|
||||
|
||||
/* Error status return values. */
|
||||
@@ -67,9 +71,9 @@
|
||||
#define REDISMODULE_CTX_FLAGS_MULTI (1<<1)
|
||||
/* The instance is a master */
|
||||
#define REDISMODULE_CTX_FLAGS_MASTER (1<<2)
|
||||
/* The instance is a slave */
|
||||
/* The instance is a replica */
|
||||
#define REDISMODULE_CTX_FLAGS_SLAVE (1<<3)
|
||||
/* The instance is read-only (usually meaning it's a slave as well) */
|
||||
/* The instance is read-only (usually meaning it's a replica as well) */
|
||||
#define REDISMODULE_CTX_FLAGS_READONLY (1<<4)
|
||||
/* The instance is running in cluster mode */
|
||||
#define REDISMODULE_CTX_FLAGS_CLUSTER (1<<5)
|
||||
@@ -87,6 +91,8 @@
|
||||
#define REDISMODULE_CTX_FLAGS_OOM_WARNING (1<<11)
|
||||
/* The command was sent over the replication link. */
|
||||
#define REDISMODULE_CTX_FLAGS_REPLICATED (1<<12)
|
||||
/* Redis is currently loading either from AOF or RDB. */
|
||||
#define REDISMODULE_CTX_FLAGS_LOADING (1<<13)
|
||||
|
||||
|
||||
#define REDISMODULE_NOTIFY_GENERIC (1<<2) /* g */
|
||||
@@ -98,7 +104,8 @@
|
||||
#define REDISMODULE_NOTIFY_EXPIRED (1<<8) /* x */
|
||||
#define REDISMODULE_NOTIFY_EVICTED (1<<9) /* e */
|
||||
#define REDISMODULE_NOTIFY_STREAM (1<<10) /* t */
|
||||
#define REDISMODULE_NOTIFY_ALL (REDISMODULE_NOTIFY_GENERIC | REDISMODULE_NOTIFY_STRING | REDISMODULE_NOTIFY_LIST | REDISMODULE_NOTIFY_SET | REDISMODULE_NOTIFY_HASH | REDISMODULE_NOTIFY_ZSET | REDISMODULE_NOTIFY_EXPIRED | REDISMODULE_NOTIFY_EVICTED | REDISMODULE_NOTIFY_STREAM) /* A */
|
||||
#define REDISMODULE_NOTIFY_KEY_MISS (1<<11) /* m */
|
||||
#define REDISMODULE_NOTIFY_ALL (REDISMODULE_NOTIFY_GENERIC | REDISMODULE_NOTIFY_STRING | REDISMODULE_NOTIFY_LIST | REDISMODULE_NOTIFY_SET | REDISMODULE_NOTIFY_HASH | REDISMODULE_NOTIFY_ZSET | REDISMODULE_NOTIFY_EXPIRED | REDISMODULE_NOTIFY_EVICTED | REDISMODULE_NOTIFY_STREAM | REDISMODULE_NOTIFY_KEY_MISS) /* A */
|
||||
|
||||
|
||||
/* A special pointer that we can use between the core and the module to signal
|
||||
@@ -132,6 +139,11 @@
|
||||
* of timers that are going to expire, sorted by expire time. */
|
||||
typedef uint64_t RedisModuleTimerID;
|
||||
|
||||
/* CommandFilter Flags */
|
||||
|
||||
/* Do filter RedisModule_Call() commands initiated by module itself. */
|
||||
#define REDISMODULE_CMDFILTER_NOSELF (1<<0)
|
||||
|
||||
/* ------------------------- End of common defines ------------------------ */
|
||||
|
||||
#ifndef REDISMODULE_CORE
|
||||
@@ -150,6 +162,8 @@ typedef struct RedisModuleBlockedClient RedisModuleBlockedClient;
|
||||
typedef struct RedisModuleClusterInfo RedisModuleClusterInfo;
|
||||
typedef struct RedisModuleDict RedisModuleDict;
|
||||
typedef struct RedisModuleDictIter RedisModuleDictIter;
|
||||
typedef struct RedisModuleCommandFilterCtx RedisModuleCommandFilterCtx;
|
||||
typedef struct RedisModuleCommandFilter RedisModuleCommandFilter;
|
||||
|
||||
typedef int (*RedisModuleCmdFunc)(RedisModuleCtx *ctx, RedisModuleString **argv, int argc);
|
||||
typedef void (*RedisModuleDisconnectFunc)(RedisModuleCtx *ctx, RedisModuleBlockedClient *bc);
|
||||
@@ -162,6 +176,7 @@ typedef void (*RedisModuleTypeDigestFunc)(RedisModuleDigest *digest, void *value
|
||||
typedef void (*RedisModuleTypeFreeFunc)(void *value);
|
||||
typedef void (*RedisModuleClusterMessageReceiver)(RedisModuleCtx *ctx, const char *sender_id, uint8_t type, const unsigned char *payload, uint32_t len);
|
||||
typedef void (*RedisModuleTimerProc)(RedisModuleCtx *ctx, void *data);
|
||||
typedef void (*RedisModuleCommandFilterFunc) (RedisModuleCommandFilterCtx *filter);
|
||||
|
||||
#define REDISMODULE_TYPE_METHOD_VERSION 1
|
||||
typedef struct RedisModuleTypeMethods {
|
||||
@@ -217,6 +232,7 @@ int REDISMODULE_API_FUNC(RedisModule_ReplyWithSimpleString)(RedisModuleCtx *ctx,
|
||||
int REDISMODULE_API_FUNC(RedisModule_ReplyWithArray)(RedisModuleCtx *ctx, long len);
|
||||
void REDISMODULE_API_FUNC(RedisModule_ReplySetArrayLength)(RedisModuleCtx *ctx, long len);
|
||||
int REDISMODULE_API_FUNC(RedisModule_ReplyWithStringBuffer)(RedisModuleCtx *ctx, const char *buf, size_t len);
|
||||
int REDISMODULE_API_FUNC(RedisModule_ReplyWithCString)(RedisModuleCtx *ctx, const char *buf);
|
||||
int REDISMODULE_API_FUNC(RedisModule_ReplyWithString)(RedisModuleCtx *ctx, RedisModuleString *str);
|
||||
int REDISMODULE_API_FUNC(RedisModule_ReplyWithNull)(RedisModuleCtx *ctx);
|
||||
int REDISMODULE_API_FUNC(RedisModule_ReplyWithDouble)(RedisModuleCtx *ctx, double d);
|
||||
@@ -338,6 +354,13 @@ void REDISMODULE_API_FUNC(RedisModule_SetDisconnectCallback)(RedisModuleBlockedC
|
||||
void REDISMODULE_API_FUNC(RedisModule_SetClusterFlags)(RedisModuleCtx *ctx, uint64_t flags);
|
||||
int REDISMODULE_API_FUNC(RedisModule_ExportSharedAPI)(RedisModuleCtx *ctx, const char *apiname, void *func);
|
||||
void *REDISMODULE_API_FUNC(RedisModule_GetSharedAPI)(RedisModuleCtx *ctx, const char *apiname);
|
||||
RedisModuleCommandFilter *REDISMODULE_API_FUNC(RedisModule_RegisterCommandFilter)(RedisModuleCtx *ctx, RedisModuleCommandFilterFunc cb, int flags);
|
||||
int REDISMODULE_API_FUNC(RedisModule_UnregisterCommandFilter)(RedisModuleCtx *ctx, RedisModuleCommandFilter *filter);
|
||||
int REDISMODULE_API_FUNC(RedisModule_CommandFilterArgsCount)(RedisModuleCommandFilterCtx *fctx);
|
||||
const RedisModuleString *REDISMODULE_API_FUNC(RedisModule_CommandFilterArgGet)(RedisModuleCommandFilterCtx *fctx, int pos);
|
||||
int REDISMODULE_API_FUNC(RedisModule_CommandFilterArgInsert)(RedisModuleCommandFilterCtx *fctx, int pos, RedisModuleString *arg);
|
||||
int REDISMODULE_API_FUNC(RedisModule_CommandFilterArgReplace)(RedisModuleCommandFilterCtx *fctx, int pos, RedisModuleString *arg);
|
||||
int REDISMODULE_API_FUNC(RedisModule_CommandFilterArgDelete)(RedisModuleCommandFilterCtx *fctx, int pos);
|
||||
#endif
|
||||
|
||||
/* This is included inline inside each Redis module. */
|
||||
@@ -360,6 +383,7 @@ static int RedisModule_Init(RedisModuleCtx *ctx, const char *name, int ver, int
|
||||
REDISMODULE_GET_API(ReplyWithArray);
|
||||
REDISMODULE_GET_API(ReplySetArrayLength);
|
||||
REDISMODULE_GET_API(ReplyWithStringBuffer);
|
||||
REDISMODULE_GET_API(ReplyWithCString);
|
||||
REDISMODULE_GET_API(ReplyWithString);
|
||||
REDISMODULE_GET_API(ReplyWithNull);
|
||||
REDISMODULE_GET_API(ReplyWithCallReply);
|
||||
@@ -501,6 +525,13 @@ static int RedisModule_Init(RedisModuleCtx *ctx, const char *name, int ver, int
|
||||
REDISMODULE_GET_API(SetClusterFlags);
|
||||
REDISMODULE_GET_API(ExportSharedAPI);
|
||||
REDISMODULE_GET_API(GetSharedAPI);
|
||||
REDISMODULE_GET_API(RegisterCommandFilter);
|
||||
REDISMODULE_GET_API(UnregisterCommandFilter);
|
||||
REDISMODULE_GET_API(CommandFilterArgsCount);
|
||||
REDISMODULE_GET_API(CommandFilterArgGet);
|
||||
REDISMODULE_GET_API(CommandFilterArgInsert);
|
||||
REDISMODULE_GET_API(CommandFilterArgReplace);
|
||||
REDISMODULE_GET_API(CommandFilterArgDelete);
|
||||
#endif
|
||||
|
||||
if (RedisModule_IsModuleNameBusy && RedisModule_IsModuleNameBusy(name)) return REDISMODULE_ERR;
|
||||
@@ -515,4 +546,9 @@ static int RedisModule_Init(RedisModuleCtx *ctx, const char *name, int ver, int
|
||||
#define RedisModuleString robj
|
||||
|
||||
#endif /* REDISMODULE_CORE */
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* REDISMOUDLE_H */
|
||||
+1
-1
@@ -46,7 +46,7 @@ char *redisGitDirty(void) {
|
||||
}
|
||||
|
||||
uint64_t redisBuildId(void) {
|
||||
char *buildid = REDIS_VERSION REDIS_BUILD_ID REDIS_GIT_DIRTY REDIS_GIT_SHA1;
|
||||
char *buildid = KEYDB_REAL_VERSION REDIS_BUILD_ID REDIS_GIT_DIRTY REDIS_GIT_SHA1;
|
||||
|
||||
return crc64(0,(unsigned char*)buildid,strlen(buildid));
|
||||
}
|
||||
+1340
-865
File diff suppressed because it is too large.
Load diff
+11
-10
@@ -109,13 +109,14 @@ void rioInitWithBuffer(rio *r, sds s) {
|
||||
static size_t rioFileWrite(rio *r, const void *buf, size_t len) {
|
||||
size_t retval;
|
||||
|
||||
retval = write(r->io.file.fd,buf,len);
|
||||
retval = fwrite(buf,len,1,r->io.file.fp);
|
||||
r->io.file.buffered += len;
|
||||
|
||||
if (r->io.file.autosync &&
|
||||
r->io.file.buffered >= r->io.file.autosync)
|
||||
{
|
||||
redis_fsync(r->io.file.fd);
|
||||
fflush(r->io.file.fp);
|
||||
redis_fsync(fileno(r->io.file.fp));
|
||||
r->io.file.buffered = 0;
|
||||
}
|
||||
return retval;
|
||||
@@ -123,18 +124,18 @@ static size_t rioFileWrite(rio *r, const void *buf, size_t len) {
|
||||
|
||||
/* Returns 1 or 0 for success/failure. */
|
||||
static size_t rioFileRead(rio *r, void *buf, size_t len) {
|
||||
return read(r->io.file.fd,buf,len);
|
||||
return fread(buf,len,1,r->io.file.fp);
|
||||
}
|
||||
|
||||
/* Returns read/write position in file. */
|
||||
static off_t rioFileTell(rio *r) {
|
||||
return lseek(r->io.file.fd, 0, SEEK_CUR);
|
||||
return ftello(r->io.file.fp);
|
||||
}
|
||||
|
||||
/* Flushes any buffer to target device if applicable. Returns 1 on success
|
||||
* and 0 on failures. */
|
||||
static int rioFileFlush(rio *r) {
|
||||
return (fsync(r->io.file.fd) == 0) ? 1 : 0;
|
||||
return (fflush(r->io.file.fp) == 0) ? 1 : 0;
|
||||
}
|
||||
|
||||
static const rio rioFileIO = {
|
||||
@@ -149,9 +150,9 @@ static const rio rioFileIO = {
|
||||
{ { NULL, 0 } } /* union for io-specific vars */
|
||||
};
|
||||
|
||||
void rioInitWithFile(rio *r, int fd) {
|
||||
void rioInitWithFile(rio *r, FILE *fp) {
|
||||
*r = rioFileIO;
|
||||
r->io.file.fd = fd;
|
||||
r->io.file.fp = fp;
|
||||
r->io.file.buffered = 0;
|
||||
r->io.file.autosync = 0;
|
||||
}
|
||||
@@ -266,8 +267,8 @@ void rioInitWithFdset(rio *r, int *fds, int numfds) {
|
||||
int j;
|
||||
|
||||
*r = rioFdsetIO;
|
||||
r->io.fdset.fds = zmalloc(sizeof(int)*numfds, MALLOC_LOCAL);
|
||||
r->io.fdset.state = zmalloc(sizeof(int)*numfds, MALLOC_LOCAL);
|
||||
r->io.fdset.fds = (int*)zmalloc(sizeof(int)*numfds, MALLOC_LOCAL);
|
||||
r->io.fdset.state = (int*)zmalloc(sizeof(int)*numfds, MALLOC_LOCAL);
|
||||
memcpy(r->io.fdset.fds,fds,sizeof(int)*numfds);
|
||||
for (j = 0; j < numfds; j++) r->io.fdset.state[j] = 0;
|
||||
r->io.fdset.numfds = numfds;
|
||||
@@ -287,7 +288,7 @@ void rioFreeFdset(rio *r) {
|
||||
/* This function can be installed both in memory and file streams when checksum
|
||||
* computation is needed. */
|
||||
void rioGenericUpdateChecksum(rio *r, const void *buf, size_t len) {
|
||||
r->cksum = crc64(r->cksum,buf,len);
|
||||
r->cksum = crc64(r->cksum,(const unsigned char*)buf,len);
|
||||
}
|
||||
|
||||
/* Set the file-based rio object to auto-fsync every 'bytes' file written.
|
||||
@@ -36,6 +36,10 @@
|
||||
#include <stdint.h>
|
||||
#include "sds.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct _rio {
|
||||
/* Backend functions.
|
||||
* Since this functions do not tolerate short writes or reads the return
|
||||
@@ -69,7 +73,7 @@ struct _rio {
|
||||
} buffer;
|
||||
/* Stdio file pointer target. */
|
||||
struct {
|
||||
int fd;
|
||||
FILE *fp;
|
||||
off_t buffered; /* Bytes written since last fsync. */
|
||||
off_t autosync; /* fsync after 'autosync' bytes written. */
|
||||
} file;
|
||||
@@ -124,7 +128,7 @@ static inline int rioFlush(rio *r) {
|
||||
return r->flush(r);
|
||||
}
|
||||
|
||||
void rioInitWithFile(rio *r, int fd);
|
||||
void rioInitWithFile(rio *r, FILE *fp);
|
||||
void rioInitWithBuffer(rio *r, sds s);
|
||||
void rioInitWithFdset(rio *r, int *fds, int numfds);
|
||||
|
||||
@@ -141,4 +145,8 @@ int rioWriteBulkObject(rio *r, struct redisObject *obj);
|
||||
void rioGenericUpdateChecksum(rio *r, const void *buf, size_t len);
|
||||
void rioSetAutoSync(rio *r, off_t bytes);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
+111
-105
@@ -191,7 +191,7 @@ char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply, int atype) {
|
||||
int j = 0;
|
||||
|
||||
string2ll(reply+1,p-reply-1,&mbulklen);
|
||||
if (server.lua_caller->resp == 2 || atype == '*') {
|
||||
if (g_pserver->lua_caller->resp == 2 || atype == '*') {
|
||||
p += 2;
|
||||
if (mbulklen == -1) {
|
||||
lua_pushboolean(lua,0);
|
||||
@@ -203,7 +203,7 @@ char *redisProtocolToLuaType_MultiBulk(lua_State *lua, char *reply, int atype) {
|
||||
p = redisProtocolToLuaType(lua,p);
|
||||
lua_settable(lua,-3);
|
||||
}
|
||||
} else if (server.lua_caller->resp == 3) {
|
||||
} else if (g_pserver->lua_caller->resp == 3) {
|
||||
/* Here we handle only Set and Map replies in RESP3 mode, since arrays
|
||||
* follow the above RESP2 code path. */
|
||||
p += 2;
|
||||
@@ -371,14 +371,14 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
int acl_retval = 0;
|
||||
int call_flags = CMD_CALL_SLOWLOG | CMD_CALL_STATS;
|
||||
struct redisCommand *cmd;
|
||||
client *c = server.lua_client;
|
||||
client *c = serverTL->lua_client;
|
||||
sds reply;
|
||||
|
||||
// Ensure our client is on the right thread
|
||||
serverAssert(!(c->flags & CLIENT_PENDING_WRITE));
|
||||
serverAssert(!(c->flags & CLIENT_UNBLOCKED));
|
||||
serverAssert(GlobalLocksAcquired());
|
||||
c->iel = serverTL - server.rgthreadvar;
|
||||
c->iel = serverTL - g_pserver->rgthreadvar;
|
||||
|
||||
/* Cached across calls. */
|
||||
static robj **argv = NULL;
|
||||
@@ -388,7 +388,7 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
static int inuse = 0; /* Recursive calls detection. */
|
||||
|
||||
/* Reflect MULTI state */
|
||||
if (server.lua_multi_emitted || (server.lua_caller->flags & CLIENT_MULTI)) {
|
||||
if (g_pserver->lua_multi_emitted || (g_pserver->lua_caller->flags & CLIENT_MULTI)) {
|
||||
c->flags |= CLIENT_MULTI;
|
||||
} else {
|
||||
c->flags &= ~CLIENT_MULTI;
|
||||
@@ -472,7 +472,12 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
/* Setup our fake client for command execution */
|
||||
c->argv = argv;
|
||||
c->argc = argc;
|
||||
c->puser = server.lua_caller->puser;
|
||||
c->puser = g_pserver->lua_caller->puser;
|
||||
|
||||
/* Process module hooks */
|
||||
moduleCallCommandFilters(c);
|
||||
argv = c->argv;
|
||||
argc = c->argc;
|
||||
|
||||
/* Log the command if debugging is active. */
|
||||
if (ldb.active && ldb.step) {
|
||||
@@ -528,13 +533,13 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
* of this script. */
|
||||
if (cmd->flags & CMD_WRITE) {
|
||||
int deny_write_type = writeCommandsDeniedByDiskError();
|
||||
if (server.lua_random_dirty && !server.lua_replicate_commands) {
|
||||
if (g_pserver->lua_random_dirty && !g_pserver->lua_replicate_commands) {
|
||||
luaPushError(lua,
|
||||
"Write commands not allowed after non deterministic commands. Call redis.replicate_commands() at the start of your script in order to switch to single commands replication mode.");
|
||||
goto cleanup;
|
||||
} else if (server.masterhost && server.repl_slave_ro &&
|
||||
!server.loading &&
|
||||
!(server.lua_caller->flags & CLIENT_MASTER))
|
||||
} else if (listLength(g_pserver->masters) && g_pserver->repl_slave_ro &&
|
||||
!g_pserver->loading &&
|
||||
!(g_pserver->lua_caller->flags & CLIENT_MASTER))
|
||||
{
|
||||
luaPushError(lua, (char*)ptrFromObj(shared.roslaveerr));
|
||||
goto cleanup;
|
||||
@@ -544,7 +549,7 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
} else {
|
||||
sds aof_write_err = sdscatfmt(sdsempty(),
|
||||
"-MISCONF Errors writing to the AOF file: %s\r\n",
|
||||
strerror(server.aof_last_write_errno));
|
||||
strerror(g_pserver->aof_last_write_errno));
|
||||
luaPushError(lua, aof_write_err);
|
||||
sdsfree(aof_write_err);
|
||||
}
|
||||
@@ -556,10 +561,10 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
* could enlarge the memory usage are not allowed, but only if this is the
|
||||
* first write in the context of this script, otherwise we can't stop
|
||||
* in the middle. */
|
||||
if (server.maxmemory && /* Maxmemory is actually enabled. */
|
||||
!server.loading && /* Don't care about mem if loading. */
|
||||
!server.masterhost && /* Slave must execute the script. */
|
||||
server.lua_write_dirty == 0 && /* Script had no side effects so far. */
|
||||
if (g_pserver->maxmemory && /* Maxmemory is actually enabled. */
|
||||
!g_pserver->loading && /* Don't care about mem if loading. */
|
||||
!listLength(g_pserver->masters) && /* Slave must execute the script. */
|
||||
g_pserver->lua_write_dirty == 0 && /* Script had no side effects so far. */
|
||||
(cmd->flags & CMD_DENYOOM))
|
||||
{
|
||||
if (getMaxmemoryState(NULL,NULL,NULL,NULL) != C_OK) {
|
||||
@@ -568,20 +573,20 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
}
|
||||
}
|
||||
|
||||
if (cmd->flags & CMD_RANDOM) server.lua_random_dirty = 1;
|
||||
if (cmd->flags & CMD_WRITE) server.lua_write_dirty = 1;
|
||||
if (cmd->flags & CMD_RANDOM) g_pserver->lua_random_dirty = 1;
|
||||
if (cmd->flags & CMD_WRITE) g_pserver->lua_write_dirty = 1;
|
||||
|
||||
/* If this is a Redis Cluster node, we need to make sure Lua is not
|
||||
* trying to access non-local keys, with the exception of commands
|
||||
* received from our master or when loading the AOF back in memory. */
|
||||
if (server.cluster_enabled && !server.loading &&
|
||||
!(server.lua_caller->flags & CLIENT_MASTER))
|
||||
if (g_pserver->cluster_enabled && !g_pserver->loading &&
|
||||
!(g_pserver->lua_caller->flags & CLIENT_MASTER))
|
||||
{
|
||||
/* Duplicate relevant flags in the lua client. */
|
||||
c->flags &= ~(CLIENT_READONLY|CLIENT_ASKING);
|
||||
c->flags |= server.lua_caller->flags & (CLIENT_READONLY|CLIENT_ASKING);
|
||||
c->flags |= g_pserver->lua_caller->flags & (CLIENT_READONLY|CLIENT_ASKING);
|
||||
if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) !=
|
||||
server.cluster->myself)
|
||||
g_pserver->cluster->myself)
|
||||
{
|
||||
luaPushError(lua,
|
||||
"Lua script attempted to access a non local key in a "
|
||||
@@ -593,22 +598,22 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
/* If we are using single commands replication, we need to wrap what
|
||||
* we propagate into a MULTI/EXEC block, so that it will be atomic like
|
||||
* a Lua script in the context of AOF and slaves. */
|
||||
if (server.lua_replicate_commands &&
|
||||
!server.lua_multi_emitted &&
|
||||
!(server.lua_caller->flags & CLIENT_MULTI) &&
|
||||
server.lua_write_dirty &&
|
||||
server.lua_repl != PROPAGATE_NONE)
|
||||
if (g_pserver->lua_replicate_commands &&
|
||||
!g_pserver->lua_multi_emitted &&
|
||||
!(g_pserver->lua_caller->flags & CLIENT_MULTI) &&
|
||||
g_pserver->lua_write_dirty &&
|
||||
g_pserver->lua_repl != PROPAGATE_NONE)
|
||||
{
|
||||
execCommandPropagateMulti(server.lua_caller);
|
||||
server.lua_multi_emitted = 1;
|
||||
execCommandPropagateMulti(g_pserver->lua_caller);
|
||||
g_pserver->lua_multi_emitted = 1;
|
||||
}
|
||||
|
||||
/* Run the command */
|
||||
if (server.lua_replicate_commands) {
|
||||
if (g_pserver->lua_replicate_commands) {
|
||||
/* Set flags according to redis.set_repl() settings. */
|
||||
if (server.lua_repl & PROPAGATE_AOF)
|
||||
if (g_pserver->lua_repl & PROPAGATE_AOF)
|
||||
call_flags |= CMD_CALL_PROPAGATE_AOF;
|
||||
if (server.lua_repl & PROPAGATE_REPL)
|
||||
if (g_pserver->lua_repl & PROPAGATE_REPL)
|
||||
call_flags |= CMD_CALL_PROPAGATE_REPL;
|
||||
}
|
||||
call(c,call_flags);
|
||||
@@ -643,7 +648,7 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
/* Sort the output array if needed, assuming it is a non-null multi bulk
|
||||
* reply as expected. */
|
||||
if ((cmd->flags & CMD_SORT_FOR_SCRIPT) &&
|
||||
(server.lua_replicate_commands == 0) &&
|
||||
(g_pserver->lua_replicate_commands == 0) &&
|
||||
(reply[0] == '*' && reply[1] != '-')) {
|
||||
luaSortArray(lua);
|
||||
}
|
||||
@@ -660,7 +665,7 @@ cleanup:
|
||||
* The object must be small, SDS-encoded, and with refcount = 1
|
||||
* (we must be the only owner) for us to cache it. */
|
||||
if (j < LUA_CMD_OBJCACHE_SIZE &&
|
||||
o->refcount == 1 &&
|
||||
o->getrefcount(std::memory_order_relaxed) == 1 &&
|
||||
(o->encoding == OBJ_ENCODING_RAW ||
|
||||
o->encoding == OBJ_ENCODING_EMBSTR) &&
|
||||
sdslen((sds)ptrFromObj(o)) <= LUA_CMD_OBJCACHE_MAX_LEN)
|
||||
@@ -759,10 +764,10 @@ int luaRedisStatusReplyCommand(lua_State *lua) {
|
||||
* already started to write, returns false and stick to whole scripts
|
||||
* replication, which is our default. */
|
||||
int luaRedisReplicateCommandsCommand(lua_State *lua) {
|
||||
if (server.lua_write_dirty) {
|
||||
if (g_pserver->lua_write_dirty) {
|
||||
lua_pushboolean(lua,0);
|
||||
} else {
|
||||
server.lua_replicate_commands = 1;
|
||||
g_pserver->lua_replicate_commands = 1;
|
||||
/* When we switch to single commands replication, we can provide
|
||||
* different math.random() sequences at every call, which is what
|
||||
* the user normally expects. */
|
||||
@@ -812,7 +817,7 @@ int luaRedisSetReplCommand(lua_State *lua) {
|
||||
int argc = lua_gettop(lua);
|
||||
int flags;
|
||||
|
||||
if (server.lua_replicate_commands == 0) {
|
||||
if (g_pserver->lua_replicate_commands == 0) {
|
||||
lua_pushstring(lua, "You can set the replication behavior only after turning on single commands replication with redis.replicate_commands().");
|
||||
return lua_error(lua);
|
||||
} else if (argc != 1) {
|
||||
@@ -825,7 +830,7 @@ int luaRedisSetReplCommand(lua_State *lua) {
|
||||
lua_pushstring(lua, "Invalid replication flags. Use REPL_AOF, REPL_REPLICA, REPL_ALL or REPL_NONE.");
|
||||
return lua_error(lua);
|
||||
}
|
||||
server.lua_repl = flags;
|
||||
g_pserver->lua_repl = flags;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -961,9 +966,12 @@ void scriptingInit(int setup) {
|
||||
lua_State *lua = lua_open();
|
||||
|
||||
if (setup) {
|
||||
server.lua_client = NULL;
|
||||
server.lua_caller = NULL;
|
||||
server.lua_timedout = 0;
|
||||
for (int iel = 0; iel < cserver.cthreads; ++iel)
|
||||
{
|
||||
g_pserver->rgthreadvar[iel].lua_client = createClient(-1, iel);
|
||||
g_pserver->rgthreadvar[iel].lua_client->flags |= CLIENT_LUA;
|
||||
}
|
||||
g_pserver->lua_timedout = 0;
|
||||
ldbInit();
|
||||
}
|
||||
|
||||
@@ -973,8 +981,8 @@ void scriptingInit(int setup) {
|
||||
/* Initialize a dictionary we use to map SHAs to scripts.
|
||||
* This is useful for replication, as we need to replicate EVALSHA
|
||||
* as EVAL, so we need to remember the associated script. */
|
||||
server.lua_scripts = dictCreate(&shaScriptObjectDictType,NULL);
|
||||
server.lua_scripts_mem = 0;
|
||||
g_pserver->lua_scripts = dictCreate(&shaScriptObjectDictType,NULL);
|
||||
g_pserver->lua_scripts_mem = 0;
|
||||
|
||||
/* Register the redis commands table and fields */
|
||||
lua_newtable(lua);
|
||||
@@ -1112,29 +1120,20 @@ void scriptingInit(int setup) {
|
||||
lua_pcall(lua,0,0,0);
|
||||
}
|
||||
|
||||
/* Create the (non connected) client that we use to execute Redis commands
|
||||
* inside the Lua interpreter.
|
||||
* Note: there is no need to create it again when this function is called
|
||||
* by scriptingReset(). */
|
||||
if (server.lua_client == NULL) {
|
||||
server.lua_client = createClient(-1, IDX_EVENT_LOOP_MAIN);
|
||||
server.lua_client->flags |= CLIENT_LUA;
|
||||
}
|
||||
|
||||
/* Lua beginners often don't use "local", this is likely to introduce
|
||||
* subtle bugs in their code. To prevent problems we protect accesses
|
||||
* to global variables. */
|
||||
scriptingEnableGlobalsProtection(lua);
|
||||
|
||||
server.lua = lua;
|
||||
g_pserver->lua = lua;
|
||||
}
|
||||
|
||||
/* Release resources related to Lua scripting.
|
||||
* This function is used in order to reset the scripting environment. */
|
||||
void scriptingRelease(void) {
|
||||
dictRelease(server.lua_scripts);
|
||||
server.lua_scripts_mem = 0;
|
||||
lua_close(server.lua);
|
||||
dictRelease(g_pserver->lua_scripts);
|
||||
g_pserver->lua_scripts_mem = 0;
|
||||
lua_close(g_pserver->lua);
|
||||
}
|
||||
|
||||
void scriptingReset(void) {
|
||||
@@ -1228,7 +1227,7 @@ sds luaCreateFunction(client *c, lua_State *lua, robj *body) {
|
||||
sha1hex(funcname+2,(char*)ptrFromObj(body),sdslen((sds)ptrFromObj(body)));
|
||||
|
||||
sds sha = sdsnewlen(funcname+2,40);
|
||||
if ((de = dictFind(server.lua_scripts,sha)) != NULL) {
|
||||
if ((de = dictFind(g_pserver->lua_scripts,sha)) != NULL) {
|
||||
sdsfree(sha);
|
||||
return (sds)dictGetKey(de);
|
||||
}
|
||||
@@ -1266,33 +1265,33 @@ sds luaCreateFunction(client *c, lua_State *lua, robj *body) {
|
||||
/* We also save a SHA1 -> Original script map in a dictionary
|
||||
* so that we can replicate / write in the AOF all the
|
||||
* EVALSHA commands as EVAL using the original script. */
|
||||
int retval = dictAdd(server.lua_scripts,sha,body);
|
||||
serverAssertWithInfo(c ? c : server.lua_client,NULL,retval == DICT_OK);
|
||||
server.lua_scripts_mem += sdsZmallocSize(sha) + getStringObjectSdsUsedMemory(body);
|
||||
int retval = dictAdd(g_pserver->lua_scripts,sha,body);
|
||||
serverAssertWithInfo(c ? c : serverTL->lua_client,NULL,retval == DICT_OK);
|
||||
g_pserver->lua_scripts_mem += sdsZmallocSize(sha) + getStringObjectSdsUsedMemory(body);
|
||||
incrRefCount(body);
|
||||
return sha;
|
||||
}
|
||||
|
||||
/* This is the Lua script "count" hook that we use to detect scripts timeout. */
|
||||
void luaMaskCountHook(lua_State *lua, lua_Debug *ar) {
|
||||
long long elapsed = mstime() - server.lua_time_start;
|
||||
long long elapsed = mstime() - g_pserver->lua_time_start;
|
||||
UNUSED(ar);
|
||||
UNUSED(lua);
|
||||
|
||||
/* Set the timeout condition if not already set and the maximum
|
||||
* execution time was reached. */
|
||||
if (elapsed >= server.lua_time_limit && server.lua_timedout == 0) {
|
||||
if (elapsed >= g_pserver->lua_time_limit && g_pserver->lua_timedout == 0) {
|
||||
serverLog(LL_WARNING,"Lua slow script detected: still in execution after %lld milliseconds. You can try killing the script using the SCRIPT KILL command.",elapsed);
|
||||
server.lua_timedout = 1;
|
||||
g_pserver->lua_timedout = 1;
|
||||
/* Once the script timeouts we reenter the event loop to permit others
|
||||
* to call SCRIPT KILL or SHUTDOWN NOSAVE if needed. For this reason
|
||||
* we need to mask the client executing the script from the event loop.
|
||||
* If we don't do that the client may disconnect and could no longer be
|
||||
* here when the EVAL command will return. */
|
||||
protectClient(server.lua_caller);
|
||||
protectClient(g_pserver->lua_caller);
|
||||
}
|
||||
if (server.lua_timedout) processEventsWhileBlocked(serverTL - server.rgthreadvar);
|
||||
if (server.lua_kill) {
|
||||
if (g_pserver->lua_timedout) processEventsWhileBlocked(serverTL - g_pserver->rgthreadvar);
|
||||
if (g_pserver->lua_kill) {
|
||||
serverLog(LL_WARNING,"Lua script killed by user with SCRIPT KILL.");
|
||||
lua_pushstring(lua,"Script killed by user with SCRIPT KILL...");
|
||||
lua_error(lua);
|
||||
@@ -1300,10 +1299,10 @@ void luaMaskCountHook(lua_State *lua, lua_Debug *ar) {
|
||||
}
|
||||
|
||||
void evalGenericCommand(client *c, int evalsha) {
|
||||
lua_State *lua = server.lua;
|
||||
lua_State *lua = g_pserver->lua;
|
||||
char funcname[43];
|
||||
long long numkeys;
|
||||
long long initial_server_dirty = server.dirty;
|
||||
long long initial_server_dirty = g_pserver->dirty;
|
||||
int delhook = 0, err;
|
||||
|
||||
/* When we replicate whole scripts, we want the same PRNG sequence at
|
||||
@@ -1318,11 +1317,11 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
*
|
||||
* Thanks to this flag we'll raise an error every time a write command
|
||||
* is called after a random command was used. */
|
||||
server.lua_random_dirty = 0;
|
||||
server.lua_write_dirty = 0;
|
||||
server.lua_replicate_commands = server.lua_always_replicate_commands;
|
||||
server.lua_multi_emitted = 0;
|
||||
server.lua_repl = PROPAGATE_AOF|PROPAGATE_REPL;
|
||||
g_pserver->lua_random_dirty = 0;
|
||||
g_pserver->lua_write_dirty = 0;
|
||||
g_pserver->lua_replicate_commands = g_pserver->lua_always_replicate_commands;
|
||||
g_pserver->lua_multi_emitted = 0;
|
||||
g_pserver->lua_repl = PROPAGATE_AOF|PROPAGATE_REPL;
|
||||
|
||||
/* Get the number of arguments that are keys */
|
||||
if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != C_OK)
|
||||
@@ -1388,7 +1387,7 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys);
|
||||
|
||||
/* Select the right DB in the context of the Lua client */
|
||||
selectDb(server.lua_client,c->db->id);
|
||||
selectDb(serverTL->lua_client,c->db->id);
|
||||
|
||||
/* Set a hook in order to be able to stop the script execution if it
|
||||
* is running for too much time.
|
||||
@@ -1397,14 +1396,14 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
*
|
||||
* If we are debugging, we set instead a "line" hook so that the
|
||||
* debugger is call-back at every line executed by the script. */
|
||||
server.lua_caller = c;
|
||||
server.lua_time_start = mstime();
|
||||
server.lua_kill = 0;
|
||||
if (server.lua_time_limit > 0 && ldb.active == 0) {
|
||||
g_pserver->lua_caller = c;
|
||||
g_pserver->lua_time_start = mstime();
|
||||
g_pserver->lua_kill = 0;
|
||||
if (g_pserver->lua_time_limit > 0 && ldb.active == 0) {
|
||||
lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000);
|
||||
delhook = 1;
|
||||
} else if (ldb.active) {
|
||||
lua_sethook(server.lua,luaLdbLineHook,LUA_MASKLINE|LUA_MASKCOUNT,100000);
|
||||
lua_sethook(g_pserver->lua,luaLdbLineHook,LUA_MASKLINE|LUA_MASKCOUNT,100000);
|
||||
delhook = 1;
|
||||
}
|
||||
|
||||
@@ -1415,15 +1414,22 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
|
||||
/* Perform some cleanup that we need to do both on error and success. */
|
||||
if (delhook) lua_sethook(lua,NULL,0,0); /* Disable hook */
|
||||
if (server.lua_timedout) {
|
||||
server.lua_timedout = 0;
|
||||
if (g_pserver->lua_timedout) {
|
||||
g_pserver->lua_timedout = 0;
|
||||
/* Restore the client that was protected when the script timeout
|
||||
* was detected. */
|
||||
unprotectClient(c);
|
||||
if (server.masterhost && server.master)
|
||||
queueClientForReprocessing(server.master);
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(g_pserver->masters, &li);
|
||||
while ((ln = listNext(&li)))
|
||||
{
|
||||
struct redisMaster *mi = (struct redisMaster*)listNodeValue(ln);
|
||||
if (mi->master)
|
||||
queueClientForReprocessing(mi->master);
|
||||
}
|
||||
}
|
||||
server.lua_caller = NULL;
|
||||
g_pserver->lua_caller = NULL;
|
||||
|
||||
/* Call the Lua garbage collector from time to time to avoid a
|
||||
* full cycle performed by Lua, which adds too latency.
|
||||
@@ -1455,12 +1461,12 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
|
||||
/* If we are using single commands replication, emit EXEC if there
|
||||
* was at least a write. */
|
||||
if (server.lua_replicate_commands) {
|
||||
if (g_pserver->lua_replicate_commands) {
|
||||
preventCommandPropagation(c);
|
||||
if (server.lua_multi_emitted) {
|
||||
if (g_pserver->lua_multi_emitted) {
|
||||
robj *propargv[1];
|
||||
propargv[0] = createStringObject("EXEC",4);
|
||||
alsoPropagate(server.execCommand,c->db->id,propargv,1,
|
||||
alsoPropagate(cserver.execCommand,c->db->id,propargv,1,
|
||||
PROPAGATE_AOF|PROPAGATE_REPL);
|
||||
decrRefCount(propargv[0]);
|
||||
}
|
||||
@@ -1473,15 +1479,15 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
* To do so we use a cache of SHA1s of scripts that we already propagated
|
||||
* as full EVAL, that's called the Replication Script Cache.
|
||||
*
|
||||
* For repliation, everytime a new slave attaches to the master, we need to
|
||||
* For repliation, everytime a new replica attaches to the master, we need to
|
||||
* flush our cache of scripts that can be replicated as EVALSHA, while
|
||||
* for AOF we need to do so every time we rewrite the AOF file. */
|
||||
if (evalsha && !server.lua_replicate_commands) {
|
||||
if (evalsha && !g_pserver->lua_replicate_commands) {
|
||||
if (!replicationScriptCacheExists((sds)ptrFromObj(c->argv[1]))) {
|
||||
/* This script is not in our script cache, replicate it as
|
||||
* EVAL, then add it into the script cache, as from now on
|
||||
* slaves and AOF know about it. */
|
||||
robj *script = (robj*)dictFetchValue(server.lua_scripts,ptrFromObj(c->argv[1]));
|
||||
robj *script = (robj*)dictFetchValue(g_pserver->lua_scripts,ptrFromObj(c->argv[1]));
|
||||
|
||||
replicationScriptCacheAdd((sds)ptrFromObj(c->argv[1]));
|
||||
serverAssertWithInfo(c,NULL,script != NULL);
|
||||
@@ -1490,7 +1496,7 @@ void evalGenericCommand(client *c, int evalsha) {
|
||||
* just to replicate it as SCRIPT LOAD, otherwise we risk running
|
||||
* an aborted script on slaves (that may then produce results there)
|
||||
* or just running a CPU costly read-only script on the slaves. */
|
||||
if (server.dirty == initial_server_dirty) {
|
||||
if (g_pserver->dirty == initial_server_dirty) {
|
||||
rewriteClientCommandVector(c,3,
|
||||
resetRefCount(createStringObject("SCRIPT",6)),
|
||||
resetRefCount(createStringObject("LOAD",4)),
|
||||
@@ -1544,31 +1550,31 @@ NULL
|
||||
scriptingReset();
|
||||
addReply(c,shared.ok);
|
||||
replicationScriptCacheFlush();
|
||||
server.dirty++; /* Propagating this command is a good idea. */
|
||||
g_pserver->dirty++; /* Propagating this command is a good idea. */
|
||||
} else if (c->argc >= 2 && !strcasecmp((const char*)ptrFromObj(c->argv[1]),"exists")) {
|
||||
int j;
|
||||
|
||||
addReplyArrayLen(c, c->argc-2);
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
if (dictFind(server.lua_scripts,ptrFromObj(c->argv[j])))
|
||||
if (dictFind(g_pserver->lua_scripts,ptrFromObj(c->argv[j])))
|
||||
addReply(c,shared.cone);
|
||||
else
|
||||
addReply(c,shared.czero);
|
||||
}
|
||||
} else if (c->argc == 3 && !strcasecmp((const char*)ptrFromObj(c->argv[1]),"load")) {
|
||||
sds sha = luaCreateFunction(c,server.lua,c->argv[2]);
|
||||
sds sha = luaCreateFunction(c,g_pserver->lua,c->argv[2]);
|
||||
if (sha == NULL) return; /* The error was sent by luaCreateFunction(). */
|
||||
addReplyBulkCBuffer(c,sha,40);
|
||||
forceCommandPropagation(c,PROPAGATE_REPL|PROPAGATE_AOF);
|
||||
} else if (c->argc == 2 && !strcasecmp((const char*)ptrFromObj(c->argv[1]),"kill")) {
|
||||
if (server.lua_caller == NULL) {
|
||||
if (g_pserver->lua_caller == NULL) {
|
||||
addReplySds(c,sdsnew("-NOTBUSY No scripts in execution right now.\r\n"));
|
||||
} else if (server.lua_caller->flags & CLIENT_MASTER) {
|
||||
} else if (g_pserver->lua_caller->flags & CLIENT_MASTER) {
|
||||
addReplySds(c,sdsnew("-UNKILLABLE The busy script was sent by a master instance in the context of replication and cannot be killed.\r\n"));
|
||||
} else if (server.lua_write_dirty) {
|
||||
} else if (g_pserver->lua_write_dirty) {
|
||||
addReplySds(c,sdsnew("-UNKILLABLE Sorry the script already executed write commands against the dataset. You can either wait the script termination or kill the server in a hard way using the SHUTDOWN NOSAVE command.\r\n"));
|
||||
} else {
|
||||
server.lua_kill = 1;
|
||||
g_pserver->lua_kill = 1;
|
||||
addReply(c,shared.ok);
|
||||
}
|
||||
} else if (c->argc == 3 && !strcasecmp((const char*)ptrFromObj(c->argv[1]),"debug")) {
|
||||
@@ -1604,7 +1610,7 @@ void ldbInit(void) {
|
||||
ldb.fd = -1;
|
||||
ldb.active = 0;
|
||||
ldb.logs = listCreate();
|
||||
listSetFreeMethod(ldb.logs,(void (*)(void*))sdsfree);
|
||||
listSetFreeMethod(ldb.logs,(void (*)(const void*))sdsfree);
|
||||
ldb.children = listCreate();
|
||||
ldb.src = NULL;
|
||||
ldb.lines = 0;
|
||||
@@ -2277,7 +2283,7 @@ void ldbEval(lua_State *lua, sds *argv, int argc) {
|
||||
* implementation, with ldb.step enabled, so as a side effect the Redis command
|
||||
* and its reply are logged. */
|
||||
void ldbRedis(lua_State *lua, sds *argv, int argc) {
|
||||
int j, saved_rc = server.lua_replicate_commands;
|
||||
int j, saved_rc = g_pserver->lua_replicate_commands;
|
||||
|
||||
lua_getglobal(lua,"redis");
|
||||
lua_pushstring(lua,"call");
|
||||
@@ -2285,10 +2291,10 @@ void ldbRedis(lua_State *lua, sds *argv, int argc) {
|
||||
for (j = 1; j < argc; j++)
|
||||
lua_pushlstring(lua,argv[j],sdslen(argv[j]));
|
||||
ldb.step = 1; /* Force redis.call() to log. */
|
||||
server.lua_replicate_commands = 1;
|
||||
g_pserver->lua_replicate_commands = 1;
|
||||
lua_pcall(lua,argc-1,1,0); /* Stack: redis, result */
|
||||
ldb.step = 0; /* Disable logging. */
|
||||
server.lua_replicate_commands = saved_rc;
|
||||
g_pserver->lua_replicate_commands = saved_rc;
|
||||
lua_pop(lua,2); /* Discard the result and clean the stack. */
|
||||
}
|
||||
|
||||
@@ -2462,9 +2468,9 @@ void luaLdbLineHook(lua_State *lua, lua_Debug *ar) {
|
||||
|
||||
/* Check if a timeout occurred. */
|
||||
if (ar->event == LUA_HOOKCOUNT && ldb.step == 0 && bp == 0) {
|
||||
mstime_t elapsed = mstime() - server.lua_time_start;
|
||||
mstime_t timelimit = server.lua_time_limit ?
|
||||
server.lua_time_limit : 5000;
|
||||
mstime_t elapsed = mstime() - g_pserver->lua_time_start;
|
||||
mstime_t timelimit = g_pserver->lua_time_limit ?
|
||||
g_pserver->lua_time_limit : 5000;
|
||||
if (elapsed >= timelimit) {
|
||||
timeout = 1;
|
||||
ldb.step = 1;
|
||||
@@ -2492,7 +2498,7 @@ void luaLdbLineHook(lua_State *lua, lua_Debug *ar) {
|
||||
lua_pushstring(lua, "timeout during Lua debugging with client closing connection");
|
||||
lua_error(lua);
|
||||
}
|
||||
server.lua_time_start = mstime();
|
||||
g_pserver->lua_time_start = mstime();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,12 +157,12 @@ sds sdsnew(const char *init) {
|
||||
}
|
||||
|
||||
/* Duplicate an sds string. */
|
||||
sds sdsdup(const sds s) {
|
||||
sds sdsdup(const char *s) {
|
||||
return sdsnewlen(s, sdslen(s));
|
||||
}
|
||||
|
||||
/* Free an sds string. No operation is performed if 's' is NULL. */
|
||||
void sdsfree(sds s) {
|
||||
void sdsfree(const char *s) {
|
||||
if (s == NULL) return;
|
||||
s_free((char*)s-sdsHdrSize(s[-1]));
|
||||
}
|
||||
@@ -1089,7 +1089,7 @@ sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen) {
|
||||
|
||||
/* Join an array of C strings using the specified separator (also a C string).
|
||||
* Returns the result as an sds string. */
|
||||
sds sdsjoin(char **argv, int argc, char *sep) {
|
||||
sds sdsjoin(char **argv, int argc, const char *sep) {
|
||||
sds join = sdsempty();
|
||||
int j;
|
||||
|
||||
|
||||
@@ -60,6 +60,10 @@ struct __attribute__ ((__packed__)) sdshdr8 {
|
||||
unsigned char flags; /* 3 lsb of type, 5 unused bits */
|
||||
#ifndef __cplusplus
|
||||
char buf[];
|
||||
#else
|
||||
char *buf() {
|
||||
return reinterpret_cast<char*>(this+1);
|
||||
}
|
||||
#endif
|
||||
};
|
||||
struct __attribute__ ((__packed__)) sdshdr16 {
|
||||
@@ -98,7 +102,7 @@ struct __attribute__ ((__packed__)) sdshdr64 {
|
||||
#define SDS_HDR(T,s) ((struct sdshdr##T *)((s)-(sizeof(struct sdshdr##T))))
|
||||
#define SDS_TYPE_5_LEN(f) ((f)>>SDS_TYPE_BITS)
|
||||
|
||||
static inline size_t sdslen(const sds s) {
|
||||
static inline size_t sdslen(const char *s) {
|
||||
unsigned char flags = s[-1];
|
||||
int type = flags & SDS_TYPE_MASK;
|
||||
|
||||
@@ -122,7 +126,7 @@ static inline size_t sdslen(const sds s) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static inline size_t sdsavail(const sds s) {
|
||||
static inline size_t sdsavail(const char * s) {
|
||||
unsigned char flags = s[-1];
|
||||
switch(flags&SDS_TYPE_MASK) {
|
||||
case SDS_TYPE_5: {
|
||||
@@ -239,8 +243,8 @@ static inline void sdssetalloc(sds s, size_t newlen) {
|
||||
sds sdsnewlen(const void *init, size_t initlen);
|
||||
sds sdsnew(const char *init);
|
||||
sds sdsempty(void);
|
||||
sds sdsdup(const sds s);
|
||||
void sdsfree(sds s);
|
||||
sds sdsdup(const char *s);
|
||||
void sdsfree(const char *s);
|
||||
sds sdsgrowzero(sds s, size_t len);
|
||||
sds sdscatlen(sds s, const void *t, size_t len);
|
||||
sds sdscat(sds s, const char *t);
|
||||
@@ -270,7 +274,7 @@ sds sdsfromlonglong(long long value);
|
||||
sds sdscatrepr(sds s, const char *p, size_t len);
|
||||
sds *sdssplitargs(const char *line, int *argc);
|
||||
sds sdsmapchars(sds s, const char *from, const char *to, size_t setlen);
|
||||
sds sdsjoin(char **argv, int argc, char *sep);
|
||||
sds sdsjoin(char **argv, int argc, const char *sep);
|
||||
sds sdsjoinsds(sds *argv, int argc, const char *sep, size_t seplen);
|
||||
|
||||
/* Low level functions exposed to the user API */
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
#pragma once
|
||||
#include <assert.h>
|
||||
#include "compactvector.h"
|
||||
|
||||
/****************************************
|
||||
* semiorderedset.h:
|
||||
*
|
||||
* The ordered set is a hash set that maintains semi-ordering, that is you can iterate in sub-linear time over the set comparing a value.
|
||||
* It has a few other useful properties vs the traditional set:
|
||||
* 1. The key need not be the underlying type, the only requirement is the value type is castable to the key
|
||||
* 2. The key need not have total ordering. The set will iterate until it finds an exact match with operator== on the value
|
||||
* This provides additional flexibility on insert allowing us to optimize this case.
|
||||
*
|
||||
*/
|
||||
|
||||
extern uint64_t dictGenHashFunction(const void *key, int len);
|
||||
|
||||
template<typename T, typename T_KEY = T, bool MEMMOVE_SAFE = false>
|
||||
class semiorderedset
|
||||
{
|
||||
friend struct setiter;
|
||||
std::vector<compactvector<T, MEMMOVE_SAFE>> m_data;
|
||||
size_t celem = 0;
|
||||
static const size_t bits_min = 8;
|
||||
size_t bits = bits_min;
|
||||
size_t idxRehash = (1ULL << bits_min);
|
||||
bool fPauseRehash = false;
|
||||
|
||||
constexpr size_t targetElementsPerBucket()
|
||||
{
|
||||
// Aim for roughly 4 cache lines per bucket (determined by imperical testing)
|
||||
// lower values are faster but use more memory
|
||||
return std::max((64/sizeof(T))*8, (size_t)2);
|
||||
}
|
||||
|
||||
public:
|
||||
semiorderedset()
|
||||
{
|
||||
m_data.resize((1ULL << bits));
|
||||
}
|
||||
|
||||
struct setiter
|
||||
{
|
||||
semiorderedset *set;
|
||||
size_t idxPrimary = 0;
|
||||
size_t idxSecondary = 0;
|
||||
|
||||
setiter(semiorderedset *set)
|
||||
{
|
||||
this->set = set;
|
||||
}
|
||||
|
||||
bool operator==(const setiter &other) const
|
||||
{
|
||||
return (idxPrimary == other.idxPrimary) && (idxSecondary == other.idxSecondary);
|
||||
}
|
||||
|
||||
bool operator!=(const setiter &other) const { return !operator==(other); }
|
||||
|
||||
inline T &operator*() { return set->m_data[idxPrimary][idxSecondary]; }
|
||||
inline const T &operator*() const { return set->m_data[idxPrimary][idxSecondary]; }
|
||||
|
||||
inline T *operator->() { return &set->m_data[idxPrimary][idxSecondary]; }
|
||||
inline const T *operator->() const { return &set->m_data[idxPrimary][idxSecondary]; }
|
||||
};
|
||||
|
||||
setiter find(const T_KEY &key)
|
||||
{
|
||||
RehashStep();
|
||||
setiter itr(this);
|
||||
itr.idxPrimary = idxFromObj(key);
|
||||
|
||||
for (int hashset = 0; hashset < 2; ++hashset) // rehashing may only be 1 resize behind, so we check up to two slots
|
||||
{
|
||||
auto &vecBucket = m_data[itr.idxPrimary];
|
||||
|
||||
auto itrFind = std::find(vecBucket.begin(), vecBucket.end(), key);
|
||||
if (itrFind != vecBucket.end())
|
||||
{
|
||||
itr.idxSecondary = itrFind - vecBucket.begin();
|
||||
return itr;
|
||||
}
|
||||
|
||||
// See if we have to check the older slot
|
||||
size_t mask = (hashmask() >> 1);
|
||||
if (itr.idxPrimary == (itr.idxPrimary & mask))
|
||||
break; // same bucket we just checked
|
||||
itr.idxPrimary &= mask;
|
||||
if (FRehashedRow(itr.idxPrimary))
|
||||
break;
|
||||
}
|
||||
|
||||
return end();
|
||||
}
|
||||
|
||||
setiter end()
|
||||
{
|
||||
setiter itr(this);
|
||||
itr.idxPrimary = m_data.size();
|
||||
return itr;
|
||||
}
|
||||
|
||||
void insert(T &e, bool fRehash = false)
|
||||
{
|
||||
if (!fRehash)
|
||||
RehashStep();
|
||||
|
||||
auto idx = idxFromObj(static_cast<T_KEY>(e));
|
||||
if (!fRehash)
|
||||
++celem;
|
||||
|
||||
typename compactvector<T, MEMMOVE_SAFE>::iterator itrInsert;
|
||||
if (!m_data[idx].empty() && !(e < m_data[idx].back()))
|
||||
itrInsert = m_data[idx].end();
|
||||
else
|
||||
itrInsert = std::upper_bound(m_data[idx].begin(), m_data[idx].end(), e);
|
||||
itrInsert = m_data[idx].insert(itrInsert, e);
|
||||
|
||||
if (celem > ((1ULL << bits)*targetElementsPerBucket()))
|
||||
grow();
|
||||
}
|
||||
|
||||
// enumeration starting from the 'itrStart'th key. Note that the iter is a hint, and need no be valid anymore
|
||||
template<typename T_VISITOR, typename T_MAX>
|
||||
setiter enumerate(const setiter &itrStart, const T_MAX &max, T_VISITOR fn, long long *pccheck)
|
||||
{
|
||||
setiter itr(itrStart);
|
||||
|
||||
if (itrStart.set == this) // really if this case isn't true its probably a bug
|
||||
itr = itrStart; // but why crash the program when we can easily fix this?
|
||||
|
||||
fPauseRehash = true;
|
||||
if (itr.idxPrimary >= m_data.size())
|
||||
itr.idxPrimary = 0;
|
||||
|
||||
for (size_t ibucket = 0; ibucket < m_data.size(); ++ibucket)
|
||||
{
|
||||
if (!enumerate_bucket(itr, max, fn, pccheck))
|
||||
break;
|
||||
itr.idxSecondary = 0;
|
||||
|
||||
++itr.idxPrimary;
|
||||
if (itr.idxPrimary >= m_data.size())
|
||||
itr.idxPrimary = 0;
|
||||
}
|
||||
fPauseRehash = false;
|
||||
return itr;
|
||||
}
|
||||
|
||||
// This will "randomly" visit nodes biased towards lower values first
|
||||
template<typename T_VISITOR>
|
||||
size_t random_visit(T_VISITOR &fn)
|
||||
{
|
||||
bool fSawAny = true;
|
||||
size_t visited = 0;
|
||||
size_t basePrimary = rand() % m_data.size();
|
||||
for (size_t idxSecondary = 0; fSawAny; ++idxSecondary)
|
||||
{
|
||||
fSawAny = false;
|
||||
for (size_t idxPrimaryCount = 0; idxPrimaryCount < m_data.size(); ++idxPrimaryCount)
|
||||
{
|
||||
size_t idxPrimary = (basePrimary + idxPrimaryCount) % m_data.size();
|
||||
if (idxSecondary < m_data[idxPrimary].size())
|
||||
{
|
||||
++visited;
|
||||
fSawAny = true;
|
||||
if (!fn(m_data[idxPrimary][idxSecondary]))
|
||||
return visited;
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
const T& random_value() const
|
||||
{
|
||||
assert(!empty());
|
||||
for (;;)
|
||||
{
|
||||
size_t idxPrimary = rand() % m_data.size();
|
||||
if (m_data[idxPrimary].empty())
|
||||
continue;
|
||||
|
||||
return m_data[idxPrimary][rand() % m_data[idxPrimary].size()];
|
||||
}
|
||||
}
|
||||
|
||||
void erase(const setiter &itr)
|
||||
{
|
||||
auto &vecRow = m_data[itr.idxPrimary];
|
||||
vecRow.erase(vecRow.begin() + itr.idxSecondary);
|
||||
--celem;
|
||||
RehashStep();
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
m_data = decltype(m_data)();
|
||||
bits = bits_min;
|
||||
m_data.resize(1ULL << bits);
|
||||
idxRehash = m_data.size();
|
||||
}
|
||||
|
||||
bool empty() const noexcept { return celem == 0; }
|
||||
size_t size() const noexcept { return celem; }
|
||||
|
||||
size_t bytes_used() const
|
||||
{
|
||||
size_t cb = sizeof(this) + (m_data.capacity()-m_data.size())*sizeof(T);
|
||||
for (auto &vec : m_data)
|
||||
{
|
||||
cb += vec.bytes_used();
|
||||
}
|
||||
return cb;
|
||||
}
|
||||
|
||||
#define DICT_STATS_VECTLEN 50
|
||||
size_t getstats(char *buf, size_t bufsize) const
|
||||
{
|
||||
unsigned long i, slots = 0, chainlen, maxchainlen = 0;
|
||||
unsigned long totchainlen = 0;
|
||||
unsigned long clvector[DICT_STATS_VECTLEN] = {0};
|
||||
size_t l = 0;
|
||||
|
||||
if (empty()) {
|
||||
return snprintf(buf,bufsize,
|
||||
"No stats available for empty dictionaries\n");
|
||||
}
|
||||
|
||||
/* Compute stats. */
|
||||
for (auto &vec : m_data) {
|
||||
if (vec.empty()) {
|
||||
clvector[0]++;
|
||||
continue;
|
||||
}
|
||||
slots++;
|
||||
/* For each hash entry on this slot... */
|
||||
chainlen = vec.size();
|
||||
|
||||
clvector[(chainlen < DICT_STATS_VECTLEN) ? chainlen : (DICT_STATS_VECTLEN-1)]++;
|
||||
if (chainlen > maxchainlen) maxchainlen = chainlen;
|
||||
totchainlen += chainlen;
|
||||
}
|
||||
|
||||
size_t used = m_data.size()-clvector[0];
|
||||
/* Generate human readable stats. */
|
||||
l += snprintf(buf+l,bufsize-l,
|
||||
"semiordered set stats:\n"
|
||||
" table size: %ld\n"
|
||||
" number of slots: %ld\n"
|
||||
" used slots: %ld\n"
|
||||
" max chain length: %ld\n"
|
||||
" avg chain length (counted): %.02f\n"
|
||||
" avg chain length (computed): %.02f\n"
|
||||
" Chain length distribution:\n",
|
||||
size(), used, slots, maxchainlen,
|
||||
(float)totchainlen/slots, (float)size()/m_data.size());
|
||||
|
||||
for (i = 0; i < DICT_STATS_VECTLEN; i++) {
|
||||
if (clvector[i] == 0) continue;
|
||||
if (l >= bufsize) break;
|
||||
l += snprintf(buf+l,bufsize-l,
|
||||
" %s%ld: %ld (%.02f%%)\n",
|
||||
(i == DICT_STATS_VECTLEN-1)?">= ":"",
|
||||
i, clvector[i], ((float)clvector[i]/m_data.size())*100);
|
||||
}
|
||||
|
||||
/* Unlike snprintf(), teturn the number of characters actually written. */
|
||||
if (bufsize) buf[bufsize-1] = '\0';
|
||||
return strlen(buf);
|
||||
}
|
||||
|
||||
private:
|
||||
inline size_t hashmask() const { return (1ULL << bits) - 1; }
|
||||
|
||||
size_t idxFromObj(const T_KEY &key)
|
||||
{
|
||||
size_t v = (size_t)dictGenHashFunction(&key, sizeof(key));
|
||||
return v & hashmask();
|
||||
}
|
||||
|
||||
bool FRehashedRow(size_t idx) const
|
||||
{
|
||||
return (idx >= (m_data.size()/2)) || (idx < idxRehash);
|
||||
}
|
||||
|
||||
void RehashStep()
|
||||
{
|
||||
if (fPauseRehash)
|
||||
return;
|
||||
|
||||
int steps = 0;
|
||||
for (; idxRehash < (m_data.size()/2); ++idxRehash)
|
||||
{
|
||||
compactvector<T, MEMMOVE_SAFE> vecT;
|
||||
std::swap(m_data[idxRehash], vecT);
|
||||
|
||||
for (auto &v : vecT)
|
||||
insert(v, true);
|
||||
|
||||
if (++steps > 1024)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void grow()
|
||||
{
|
||||
assert(idxRehash >= (m_data.size()/2)); // we should have finished rehashing by the time we need to grow again
|
||||
|
||||
++bits;
|
||||
m_data.resize(1ULL << bits);
|
||||
idxRehash = 0;
|
||||
RehashStep();
|
||||
}
|
||||
|
||||
template<typename T_VISITOR, typename T_MAX>
|
||||
inline bool enumerate_bucket(setiter &itr, const T_MAX &max, T_VISITOR &fn, long long *pcheckLimit)
|
||||
{
|
||||
auto &vec = m_data[itr.idxPrimary];
|
||||
for (; itr.idxSecondary < vec.size(); ++itr.idxSecondary)
|
||||
{
|
||||
// Assert we're ordered by T_MAX
|
||||
assert((itr.idxSecondary+1) >= vec.size()
|
||||
|| static_cast<T_MAX>(vec[itr.idxSecondary]) <= static_cast<T_MAX>(vec[itr.idxSecondary+1]));
|
||||
|
||||
(*pcheckLimit)--;
|
||||
if (max < static_cast<T_MAX>(*itr))
|
||||
return *pcheckLimit > 0;
|
||||
|
||||
size_t sizeBefore = vec.size();
|
||||
if (!fn(*itr))
|
||||
{
|
||||
itr.idxSecondary++; // we still visited this node
|
||||
return false;
|
||||
}
|
||||
if (vec.size() != sizeBefore)
|
||||
{
|
||||
assert(vec.size() == (sizeBefore-1)); // they may only remove the element passed to them
|
||||
--itr.idxSecondary; // they deleted the element
|
||||
}
|
||||
}
|
||||
vec.shrink_to_fit();
|
||||
return *pcheckLimit > 0;
|
||||
}
|
||||
};
|
||||
+133
-133
@@ -375,7 +375,7 @@ sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master);
|
||||
void sentinelScheduleScriptExecution(char *path, ...);
|
||||
void sentinelStartFailover(sentinelRedisInstance *master);
|
||||
void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata);
|
||||
int sentinelSendSlaveOf(sentinelRedisInstance *ri, char *host, int port);
|
||||
int sentinelSendSlaveOf(sentinelRedisInstance *ri, const char *host, int port);
|
||||
char *sentinelVoteLeader(sentinelRedisInstance *master, uint64_t req_epoch, char *req_runid, uint64_t *leader_epoch);
|
||||
void sentinelFlushConfig(void);
|
||||
void sentinelGenerateInitialMonitorEvents(void);
|
||||
@@ -394,7 +394,7 @@ void releaseSentinelRedisInstance(sentinelRedisInstance *ri);
|
||||
|
||||
void dictInstancesValDestructor (void *privdata, void *obj) {
|
||||
UNUSED(privdata);
|
||||
releaseSentinelRedisInstance(obj);
|
||||
releaseSentinelRedisInstance((sentinelRedisInstance*)obj);
|
||||
}
|
||||
|
||||
/* Instance name (sds) -> instance (sentinelRedisInstance pointer)
|
||||
@@ -460,8 +460,8 @@ struct redisCommand sentinelcmds[] = {
|
||||
/* This function overwrites a few normal Redis config default with Sentinel
|
||||
* specific defaults. */
|
||||
void initSentinelConfig(void) {
|
||||
server.port = REDIS_SENTINEL_PORT;
|
||||
server.protected_mode = 0; /* Sentinel must be exposed. */
|
||||
g_pserver->port = REDIS_SENTINEL_PORT;
|
||||
g_pserver->protected_mode = 0; /* Sentinel must be exposed. */
|
||||
}
|
||||
|
||||
/* Perform the Sentinel mode initialization. */
|
||||
@@ -470,12 +470,12 @@ void initSentinel(void) {
|
||||
|
||||
/* Remove usual Redis commands from the command table, then just add
|
||||
* the SENTINEL command. */
|
||||
dictEmpty(server.commands,NULL);
|
||||
dictEmpty(g_pserver->commands,NULL);
|
||||
for (j = 0; j < sizeof(sentinelcmds)/sizeof(sentinelcmds[0]); j++) {
|
||||
int retval;
|
||||
struct redisCommand *cmd = sentinelcmds+j;
|
||||
|
||||
retval = dictAdd(server.commands, sdsnew(cmd->name), cmd);
|
||||
retval = dictAdd(g_pserver->commands, sdsnew(cmd->name), cmd);
|
||||
serverAssert(retval == DICT_OK);
|
||||
|
||||
/* Translate the command string flags description into an actual
|
||||
@@ -504,14 +504,14 @@ void initSentinel(void) {
|
||||
void sentinelIsRunning(void) {
|
||||
int j;
|
||||
|
||||
if (server.configfile == NULL) {
|
||||
if (cserver.configfile == NULL) {
|
||||
serverLog(LL_WARNING,
|
||||
"Sentinel started without a config file. Exiting...");
|
||||
exit(1);
|
||||
} else if (access(server.configfile,W_OK) == -1) {
|
||||
} else if (access(cserver.configfile,W_OK) == -1) {
|
||||
serverLog(LL_WARNING,
|
||||
"Sentinel config file %s is not writable: %s. Exiting...",
|
||||
server.configfile,strerror(errno));
|
||||
cserver.configfile,strerror(errno));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -554,7 +554,7 @@ sentinelAddr *createSentinelAddr(char *hostname, int port) {
|
||||
errno = ENOENT;
|
||||
return NULL;
|
||||
}
|
||||
sa = zmalloc(sizeof(*sa), MALLOC_LOCAL);
|
||||
sa = (sentinelAddr*)zmalloc(sizeof(*sa), MALLOC_LOCAL);
|
||||
sa->ip = sdsnew(ip);
|
||||
sa->port = port;
|
||||
return sa;
|
||||
@@ -564,7 +564,7 @@ sentinelAddr *createSentinelAddr(char *hostname, int port) {
|
||||
sentinelAddr *dupSentinelAddr(sentinelAddr *src) {
|
||||
sentinelAddr *sa;
|
||||
|
||||
sa = zmalloc(sizeof(*sa), MALLOC_LOCAL);
|
||||
sa = (sentinelAddr*)zmalloc(sizeof(*sa), MALLOC_LOCAL);
|
||||
sa->ip = sdsnew(src->ip);
|
||||
sa->port = src->port;
|
||||
return sa;
|
||||
@@ -607,7 +607,7 @@ int sentinelAddrIsEqual(sentinelAddr *a, sentinelAddr *b) {
|
||||
*
|
||||
* Any other specifier after "%@" is processed by printf itself.
|
||||
*/
|
||||
void sentinelEvent(int level, char *type, sentinelRedisInstance *ri,
|
||||
void sentinelEvent(int level, const char *type, sentinelRedisInstance *ri,
|
||||
const char *fmt, ...) {
|
||||
va_list ap;
|
||||
char msg[LOG_MAX_LEN];
|
||||
@@ -641,7 +641,7 @@ void sentinelEvent(int level, char *type, sentinelRedisInstance *ri,
|
||||
}
|
||||
|
||||
/* Log the message if the log level allows it to be logged. */
|
||||
if (level >= server.verbosity)
|
||||
if (level >= cserver.verbosity)
|
||||
serverLog(level,"%s %s",type,msg);
|
||||
|
||||
/* Publish the message via Pub/Sub if it's not a debugging one. */
|
||||
@@ -674,7 +674,7 @@ void sentinelGenerateInitialMonitorEvents(void) {
|
||||
|
||||
di = dictGetIterator(sentinel.masters);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
sentinelEvent(LL_WARNING,"+monitor",ri,"%@ quorum %d",ri->quorum);
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
@@ -708,10 +708,10 @@ void sentinelScheduleScriptExecution(char *path, ...) {
|
||||
va_end(ap);
|
||||
argv[0] = sdsnew(path);
|
||||
|
||||
sj = zmalloc(sizeof(*sj), MALLOC_LOCAL);
|
||||
sj = (sentinelScriptJob*)zmalloc(sizeof(*sj), MALLOC_LOCAL);
|
||||
sj->flags = SENTINEL_SCRIPT_NONE;
|
||||
sj->retry_num = 0;
|
||||
sj->argv = zmalloc(sizeof(char*)*(argc+1), MALLOC_LOCAL);
|
||||
sj->argv = (char**)zmalloc(sizeof(char*)*(argc+1), MALLOC_LOCAL);
|
||||
sj->start_time = 0;
|
||||
sj->pid = 0;
|
||||
memcpy(sj->argv,argv,sizeof(char*)*(argc+1));
|
||||
@@ -725,7 +725,7 @@ void sentinelScheduleScriptExecution(char *path, ...) {
|
||||
|
||||
listRewind(sentinel.scripts_queue,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sj = ln->value;
|
||||
sj = (sentinelScriptJob*)ln->value;
|
||||
|
||||
if (sj->flags & SENTINEL_SCRIPT_RUNNING) continue;
|
||||
/* The first node is the oldest as we add on tail. */
|
||||
@@ -746,7 +746,7 @@ listNode *sentinelGetScriptListNodeByPid(pid_t pid) {
|
||||
|
||||
listRewind(sentinel.scripts_queue,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sentinelScriptJob *sj = ln->value;
|
||||
sentinelScriptJob *sj = (sentinelScriptJob*)ln->value;
|
||||
|
||||
if ((sj->flags & SENTINEL_SCRIPT_RUNNING) && sj->pid == pid)
|
||||
return ln;
|
||||
@@ -767,7 +767,7 @@ void sentinelRunPendingScripts(void) {
|
||||
while (sentinel.running_scripts < SENTINEL_SCRIPT_MAX_RUNNING &&
|
||||
(ln = listNext(&li)) != NULL)
|
||||
{
|
||||
sentinelScriptJob *sj = ln->value;
|
||||
sentinelScriptJob *sj = (sentinelScriptJob*)ln->value;
|
||||
pid_t pid;
|
||||
|
||||
/* Skip if already running. */
|
||||
@@ -839,7 +839,7 @@ void sentinelCollectTerminatedScripts(void) {
|
||||
serverLog(LL_WARNING,"wait3() returned a pid (%ld) we can't find in our scripts execution queue!", (long)pid);
|
||||
continue;
|
||||
}
|
||||
sj = ln->value;
|
||||
sj = (sentinelScriptJob*)ln->value;
|
||||
|
||||
/* If the script was terminated by a signal or returns an
|
||||
* exit code of "1" (that means: please retry), we reschedule it
|
||||
@@ -874,7 +874,7 @@ void sentinelKillTimedoutScripts(void) {
|
||||
|
||||
listRewind(sentinel.scripts_queue,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sentinelScriptJob *sj = ln->value;
|
||||
sentinelScriptJob *sj = (sentinelScriptJob*)ln->value;
|
||||
|
||||
if (sj->flags & SENTINEL_SCRIPT_RUNNING &&
|
||||
(now - sj->start_time) > SENTINEL_SCRIPT_MAX_RUNTIME)
|
||||
@@ -894,7 +894,7 @@ void sentinelPendingScriptsCommand(client *c) {
|
||||
addReplyArrayLen(c,listLength(sentinel.scripts_queue));
|
||||
listRewind(sentinel.scripts_queue,&li);
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
sentinelScriptJob *sj = ln->value;
|
||||
sentinelScriptJob *sj = (sentinelScriptJob*)ln->value;
|
||||
int j = 0;
|
||||
|
||||
addReplyMapLen(c,5);
|
||||
@@ -939,7 +939,7 @@ void sentinelPendingScriptsCommand(client *c) {
|
||||
*
|
||||
* from/to fields are respectively master -> promoted slave addresses for
|
||||
* "start" and "end". */
|
||||
void sentinelCallClientReconfScript(sentinelRedisInstance *master, int role, char *state, sentinelAddr *from, sentinelAddr *to) {
|
||||
void sentinelCallClientReconfScript(sentinelRedisInstance *master, int role, const char *state, sentinelAddr *from, sentinelAddr *to) {
|
||||
char fromport[32], toport[32];
|
||||
|
||||
if (master->client_reconfig_script == NULL) return;
|
||||
@@ -955,7 +955,7 @@ void sentinelCallClientReconfScript(sentinelRedisInstance *master, int role, cha
|
||||
|
||||
/* Create a not yet connected link object. */
|
||||
instanceLink *createInstanceLink(void) {
|
||||
instanceLink *link = zmalloc(sizeof(*link), MALLOC_LOCAL);
|
||||
instanceLink *link = (instanceLink*)zmalloc(sizeof(*link), MALLOC_LOCAL);
|
||||
|
||||
link->refcount = 1;
|
||||
link->disconnected = 1;
|
||||
@@ -1053,7 +1053,7 @@ int sentinelTryConnectionSharing(sentinelRedisInstance *ri) {
|
||||
|
||||
di = dictGetIterator(sentinel.masters);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *master = dictGetVal(de), *match;
|
||||
sentinelRedisInstance *master = (sentinelRedisInstance*)dictGetVal(de), *match;
|
||||
/* We want to share with the same physical Sentinel referenced
|
||||
* in other masters, so skip our master. */
|
||||
if (master == ri->master) continue;
|
||||
@@ -1087,7 +1087,7 @@ int sentinelUpdateSentinelAddressInAllMasters(sentinelRedisInstance *ri) {
|
||||
|
||||
di = dictGetIterator(sentinel.masters);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *master = dictGetVal(de), *match;
|
||||
sentinelRedisInstance *master = (sentinelRedisInstance*)dictGetVal(de), *match;
|
||||
match = getSentinelRedisInstanceByAddrAndRunID(master->sentinels,
|
||||
NULL,0,ri->runid);
|
||||
/* If there is no match, this master does not know about this
|
||||
@@ -1122,7 +1122,7 @@ int sentinelUpdateSentinelAddressInAllMasters(sentinelRedisInstance *ri) {
|
||||
* Note: we don't free the hiredis context as hiredis will do it for us
|
||||
* for async connections. */
|
||||
void instanceLinkConnectionError(const redisAsyncContext *c) {
|
||||
instanceLink *link = c->data;
|
||||
instanceLink *link = (instanceLink*)c->data;
|
||||
int pubsub;
|
||||
|
||||
if (!link) return;
|
||||
@@ -1205,7 +1205,7 @@ sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *
|
||||
}
|
||||
|
||||
/* Create the instance object. */
|
||||
ri = zmalloc(sizeof(*ri), MALLOC_LOCAL);
|
||||
ri = (sentinelRedisInstance*)zmalloc(sizeof(*ri), MALLOC_LOCAL);
|
||||
/* Note that all the instances are started in the disconnected state,
|
||||
* the event loop will take care of connecting them. */
|
||||
ri->flags = flags;
|
||||
@@ -1303,7 +1303,7 @@ sentinelRedisInstance *sentinelRedisInstanceLookupSlave(
|
||||
serverAssert(ri->flags & SRI_MASTER);
|
||||
anetFormatAddr(buf,sizeof(buf),ip,port);
|
||||
key = sdsnew(buf);
|
||||
slave = dictFetchValue(ri->slaves,key);
|
||||
slave = (sentinelRedisInstance*)dictFetchValue(ri->slaves,key);
|
||||
sdsfree(key);
|
||||
return slave;
|
||||
}
|
||||
@@ -1336,7 +1336,7 @@ int removeMatchingSentinelFromMaster(sentinelRedisInstance *master, char *runid)
|
||||
|
||||
di = dictGetSafeIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (ri->runid && strcmp(ri->runid,runid) == 0) {
|
||||
dictDelete(master->sentinels,ri->name);
|
||||
@@ -1361,7 +1361,7 @@ sentinelRedisInstance *getSentinelRedisInstanceByAddrAndRunID(dict *instances, c
|
||||
serverAssert(ip || runid); /* User must pass at least one search param. */
|
||||
di = dictGetIterator(instances);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (runid && !ri->runid) continue;
|
||||
if ((runid == NULL || strcmp(ri->runid, runid) == 0) &&
|
||||
@@ -1381,7 +1381,7 @@ sentinelRedisInstance *sentinelGetMasterByName(char *name) {
|
||||
sentinelRedisInstance *ri;
|
||||
sds sdsname = sdsnew(name);
|
||||
|
||||
ri = dictFetchValue(sentinel.masters,sdsname);
|
||||
ri = (sentinelRedisInstance*)dictFetchValue(sentinel.masters,sdsname);
|
||||
sdsfree(sdsname);
|
||||
return ri;
|
||||
}
|
||||
@@ -1393,7 +1393,7 @@ void sentinelAddFlagsToDictOfRedisInstances(dict *instances, int flags) {
|
||||
|
||||
di = dictGetIterator(instances);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
ri->flags |= flags;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
@@ -1407,7 +1407,7 @@ void sentinelDelFlagsToDictOfRedisInstances(dict *instances, int flags) {
|
||||
|
||||
di = dictGetIterator(instances);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
ri->flags &= ~flags;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
@@ -1467,7 +1467,7 @@ int sentinelResetMastersByPattern(char *pattern, int flags) {
|
||||
|
||||
di = dictGetIterator(sentinel.masters);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (ri->name) {
|
||||
if (stringmatch(pattern,ri->name,0)) {
|
||||
@@ -1501,10 +1501,10 @@ int sentinelResetMasterAndChangeAddress(sentinelRedisInstance *master, char *ip,
|
||||
* Don't include the one having the address we are switching to. */
|
||||
di = dictGetIterator(master->slaves);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *slave = dictGetVal(de);
|
||||
sentinelRedisInstance *slave = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (sentinelAddrIsEqual(slave->addr,newaddr)) continue;
|
||||
slaves = zrealloc(slaves,sizeof(sentinelAddr*)*(numslaves+1), MALLOC_LOCAL);
|
||||
slaves = (sentinelAddr**)zrealloc(slaves,sizeof(sentinelAddr*)*(numslaves+1), MALLOC_LOCAL);
|
||||
slaves[numslaves++] = createSentinelAddr(slave->addr->ip,
|
||||
slave->addr->port);
|
||||
}
|
||||
@@ -1514,7 +1514,7 @@ int sentinelResetMasterAndChangeAddress(sentinelRedisInstance *master, char *ip,
|
||||
* as a slave as well, so that we'll be able to sense / reconfigure
|
||||
* the old master. */
|
||||
if (!sentinelAddrIsEqual(newaddr,master->addr)) {
|
||||
slaves = zrealloc(slaves,sizeof(sentinelAddr*)*(numslaves+1), MALLOC_LOCAL);
|
||||
slaves = (sentinelAddr**)zrealloc(slaves,sizeof(sentinelAddr*)*(numslaves+1), MALLOC_LOCAL);
|
||||
slaves[numslaves++] = createSentinelAddr(master->addr->ip,
|
||||
master->addr->port);
|
||||
}
|
||||
@@ -1584,14 +1584,14 @@ void sentinelPropagateDownAfterPeriod(sentinelRedisInstance *master) {
|
||||
for (j = 0; d[j]; j++) {
|
||||
di = dictGetIterator(d[j]);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
ri->down_after_period = master->down_after_period;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
}
|
||||
|
||||
char *sentinelGetInstanceTypeString(sentinelRedisInstance *ri) {
|
||||
const char *sentinelGetInstanceTypeString(sentinelRedisInstance *ri) {
|
||||
if (ri->flags & SRI_MASTER) return "master";
|
||||
else if (ri->flags & SRI_SLAVE) return "slave";
|
||||
else if (ri->flags & SRI_SENTINEL) return "sentinel";
|
||||
@@ -1605,16 +1605,16 @@ char *sentinelGetInstanceTypeString(sentinelRedisInstance *ri) {
|
||||
* we check the one of the master), and map the command that we should send
|
||||
* to the set of renamed commads. However, if the command was not renamed,
|
||||
* we just return "command" itself. */
|
||||
char *sentinelInstanceMapCommand(sentinelRedisInstance *ri, char *command) {
|
||||
const char *sentinelInstanceMapCommand(sentinelRedisInstance *ri, const char *command) {
|
||||
sds sc = sdsnew(command);
|
||||
if (ri->master) ri = ri->master;
|
||||
char *retval = dictFetchValue(ri->renamed_commands, sc);
|
||||
char *retval = (char*)dictFetchValue(ri->renamed_commands, sc);
|
||||
sdsfree(sc);
|
||||
return retval ? retval : command;
|
||||
}
|
||||
|
||||
/* ============================ Config handling ============================= */
|
||||
char *sentinelHandleConfiguration(char **argv, int argc) {
|
||||
const char *sentinelHandleConfiguration(char **argv, int argc) {
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
if (!strcasecmp(argv[0],"monitor") && argc == 5) {
|
||||
@@ -1781,7 +1781,7 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
sentinelAddr *master_addr;
|
||||
|
||||
/* sentinel monitor */
|
||||
master = dictGetVal(de);
|
||||
master = (sentinelRedisInstance*)dictGetVal(de);
|
||||
master_addr = sentinelGetCurrentMasterAddress(master);
|
||||
line = sdscatprintf(sdsempty(),"sentinel monitor %s %s %d %d",
|
||||
master->name, master_addr->ip, master_addr->port,
|
||||
@@ -1853,7 +1853,7 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
while((de = dictNext(di2)) != NULL) {
|
||||
sentinelAddr *slave_addr;
|
||||
|
||||
ri = dictGetVal(de);
|
||||
ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
slave_addr = ri->addr;
|
||||
|
||||
/* If master_addr (obtained using sentinelGetCurrentMasterAddress()
|
||||
@@ -1873,7 +1873,7 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
/* sentinel known-sentinel */
|
||||
di2 = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di2)) != NULL) {
|
||||
ri = dictGetVal(de);
|
||||
ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
if (ri->runid == NULL) continue;
|
||||
line = sdscatprintf(sdsempty(),
|
||||
"sentinel known-sentinel %s %s %d %s",
|
||||
@@ -1885,8 +1885,8 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
/* sentinel rename-command */
|
||||
di2 = dictGetIterator(master->renamed_commands);
|
||||
while((de = dictNext(di2)) != NULL) {
|
||||
sds oldname = dictGetKey(de);
|
||||
sds newname = dictGetVal(de);
|
||||
sds oldname = (sds)dictGetKey(de);
|
||||
sds newname = (sds)dictGetVal(de);
|
||||
line = sdscatprintf(sdsempty(),
|
||||
"sentinel rename-command %s %s %s",
|
||||
master->name, oldname, newname);
|
||||
@@ -1926,15 +1926,15 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
* On failure the function logs a warning on the Redis log. */
|
||||
void sentinelFlushConfig(void) {
|
||||
int fd = -1;
|
||||
int saved_hz = server.hz;
|
||||
int saved_hz = g_pserver->hz;
|
||||
int rewrite_status;
|
||||
|
||||
server.hz = CONFIG_DEFAULT_HZ;
|
||||
rewrite_status = rewriteConfig(server.configfile);
|
||||
server.hz = saved_hz;
|
||||
g_pserver->hz = CONFIG_DEFAULT_HZ;
|
||||
rewrite_status = rewriteConfig(cserver.configfile);
|
||||
g_pserver->hz = saved_hz;
|
||||
|
||||
if (rewrite_status == -1) goto werr;
|
||||
if ((fd = open(server.configfile,O_RDONLY)) == -1) goto werr;
|
||||
if ((fd = open(cserver.configfile,O_RDONLY)) == -1) goto werr;
|
||||
if (fsync(fd) == -1) goto werr;
|
||||
if (close(fd) == EOF) goto werr;
|
||||
return;
|
||||
@@ -1982,7 +1982,7 @@ void sentinelSendAuthIfNeeded(sentinelRedisInstance *ri, redisAsyncContext *c) {
|
||||
*
|
||||
* This makes it possible to list all the sentinel instances connected
|
||||
* to a Redis servewr with CLIENT LIST, grepping for a specific name format. */
|
||||
void sentinelSetClientName(sentinelRedisInstance *ri, redisAsyncContext *c, char *type) {
|
||||
void sentinelSetClientName(sentinelRedisInstance *ri, redisAsyncContext *c, const char *type) {
|
||||
char name[64];
|
||||
|
||||
snprintf(name,sizeof(name),"sentinel-%.8s-%s",sentinel.myid,type);
|
||||
@@ -2018,7 +2018,7 @@ void sentinelReconnectInstance(sentinelRedisInstance *ri) {
|
||||
link->pending_commands = 0;
|
||||
link->cc_conn_time = mstime();
|
||||
link->cc->data = link;
|
||||
redisAeAttach(server.rgthreadvar[IDX_EVENT_LOOP_MAIN].el,link->cc);
|
||||
redisAeAttach(g_pserver->rgthreadvar[IDX_EVENT_LOOP_MAIN].el,link->cc);
|
||||
redisAsyncSetConnectCallback(link->cc,
|
||||
sentinelLinkEstablishedCallback);
|
||||
redisAsyncSetDisconnectCallback(link->cc,
|
||||
@@ -2042,7 +2042,7 @@ void sentinelReconnectInstance(sentinelRedisInstance *ri) {
|
||||
|
||||
link->pc_conn_time = mstime();
|
||||
link->pc->data = link;
|
||||
redisAeAttach(server.rgthreadvar[IDX_EVENT_LOOP_MAIN].el,link->pc);
|
||||
redisAeAttach(g_pserver->rgthreadvar[IDX_EVENT_LOOP_MAIN].el,link->pc);
|
||||
redisAsyncSetConnectCallback(link->pc,
|
||||
sentinelLinkEstablishedCallback);
|
||||
redisAsyncSetDisconnectCallback(link->pc,
|
||||
@@ -2337,13 +2337,13 @@ void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) {
|
||||
}
|
||||
|
||||
void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = privdata;
|
||||
instanceLink *link = c->data;
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)privdata;
|
||||
instanceLink *link = (instanceLink*)c->data;
|
||||
redisReply *r;
|
||||
|
||||
if (!reply || !link) return;
|
||||
link->pending_commands--;
|
||||
r = reply;
|
||||
r = (redisReply*)reply;
|
||||
|
||||
if (r->type == REDIS_REPLY_STRING)
|
||||
sentinelRefreshInstanceInfo(ri,r->str);
|
||||
@@ -2352,7 +2352,7 @@ void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata
|
||||
/* Just discard the reply. We use this when we are not monitoring the return
|
||||
* value of the command but its effects directly. */
|
||||
void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
instanceLink *link = c->data;
|
||||
instanceLink *link = (instanceLink*)c->data;
|
||||
UNUSED(reply);
|
||||
UNUSED(privdata);
|
||||
|
||||
@@ -2360,13 +2360,13 @@ void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privd
|
||||
}
|
||||
|
||||
void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = privdata;
|
||||
instanceLink *link = c->data;
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)privdata;
|
||||
instanceLink *link = (instanceLink*)c->data;
|
||||
redisReply *r;
|
||||
|
||||
if (!reply || !link) return;
|
||||
link->pending_commands--;
|
||||
r = reply;
|
||||
r = (redisReply*)reply;
|
||||
|
||||
if (r->type == REDIS_REPLY_STATUS ||
|
||||
r->type == REDIS_REPLY_ERROR) {
|
||||
@@ -2402,13 +2402,13 @@ void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata
|
||||
/* This is called when we get the reply about the PUBLISH command we send
|
||||
* to the master to advertise this sentinel. */
|
||||
void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = privdata;
|
||||
instanceLink *link = c->data;
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)privdata;
|
||||
instanceLink *link = (instanceLink*)c->data;
|
||||
redisReply *r;
|
||||
|
||||
if (!reply || !link) return;
|
||||
link->pending_commands--;
|
||||
r = reply;
|
||||
r = (redisReply*)reply;
|
||||
|
||||
/* Only update pub_time if we actually published our message. Otherwise
|
||||
* we'll retry again in 100 milliseconds. */
|
||||
@@ -2421,7 +2421,7 @@ void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privd
|
||||
*
|
||||
* If the master name specified in the message is not known, the message is
|
||||
* discarded. */
|
||||
void sentinelProcessHelloMessage(char *hello, int hello_len) {
|
||||
void sentinelProcessHelloMessage(const char *hello, int hello_len) {
|
||||
/* Format is composed of 8 tokens:
|
||||
* 0=ip,1=port,2=runid,3=current_epoch,4=master_name,
|
||||
* 5=master_ip,6=master_port,7=master_config_epoch. */
|
||||
@@ -2526,12 +2526,12 @@ cleanup:
|
||||
/* This is our Pub/Sub callback for the Hello channel. It's useful in order
|
||||
* to discover other sentinels attached at the same master. */
|
||||
void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = privdata;
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)privdata;
|
||||
redisReply *r;
|
||||
UNUSED(c);
|
||||
|
||||
if (!reply || !ri) return;
|
||||
r = reply;
|
||||
r = (redisReply*)reply;
|
||||
|
||||
/* Update the last activity in the pubsub channel. Note that since we
|
||||
* receive our messages as well this timestamp can be used to detect
|
||||
@@ -2585,7 +2585,7 @@ int sentinelSendHello(sentinelRedisInstance *ri) {
|
||||
announce_ip = ip;
|
||||
}
|
||||
announce_port = sentinel.announce_port ?
|
||||
sentinel.announce_port : server.port;
|
||||
sentinel.announce_port : g_pserver->port;
|
||||
|
||||
/* Format and send the Hello message. */
|
||||
snprintf(payload,sizeof(payload),
|
||||
@@ -2613,7 +2613,7 @@ void sentinelForceHelloUpdateDictOfRedisInstances(dict *instances) {
|
||||
|
||||
di = dictGetSafeIterator(instances);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
if (ri->last_pub_time >= (SENTINEL_PUBLISH_PERIOD+1))
|
||||
ri->last_pub_time -= (SENTINEL_PUBLISH_PERIOD+1);
|
||||
}
|
||||
@@ -2940,7 +2940,7 @@ void addReplyDictOfRedisInstances(client *c, dict *instances) {
|
||||
di = dictGetIterator(instances);
|
||||
addReplyArrayLen(c,dictSize(instances));
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
addReplySentinelRedisInstance(c,ri);
|
||||
}
|
||||
@@ -2955,7 +2955,7 @@ sentinelRedisInstance *sentinelGetMasterByNameOrReplyError(client *c,
|
||||
{
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
ri = dictFetchValue(sentinel.masters,ptrFromObj(name));
|
||||
ri = (sentinelRedisInstance*)dictFetchValue(sentinel.masters,ptrFromObj(name));
|
||||
if (!ri) {
|
||||
addReplyError(c,"No such master with that name");
|
||||
return NULL;
|
||||
@@ -2975,7 +2975,7 @@ int sentinelIsQuorumReachable(sentinelRedisInstance *master, int *usableptr) {
|
||||
|
||||
di = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (ri->flags & (SRI_S_DOWN|SRI_O_DOWN)) continue;
|
||||
usable++;
|
||||
@@ -2989,11 +2989,11 @@ int sentinelIsQuorumReachable(sentinelRedisInstance *master, int *usableptr) {
|
||||
}
|
||||
|
||||
void sentinelCommand(client *c) {
|
||||
if (!strcasecmp(ptrFromObj(c->argv[1]),"masters")) {
|
||||
if (!strcasecmp(szFromObj(c->argv[1]),"masters")) {
|
||||
/* SENTINEL MASTERS */
|
||||
if (c->argc != 2) goto numargserr;
|
||||
addReplyDictOfRedisInstances(c,sentinel.masters);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"master")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"master")) {
|
||||
/* SENTINEL MASTER <name> */
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
@@ -3001,8 +3001,8 @@ void sentinelCommand(client *c) {
|
||||
if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2]))
|
||||
== NULL) return;
|
||||
addReplySentinelRedisInstance(c,ri);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"slaves") ||
|
||||
!strcasecmp(ptrFromObj(c->argv[1]),"replicas"))
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"slaves") ||
|
||||
!strcasecmp(szFromObj(c->argv[1]),"replicas"))
|
||||
{
|
||||
/* SENTINEL REPLICAS <master-name> */
|
||||
sentinelRedisInstance *ri;
|
||||
@@ -3011,7 +3011,7 @@ void sentinelCommand(client *c) {
|
||||
if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
|
||||
return;
|
||||
addReplyDictOfRedisInstances(c,ri->slaves);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"sentinels")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"sentinels")) {
|
||||
/* SENTINEL SENTINELS <master-name> */
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
@@ -3019,7 +3019,7 @@ void sentinelCommand(client *c) {
|
||||
if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2])) == NULL)
|
||||
return;
|
||||
addReplyDictOfRedisInstances(c,ri->sentinels);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"is-master-down-by-addr")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"is-master-down-by-addr")) {
|
||||
/* SENTINEL IS-MASTER-DOWN-BY-ADDR <ip> <port> <current-epoch> <runid>
|
||||
*
|
||||
* Arguments:
|
||||
@@ -3050,7 +3050,7 @@ void sentinelCommand(client *c) {
|
||||
!= C_OK)
|
||||
return;
|
||||
ri = getSentinelRedisInstanceByAddrAndRunID(sentinel.masters,
|
||||
ptrFromObj(c->argv[2]),port,NULL);
|
||||
szFromObj(c->argv[2]),port,NULL);
|
||||
|
||||
/* It exists? Is actually a master? Is subjectively down? It's down.
|
||||
* Note: if we are in tilt mode we always reply with "0". */
|
||||
@@ -3060,9 +3060,9 @@ void sentinelCommand(client *c) {
|
||||
|
||||
/* Vote for the master (or fetch the previous vote) if the request
|
||||
* includes a runid, otherwise the sender is not seeking for a vote. */
|
||||
if (ri && ri->flags & SRI_MASTER && strcasecmp(ptrFromObj(c->argv[5]),"*")) {
|
||||
if (ri && ri->flags & SRI_MASTER && strcasecmp(szFromObj(c->argv[5]),"*")) {
|
||||
leader = sentinelVoteLeader(ri,(uint64_t)req_epoch,
|
||||
ptrFromObj(c->argv[5]),
|
||||
szFromObj(c->argv[5]),
|
||||
&leader_epoch);
|
||||
}
|
||||
|
||||
@@ -3073,16 +3073,16 @@ void sentinelCommand(client *c) {
|
||||
addReplyBulkCString(c, leader ? leader : "*");
|
||||
addReplyLongLong(c, (long long)leader_epoch);
|
||||
if (leader) sdsfree(leader);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"reset")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"reset")) {
|
||||
/* SENTINEL RESET <pattern> */
|
||||
if (c->argc != 3) goto numargserr;
|
||||
addReplyLongLong(c,sentinelResetMastersByPattern(ptrFromObj(c->argv[2]),SENTINEL_GENERATE_EVENT));
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"get-master-addr-by-name")) {
|
||||
addReplyLongLong(c,sentinelResetMastersByPattern(szFromObj(c->argv[2]),SENTINEL_GENERATE_EVENT));
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"get-master-addr-by-name")) {
|
||||
/* SENTINEL GET-MASTER-ADDR-BY-NAME <master-name> */
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
if (c->argc != 3) goto numargserr;
|
||||
ri = sentinelGetMasterByName(ptrFromObj(c->argv[2]));
|
||||
ri = sentinelGetMasterByName(szFromObj(c->argv[2]));
|
||||
if (ri == NULL) {
|
||||
addReplyNullArray(c);
|
||||
} else {
|
||||
@@ -3092,7 +3092,7 @@ void sentinelCommand(client *c) {
|
||||
addReplyBulkCString(c,addr->ip);
|
||||
addReplyBulkLongLong(c,addr->port);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"failover")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"failover")) {
|
||||
/* SENTINEL FAILOVER <master-name> */
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
@@ -3112,12 +3112,12 @@ void sentinelCommand(client *c) {
|
||||
sentinelStartFailover(ri);
|
||||
ri->flags |= SRI_FORCE_FAILOVER;
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"pending-scripts")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"pending-scripts")) {
|
||||
/* SENTINEL PENDING-SCRIPTS */
|
||||
|
||||
if (c->argc != 2) goto numargserr;
|
||||
sentinelPendingScriptsCommand(c);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"monitor")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"monitor")) {
|
||||
/* SENTINEL MONITOR <name> <ip> <port> <quorum> */
|
||||
sentinelRedisInstance *ri;
|
||||
long quorum, port;
|
||||
@@ -3137,14 +3137,14 @@ void sentinelCommand(client *c) {
|
||||
/* Make sure the IP field is actually a valid IP before passing it
|
||||
* to createSentinelRedisInstance(), otherwise we may trigger a
|
||||
* DNS lookup at runtime. */
|
||||
if (anetResolveIP(NULL,ptrFromObj(c->argv[3]),ip,sizeof(ip)) == ANET_ERR) {
|
||||
if (anetResolveIP(NULL,szFromObj(c->argv[3]),ip,sizeof(ip)) == ANET_ERR) {
|
||||
addReplyError(c,"Invalid IP address specified");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Parameters are valid. Try to create the master instance. */
|
||||
ri = createSentinelRedisInstance(ptrFromObj(c->argv[2]),SRI_MASTER,
|
||||
ptrFromObj(c->argv[3]),port,quorum,NULL);
|
||||
ri = createSentinelRedisInstance(szFromObj(c->argv[2]),SRI_MASTER,
|
||||
szFromObj(c->argv[3]),port,quorum,NULL);
|
||||
if (ri == NULL) {
|
||||
switch(errno) {
|
||||
case EBUSY:
|
||||
@@ -3162,12 +3162,12 @@ void sentinelCommand(client *c) {
|
||||
sentinelEvent(LL_WARNING,"+monitor",ri,"%@ quorum %d",ri->quorum);
|
||||
addReply(c,shared.ok);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"flushconfig")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"flushconfig")) {
|
||||
if (c->argc != 2) goto numargserr;
|
||||
sentinelFlushConfig();
|
||||
addReply(c,shared.ok);
|
||||
return;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"remove")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"remove")) {
|
||||
/* SENTINEL REMOVE <name> */
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
@@ -3178,7 +3178,7 @@ void sentinelCommand(client *c) {
|
||||
dictDelete(sentinel.masters,ptrFromObj(c->argv[2]));
|
||||
sentinelFlushConfig();
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"ckquorum")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"ckquorum")) {
|
||||
/* SENTINEL CKQUORUM <name> */
|
||||
sentinelRedisInstance *ri;
|
||||
int usable;
|
||||
@@ -3205,10 +3205,10 @@ void sentinelCommand(client *c) {
|
||||
e = sdscat(e,"\r\n");
|
||||
addReplySds(c,e);
|
||||
}
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"set")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"set")) {
|
||||
if (c->argc < 3) goto numargserr;
|
||||
sentinelSetCommand(c);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"info-cache")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"info-cache")) {
|
||||
/* SENTINEL INFO-CACHE <name> */
|
||||
if (c->argc < 2) goto numargserr;
|
||||
mstime_t now = mstime();
|
||||
@@ -3224,7 +3224,7 @@ void sentinelCommand(client *c) {
|
||||
|
||||
for (int i = 2; i < c->argc; i++) {
|
||||
sentinelRedisInstance *ri;
|
||||
ri = sentinelGetMasterByName(ptrFromObj(c->argv[i]));
|
||||
ri = sentinelGetMasterByName(szFromObj(c->argv[i]));
|
||||
if (!ri) continue; /* ignore non-existing names */
|
||||
dictAdd(masters_local, ri->name, ri);
|
||||
}
|
||||
@@ -3244,7 +3244,7 @@ void sentinelCommand(client *c) {
|
||||
dictEntry *de;
|
||||
di = dictGetIterator(masters_local);
|
||||
while ((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
addReplyBulkCBuffer(c,ri->name,strlen(ri->name));
|
||||
addReplyArrayLen(c,dictSize(ri->slaves) + 1); /* +1 for self */
|
||||
addReplyArrayLen(c,2);
|
||||
@@ -3258,7 +3258,7 @@ void sentinelCommand(client *c) {
|
||||
dictEntry *sde;
|
||||
sdi = dictGetIterator(ri->slaves);
|
||||
while ((sde = dictNext(sdi)) != NULL) {
|
||||
sentinelRedisInstance *sri = dictGetVal(sde);
|
||||
sentinelRedisInstance *sri = (sentinelRedisInstance*)dictGetVal(sde);
|
||||
addReplyArrayLen(c,2);
|
||||
addReplyLongLong(c, now - sri->info_refresh);
|
||||
if (sri->info)
|
||||
@@ -3270,24 +3270,24 @@ void sentinelCommand(client *c) {
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
if (masters_local != sentinel.masters) dictRelease(masters_local);
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[1]),"simulate-failure")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[1]),"simulate-failure")) {
|
||||
/* SENTINEL SIMULATE-FAILURE <flag> <flag> ... <flag> */
|
||||
int j;
|
||||
|
||||
sentinel.simfailure_flags = SENTINEL_SIMFAILURE_NONE;
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
if (!strcasecmp(ptrFromObj(c->argv[j]),"crash-after-election")) {
|
||||
if (!strcasecmp(szFromObj(c->argv[j]),"crash-after-election")) {
|
||||
sentinel.simfailure_flags |=
|
||||
SENTINEL_SIMFAILURE_CRASH_AFTER_ELECTION;
|
||||
serverLog(LL_WARNING,"Failure simulation: this Sentinel "
|
||||
"will crash after being successfully elected as failover "
|
||||
"leader");
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"crash-after-promotion")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"crash-after-promotion")) {
|
||||
sentinel.simfailure_flags |=
|
||||
SENTINEL_SIMFAILURE_CRASH_AFTER_PROMOTION;
|
||||
serverLog(LL_WARNING,"Failure simulation: this Sentinel "
|
||||
"will crash after promoting the selected replica to master");
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"help")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"help")) {
|
||||
addReplyArrayLen(c,2);
|
||||
addReplyBulkCString(c,"crash-after-election");
|
||||
addReplyBulkCString(c,"crash-after-promotion");
|
||||
@@ -3326,7 +3326,7 @@ void sentinelInfoCommand(client *c) {
|
||||
}
|
||||
|
||||
int defsections = 0, allsections = 0;
|
||||
char *section = c->argc == 2 ? ptrFromObj(c->argv[1]) : NULL;
|
||||
char *section = c->argc == 2 ? szFromObj(c->argv[1]) : NULL;
|
||||
if (section) {
|
||||
allsections = !strcasecmp(section,"all");
|
||||
defsections = !strcasecmp(section,"default");
|
||||
@@ -3363,8 +3363,8 @@ void sentinelInfoCommand(client *c) {
|
||||
|
||||
di = dictGetIterator(sentinel.masters);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
char *status = "ok";
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
const char *status = "ok";
|
||||
|
||||
if (ri->flags & SRI_O_DOWN) status = "odown";
|
||||
else if (ri->flags & SRI_S_DOWN) status = "sdown";
|
||||
@@ -3394,7 +3394,7 @@ void sentinelRoleCommand(client *c) {
|
||||
|
||||
di = dictGetIterator(sentinel.masters);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
addReplyBulkCString(c,ri->name);
|
||||
}
|
||||
@@ -3414,7 +3414,7 @@ void sentinelSetCommand(client *c) {
|
||||
/* Process option - value pairs. */
|
||||
for (j = 3; j < c->argc; j++) {
|
||||
int moreargs = (c->argc-1) - j;
|
||||
option = ptrFromObj(c->argv[j]);
|
||||
option = szFromObj(c->argv[j]);
|
||||
long long ll;
|
||||
int old_j = j; /* Used to know what to log as an event. */
|
||||
|
||||
@@ -3448,7 +3448,7 @@ void sentinelSetCommand(client *c) {
|
||||
changes++;
|
||||
} else if (!strcasecmp(option,"notification-script") && moreargs > 0) {
|
||||
/* notification-script <path> */
|
||||
char *value = ptrFromObj(c->argv[++j]);
|
||||
char *value = szFromObj(c->argv[++j]);
|
||||
if (sentinel.deny_scripts_reconfig) {
|
||||
addReplyError(c,
|
||||
"Reconfiguration of scripts path is denied for "
|
||||
@@ -3468,7 +3468,7 @@ void sentinelSetCommand(client *c) {
|
||||
changes++;
|
||||
} else if (!strcasecmp(option,"client-reconfig-script") && moreargs > 0) {
|
||||
/* client-reconfig-script <path> */
|
||||
char *value = ptrFromObj(c->argv[++j]);
|
||||
char *value = szFromObj(c->argv[++j]);
|
||||
if (sentinel.deny_scripts_reconfig) {
|
||||
addReplyError(c,
|
||||
"Reconfiguration of scripts path is denied for "
|
||||
@@ -3489,7 +3489,7 @@ void sentinelSetCommand(client *c) {
|
||||
changes++;
|
||||
} else if (!strcasecmp(option,"auth-pass") && moreargs > 0) {
|
||||
/* auth-pass <password> */
|
||||
char *value = ptrFromObj(c->argv[++j]);
|
||||
char *value = szFromObj(c->argv[++j]);
|
||||
sdsfree(ri->auth_pass);
|
||||
ri->auth_pass = strlen(value) ? sdsnew(value) : NULL;
|
||||
changes++;
|
||||
@@ -3504,8 +3504,8 @@ void sentinelSetCommand(client *c) {
|
||||
changes++;
|
||||
} else if (!strcasecmp(option,"rename-command") && moreargs > 1) {
|
||||
/* rename-command <oldname> <newname> */
|
||||
sds oldname = ptrFromObj(c->argv[++j]);
|
||||
sds newname = ptrFromObj(c->argv[++j]);
|
||||
sds oldname = szFromObj(c->argv[++j]);
|
||||
sds newname = szFromObj(c->argv[++j]);
|
||||
|
||||
if ((sdslen(oldname) == 0) || (sdslen(newname) == 0)) {
|
||||
badarg = sdslen(newname) ? j-1 : j;
|
||||
@@ -3565,11 +3565,11 @@ badfmt: /* Bad format errors */
|
||||
* Because we have a Sentinel PUBLISH, the code to send hello messages is the same
|
||||
* for all the three kind of instances: masters, slaves, sentinels. */
|
||||
void sentinelPublishCommand(client *c) {
|
||||
if (strcmp(ptrFromObj(c->argv[1]),SENTINEL_HELLO_CHANNEL)) {
|
||||
if (strcmp(szFromObj(c->argv[1]),SENTINEL_HELLO_CHANNEL)) {
|
||||
addReplyError(c, "Only HELLO messages are accepted by Sentinel instances.");
|
||||
return;
|
||||
}
|
||||
sentinelProcessHelloMessage(ptrFromObj(c->argv[2]),sdslen(ptrFromObj(c->argv[2])));
|
||||
sentinelProcessHelloMessage(szFromObj(c->argv[2]),sdslen(szFromObj(c->argv[2])));
|
||||
addReplyLongLong(c,1);
|
||||
}
|
||||
|
||||
@@ -3659,7 +3659,7 @@ void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) {
|
||||
/* Count all the other sentinels. */
|
||||
di = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (ri->flags & SRI_MASTER_DOWN) quorum++;
|
||||
}
|
||||
@@ -3686,13 +3686,13 @@ void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) {
|
||||
/* Receive the SENTINEL is-master-down-by-addr reply, see the
|
||||
* sentinelAskMasterStateToOtherSentinels() function for more information. */
|
||||
void sentinelReceiveIsMasterDownReply(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = privdata;
|
||||
instanceLink *link = c->data;
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)privdata;
|
||||
instanceLink *link = (instanceLink*)c->data;
|
||||
redisReply *r;
|
||||
|
||||
if (!reply || !link) return;
|
||||
link->pending_commands--;
|
||||
r = reply;
|
||||
r = (redisReply*)reply;
|
||||
|
||||
/* Ignore every error or unexpected reply.
|
||||
* Note that if the command returns an error for any reason we'll
|
||||
@@ -3734,7 +3734,7 @@ void sentinelAskMasterStateToOtherSentinels(sentinelRedisInstance *master, int f
|
||||
|
||||
di = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
mstime_t elapsed = mstime() - ri->last_master_down_reply_time;
|
||||
char port[32];
|
||||
int retval;
|
||||
@@ -3860,7 +3860,7 @@ char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
|
||||
/* Count other sentinels votes */
|
||||
di = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
if (ri->leader != NULL && ri->leader_epoch == sentinel.current_epoch)
|
||||
sentinelLeaderIncr(counters,ri->leader);
|
||||
}
|
||||
@@ -3875,7 +3875,7 @@ char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
|
||||
|
||||
if (votes > max_votes) {
|
||||
max_votes = votes;
|
||||
winner = dictGetKey(de);
|
||||
winner = (char*)dictGetKey(de);
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
@@ -3917,7 +3917,7 @@ char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
|
||||
* The command returns C_OK if the SLAVEOF command was accepted for
|
||||
* (later) delivery otherwise C_ERR. The command replies are just
|
||||
* discarded. */
|
||||
int sentinelSendSlaveOf(sentinelRedisInstance *ri, char *host, int port) {
|
||||
int sentinelSendSlaveOf(sentinelRedisInstance *ri, const char *host, int port) {
|
||||
char portstr[32];
|
||||
int retval;
|
||||
|
||||
@@ -4096,7 +4096,7 @@ int compareSlavesForPromotion(const void *a, const void *b) {
|
||||
}
|
||||
|
||||
sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master) {
|
||||
sentinelRedisInstance **instance =
|
||||
sentinelRedisInstance **instance = (sentinelRedisInstance**)
|
||||
zmalloc(sizeof(instance[0])*dictSize(master->slaves), MALLOC_LOCAL);
|
||||
sentinelRedisInstance *selected = NULL;
|
||||
int instances = 0;
|
||||
@@ -4110,7 +4110,7 @@ sentinelRedisInstance *sentinelSelectSlave(sentinelRedisInstance *master) {
|
||||
|
||||
di = dictGetIterator(master->slaves);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *slave = dictGetVal(de);
|
||||
sentinelRedisInstance *slave = (sentinelRedisInstance*)dictGetVal(de);
|
||||
mstime_t info_validity_time;
|
||||
|
||||
if (slave->flags & (SRI_S_DOWN|SRI_O_DOWN)) continue;
|
||||
@@ -4245,7 +4245,7 @@ void sentinelFailoverDetectEnd(sentinelRedisInstance *master) {
|
||||
* configured. */
|
||||
di = dictGetIterator(master->slaves);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *slave = dictGetVal(de);
|
||||
sentinelRedisInstance *slave = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (slave->flags & (SRI_PROMOTED|SRI_RECONF_DONE)) continue;
|
||||
if (slave->flags & SRI_S_DOWN) continue;
|
||||
@@ -4275,7 +4275,7 @@ void sentinelFailoverDetectEnd(sentinelRedisInstance *master) {
|
||||
|
||||
di = dictGetIterator(master->slaves);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *slave = dictGetVal(de);
|
||||
sentinelRedisInstance *slave = (sentinelRedisInstance*)dictGetVal(de);
|
||||
int retval;
|
||||
|
||||
if (slave->flags & (SRI_RECONF_DONE|SRI_RECONF_SENT)) continue;
|
||||
@@ -4303,7 +4303,7 @@ void sentinelFailoverReconfNextSlave(sentinelRedisInstance *master) {
|
||||
|
||||
di = dictGetIterator(master->slaves);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *slave = dictGetVal(de);
|
||||
sentinelRedisInstance *slave = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
if (slave->flags & (SRI_RECONF_SENT|SRI_RECONF_INPROG))
|
||||
in_progress++;
|
||||
@@ -4314,7 +4314,7 @@ void sentinelFailoverReconfNextSlave(sentinelRedisInstance *master) {
|
||||
while(in_progress < master->parallel_syncs &&
|
||||
(de = dictNext(di)) != NULL)
|
||||
{
|
||||
sentinelRedisInstance *slave = dictGetVal(de);
|
||||
sentinelRedisInstance *slave = (sentinelRedisInstance*)dictGetVal(de);
|
||||
int retval;
|
||||
|
||||
/* Skip the promoted slave, and already configured slaves. */
|
||||
@@ -4461,7 +4461,7 @@ void sentinelHandleDictOfRedisInstances(dict *instances) {
|
||||
/* There are a number of things we need to perform against every master. */
|
||||
di = dictGetIterator(instances);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
sentinelRedisInstance *ri = (sentinelRedisInstance*)dictGetVal(de);
|
||||
|
||||
sentinelHandleRedisInstance(ri);
|
||||
if (ri->flags & SRI_MASTER) {
|
||||
@@ -4521,6 +4521,6 @@ void sentinelTimer(void) {
|
||||
* exactly continue to stay synchronized asking to be voted at the
|
||||
* same time again and again (resulting in nobody likely winning the
|
||||
* election because of split brain voting). */
|
||||
server.hz = CONFIG_DEFAULT_HZ + rand() % CONFIG_DEFAULT_HZ;
|
||||
g_pserver->hz = CONFIG_DEFAULT_HZ + rand() % CONFIG_DEFAULT_HZ;
|
||||
}
|
||||
|
||||
+1122
-905
File diff suppressed because it is too large.
Load diff
+649
-231
File diff suppressed because it is too large.
Load diff
@@ -46,12 +46,12 @@
|
||||
* Incrementing the ref count of all the objects retained is up to
|
||||
* this function. */
|
||||
slowlogEntry *slowlogCreateEntry(client *c, robj **argv, int argc, long long duration) {
|
||||
slowlogEntry *se = zmalloc(sizeof(*se), MALLOC_LOCAL);
|
||||
slowlogEntry *se = (slowlogEntry*)zmalloc(sizeof(*se), MALLOC_LOCAL);
|
||||
int j, slargc = argc;
|
||||
|
||||
if (slargc > SLOWLOG_ENTRY_MAX_ARGC) slargc = SLOWLOG_ENTRY_MAX_ARGC;
|
||||
se->argc = slargc;
|
||||
se->argv = zmalloc(sizeof(robj*)*slargc, MALLOC_LOCAL);
|
||||
se->argv = (robj**)zmalloc(sizeof(robj*)*slargc, MALLOC_LOCAL);
|
||||
for (j = 0; j < slargc; j++) {
|
||||
/* Logging too many arguments is a useless memory waste, so we stop
|
||||
* at SLOWLOG_ENTRY_MAX_ARGC, but use the last argument to specify
|
||||
@@ -64,15 +64,15 @@ slowlogEntry *slowlogCreateEntry(client *c, robj **argv, int argc, long long dur
|
||||
/* Trim too long strings as well... */
|
||||
if (argv[j]->type == OBJ_STRING &&
|
||||
sdsEncodedObject(argv[j]) &&
|
||||
sdslen(ptrFromObj(argv[j])) > SLOWLOG_ENTRY_MAX_STRING)
|
||||
sdslen(szFromObj(argv[j])) > SLOWLOG_ENTRY_MAX_STRING)
|
||||
{
|
||||
sds s = sdsnewlen(ptrFromObj(argv[j]), SLOWLOG_ENTRY_MAX_STRING);
|
||||
|
||||
s = sdscatprintf(s,"... (%lu more bytes)",
|
||||
(unsigned long)
|
||||
sdslen(ptrFromObj(argv[j])) - SLOWLOG_ENTRY_MAX_STRING);
|
||||
sdslen(szFromObj(argv[j])) - SLOWLOG_ENTRY_MAX_STRING);
|
||||
se->argv[j] = createObject(OBJ_STRING,s);
|
||||
} else if (argv[j]->refcount == OBJ_SHARED_REFCOUNT) {
|
||||
} else if (argv[j]->getrefcount(std::memory_order_relaxed) == OBJ_SHARED_REFCOUNT) {
|
||||
se->argv[j] = argv[j];
|
||||
} else {
|
||||
/* Here we need to dupliacate the string objects composing the
|
||||
@@ -87,9 +87,9 @@ slowlogEntry *slowlogCreateEntry(client *c, robj **argv, int argc, long long dur
|
||||
}
|
||||
se->time = time(NULL);
|
||||
se->duration = duration;
|
||||
se->id = server.slowlog_entry_id++;
|
||||
se->id = g_pserver->slowlog_entry_id++;
|
||||
se->peerid = sdsnew(getClientPeerId(c));
|
||||
se->cname = c->name ? sdsnew(ptrFromObj(c->name)) : sdsempty();
|
||||
se->cname = c->name ? sdsnew(szFromObj(c->name)) : sdsempty();
|
||||
return se;
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ slowlogEntry *slowlogCreateEntry(client *c, robj **argv, int argc, long long dur
|
||||
* function matches the one of the 'free' method of adlist.c.
|
||||
*
|
||||
* This function will take care to release all the retained object. */
|
||||
void slowlogFreeEntry(void *septr) {
|
||||
slowlogEntry *se = septr;
|
||||
void slowlogFreeEntry(const void *septr) {
|
||||
slowlogEntry *se = (slowlogEntry*)septr;
|
||||
int j;
|
||||
|
||||
for (j = 0; j < se->argc; j++)
|
||||
@@ -112,35 +112,35 @@ void slowlogFreeEntry(void *septr) {
|
||||
/* Initialize the slow log. This function should be called a single time
|
||||
* at server startup. */
|
||||
void slowlogInit(void) {
|
||||
server.slowlog = listCreate();
|
||||
server.slowlog_entry_id = 0;
|
||||
listSetFreeMethod(server.slowlog,slowlogFreeEntry);
|
||||
g_pserver->slowlog = listCreate();
|
||||
g_pserver->slowlog_entry_id = 0;
|
||||
listSetFreeMethod(g_pserver->slowlog,slowlogFreeEntry);
|
||||
}
|
||||
|
||||
/* Push a new entry into the slow log.
|
||||
* This function will make sure to trim the slow log accordingly to the
|
||||
* configured max length. */
|
||||
void slowlogPushEntryIfNeeded(client *c, robj **argv, int argc, long long duration) {
|
||||
if (server.slowlog_log_slower_than < 0) return; /* Slowlog disabled */
|
||||
if (duration >= server.slowlog_log_slower_than)
|
||||
listAddNodeHead(server.slowlog,
|
||||
if (g_pserver->slowlog_log_slower_than < 0) return; /* Slowlog disabled */
|
||||
if (duration >= g_pserver->slowlog_log_slower_than)
|
||||
listAddNodeHead(g_pserver->slowlog,
|
||||
slowlogCreateEntry(c,argv,argc,duration));
|
||||
|
||||
/* Remove old entries if needed. */
|
||||
while (listLength(server.slowlog) > server.slowlog_max_len)
|
||||
listDelNode(server.slowlog,listLast(server.slowlog));
|
||||
while (listLength(g_pserver->slowlog) > g_pserver->slowlog_max_len)
|
||||
listDelNode(g_pserver->slowlog,listLast(g_pserver->slowlog));
|
||||
}
|
||||
|
||||
/* Remove all the entries from the current slow log. */
|
||||
void slowlogReset(void) {
|
||||
while (listLength(server.slowlog) > 0)
|
||||
listDelNode(server.slowlog,listLast(server.slowlog));
|
||||
while (listLength(g_pserver->slowlog) > 0)
|
||||
listDelNode(g_pserver->slowlog,listLast(g_pserver->slowlog));
|
||||
}
|
||||
|
||||
/* The SLOWLOG command. Implements all the subcommands needed to handle the
|
||||
* Redis slow log. */
|
||||
void slowlogCommand(client *c) {
|
||||
if (c->argc == 2 && !strcasecmp(ptrFromObj(c->argv[1]),"help")) {
|
||||
if (c->argc == 2 && !strcasecmp(szFromObj(c->argv[1]),"help")) {
|
||||
const char *help[] = {
|
||||
"GET [count] -- Return top entries from the slowlog (default: 10)."
|
||||
" Entries are made of:",
|
||||
@@ -150,13 +150,13 @@ void slowlogCommand(client *c) {
|
||||
NULL
|
||||
};
|
||||
addReplyHelp(c, help);
|
||||
} else if (c->argc == 2 && !strcasecmp(ptrFromObj(c->argv[1]),"reset")) {
|
||||
} else if (c->argc == 2 && !strcasecmp(szFromObj(c->argv[1]),"reset")) {
|
||||
slowlogReset();
|
||||
addReply(c,shared.ok);
|
||||
} else if (c->argc == 2 && !strcasecmp(ptrFromObj(c->argv[1]),"len")) {
|
||||
addReplyLongLong(c,listLength(server.slowlog));
|
||||
} else if (c->argc == 2 && !strcasecmp(szFromObj(c->argv[1]),"len")) {
|
||||
addReplyLongLong(c,listLength(g_pserver->slowlog));
|
||||
} else if ((c->argc == 2 || c->argc == 3) &&
|
||||
!strcasecmp(ptrFromObj(c->argv[1]),"get"))
|
||||
!strcasecmp(szFromObj(c->argv[1]),"get"))
|
||||
{
|
||||
long count = 10, sent = 0;
|
||||
listIter li;
|
||||
@@ -168,12 +168,12 @@ NULL
|
||||
getLongFromObjectOrReply(c,c->argv[2],&count,NULL) != C_OK)
|
||||
return;
|
||||
|
||||
listRewind(server.slowlog,&li);
|
||||
listRewind(g_pserver->slowlog,&li);
|
||||
totentries = addReplyDeferredLen(c);
|
||||
while(count-- && (ln = listNext(&li))) {
|
||||
int j;
|
||||
|
||||
se = ln->value;
|
||||
se = (slowlogEntry*)ln->value;
|
||||
addReplyArrayLen(c,6);
|
||||
addReplyLongLong(c,se->id);
|
||||
addReplyLongLong(c,se->time);
|
||||
+42
-41
@@ -36,7 +36,7 @@
|
||||
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank);
|
||||
|
||||
redisSortOperation *createSortOperation(int type, robj *pattern) {
|
||||
redisSortOperation *so = zmalloc(sizeof(*so), MALLOC_LOCAL);
|
||||
redisSortOperation *so = (redisSortOperation*)zmalloc(sizeof(*so), MALLOC_LOCAL);
|
||||
so->type = type;
|
||||
so->pattern = pattern;
|
||||
return so;
|
||||
@@ -61,12 +61,13 @@ redisSortOperation *createSortOperation(int type, robj *pattern) {
|
||||
robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst, int writeflag) {
|
||||
char *p, *f, *k;
|
||||
sds spat, ssub;
|
||||
robj *keyobj, *fieldobj = NULL, *o;
|
||||
robj *keyobj, *fieldobj = NULL;
|
||||
robj_roptr o;
|
||||
int prefixlen, sublen, postfixlen, fieldlen;
|
||||
|
||||
/* If the pattern is "#" return the substitution object itself in order
|
||||
* to implement the "SORT ... GET #" feature. */
|
||||
spat = ptrFromObj(pattern);
|
||||
spat = szFromObj(pattern);
|
||||
if (spat[0] == '#' && spat[1] == '\0') {
|
||||
incrRefCount(subst);
|
||||
return subst;
|
||||
@@ -76,7 +77,7 @@ robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst, int writeflag)
|
||||
* a decoded object on the fly. Otherwise getDecodedObject will just
|
||||
* increment the ref count, that we'll decrement later. */
|
||||
subst = getDecodedObject(subst);
|
||||
ssub = ptrFromObj(subst);
|
||||
ssub = szFromObj(subst);
|
||||
|
||||
/* If we can't find '*' in the pattern we return NULL as to GET a
|
||||
* fixed key does not make sense. */
|
||||
@@ -99,7 +100,7 @@ robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst, int writeflag)
|
||||
sublen = sdslen(ssub);
|
||||
postfixlen = sdslen(spat)-(prefixlen+1)-(fieldlen ? fieldlen+2 : 0);
|
||||
keyobj = createStringObject(NULL,prefixlen+sublen+postfixlen);
|
||||
k = ptrFromObj(keyobj);
|
||||
k = szFromObj(keyobj);
|
||||
memcpy(k,spat,prefixlen);
|
||||
memcpy(k+prefixlen,ssub,sublen);
|
||||
memcpy(k+prefixlen+sublen,p+1,postfixlen);
|
||||
@@ -110,14 +111,14 @@ robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst, int writeflag)
|
||||
o = lookupKeyRead(db,keyobj);
|
||||
else
|
||||
o = lookupKeyWrite(db,keyobj);
|
||||
if (o == NULL) goto noobj;
|
||||
if (o == nullptr) goto noobj;
|
||||
|
||||
if (fieldobj) {
|
||||
if (o->type != OBJ_HASH) goto noobj;
|
||||
|
||||
/* Retrieve value from hash by the field name. The returend object
|
||||
* is a new object with refcount already incremented. */
|
||||
o = hashTypeGetValueObject(o, ptrFromObj(fieldobj));
|
||||
o = hashTypeGetValueObject(o, szFromObj(fieldobj));
|
||||
} else {
|
||||
if (o->type != OBJ_STRING) goto noobj;
|
||||
|
||||
@@ -127,7 +128,7 @@ robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst, int writeflag)
|
||||
}
|
||||
decrRefCount(keyobj);
|
||||
if (fieldobj) decrRefCount(fieldobj);
|
||||
return o;
|
||||
return o.unsafe_robjcast();
|
||||
|
||||
noobj:
|
||||
decrRefCount(keyobj);
|
||||
@@ -139,10 +140,10 @@ noobj:
|
||||
* the additional parameter is not standard but a BSD-specific we have to
|
||||
* pass sorting parameters via the global 'server' structure */
|
||||
int sortCompare(const void *s1, const void *s2) {
|
||||
const redisSortObject *so1 = s1, *so2 = s2;
|
||||
const redisSortObject *so1 = (redisSortObject*)s1, *so2 = (redisSortObject*)s2;
|
||||
int cmp;
|
||||
|
||||
if (!server.sort_alpha) {
|
||||
if (!g_pserver->sort_alpha) {
|
||||
/* Numeric sorting. Here it's trivial as we precomputed scores */
|
||||
if (so1->u.score > so2->u.score) {
|
||||
cmp = 1;
|
||||
@@ -156,7 +157,7 @@ int sortCompare(const void *s1, const void *s2) {
|
||||
}
|
||||
} else {
|
||||
/* Alphanumeric sorting */
|
||||
if (server.sort_bypattern) {
|
||||
if (g_pserver->sort_bypattern) {
|
||||
if (!so1->u.cmpobj || !so2->u.cmpobj) {
|
||||
/* At least one compare object is NULL */
|
||||
if (so1->u.cmpobj == so2->u.cmpobj)
|
||||
@@ -167,24 +168,24 @@ int sortCompare(const void *s1, const void *s2) {
|
||||
cmp = 1;
|
||||
} else {
|
||||
/* We have both the objects, compare them. */
|
||||
if (server.sort_store) {
|
||||
if (g_pserver->sort_store) {
|
||||
cmp = compareStringObjects(so1->u.cmpobj,so2->u.cmpobj);
|
||||
} else {
|
||||
/* Here we can use strcoll() directly as we are sure that
|
||||
* the objects are decoded string objects. */
|
||||
cmp = strcoll(ptrFromObj(so1->u.cmpobj),ptrFromObj(so2->u.cmpobj));
|
||||
cmp = strcoll(szFromObj(so1->u.cmpobj),szFromObj(so2->u.cmpobj));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
/* Compare elements directly. */
|
||||
if (server.sort_store) {
|
||||
if (g_pserver->sort_store) {
|
||||
cmp = compareStringObjects(so1->obj,so2->obj);
|
||||
} else {
|
||||
cmp = collateStringObjects(so1->obj,so2->obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
return server.sort_desc ? -cmp : cmp;
|
||||
return g_pserver->sort_desc ? -cmp : cmp;
|
||||
}
|
||||
|
||||
/* The SORT command is the most complex command in Redis. Warning: this code
|
||||
@@ -210,13 +211,13 @@ void sortCommand(client *c) {
|
||||
/* The SORT command has an SQL-alike syntax, parse it */
|
||||
while(j < c->argc) {
|
||||
int leftargs = c->argc-j-1;
|
||||
if (!strcasecmp(ptrFromObj(c->argv[j]),"asc")) {
|
||||
if (!strcasecmp(szFromObj(c->argv[j]),"asc")) {
|
||||
desc = 0;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"desc")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"desc")) {
|
||||
desc = 1;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"alpha")) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"alpha")) {
|
||||
alpha = 1;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"limit") && leftargs >= 2) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"limit") && leftargs >= 2) {
|
||||
if ((getLongFromObjectOrReply(c, c->argv[j+1], &limit_start, NULL)
|
||||
!= C_OK) ||
|
||||
(getLongFromObjectOrReply(c, c->argv[j+2], &limit_count, NULL)
|
||||
@@ -226,27 +227,27 @@ void sortCommand(client *c) {
|
||||
break;
|
||||
}
|
||||
j+=2;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"store") && leftargs >= 1) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"store") && leftargs >= 1) {
|
||||
storekey = c->argv[j+1];
|
||||
j++;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"by") && leftargs >= 1) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"by") && leftargs >= 1) {
|
||||
sortby = c->argv[j+1];
|
||||
/* If the BY pattern does not contain '*', i.e. it is constant,
|
||||
* we don't need to sort nor to lookup the weight keys. */
|
||||
if (strchr(ptrFromObj(c->argv[j+1]),'*') == NULL) {
|
||||
if (strchr(szFromObj(c->argv[j+1]),'*') == NULL) {
|
||||
dontsort = 1;
|
||||
} else {
|
||||
/* If BY is specified with a real patter, we can't accept
|
||||
* it in cluster mode. */
|
||||
if (server.cluster_enabled) {
|
||||
if (g_pserver->cluster_enabled) {
|
||||
addReplyError(c,"BY option of SORT denied in Cluster mode.");
|
||||
syntax_error++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
j++;
|
||||
} else if (!strcasecmp(ptrFromObj(c->argv[j]),"get") && leftargs >= 1) {
|
||||
if (server.cluster_enabled) {
|
||||
} else if (!strcasecmp(szFromObj(c->argv[j]),"get") && leftargs >= 1) {
|
||||
if (g_pserver->cluster_enabled) {
|
||||
addReplyError(c,"GET option of SORT denied in Cluster mode.");
|
||||
syntax_error++;
|
||||
break;
|
||||
@@ -271,7 +272,7 @@ void sortCommand(client *c) {
|
||||
|
||||
/* Lookup the key to sort. It must be of the right types */
|
||||
if (storekey)
|
||||
sortval = lookupKeyRead(c->db,c->argv[1]);
|
||||
sortval = lookupKeyRead(c->db,c->argv[1]).unsafe_robjcast();
|
||||
else
|
||||
sortval = lookupKeyWrite(c->db,c->argv[1]);
|
||||
if (sortval && sortval->type != OBJ_SET &&
|
||||
@@ -347,7 +348,7 @@ void sortCommand(client *c) {
|
||||
}
|
||||
|
||||
/* Load the sorting vector with all the objects to sort */
|
||||
vector = zmalloc(sizeof(redisSortObject)*vectorlen, MALLOC_LOCAL);
|
||||
vector = (redisSortObject*)zmalloc(sizeof(redisSortObject)*vectorlen, MALLOC_LOCAL);
|
||||
j = 0;
|
||||
|
||||
if (sortval->type == OBJ_LIST && dontsort) {
|
||||
@@ -403,7 +404,7 @@ void sortCommand(client *c) {
|
||||
* Note that in this case we also handle LIMIT here in a direct
|
||||
* way, just getting the required range, as an optimization. */
|
||||
|
||||
zset *zs = ptrFromObj(sortval);
|
||||
zset *zs = (zset*)ptrFromObj(sortval);
|
||||
zskiplist *zsl = zs->zsl;
|
||||
zskiplistNode *ln;
|
||||
sds sdsele;
|
||||
@@ -417,7 +418,7 @@ void sortCommand(client *c) {
|
||||
if (start > 0)
|
||||
ln = zslGetElementByRank(zsl,zsetlen-start);
|
||||
} else {
|
||||
ln = zsl->header->level[0].forward;
|
||||
ln = zsl->header->level(0)->forward;
|
||||
if (start > 0)
|
||||
ln = zslGetElementByRank(zsl,start+1);
|
||||
}
|
||||
@@ -429,7 +430,7 @@ void sortCommand(client *c) {
|
||||
vector[j].u.score = 0;
|
||||
vector[j].u.cmpobj = NULL;
|
||||
j++;
|
||||
ln = desc ? ln->backward : ln->level[0].forward;
|
||||
ln = desc ? ln->backward : ln->level(0)->forward;
|
||||
}
|
||||
/* Fix start/end: output code is not aware of this optimization. */
|
||||
end -= start;
|
||||
@@ -441,7 +442,7 @@ void sortCommand(client *c) {
|
||||
sds sdsele;
|
||||
di = dictGetIterator(set);
|
||||
while((setele = dictNext(di)) != NULL) {
|
||||
sdsele = dictGetKey(setele);
|
||||
sdsele = (sds)dictGetKey(setele);
|
||||
vector[j].obj = createStringObject(sdsele,sdslen(sdsele));
|
||||
vector[j].u.score = 0;
|
||||
vector[j].u.cmpobj = NULL;
|
||||
@@ -472,9 +473,9 @@ void sortCommand(client *c) {
|
||||
if (sdsEncodedObject(byval)) {
|
||||
char *eptr;
|
||||
|
||||
vector[j].u.score = strtod(ptrFromObj(byval),&eptr);
|
||||
vector[j].u.score = strtod(szFromObj(byval),&eptr);
|
||||
if (eptr[0] != '\0' || errno == ERANGE ||
|
||||
isnan(vector[j].u.score))
|
||||
std::isnan(vector[j].u.score))
|
||||
{
|
||||
int_conversion_error = 1;
|
||||
}
|
||||
@@ -495,10 +496,10 @@ void sortCommand(client *c) {
|
||||
}
|
||||
}
|
||||
|
||||
server.sort_desc = desc;
|
||||
server.sort_alpha = alpha;
|
||||
server.sort_bypattern = sortby ? 1 : 0;
|
||||
server.sort_store = storekey ? 1 : 0;
|
||||
g_pserver->sort_desc = desc;
|
||||
g_pserver->sort_alpha = alpha;
|
||||
g_pserver->sort_bypattern = sortby ? 1 : 0;
|
||||
g_pserver->sort_store = storekey ? 1 : 0;
|
||||
if (sortby && (start != 0 || end != vectorlen-1))
|
||||
pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end);
|
||||
else
|
||||
@@ -520,7 +521,7 @@ void sortCommand(client *c) {
|
||||
if (!getop) addReplyBulk(c,vector[j].obj);
|
||||
listRewind(operations,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
redisSortOperation *sop = ln->value;
|
||||
redisSortOperation *sop = (redisSortOperation*)ln->value;
|
||||
robj *val = lookupKeyByPattern(c->db,sop->pattern,
|
||||
vector[j].obj,storekey!=NULL);
|
||||
|
||||
@@ -550,7 +551,7 @@ void sortCommand(client *c) {
|
||||
} else {
|
||||
listRewind(operations,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
redisSortOperation *sop = ln->value;
|
||||
redisSortOperation *sop = (redisSortOperation*)ln->value;
|
||||
robj *val = lookupKeyByPattern(c->db,sop->pattern,
|
||||
vector[j].obj,storekey!=NULL);
|
||||
|
||||
@@ -573,11 +574,11 @@ void sortCommand(client *c) {
|
||||
setKey(c->db,storekey,sobj);
|
||||
notifyKeyspaceEvent(NOTIFY_LIST,"sortstore",storekey,
|
||||
c->db->id);
|
||||
server.dirty += outputlen;
|
||||
g_pserver->dirty += outputlen;
|
||||
} else if (dbDelete(c->db,storekey)) {
|
||||
signalModifiedKey(c->db,storekey);
|
||||
notifyKeyspaceEvent(NOTIFY_GENERIC,"del",storekey,c->db->id);
|
||||
server.dirty++;
|
||||
g_pserver->dirty++;
|
||||
}
|
||||
decrRefCount(sobj);
|
||||
addReplyLongLong(c,outputlen);
|
||||
@@ -55,7 +55,7 @@ static int label_margin_top = 1;
|
||||
|
||||
/* Create a new sequence. */
|
||||
struct sequence *createSparklineSequence(void) {
|
||||
struct sequence *seq = zmalloc(sizeof(*seq), MALLOC_LOCAL);
|
||||
struct sequence *seq = (sequence*)zmalloc(sizeof(*seq), MALLOC_LOCAL);
|
||||
seq->length = 0;
|
||||
seq->samples = NULL;
|
||||
return seq;
|
||||
@@ -70,7 +70,7 @@ void sparklineSequenceAddSample(struct sequence *seq, double value, char *label)
|
||||
if (value < seq->min) seq->min = value;
|
||||
else if (value > seq->max) seq->max = value;
|
||||
}
|
||||
seq->samples = zrealloc(seq->samples,sizeof(struct sample)*(seq->length+1), MALLOC_SHARED);
|
||||
seq->samples = (sample*)zrealloc(seq->samples,sizeof(struct sample)*(seq->length+1), MALLOC_SHARED);
|
||||
seq->samples[seq->length].value = value;
|
||||
seq->samples[seq->length].label = label;
|
||||
seq->length++;
|
||||
@@ -99,7 +99,7 @@ sds sparklineRenderRange(sds output, struct sequence *seq, int rows, int offset,
|
||||
double relmax = seq->max - seq->min;
|
||||
int steps = charset_len*rows;
|
||||
int row = 0;
|
||||
char *chars = zmalloc(len, MALLOC_LOCAL);
|
||||
char *chars = (char*)zmalloc(len, MALLOC_LOCAL);
|
||||
int loop = 1;
|
||||
int opt_fill = flags & SPARKLINE_FILL;
|
||||
int opt_log = flags & SPARKLINE_LOG_SCALE;
|
||||
@@ -47,10 +47,18 @@ struct sequence {
|
||||
#define SPARKLINE_FILL 1 /* Fill the area under the curve. */
|
||||
#define SPARKLINE_LOG_SCALE 2 /* Use logarithmic scale. */
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct sequence *createSparklineSequence(void);
|
||||
void sparklineSequenceAddSample(struct sequence *seq, double value, char *label);
|
||||
void freeSparklineSequence(struct sequence *seq);
|
||||
sds sparklineRenderRange(sds output, struct sequence *seq, int rows, int offset, int len, int flags);
|
||||
sds sparklineRender(sds output, struct sequence *seq, int columns, int rows, int flags);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* __SPARKLINE_H */
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user