Compare commits
601
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
067e365042 | ||
|
|
fda2b30346 | ||
|
|
924dc9731f | ||
|
|
51e01c0450 | ||
|
|
7fb90a670e | ||
|
|
57e931debc | ||
|
|
2a232dfa9a | ||
|
|
19853db892 | ||
|
|
b2604dc58c | ||
|
|
f8934657b2 | ||
|
|
2de5bab368 | ||
|
|
895409ca78 | ||
|
|
93cd75bbe0 | ||
|
|
ac33c049c6 | ||
|
|
20a0959964 | ||
|
|
cc24447a1a | ||
|
|
62f9d34c56 | ||
|
|
30c42f12b0 | ||
|
|
75ef41058d | ||
|
|
2fa9fb647f | ||
|
|
57852ff207 | ||
|
|
a99766fda1 | ||
|
|
f0f9d583ad | ||
|
|
1f665d6e82 | ||
|
|
e3c0125b70 | ||
|
|
a887af34e1 | ||
|
|
53ae687d59 | ||
|
|
a53c734094 | ||
|
|
aa16f87b87 | ||
|
|
6f20482a86 | ||
|
|
9d4d810861 | ||
|
|
1766d91697 | ||
|
|
e173f7a0e3 | ||
|
|
cc4df5a6b8 | ||
|
|
ed4980243a | ||
|
|
b809676a9e | ||
|
|
de88bc63d5 | ||
|
|
f35abe2ff5 | ||
|
|
83beaa886c | ||
|
|
753b707d2a | ||
|
|
551bee86b4 | ||
|
|
8612e6de88 | ||
|
|
d7a07a2012 | ||
|
|
0afb7a48c0 | ||
|
|
54157bc49e | ||
|
|
612bc784fc | ||
|
|
683f41adf2 | ||
|
|
885b6fc577 | ||
|
|
a92ae77740 | ||
|
|
7fd0149d34 | ||
|
|
9bf6921f3d | ||
|
|
183458f76a | ||
|
|
1f0c0df4a8 | ||
|
|
95b1979c32 | ||
|
|
97f1fc65cf | ||
|
|
42231117a7 | ||
|
|
e7887e6060 | ||
|
|
f86798ba6b | ||
|
|
a3e7a665ad | ||
|
|
a953c88381 | ||
|
|
f9bca13a1a | ||
|
|
9be3ee8283 | ||
|
|
75c57d53ea | ||
|
|
a6fe4ca321 | ||
|
|
e14829de30 | ||
|
|
f29b12d0bf | ||
|
|
46319094db | ||
|
|
e21e0ba3dc | ||
|
|
e3bae84606 | ||
|
|
54c46bafa3 | ||
|
|
be8f4d49d4 | ||
|
|
5c7286efbd | ||
|
|
5cd83ef539 | ||
|
|
d830dcb12d | ||
|
|
1506c64c8b | ||
|
|
28f32c99d0 | ||
|
|
ef897a41e8 | ||
|
|
af7647b20d | ||
|
|
1206bdf13f | ||
|
|
72980c7005 | ||
|
|
fb2f637c4a | ||
|
|
7970d53997 | ||
|
|
fceef8e0dd | ||
|
|
fe596d67e3 | ||
|
|
22d17bc14f | ||
|
|
f62dfa0f50 | ||
|
|
d06d8d6ffa | ||
|
|
41f12ac988 | ||
|
|
f16ad11c71 | ||
|
|
94bc467328 | ||
|
|
1c343ec29f | ||
|
|
5260ce1260 | ||
|
|
670d164fbe | ||
|
|
9162b5f8f9 | ||
|
|
36bbfeef7b | ||
|
|
f7d9827330 | ||
|
|
3f8865bcdc | ||
|
|
9f8dcfe69a | ||
|
|
3a482689c5 | ||
|
|
20c2a38ad0 | ||
|
|
2c17591224 | ||
|
|
bb2011d992 | ||
|
|
e06b3819ea | ||
|
|
e7affd266c | ||
|
|
f26f79ea37 | ||
|
|
56d26c2380 | ||
|
|
aa19fd612b | ||
|
|
96e0fe6232 | ||
|
|
38a06e86cf | ||
|
|
1d5b12c54a | ||
|
|
73fefd0bc0 | ||
|
|
3ac1dad77a | ||
|
|
76efe1225f | ||
|
|
8ef79e72ac | ||
|
|
58799718be | ||
|
|
605303d9c6 | ||
|
|
61eb0eae83 | ||
|
|
d5d92deb6c | ||
|
|
8204ab0098 | ||
|
|
64e6d7af47 | ||
|
|
4fd35a28d3 | ||
|
|
92dcae8fe4 | ||
|
|
1617c36c35 | ||
|
|
2ed450c322 | ||
|
|
9865ce0e64 | ||
|
|
6785b39eba | ||
|
|
9b3bc82c1a | ||
|
|
08c7363647 | ||
|
|
c7f93143f6 | ||
|
|
6a13193d8f | ||
|
|
d34c2fa3bb | ||
|
|
32d0a79f78 | ||
|
|
a2c2ef7de5 | ||
|
|
a2403227c7 | ||
|
|
113be48221 | ||
|
|
e8ebd7d0e0 | ||
|
|
1e221d101c | ||
|
|
14fb0ac649 | ||
|
|
134fd9eaf4 | ||
|
|
3758f27bc1 | ||
|
|
3307db49bd | ||
|
|
072982d83c | ||
|
|
dc8584696a | ||
|
|
8a588ac14d | ||
|
|
b187c591e3 | ||
|
|
efbe173962 | ||
|
|
3e0aef1e2e | ||
|
|
7a0c5fdf12 | ||
|
|
88c2307535 | ||
|
|
3495caf4fb | ||
|
|
69fa133ec2 | ||
|
|
6c16ecaaaa | ||
|
|
d0566daeaf | ||
|
|
aa5dfb3c2c | ||
|
|
a700bc74a8 | ||
|
|
94e3bb568a | ||
|
|
b239a32aae | ||
|
|
d98fa718e0 | ||
|
|
39603a7e31 | ||
|
|
ce37488919 | ||
|
|
17b05afda9 | ||
|
|
762b1ae2be | ||
|
|
c68c78719f | ||
|
|
33f943b4cd | ||
|
|
56161ca0a4 | ||
|
|
7f772355f4 | ||
|
|
ce2b2f22d9 | ||
|
|
ce7c47265b | ||
|
|
4ddc77041f | ||
|
|
01e3f9ba1d | ||
|
|
ea0e2524aa | ||
|
|
a9e62ab9fa | ||
|
|
04d901aed5 | ||
|
|
194b78050e | ||
|
|
a7da78e472 | ||
|
|
4c04744734 | ||
|
|
ba52cd06c8 | ||
|
|
67133d2f48 | ||
|
|
8c6e92c3bc | ||
|
|
7b87cda70e | ||
|
|
796f4ae9f7 | ||
|
|
8b9d5ecbd1 | ||
|
|
0b7aa26164 | ||
|
|
60e5d1724c | ||
|
|
6baac558d8 | ||
|
|
27ca133d35 | ||
|
|
cdf2271c5b | ||
|
|
bae30479fb | ||
|
|
832a298005 | ||
|
|
7c4decb101 | ||
|
|
3e0e51dd9f | ||
|
|
2692339138 | ||
|
|
005f564eb3 | ||
|
|
b252fab06c | ||
|
|
433e835d3e | ||
|
|
658ad301cc | ||
|
|
63d1f9e570 | ||
|
|
715a6d3a78 | ||
|
|
939c586ef7 | ||
|
|
5c78f87666 | ||
|
|
2a48bd4a37 | ||
|
|
71d0e7e0ea | ||
|
|
74435aba47 | ||
|
|
72ff03346f | ||
|
|
8a170c817d | ||
|
|
3625b52791 | ||
|
|
2102778606 | ||
|
|
931beae9b0 | ||
|
|
0b0f872f3f | ||
|
|
76c31d425e | ||
|
|
088b9eadc4 | ||
|
|
4f686555ce | ||
|
|
1e4ba6e7e6 | ||
|
|
76fda9f8e1 | ||
|
|
48c49c4851 | ||
|
|
3318b74705 | ||
|
|
c49955fd77 | ||
|
|
0ef4f44c5a | ||
|
|
8226be61ec | ||
|
|
40abeb1f40 | ||
|
|
1c130c6b03 | ||
|
|
3bc119c155 | ||
|
|
fcd2065f8e | ||
|
|
5344357f80 | ||
|
|
8b7e23bdde | ||
|
|
bc8ea04a7d | ||
|
|
e8357d0f85 | ||
|
|
1db45ba58c | ||
|
|
11d9ecb71d | ||
|
|
7b5ce1ffb1 | ||
|
|
4a3db25504 | ||
|
|
e8631a6991 | ||
|
|
9e422f74a6 | ||
|
|
2c55622333 | ||
|
|
2555b2f4bd | ||
|
|
e1b129811a | ||
|
|
0bcc7cb4bf | ||
|
|
f9a4a80f49 | ||
|
|
2d76736a2e | ||
|
|
53575c4708 | ||
|
|
93e7a130fc | ||
|
|
e29d330724 | ||
|
|
3a3458ee7b | ||
|
|
cac4bae11a | ||
|
|
c3f85c0107 | ||
|
|
7d9b45b4a1 | ||
|
|
e3cf812c9e | ||
|
|
db06108bc1 | ||
|
|
897adc1c8c | ||
|
|
e6b6813656 | ||
|
|
32c917964e | ||
|
|
12e435d2a4 | ||
|
|
7dd4432798 | ||
|
|
e0918a332d | ||
|
|
cb4e2ee9e7 | ||
|
|
a69178fdd2 | ||
|
|
20c040d364 | ||
|
|
9eeb03e5f7 | ||
|
|
fdaab02347 | ||
|
|
9caa1ae96a | ||
|
|
ab3afe2f4d | ||
|
|
85a2f2354e | ||
|
|
5eb7ac0c92 | ||
|
|
192a213274 | ||
|
|
0feb2aabca | ||
|
|
fcd2155b6f | ||
|
|
78954ca3a2 | ||
|
|
8827dc4eec | ||
|
|
95098b7230 | ||
|
|
c0ccd4da7d | ||
|
|
5c48432340 | ||
|
|
bcab07f7fc | ||
|
|
8b5e0b213e | ||
|
|
cffeafe391 | ||
|
|
8e8f8189eb | ||
|
|
0bbdaca6a0 | ||
|
|
402110f9fd | ||
|
|
d541f65d66 | ||
|
|
dde8dff73f | ||
|
|
54f0156e8c | ||
|
|
848d0461f9 | ||
|
|
81ceef7d22 | ||
|
|
9df77fc0c4 | ||
|
|
3bc35f9ce9 | ||
|
|
ba0afb4566 | ||
|
|
e9cd51c7eb | ||
|
|
681bf7468b | ||
|
|
db40da0a47 | ||
|
|
4e0a99ba51 | ||
|
|
5532b5308a | ||
|
|
837ca39081 | ||
|
|
142d133c8a | ||
|
|
1ee18db922 | ||
|
|
82c31f750d | ||
|
|
3b20003503 | ||
|
|
b7571b7453 | ||
|
|
f9dc3cb04d | ||
|
|
261da523e8 | ||
|
|
e8e717e145 | ||
|
|
2067644a8c | ||
|
|
80140fa006 | ||
|
|
3c3c16561a | ||
|
|
a9e057e095 | ||
|
|
0b7d08efb9 | ||
|
|
d9314079ca | ||
|
|
f5c03044a6 | ||
|
|
b5659cb0a6 | ||
|
|
1ccb661569 | ||
|
|
a79386b1af | ||
|
|
1fc04a6221 | ||
|
|
c756936b1d | ||
|
|
8ea5b46d30 | ||
|
|
1efc1e052d | ||
|
|
d55474e558 | ||
|
|
88530804e8 | ||
|
|
83d2830372 | ||
|
|
9c037ba85f | ||
|
|
da2fbcf93d | ||
|
|
67bb2c46b2 | ||
|
|
4930d903fc | ||
|
|
3a6a1e42f1 | ||
|
|
d5be696db8 | ||
|
|
1c12bcbcfb | ||
|
|
433ce7f85c | ||
|
|
352208ff68 | ||
|
|
d2ca4bb62d | ||
|
|
349c978189 | ||
|
|
b612affba3 | ||
|
|
ce637b2fef | ||
|
|
aaaed66c56 | ||
|
|
9682295f68 | ||
|
|
be9860d0e9 | ||
|
|
cf34507b87 | ||
|
|
096b5e921e | ||
|
|
cef505d739 | ||
|
|
bf066c875f | ||
|
|
f0868e080d | ||
|
|
4ab162a559 | ||
|
|
5afcca34ce | ||
|
|
ba4e20835a | ||
|
|
e887c62e45 | ||
|
|
f1b7608128 | ||
|
|
0c9f06a237 | ||
|
|
ec1ee66256 | ||
|
|
f2277475b2 | ||
|
|
4ab45183fc | ||
|
|
8aeb0c196a | ||
|
|
69a93194fd | ||
|
|
a8fb1a328d | ||
|
|
60e60f4ee0 | ||
|
|
7f9d289e10 | ||
|
|
307a189900 | ||
|
|
543ede03f2 | ||
|
|
aaf6db459b | ||
|
|
4628ac0065 | ||
|
|
5317a582cf | ||
|
|
3ed947fb30 | ||
|
|
28dce36f76 | ||
|
|
ac8fbe8829 | ||
|
|
fdf81b2d35 | ||
|
|
f29123364b | ||
|
|
f90a4af3d7 | ||
|
|
ded86076b3 | ||
|
|
156929ee97 | ||
|
|
5660ff1cc1 | ||
|
|
e3234116ad | ||
|
|
e73839e7d5 | ||
|
|
f22397dd7f | ||
|
|
1c88c5941b | ||
|
|
552eb5407a | ||
|
|
0609380603 | ||
|
|
8f52173b2c | ||
|
|
7fb14b73ba | ||
|
|
6dd2dbbd36 | ||
|
|
3cf6f1f54f | ||
|
|
80d4c52cdf | ||
|
|
eb746ec408 | ||
|
|
0064b1a583 | ||
|
|
6c527a89a0 | ||
|
|
c1041c570f | ||
|
|
6540e9eeaa | ||
|
|
9e0b9f12b2 | ||
|
|
6e33c908dd | ||
|
|
72c5ebcba4 | ||
|
|
35667d75c3 | ||
|
|
fc0fb0bad3 | ||
|
|
78782ed59f | ||
|
|
7f1c3607ec | ||
|
|
4290455145 | ||
|
|
b47b343fab | ||
|
|
906c4d77c0 | ||
|
|
8e6625e6ae | ||
|
|
a006fcb8a7 | ||
|
|
386a46946b | ||
|
|
3b54ee6ea4 | ||
|
|
896e15f3e3 | ||
|
|
68a3af5f9c | ||
|
|
e942f3ce0f | ||
|
|
df4bdbf688 | ||
|
|
90b844212d | ||
|
|
4a25983f8f | ||
|
|
491532a713 | ||
|
|
c138631cd1 | ||
|
|
93253c2762 | ||
|
|
30639c8ca9 | ||
|
|
d3efe04c47 | ||
|
|
a9caca0424 | ||
|
|
6972f18cbd | ||
|
|
4d2e8fa189 | ||
|
|
5fa3248bad | ||
|
|
4fdd7a0546 | ||
|
|
a98369929e | ||
|
|
f4da796c53 | ||
|
|
c641b670c3 | ||
|
|
82b53c650c | ||
|
|
5317f5e99a | ||
|
|
22c9cfaf57 | ||
|
|
6d5790d682 | ||
|
|
ad6b0f70b2 | ||
|
|
1faf82663f | ||
|
|
d77e231682 | ||
|
|
fe30847016 | ||
|
|
e150ec7d0c | ||
|
|
67ed5f00aa | ||
|
|
b9e90a70fa | ||
|
|
258d377d8e | ||
|
|
58f104e2ee | ||
|
|
2586ea7637 | ||
|
|
218cc5fc39 | ||
|
|
bb6d850160 | ||
|
|
ae0b7680b3 | ||
|
|
3a2ff55617 | ||
|
|
2209d077d3 | ||
|
|
c65b75e740 | ||
|
|
584052ee6b | ||
|
|
ed813863f0 | ||
|
|
365094028b | ||
|
|
9dfe426fc8 | ||
|
|
133fccb03f | ||
|
|
429aff4ef4 | ||
|
|
cc11d103c0 | ||
|
|
df32eb6827 | ||
|
|
2e5c394fa8 | ||
|
|
e26f4486b0 | ||
|
|
a2ff90919f | ||
|
|
1ed0ad77f0 | ||
|
|
8287945ff8 | ||
|
|
2e8e0ad44e | ||
|
|
8eae54aa1e | ||
|
|
2705306ba1 | ||
|
|
5b864617bc | ||
|
|
c4ef1d6494 | ||
|
|
3e1d772677 | ||
|
|
04cf02e8dc | ||
|
|
21765c8588 | ||
|
|
03344196f3 | ||
|
|
8caecc9ab4 | ||
|
|
ef5e7fbaa2 | ||
|
|
c0e818ab08 | ||
|
|
caf7b9b425 | ||
|
|
787b297046 | ||
|
|
55b88e0044 | ||
|
|
aca6cb529b | ||
|
|
c1a7d3e61f | ||
|
|
442b06db54 | ||
|
|
ed8c55237b | ||
|
|
3e8a92ef8d | ||
|
|
3b0edb80ec | ||
|
|
0f1f25784f | ||
|
|
f0782a6e86 | ||
|
|
0f2597092f | ||
|
|
6984692060 | ||
|
|
36676c2318 | ||
|
|
bbf39b7a3a | ||
|
|
b74c899da3 | ||
|
|
e8bae92e54 | ||
|
|
385c25f70f | ||
|
|
d2040ab9b1 | ||
|
|
59cf0b1902 | ||
|
|
54e99fb226 | ||
|
|
9b401819c0 | ||
|
|
5f5118bdad | ||
|
|
e5b1e7be64 | ||
|
|
8d011492a0 | ||
|
|
47750998a6 | ||
|
|
08da025f56 | ||
|
|
efb092baa6 | ||
|
|
7d97a4c99b | ||
|
|
3072a1e781 | ||
|
|
dd8d883c9c | ||
|
|
138695d990 | ||
|
|
c0f8665414 | ||
|
|
4b9ac6edd0 | ||
|
|
c5edd91716 | ||
|
|
35e8bc305d | ||
|
|
1734f7aedb | ||
|
|
db9e718c8a | ||
|
|
69cc3b692f | ||
|
|
e41a3edfab | ||
|
|
12a88d575d | ||
|
|
0c1bb1313c | ||
|
|
68d6d1597f | ||
|
|
8dea2029a4 | ||
|
|
f1c9a203b2 | ||
|
|
a89c8bb87c | ||
|
|
806788d009 | ||
|
|
8b8c1cd4c2 | ||
|
|
b21f4d63de | ||
|
|
76a6e82d89 | ||
|
|
0e31eaa27f | ||
|
|
38c620b3b5 | ||
|
|
addd4de9c1 | ||
|
|
8d95a47408 | ||
|
|
2a7847a3b5 | ||
|
|
746ce35f5f | ||
|
|
5edc7f76ed | ||
|
|
d769cad4bf | ||
|
|
55c059e270 | ||
|
|
fe9a489b29 | ||
|
|
55e36e1132 | ||
|
|
339322fe58 | ||
|
|
013a4ce242 | ||
|
|
fef88681f2 | ||
|
|
a2c76ffb1c | ||
|
|
ba993cc685 | ||
|
|
5580350a7b | ||
|
|
c1d67ea9b4 | ||
|
|
dcac007b81 | ||
|
|
386467acfb | ||
|
|
a9360c62e8 | ||
|
|
044b627549 | ||
|
|
630fb3539f | ||
|
|
d3a3ef0bc1 | ||
|
|
b15411df98 | ||
|
|
29f4df8018 | ||
|
|
6b373edb77 | ||
|
|
3b7a757468 | ||
|
|
25cebf7285 | ||
|
|
540536c055 | ||
|
|
09dec3613e | ||
|
|
afd3db17a0 | ||
|
|
a929867cca | ||
|
|
e163332858 | ||
|
|
b1c1386374 | ||
|
|
8c254415f7 | ||
|
|
1d7d1d9b1f | ||
|
|
2c273e3591 | ||
|
|
d7da507683 | ||
|
|
5765444454 | ||
|
|
7d7b3810e7 | ||
|
|
ce68caea37 | ||
|
|
b20ae393f1 | ||
|
|
e087d8a20d | ||
|
|
a88a057a1f | ||
|
|
2a08c7e5ac | ||
|
|
136537dcb0 | ||
|
|
8e553ec67c | ||
|
|
c7b7439528 | ||
|
|
c4fbc1d336 | ||
|
|
19b863c7fa | ||
|
|
141bac4c79 | ||
|
|
7cec9e48ce | ||
|
|
18b8bad53c | ||
|
|
af788b5852 | ||
|
|
34c404e069 | ||
|
|
a1dca2efab | ||
|
|
ede33fb912 | ||
|
|
e1b77b61f3 | ||
|
|
51bd9da1fd | ||
|
|
7e8abcf693 | ||
|
|
f2bdf601be | ||
|
|
21e6b0fbe9 | ||
|
|
fc08c8599f | ||
|
|
fe8352540f | ||
|
|
db6d628c3e | ||
|
|
5e0e03be41 | ||
|
|
8251d2d150 | ||
|
|
4a64286c36 | ||
|
|
72f7abf6a2 | ||
|
|
44f7afe28a | ||
|
|
a1349728ea | ||
|
|
6dc26795aa | ||
|
|
218358bbbd | ||
|
|
3107e7ca60 | ||
|
|
1ae50a9b1d | ||
|
|
59e03a8f35 | ||
|
|
bf670e0745 | ||
|
|
a3755ae9ee | ||
|
|
6fc53e16ad | ||
|
|
be0bb19fd3 | ||
|
|
1a73c992a3 | ||
|
|
32563b4a5f | ||
|
|
21648473aa | ||
|
|
5b2082ead3 | ||
|
|
f106a79309 | ||
|
|
f885fa8bac | ||
|
|
344a065d51 | ||
|
|
7bf7b7350c | ||
|
|
dced9c0619 | ||
|
|
007e1c7cb2 | ||
|
|
100cd7b21e |
@@ -19,7 +19,6 @@ src/transfer.sh
|
||||
src/configs
|
||||
redis.ds
|
||||
src/redis.conf
|
||||
src/nodes.conf
|
||||
deps/lua/src/lua
|
||||
deps/lua/src/luac
|
||||
deps/lua/src/liblua.a
|
||||
|
||||
+11
-715
@@ -1,720 +1,16 @@
|
||||
Redis 3.0 release notes
|
||||
=======================
|
||||
Hello! This file is just a placeholder, since this is the "unstable" branch
|
||||
of Redis, the place where all the development happens.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
Upgrade urgency levels:
|
||||
There is no release notes for this branch, it gets forked into another branch
|
||||
every time there is a partial feature freeze in order to eventually create
|
||||
a new stable release.
|
||||
|
||||
LOW: No need to upgrade unless there are new features you want to use.
|
||||
MODERATE: Program an upgrade of the server, but it's not urgent.
|
||||
HIGH: There is a critical bug that may affect a subset of users. Upgrade!
|
||||
CRITICAL: There is a critical bug affecting MOST USERS. Upgrade ASAP.
|
||||
--------------------------------------------------------------------------------
|
||||
Usually "unstable" is stable enough for you to use it in development enviromnets
|
||||
however you should never use it in production environments. It is possible
|
||||
to download the latest stable release here:
|
||||
|
||||
--[ Redis 3.0.5 ] Release date: 15 Oct 2015
|
||||
http://download.redis.io/releases/redis-stable.tar.gz
|
||||
|
||||
Upgrade urgency: MODERATE, the most important thing is a fix in the replication
|
||||
code that may make the slave hanging forever if the master
|
||||
remains with an open socket even if it is no longer able to
|
||||
reply.
|
||||
More information is available at http://redis.io
|
||||
|
||||
* [FIX] MOVE now moves the TTL as well. A bug lasting forever... finally
|
||||
fixed thanks to Andy Grunwald that reported it.
|
||||
(reported by Andy Grunwald, fixed by Salvatore Sanfilippo)
|
||||
* [FIX] Fix a false positive in HSTRLEN test.
|
||||
* [FIX] Fix a bug in redis-cli --pipe mode that was not able to read back
|
||||
replies from the server incrementally. Now a mass import will use
|
||||
a lot less memory, and you can use --pipe to do incremental streaming.
|
||||
(reported by Twitter user @fsaintjacques, fixed by Salvatore
|
||||
Sanfilippo)
|
||||
* [FIX] Slave detection of master timeout. (fixed by Kevin McGehee, refactoring
|
||||
and regression test by Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] Cluster: redis-trib fix can fix an additional case for opens lots.
|
||||
(Salvatore Sanfilippo)
|
||||
* [NEW] Cluster: redis-trib import support for --copy and --replace options
|
||||
(David Thomson)
|
||||
|
||||
--[ Redis 3.0.4 ] Release date: 8 Sep 2015
|
||||
|
||||
Upgrade urgency: HIGH for Redis and Sentinel. However note that in order to
|
||||
fix certain replication bugs, the replication internals were
|
||||
modified in a very heavy way. So while this release is
|
||||
conceptually saner, it may contain regressions. For this
|
||||
reason, before the release, QA activities were performed by
|
||||
me (antirez) and Redis Labs and no evident bug was found.
|
||||
|
||||
* [FIX] A number of bugs related to replication PSYNC and the (yet experimental)
|
||||
diskless replication feature were fixed. The bugs could lead to
|
||||
inconsistency between masters and slaves. (Salvatore Sanfilippo, Oran
|
||||
Agra fixed the issue found by Yuval Inbar)
|
||||
* [FIX] A replication bug in the context of PSYNC partial resynchonization was
|
||||
found and fixed. This bug happens even when diskless replication is off
|
||||
in the case different slaves connect at different times while the master
|
||||
is creating an RDB file, and later a partial resynchronization is
|
||||
attempted by a slave that connected not as the first one. (Salvatore
|
||||
Sanfilippo, Oran Agra)
|
||||
* [FIX] Chained replication and PSYNC interactions leading to potential stale
|
||||
chained slaves data set, see issue #2694. (Salvatore Sanfilippo fixed
|
||||
an issue reported by "GeorgeBJ" user at Github)
|
||||
* [FIX] redis-cli --scan iteration fixed when returned cursor overflows
|
||||
32 bit signed integer. (Ofir Luzon, Yuval Inbar)
|
||||
* [FIX] Sentinel: fixed a bug during the master switch process, where for a
|
||||
failed conditional check, the new configuration is rewritten, during
|
||||
a small window of time, in a corrupted way where the master is
|
||||
also reported to be one of the slaves. This bug is rare to trigger
|
||||
but apparently it happens in the wild, and the effect is to see
|
||||
a replication loop where the master will try to replicate with itself.
|
||||
A detailed explanation of the bug and its effects can be found in
|
||||
the commit message here: https://github.com/antirez/redis/commit/c20218eb5770b2cafb12bc7092313b8358fedc0a.
|
||||
The bug was found by Jan-Erik Rediger using a static analyzer and
|
||||
fixed by Salvatore Sanfilippo.
|
||||
* [FIX] Sentinel lack of arity checks for certain commands.
|
||||
(Rogerio Goncalves, Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] Replication internals rewritten in order to be more resistant to bugs.
|
||||
The replication handshake in the slave side was rewritten as a non
|
||||
blocking state machine. (Salvatore Sanfilippo, Oran Agra)
|
||||
* [NEW] New "replication capabilities" feature introduced in order to signal
|
||||
from the master to the slave what are the features supported, so that
|
||||
the master can choose the kind of replication to start (diskless or
|
||||
not) when master and slave are of different versions. (Oran Agra,
|
||||
Salvatore Sanfilippo)
|
||||
* [NEW] Log clients details when SLAVEOF command is received. (Salvatore
|
||||
Sanfilippo with inputs from Nick Craver and Marc Gravell).
|
||||
|
||||
--[ Redis 3.0.3 ] Release date: 17 Jul 2015
|
||||
|
||||
Upgrade urgency: LOW for Redis and Sentinel.
|
||||
|
||||
* [FIX] Fix blocking operations timeout precision when HZ is at its default
|
||||
value (not increased) and there are thousands of clients connected
|
||||
at the same time. This bug affected Sidekiq users that experienced
|
||||
a very long delay for BLPOP and similar commands to return for
|
||||
timeout. Check commit b029ff1 for more info. (Salvatore Sanfilippo)
|
||||
* [FIX] MIGRATE "creating socket: Invalid argument" error fix. Check
|
||||
issues #2609 and #2612 for more info. (Salvatore Sanfilippo)
|
||||
* [FIX] Be able to connect to the master even when the slave is bound to
|
||||
just the loopback interface and has no valid public address in the
|
||||
network the master is reacahble. (Salvatore Sanfilippo)
|
||||
* [FIX] ZADD with options encoding promotion fixed. (linfangrong)
|
||||
* [FIX] Reset aof_delayed_fsync on CONFIG RESETSTATS. (Tom Kiemes)
|
||||
* [FIX] PFCOUNT key parsing in cluster fixed. (MOON_CLJ)
|
||||
* [FIX] Fix Solaris compilation of Redis 3.0. (Jan-Erik Rediger)
|
||||
|
||||
* [NEW] Variadic EXISTS command. Now the command accepts multiple arguments
|
||||
and returns the total count of existing keys.
|
||||
|
||||
--[ Redis 3.0.2 ] Release date: 4 Jun 2015
|
||||
|
||||
Upgrade urgency: HIGH for Redis because of a security issue.
|
||||
LOW for Sentinel.
|
||||
|
||||
* [FIX] Critical security issue fix by Ben Murphy: http://t.co/LpGTyZmfS7
|
||||
* [FIX] SMOVE reply fixed when src and dst keys are the same. (Glenn Nethercutt)
|
||||
* [FIX] Lua cmsgpack lib updated to support str8 type. (Sebastian Waisbrot)
|
||||
|
||||
* [NEW] ZADD support for options: NX, XX, CH. See new doc at redis.io.
|
||||
(Salvatore Sanfilippo)
|
||||
* [NEW] Senitnel: CKQUORUM and FLUSHCONFIG commands back ported.
|
||||
(Salvatore Sanfilippo and Bill Anderson)
|
||||
|
||||
--[ Redis 3.0.1 ] Release date: 5 May 2015
|
||||
|
||||
Upgrade urgency: LOW for Redis and Cluster, MODERATE for Sentinel.
|
||||
|
||||
* [FIX] Sentinel memory leak due to hiredis fixed. (Salvatore Sanfilippo)
|
||||
* [FIX] Sentinel memory leak on duplicated instance. (Charsyam)
|
||||
* [FIX] Redis crash on Lua reaching output buffer limits. (Yossi Gottlieb)
|
||||
* [FIX] Sentinel flushes config on +slave events. (Bill Anderson)
|
||||
|
||||
--[ Redis 3.0.0 ] Release date: 1 Apr 2015
|
||||
|
||||
>> What's new in Redis 3.0 compared to Redis 2.8?
|
||||
|
||||
* Redis Cluster: a distributed implementation of a subset of Redis.
|
||||
* New "embedded string" object encoding resulting in less cache
|
||||
misses. Big speed gain under certain work loads.
|
||||
* AOF child -> parent final data transmission to minimize latency due
|
||||
to "last write" during AOF rewrites.
|
||||
* Much improved LRU approximation algorithm for keys eviction.
|
||||
* WAIT command to block waiting for a write to be transmitted to
|
||||
the specified number of slaves.
|
||||
* MIGRATE connection caching. Much faster keys migraitons.
|
||||
* MIGRATE new options COPY and REPLACE.
|
||||
* CLIENT PAUSE command: stop processing client requests for a
|
||||
specified amount of time.
|
||||
* BITCOUNT performance improvements.
|
||||
* CONFIG SET accepts memory values in different units (for example
|
||||
you can use "CONFIG SET maxmemory 1gb").
|
||||
* Redis log format slightly changed reporting in each line the role of the
|
||||
instance (master/slave) or if it's a saving child log.
|
||||
* INCR performance improvements.
|
||||
|
||||
>> Refactoring changes (no new features nor bug fixes)
|
||||
|
||||
* Blocking operations full refactoring (blocked.c)
|
||||
* Client output buffer memory tracking refactored.
|
||||
|
||||
Changes between RC6 and 3.0.0 stable:
|
||||
|
||||
>> General changes
|
||||
|
||||
* Fixes to diskless replication. (Oran Agra)
|
||||
* Test for BLPOP replication on role change. (Salvatore Sanfilippo)
|
||||
* prepareClientToWrite() error handling improvements. (Salvatore Sanfilippo)
|
||||
* Remove dict.c no longer used function. (Salvatore Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
None
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
None
|
||||
|
||||
--[ Redis 3.0.0 RC6 (version 2.9.106) ] Release date: 24 mar 2015
|
||||
|
||||
Upgrade urgency: HIGH because of bugs related to Redis Custer and replication.
|
||||
|
||||
This is the 6th release candidate of Redis 3.0.0. This release fixes important
|
||||
issues discovered during stress testing, and implements safest behavior
|
||||
for blocking operations during clients reshardings, and a new much needed
|
||||
functionality of Redis Cluster manual failovers.
|
||||
|
||||
In order to fix certain bugs quite a bit of refactoring was needed which
|
||||
is usually non advisabble in a Release Candidate, but needed in order to
|
||||
end with a clean fix.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] Redis (non clustered & clustered) replication bug involving blocking
|
||||
operations: see issue #2473. (Salvatore Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] clientsArePaused() fix crashing the old master during manual failover.
|
||||
(Salvatore Sanfilippo)
|
||||
* [FIX] Lua scripts replication in Redis Cluster was totally broken.
|
||||
(Salvatore Sanfilippo)
|
||||
* [FIX] Redirect clients blocked into list operations when the hash slot
|
||||
they are blocked into is migrated to another instance or the cluster
|
||||
state turns into "fail". (Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] TAKEOVER option for CLUSTER FAILOVER implemented. It is now possible
|
||||
to fix a cluster manually in the minority side of the partition, for
|
||||
example in order to allow for multi DC setups & recovery.
|
||||
(Salvatore Sanfilippo)
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
No changes in Sentinel.
|
||||
|
||||
--[ Redis 3.0.0 RC5 (version 2.9.105) ] Release date: 20 mar 2015
|
||||
|
||||
Upgrade urgency: Moderate for Redis Cluster users, low otherwise.
|
||||
|
||||
This is the 5th release candidate of Redis 3.0.0, released in order to fix
|
||||
a moderate bug in Redis Cluster. This RC does not shift in the future the
|
||||
Redis 3.0.0 final release which is scheduled in a few days (we are in the
|
||||
process of finishing the documentation for Redis Cluster).
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] Fix LATENCY command crash. (Salvatore Sanfilippo, thx to Ingmar)
|
||||
* [FIX] Config: missing activerehashing option support in CONFIG SET added.
|
||||
(Salvatore Sanfilippo, thx to Bill Anderson)
|
||||
* [FIX] Fix for backtrace generation issue. (Mariano Pérez Rodríguez, Matt Stancliff, Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] Redis-cli --latency-dist backported from unstable.
|
||||
(Salvatore Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] Avoid redundant SELECT in MIGRATE. (Tommy Wang, Salvatore Sanfilippo)
|
||||
* [FIX] More robust slave check in CLUSTER REPLICATE. (Salvatore Sanfilippo)
|
||||
* [FIX] Fixed possible Redis Cluster node crash due to wrong separation of
|
||||
concerns between getNodeByQuery() and Cluster global state update
|
||||
fnuction. (Salvatore Sanfilippo, thx to Ingmar)
|
||||
|
||||
* [NEW] Add command CLUSTER MYID to easily featch instance ID. (Michel Martens)
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* [NEW] Support for CLIENT command added. It was missing in the command table.
|
||||
(Leandro López)
|
||||
|
||||
--[ Redis 3.0.0 RC4 (version 2.9.104) ] Release date: 13 feb 2015
|
||||
|
||||
Upgrade urgency: High for Redis if you use LRU eviction, low otherwise.
|
||||
|
||||
This is the 4th release candidate of Redis 3.0.0, it fixes problems with
|
||||
LRU eviction that are not present in older release (2.8.x is not affected)
|
||||
and adds new tools to inspect latency and load-test LRU.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] redis-cli CSV output NIL spurious newline removed. (Matt Collier)
|
||||
* [FIX] Memory efficiency test in unit test is now much faster: it affacted
|
||||
the total "make test" execution time in a bad way. (Salvatore
|
||||
Sanfilippo)
|
||||
* [FIX] Fixes and improvements to dict.c and LRU eviction. Redis 3.0.0 new
|
||||
LRU eviction had bugs creating high latency spikes when LRU was
|
||||
happening during the keys dictionary rehashing. This bug is not
|
||||
present into 2.8, was 3.0 specific. As a side effect of this issue
|
||||
dict.c is now improved, and LRU algorithm is more precise (better
|
||||
approximates true LRU). This was a joint effort, see issue
|
||||
#2306 for details. (Oran Agra, Sun He, Salvatore Sanfilippo).
|
||||
Thanks to Charsyam for spotting an integer overflow.
|
||||
|
||||
* [NEW] New latency tool: redis-cli --latency-dist is able to show an
|
||||
xterm-256 based spectrum of latencies over time. (Salvatore Sanfilippo)
|
||||
* [NEW] redis-cli --lru-test implemented (cache workload simulator). (Salvatore
|
||||
Sanfilippo)
|
||||
* [NEW] redis-cli --stat now shows LOAD when Redis is loading data.
|
||||
* [NEW] Support "1G" etc. units in CONFIG SET. (Chris Lamb, Salvatore
|
||||
Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* None.
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* None.
|
||||
|
||||
--[ Redis 3.0.0 RC3 (version 2.9.103) ] Release date: 30 jan 2015
|
||||
|
||||
Upgrade urgency: High for Redis Cluster users, low otherwise.
|
||||
|
||||
This is the third release candidate for Redis 3.0.0, the new RC fixes
|
||||
several critical issues with Redis Cluster.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] AOF bug unlikely to happen in practice and mostly harmless: child
|
||||
process segfaults when parent is not reachable via pipe. (Sun He)
|
||||
* [FIX] Scripting engine now reports an error when misused with Lua debug
|
||||
hooks, instead of crashing. (Salvatore Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] Several issues with Redis Cluster internal nodes objects handling.
|
||||
(Matt Stancliff & Salvatore Sanfilippo)
|
||||
* [FIX] Improvements in the Cluster test.
|
||||
(Matt Stancliff & Salvatore Sanfilippo).
|
||||
* [FIX] Cluster memory leaks / double frees (Matt Stancliff).
|
||||
* [FIX] /dev/urandom surrogate for generation of unique IDs in a more
|
||||
cheap way. (Salvatore Sanfilippo)
|
||||
* [FIX] Fixes and improvements to PING / PONG packets gossip sections
|
||||
in order to improve (and fix) failure detection and speedup
|
||||
cluster info propagation. (Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] CLUSTER count-failure-reports command added. (Salvatore Sanfilippo)
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
No changes for Sentinel.
|
||||
|
||||
--[ Redis 3.0.0 RC2 (version 2.9.102) ] Release date: 13 jan 2015
|
||||
|
||||
Upgrade urgency: LOW.
|
||||
|
||||
This is the second release candidate of Redis 3.0.0. The major changes
|
||||
are back porting of things implemented into the unstable branch while
|
||||
this was still possible (with the new development model adopted only
|
||||
bug fixes will be merged in the future).
|
||||
|
||||
RC2 also fixes a few Redis Cluster non critical bugs.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] A number of minor bug fixes.
|
||||
|
||||
* [NEW] Diskless replication backportede.
|
||||
* [NEW] Lua bitops and updated cmsgpack backported.
|
||||
* [NEW] Transparent Huge Pages warnings and reporting backported.
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] Fix PUBLISH cluster bus message count field.
|
||||
* [FIX] It is no longer possible to write outside node hash slots using Lua.
|
||||
* [FIX] Valgrind warnings (no actual bugs).
|
||||
* [FIX] Less strict in acceptiong myself->ip if it's not populated.
|
||||
|
||||
* [NEW] Better testing of Lua scripts.
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
No changes to Sentinel.
|
||||
|
||||
--[ Redis 3.0.0 RC1 (version 2.9.101) ] Release date: 9 oct 2014
|
||||
|
||||
This is the first release candidate of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] An very large number of small fixes, old and new, merged in the
|
||||
context of a the issue #1906. Please see the issue page here
|
||||
for exact credits: https://github.com/antirez/redis/pull/1906
|
||||
of each commit. (Matt Stancliff and many others).
|
||||
* [FIX] SAVE is no longer propagated to AOF / slaves.
|
||||
* [FIX] GETRANGE test no longer fails for 32 bit builds (Matt Stancliff).
|
||||
* [FIX] Limit SCAN latency when the hash table is in an odd state (very few
|
||||
populted buckets because rehashing is in progress). (Xiaost and
|
||||
Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] Redis is now able to load truncated AOF files without requiring a
|
||||
redis-check-aof utility run. The default now is to load truncated
|
||||
(but apparently not corrupted) AOFs, you can change this in redis.conf.
|
||||
(Salvatore Sanfilippo).
|
||||
* [NEW] DEBUG POPULATE two args form implemented. It is now possible to
|
||||
call it with DEBUG POPULATE <count> <prefix>. Default prefix
|
||||
is "key:" as usually.
|
||||
* [NEW] INCR: Modify incremented object in-place when possible. This results
|
||||
in speed improvements + possibly better memory locality.
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] Cluster: claim ping_sent time even if we can't connect.
|
||||
* [FIX] redis-trib should not abort easily on connection issues.
|
||||
* [FIX] Cluster test: less console-spammy resharding test.
|
||||
* [FIX] Fix logic to detect we are among a minority.
|
||||
* [FIX] Process gossip section only for known nodes.
|
||||
|
||||
* [NEW] Redis Cluster is stable and tested enough, there is a clear MVP,
|
||||
so it was promoted from beta to stable.
|
||||
* [NEW] New unit 09, Pub/Sub across the cluster.
|
||||
* [NEW] New unit 08, update messages.
|
||||
* [NEW] New cluster option to work with partial slots coverage.
|
||||
* [NEW] More chatty cluster slaves when failover is stalled. They log reason
|
||||
with rate limiting, only when reason changes or a given time
|
||||
has elapsed.
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* [FIX] Sentinel critical bug fixed: the absolute majority was computed in a
|
||||
wrong way because of a programming error. Now the implementation does
|
||||
what the specification says and the majority to authorize a failover
|
||||
(that should not be confused with the ODOWN quorum) is the majority of
|
||||
*all* the Sentinels ever seen for a given master, regardless of their
|
||||
current state.
|
||||
* [FIX] Resolved a memory leak in the hiredis library causing a memory leak
|
||||
in Redis Sentinel when a monitored instance or another Sentinel is
|
||||
unavailable. Every reconnection attempt will leak a small amount of
|
||||
memory, but in the long run the process can reach a considerable size.
|
||||
|
||||
* [NEW] Sentinel: ability to announce itself with an arbitrary IP/port to work
|
||||
in the context of natted networks. However this is probably still
|
||||
not enough since there is no equivalent mechanism for slaves listed
|
||||
in the master INFO output. (Dara Kong and Salvatore Sanfilippo)
|
||||
|
||||
--[ Redis 3.0.0 Beta 8 (version 2.9.57) ] Release date: 29 jul 2014
|
||||
|
||||
This is the 8th beta of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] Solaris compilation issues. (Matt Stancliff, Salvatore Sanfilippo)
|
||||
* [FIX] Allow shared integer objects if maxmemory policy is not LRU based.
|
||||
(Salvatore Sanfilippo)
|
||||
* [FIX] PFSELFTEST: less false positives. (Salvatore Sanfilippo)
|
||||
* [FIX] Fail SYNC if background save child aborted due to a signal. (Yossi
|
||||
Gottlieb)
|
||||
|
||||
* [NEW] Latency framework backported from unstable branch. (Salvatore
|
||||
Sanfilippo)
|
||||
* [NEW] AOF rewrite improved for latency. (Salvatore Sanfilippo)
|
||||
* [NEW] Pub/Sub PING. (Salvatore Sanfilippo)
|
||||
* [NEW] Much faster ZUNIONSTORE. (Kyle Hubert, Salvatore Sanfilippo)
|
||||
* [NEW] Faster ll2string() implementation. (Salvatore Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] CLUSTER RESET: Flush slave dataset on reset. (Salvatore Sanfilippo)
|
||||
* [FIX] Replica migration: don't migrate to masters that never had slaves
|
||||
in the past, but only to masters that remained orphaned after
|
||||
failure events. (Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] redis-trib: allow to reshard in non-interactive way. (Salvatore
|
||||
Sanfilippo)
|
||||
* [NEW] Cluster test: unit 04, check consistency during resharding. (Salvatore
|
||||
Sanfilippo)
|
||||
* [NEW] Cluster test: unit 05, slave selection. (Salvatore Sanfilippo)
|
||||
* [NEW] Cluster test: unit 06, slaves with stale data can't failover. (Salvatore
|
||||
Sanfilippo)
|
||||
* [NEW] Cluster test: unit 07, replicas migration. (Salvatore Sanfilippo)
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* No Sentinel changes in this release.
|
||||
|
||||
--[ Redis 3.0.0 Beta 7 (version 2.9.56) ] Release date: 30 jun 2014
|
||||
|
||||
This is the 7th beta of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] Scripting fixes backported from unstable, see Redis 2.8.12 changelog
|
||||
for more info. (Salvatore Sanfilippo)
|
||||
* [FIX] Cancel SHUTDOWN if initial AOF is being written. (Matt Stancliff)
|
||||
|
||||
* [NEW] New command: COMMAND, for commands introspection (Matt Stancliff &
|
||||
Salvatore Sanfilippo)
|
||||
* [NEW] hiredis: Update to latest version. (Matt Stancliff)
|
||||
* [NEW] Jemalloc updated to 3.6.0. (Salvatore Sanfilippo)
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] Cluster: clear NOADDR flag when updating node address.
|
||||
(Salvatore Sanfilippo)
|
||||
|
||||
* [NEW] New CLUSTER SLOTS command to simplify Cluster clients operations.
|
||||
(Matt Stancliff)
|
||||
* [NEW] More Cluster tests. (Salvatore Sanfilippo)
|
||||
* [NEW] Log when failover authorization are granted / denied.
|
||||
(Salvatore Sanfilippo)
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* [FIX] A few Sentinel bugs fixed and improvements, see Redis 2.8.12
|
||||
changelog for more info. (Salvatore Sanfilippo & Matt Stancliff)
|
||||
* [NEW] New Sentinel-Client handshake protocol, ROLE command, CLIENT KILL,
|
||||
all backported to 3.0 branch. (Salvatore Sanfilippo)
|
||||
|
||||
--[ Redis 3.0.0 Beta 6 (version 2.9.55) ] Release date: 9 jun 2014
|
||||
|
||||
This is the 6th beta of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] Fix software watchdog signal handler crash due to re-entering.
|
||||
* [FIX] Better Lua number -> string conversion for Lua scripts.
|
||||
* [FIX] Serious replication bug when min-slaves-* feature is used in slaves
|
||||
configuration fixed.
|
||||
* [FIX] Blocking pop on lists now works when the list is created by commands
|
||||
other than *PUSH* (for example SORT STORE).
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] CRITICAL: For a bug in the implementation of CLUSTER SET-CONFIG-EPOCH
|
||||
introduced with beta-3 (especially beta-4 where the command
|
||||
is actually used by redis-trib), a configEpoch for a node could
|
||||
jump backward, breaking the eventual consistency property of the
|
||||
slots -> nodes mapping in the cluster.
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* No changes for Sentinel in this release.
|
||||
|
||||
--[ Redis 3.0.0 Beta 5 (version 2.9.54) ] Release date: 26 may 2014
|
||||
|
||||
This is the 5th beta of Redis 3.0.0. It does not include any real
|
||||
worthwhile change (just three days passed since the previous beta), but
|
||||
fixes two stupid bugs preventing cluster tests to pass.
|
||||
|
||||
--[ Redis 3.0.0 Beta 4 (version 2.9.53) ] Release date: 23 may 2014
|
||||
|
||||
This is the fourth beta of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [NEW] Scripting engine performances improvements.
|
||||
* [NEW] Log format slightly changed to report current node role.
|
||||
|
||||
* [FIX] Correct the HyperLogLog stale cache flag to prevent unnecessary
|
||||
computation.
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [NEW] redis-trib: ability to import data from standalone Redis instances.
|
||||
* [NEW] redis-trib: "fix" subcommand much better at fixing errors.
|
||||
* [NEW] CLUSTER FAILOVER FORCE implemented.
|
||||
* [NEW] CLUSTER RESET implemented, it is now possible to completely reset
|
||||
nodes and create a new cluster without restarting anything.
|
||||
* [NEW] Slave validity factor (max estimated data age to still failover)
|
||||
is now under the control of the user, and can be configured via
|
||||
redis.conf or CONFIG SET. Option name cluster-slave-validity-factor.
|
||||
* [NEW] Cluster test: failure detection and failover initial tests.
|
||||
* [NEW] CLUSTER MEET: better error messages when address is invalid.
|
||||
* [NEW] Bulk-accept new Cluster nodes in the Cluster bus instead of
|
||||
performing just a single accept() per event fired.
|
||||
|
||||
* [FIX] Bypass data_age check for manual failovers.
|
||||
* [FIX] Fixed data_age computation / check integer overflow.
|
||||
* [FIX] Various fixes to Tcl client.tcl Redis Cluster client used in tests.
|
||||
* [FIX] Better handling of stolen slots.
|
||||
* [FIX] Don't accept cluster bus connections during startup.
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* [NEW] Generate +config-update-from event when a new config is received.
|
||||
* [NEW] Log when a failover will be re-attempted again.
|
||||
|
||||
* [FIX] Sentinel: Add "dir /tmp" directive in example sentinel.conf.
|
||||
|
||||
--[ Redis 3.0.0 Beta 3 (version 2.9.52) ] Release date: 5 may 2014
|
||||
|
||||
This is the third beta of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [NEW] New data structure: the HyperLogLog (see 2.8 release notes).
|
||||
* [NEW] Lexicograhical range queries in sorted sets (see 2.8 release notes).
|
||||
* [NEW] LRU algorithm precision greatly improved.
|
||||
|
||||
* [FIX] Redis is now much more responsive to reply with LOADING / BUSY errors.
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [NEW] Cluster testing framework and initial tests.
|
||||
* [NEW] Cluster epochs collision resolution (make Redis Cluster more resilient
|
||||
to admin and programming errors).
|
||||
* [NEW] Persist / fsync some global state to ensure correct crash-recovery
|
||||
semantics.
|
||||
* [NEW] New command introduced: CLUSTER SET-CONFIG-EPOCH, still not used
|
||||
by redis-trib. Will be used to speedup the assignment of unique
|
||||
epochs to different nodes at cluster creation time. For now this is
|
||||
handled as a side effect of the cluster epochs collision resolution.
|
||||
|
||||
* [FIX] Different fixes to redis-trib cluster creation.
|
||||
* [FIX] Fix an error in the CLUSTER NODES output for nodes slots.
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* [NEW] Sentinels are now able to send update messages in a peer-to-peer
|
||||
fashion even if no Redis instances are available. Now the Sentinel
|
||||
liveness property that the most updated configuration in a given
|
||||
partition is propagated to all the Sentinels is extended to partitions
|
||||
without reachable instances.
|
||||
* [NEW] Sentinel safety properties are now ensured in a crash-recovery system
|
||||
model since some state is persisted on disk before replying to other
|
||||
nodes, and reloaded at startup.
|
||||
* [NEW] Sentinel now uses CLIENT SETNAME so that it is easy to identify
|
||||
Sentinels using CLIENT LIST among other clients.
|
||||
* [NEW] Sentinel failure detection and reconnection code improved.
|
||||
|
||||
--[ Redis 3.0.0 Beta 2 (version 2.9.51) ] Release date: 11 mar 2014
|
||||
|
||||
This is the second beta of Redis 3.0.0.
|
||||
|
||||
>> General changes
|
||||
|
||||
* [FIX] Sometimes the absolute config file path was obtained in a wrong way.
|
||||
This happened when there was a "dir" directive inside the config file
|
||||
and at the same time the configuration file was given as a relative
|
||||
path to redis-server or redis-sentinel executables.
|
||||
* [FIX] redis-cli: Automatically enter --slave mode when SYNC or PSYNC are
|
||||
called during an interactive session.
|
||||
* [FIX] BITCOUNT: fixed unaligned access causing issues in sparc and other
|
||||
archs not capable of dealing with unaligned accesses. This also makes
|
||||
the code faster in archs where unaligned accesses are allowed.
|
||||
* [FIX] Force INFO used_memory_peak to match peak memory. This generated some
|
||||
confusion among users even if it was not an actual bug.
|
||||
* [FIX] Fixed an critical EVALSHA script cache bug: scripts executed may not
|
||||
propagate to AOF / Slaves correctly under certain conditions.
|
||||
See issue #1549 at Github for more information.
|
||||
* [FIX] Fixed multiple bugs resulting into closing the link with master or slave
|
||||
during replication without good reasons. This will result in useless
|
||||
resynchronizations, or infinite loops where the replication link can't
|
||||
be established.
|
||||
* [FIX] Don't count the time needed to populate the buffers of clients waiting
|
||||
in MONITOR mode when populating the Slow Log entries.
|
||||
|
||||
* [NEW] Redis-cli updated to use SCAN instead of random sampling via
|
||||
RANDOMKEY in order to implement --bigkeys feature. Moreover the
|
||||
implementation now supports pipelining and reports more information
|
||||
at the end of the scan. Much faster, much better. A special thank
|
||||
you to Michael Grunder for this improvement.
|
||||
* [NEW] redis-cli now supports a new --intrinsic-latency mode that is able
|
||||
to meter the latency of a system due to kernel / hypervisor.
|
||||
How to use it is explained at http://redis.io/topics/latency.
|
||||
* [NEW] New command BITPOS: find first bit set or clear in a bitmap.
|
||||
* [NEW] CONFIG REWRITE calls are now logged.
|
||||
* [NEW] AOF write errors (like no space on device) no longer abort Redis if the
|
||||
fsync policy is none or every second. The database enters a read-only
|
||||
mode where every write is refused with an error. Normal operations are
|
||||
restored as soon as Redis is able to append again data to the AOF file.
|
||||
* [NEW] Sentinel now accepts SHUTDOWN command.
|
||||
|
||||
|
||||
>> Cluster changes
|
||||
|
||||
* [FIX] Bind the first interface listed in the "bind" configuration directive
|
||||
if any, in order to perform outgoing connections. This fixes Cluster
|
||||
usage when an address is bound but there are multiple interfaces that
|
||||
may be used to connect with other nodes.
|
||||
* [FIX] When an "Importing" slot is closed via CLUSTER SETSLOT NODE ...
|
||||
increment the configEpoch in the special case it is zero.
|
||||
* [FIX] Current transaction is invalidated on redirection errors.
|
||||
* [FIX] Abort if port does not allow for a valid cluster bus port that is
|
||||
always at fixed +10000 offset.
|
||||
* [FIX] Keys extraction algorithm fixed for ZUNIONSTORE/ZINTERSTORE and SORT.
|
||||
* [FIX] Better failover timeout and retry times: failover should now work
|
||||
reliabily when node-timeout is very small (a few milliseconds).
|
||||
* [FIX] Don't allow SORT GET/BY options in Cluster mode.
|
||||
* [FIX] Clear importing/migrating state when turning from master to slave role.
|
||||
* [FIX] Set slot error if we receive an update for a busy slot.
|
||||
* [FIX] Update node configEpoch on UPDATE messages.
|
||||
|
||||
* [NEW] Support multi-key operations as long as keys resolve to the same
|
||||
hash slot, and the slot is not migrating, or it is migrating but all
|
||||
the mentioned keys are available.
|
||||
* [NEW] New DEBUG command CMDKEYS available to debug / test keys identification
|
||||
in Redis commands.
|
||||
* [NEW] redis-trib: create subcommand is now able to assign spare slaves.
|
||||
* [NEW] redis-trib: new subcommand 'call'. Exec command in all nodes.
|
||||
|
||||
|
||||
>> Sentinel changes
|
||||
|
||||
* [FIX] Sentinel "IDONTKNOW" error removed as it does not made sense with the
|
||||
new Sentinel design. This error was actually a fix for a design error
|
||||
in the first implementation of Sentinel.
|
||||
* [FIX] Sentinel: added a missing exit() call to abort after config file
|
||||
checks at startup. This error was introduced with an improvement in
|
||||
a previous 2.8 release.
|
||||
* [FIX] Sentinel: better nodes fail over start time desynchronization to avoid
|
||||
split-brain during the voting process needed to get authorization to
|
||||
fail over. This means the system is less likely to need to retry
|
||||
and will fail over faster. No changes in behavior / correctness.
|
||||
|
||||
* [NEW] Sentinel unit tests and framework. More tests needed and units must
|
||||
be improved in order to have less false positives, but it is a start
|
||||
and features a debugging console that is useful to fix tests or to
|
||||
inspect bugs causing tests failures.
|
||||
* [NEW] New Sentinel events: +/-monitor and +set used to monitor when an
|
||||
instance to monitor is added or removed, or when a configuration
|
||||
is modified via SENTINEL SET.
|
||||
|
||||
--[ Redis 3.0.0 Beta 1 (version 2.9.50) ] Release date: 11 Feb 2014
|
||||
|
||||
This is the first beta of Redis 3.0.0.
|
||||
|
||||
Migrating from 2.8 to 3.0
|
||||
=========================
|
||||
|
||||
Redis 2.8 is mostly a strict subset of 3.0, you should not have any problem
|
||||
upgrading your application from 2.8 to 3.0. However this is a list of small
|
||||
non-backward compatible changes introduced in the 3.0 release:
|
||||
|
||||
* The log format was modified. The prefix of each line included the pid
|
||||
in the following format [1234]. Now instead it is 1234:? Where
|
||||
'?' is actually the role of the instance. M for master, S for slave, C
|
||||
if this process is a saving child (for RDB/AOF), and X for Sentinel.
|
||||
|
||||
* The default maxmemory policy in Redis 3.0 is no longer "volatile-lru" as
|
||||
it used to be in 2.8, but "noeviction". The policies behavior is the same
|
||||
(but LRU eviction is much more precise in 3.0), so only the default value
|
||||
changed. Just make sure to specify in your redis.conf what you mean.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Credits: Where not specified the implementation and design is done by
|
||||
Salvatore Sanfilippo. Thanks to Pivotal for making all this possible.
|
||||
Also many thanks to all the other contributors and the amazing community
|
||||
we have.
|
||||
|
||||
See commit messages for more credits.
|
||||
|
||||
Cheers,
|
||||
Salvatore
|
||||
Happy hacking!
|
||||
|
||||
@@ -1 +1 @@
|
||||
Please check https://github.com/antirez/redis/issues
|
||||
Plese check https://github.com/antirez/redis/issues
|
||||
|
||||
+5
-9
@@ -12,17 +12,15 @@ 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 Reddit sub:
|
||||
all the support in the Redis Google Group.
|
||||
|
||||
http://reddit.com/r/redis
|
||||
|
||||
There is also an active community of Redis users at Stack Overflow:
|
||||
|
||||
http://stackoverflow.com/questions/tagged/redis
|
||||
Redis Google Group address:
|
||||
|
||||
https://groups.google.com/forum/?fromgroups#!forum/redis-db
|
||||
|
||||
# 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. Drop a message to the Redis Google Group with a proposal of semantics/API.
|
||||
|
||||
2. If in step 1 you get an acknowledge from the project leaders, use the
|
||||
following procedure to submit a patch:
|
||||
@@ -33,6 +31,4 @@ each source file that you contribute.
|
||||
d. Initiate a pull request on github ( http://help.github.com/send-pull-requests/ )
|
||||
e. Done :)
|
||||
|
||||
For minor fixes just open a pull request on Github.
|
||||
|
||||
Thanks!
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2006-2015, Salvatore Sanfilippo
|
||||
Copyright (c) 2006-2014, Salvatore Sanfilippo
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
@@ -26,25 +26,6 @@ After building Redis is a good idea to test it, using:
|
||||
|
||||
% make test
|
||||
|
||||
Fixing build problems with dependencies or cached build options
|
||||
—--------
|
||||
Redis has some dependencies which are included into the "deps" directory.
|
||||
"make" does not rebuild dependencies automatically, even if something in the
|
||||
source code of dependencies is changes.
|
||||
|
||||
When you update the source code with `git pull` or when code inside the
|
||||
dependencies tree is modified in any other way, make sure to use the following
|
||||
command in order to really clean everything and rebuild from scratch:
|
||||
|
||||
make distclean
|
||||
|
||||
This will clean: jemalloc, lua, hiredis, linenoise.
|
||||
|
||||
Also if you force certain build options like 32bit target, no C compiler
|
||||
optimizations (for debugging purposes), and other similar build time options,
|
||||
those options are cached indefinitely until you issue a "make distclean"
|
||||
command.
|
||||
|
||||
Fixing problems building 32 bit binaries
|
||||
---------
|
||||
|
||||
|
||||
Vendored
+2
-7
@@ -58,17 +58,12 @@ ifeq ($(uname_S),SunOS)
|
||||
LUA_CFLAGS= -D__C99FEATURES__=1
|
||||
endif
|
||||
|
||||
LUA_CFLAGS+= -O2 -Wall -DLUA_ANSI -DENABLE_CJSON_GLOBAL $(CFLAGS)
|
||||
LUA_CFLAGS+= -O2 -Wall -DLUA_ANSI $(CFLAGS)
|
||||
LUA_LDFLAGS+= $(LDFLAGS)
|
||||
# lua's Makefile defines AR="ar rcu", which is unusual, and makes it more
|
||||
# challenging to cross-compile lua (and redis). These defines make it easier
|
||||
# to fit redis into cross-compilation environments, which typically set AR.
|
||||
AR=ar
|
||||
ARFLAGS=rcu
|
||||
|
||||
lua: .make-prerequisites
|
||||
@printf '%b %b\n' $(MAKECOLOR)MAKE$(ENDCOLOR) $(BINCOLOR)$@$(ENDCOLOR)
|
||||
cd lua/src && $(MAKE) all CFLAGS="$(LUA_CFLAGS)" MYLDFLAGS="$(LUA_LDFLAGS)" AR="$(AR) $(ARFLAGS)"
|
||||
cd lua/src && $(MAKE) all CFLAGS="$(LUA_CFLAGS)" MYLDFLAGS="$(LUA_LDFLAGS)"
|
||||
|
||||
.PHONY: lua
|
||||
|
||||
|
||||
Vendored
-1
@@ -443,7 +443,6 @@ void redisProcessCallbacks(redisAsyncContext *ac) {
|
||||
if (((redisReply*)reply)->type == REDIS_REPLY_ERROR) {
|
||||
c->err = REDIS_ERR_OTHER;
|
||||
snprintf(c->errstr,sizeof(c->errstr),"%s",((redisReply*)reply)->str);
|
||||
c->reader->fn->freeObject(reply);
|
||||
__redisAsyncDisconnect(ac);
|
||||
return;
|
||||
}
|
||||
|
||||
Vendored
-4
@@ -5,10 +5,6 @@
|
||||
#define _BSD_SOURCE
|
||||
#endif
|
||||
|
||||
#if defined(_AIX)
|
||||
#define _ALL_SOURCE
|
||||
#endif
|
||||
|
||||
#if defined(__sun__)
|
||||
#define _POSIX_C_SOURCE 200112L
|
||||
#elif defined(__linux__) || defined(__OpenBSD__) || defined(__NetBSD__)
|
||||
|
||||
Vendored
-1
@@ -300,7 +300,6 @@ static int _redisContextConnectTcp(redisContext *c, const char *addr, int port,
|
||||
break;
|
||||
}
|
||||
}
|
||||
freeaddrinfo(bservinfo);
|
||||
if (!bound) {
|
||||
char buf[128];
|
||||
snprintf(buf,sizeof(buf),"Can't bind socket: %s",strerror(errno));
|
||||
|
||||
Vendored
+1
-1
@@ -35,7 +35,7 @@
|
||||
|
||||
#include "hiredis.h"
|
||||
|
||||
#if defined(__sun) || defined(_AIX)
|
||||
#if defined(__sun)
|
||||
#define AF_LOCAL AF_UNIX
|
||||
#endif
|
||||
|
||||
|
||||
Vendored
+4
-7
@@ -123,7 +123,7 @@ void sdsclear(sds s) {
|
||||
/* Enlarge the free space at the end of the sds string so that the caller
|
||||
* is sure that after calling this function can overwrite up to addlen
|
||||
* bytes after the end of the string, plus one more byte for nul term.
|
||||
*
|
||||
*
|
||||
* Note: this does not change the *length* of the sds string as returned
|
||||
* by sdslen(), but only the free buffer space we have. */
|
||||
sds sdsMakeRoomFor(sds s, size_t addlen) {
|
||||
@@ -200,12 +200,10 @@ size_t sdsAllocSize(sds s) {
|
||||
void sdsIncrLen(sds s, int incr) {
|
||||
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
|
||||
|
||||
if (incr >= 0)
|
||||
assert(sh->free >= (unsigned int)incr);
|
||||
else
|
||||
assert(sh->len >= (unsigned int)(-incr));
|
||||
assert(sh->free >= incr);
|
||||
sh->len += incr;
|
||||
sh->free -= incr;
|
||||
assert(sh->free >= 0);
|
||||
s[sh->len] = '\0';
|
||||
}
|
||||
|
||||
@@ -390,7 +388,6 @@ sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
|
||||
buf[buflen-2] = '\0';
|
||||
va_copy(cpy,ap);
|
||||
vsnprintf(buf, buflen, fmt, cpy);
|
||||
va_end(ap);
|
||||
if (buf[buflen-2] != '\0') {
|
||||
if (buf != staticbuf) zfree(buf);
|
||||
buflen *= 2;
|
||||
@@ -460,7 +457,7 @@ sds sdscatfmt(sds s, char const *fmt, ...) {
|
||||
i = initlen; /* Position of the next byte to write to dest str. */
|
||||
while(*f) {
|
||||
char next, *str;
|
||||
unsigned int l;
|
||||
int l;
|
||||
long long num;
|
||||
unsigned long long unum;
|
||||
|
||||
|
||||
Vendored
+2
-2
@@ -39,8 +39,8 @@
|
||||
typedef char *sds;
|
||||
|
||||
struct sdshdr {
|
||||
unsigned int len;
|
||||
unsigned int free;
|
||||
int len;
|
||||
int free;
|
||||
char buf[];
|
||||
};
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -51,7 +51,7 @@ static redisContext *select_database(redisContext *c) {
|
||||
assert(reply != NULL);
|
||||
freeReplyObject(reply);
|
||||
|
||||
/* Make sure the DB is empty */
|
||||
/* Make sure the DB is emtpy */
|
||||
reply = redisCommand(c,"DBSIZE");
|
||||
assert(reply != NULL);
|
||||
if (reply->type == REDIS_REPLY_INTEGER && reply->integer == 0) {
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
linenoise_example
|
||||
*.dSYM
|
||||
history.txt
|
||||
linenoise_example*
|
||||
|
||||
Vendored
+8
-15
@@ -1,13 +1,8 @@
|
||||
# Linenoise
|
||||
|
||||
A minimal, zero-config, BSD licensed, readline replacement used in Redis,
|
||||
MongoDB, and Android.
|
||||
A minimal, zero-config, BSD licensed, readline replacement.
|
||||
|
||||
* Single and multi line editing mode with the usual key bindings implemented.
|
||||
* History handling.
|
||||
* Completion.
|
||||
* About 1,100 lines of BSD license source code.
|
||||
* Only uses a subset of VT100 escapes (ANSI.SYS compatible).
|
||||
News: linenoise is now part of [Android](http://android.git.kernel.org/?p=platform/system/core.git;a=tree;f=liblinenoise;h=56450eaed7f783760e5e6a5993ef75cde2e29dea;hb=HEAD Android)!
|
||||
|
||||
## Can a line editing library be 20k lines of code?
|
||||
|
||||
@@ -15,7 +10,7 @@ Line editing with some support for history is a really important feature for com
|
||||
|
||||
So what usually happens is either:
|
||||
|
||||
* Large programs with configure scripts disabling line editing if readline is not present in the system, or not supporting it at all since readline is GPL licensed and libedit (the BSD clone) is not as known and available as readline is (Real world example of this problem: Tclsh).
|
||||
* Large programs with configure scripts disabling line editing if readline is not present in the system, or not supporting it at all since readline is GPL licensed and libedit (the BSD clone) is not as known and available as readline is (Readl world example of this problem: Tclsh).
|
||||
* Smaller programs not using a configure script not supporting line editing at all (A problem we had with Redis-cli for instance).
|
||||
|
||||
The result is a pollution of binaries without line editing support.
|
||||
@@ -24,29 +19,27 @@ So I spent more or less two hours doing a reality check resulting in this little
|
||||
|
||||
## Terminals, in 2010.
|
||||
|
||||
Apparently almost every terminal you can happen to use today has some kind of support for basic VT100 escape sequences. So I tried to write a lib using just very basic VT100 features. The resulting library appears to work everywhere I tried to use it, and now can work even on ANSI.SYS compatible terminals, since no
|
||||
VT220 specific sequences are used anymore.
|
||||
Apparently almost every terminal you can happen to use today has some kind of support for VT100 alike escape sequences. So I tried to write a lib using just very basic VT100 features. The resulting library appears to work everywhere I tried to use it.
|
||||
|
||||
The library is currently about 1100 lines of code. In order to use it in your project just look at the *example.c* file in the source distribution, it is trivial. Linenoise is BSD code, so you can use both in free software and commercial software.
|
||||
Since it's so young I guess there are a few bugs, or the lib may not compile or work with some operating system, but it's a matter of a few weeks and eventually we'll get it right, and there will be no excuses for not shipping command line tools without built-in line editing support.
|
||||
|
||||
The library is currently less than 400 lines of code. In order to use it in your project just look at the *example.c* file in the source distribution, it is trivial. Linenoise is BSD code, so you can use both in free software and commercial software.
|
||||
|
||||
## Tested with...
|
||||
|
||||
* Linux text only console ($TERM = linux)
|
||||
* Linux KDE terminal application ($TERM = xterm)
|
||||
* Linux xterm ($TERM = xterm)
|
||||
* Linux Buildroot ($TERM = vt100)
|
||||
* Mac OS X iTerm ($TERM = xterm)
|
||||
* Mac OS X default Terminal.app ($TERM = xterm)
|
||||
* OpenBSD 4.5 through an OSX Terminal.app ($TERM = screen)
|
||||
* IBM AIX 6.1
|
||||
* FreeBSD xterm ($TERM = xterm)
|
||||
* ANSI.SYS
|
||||
|
||||
Please test it everywhere you can and report back!
|
||||
|
||||
## Let's push this forward!
|
||||
|
||||
Patches should be provided in the respect of linenoise sensibility for small
|
||||
easy to understand code.
|
||||
Please fork it and add something interesting and send me a pull request. What's especially interesting are fixes, new key bindings, completion.
|
||||
|
||||
Send feedbacks to antirez at gmail
|
||||
|
||||
Vendored
+4
-41
@@ -1,6 +1,5 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "linenoise.h"
|
||||
|
||||
|
||||
@@ -11,52 +10,16 @@ void completion(const char *buf, linenoiseCompletions *lc) {
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int main(void) {
|
||||
char *line;
|
||||
char *prgname = argv[0];
|
||||
|
||||
/* Parse options, with --multiline we enable multi line editing. */
|
||||
while(argc > 1) {
|
||||
argc--;
|
||||
argv++;
|
||||
if (!strcmp(*argv,"--multiline")) {
|
||||
linenoiseSetMultiLine(1);
|
||||
printf("Multi-line mode enabled.\n");
|
||||
} else if (!strcmp(*argv,"--keycodes")) {
|
||||
linenoisePrintKeyCodes();
|
||||
exit(0);
|
||||
} else {
|
||||
fprintf(stderr, "Usage: %s [--multiline] [--keycodes]\n", prgname);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Set the completion callback. This will be called every time the
|
||||
* user uses the <tab> key. */
|
||||
linenoiseSetCompletionCallback(completion);
|
||||
|
||||
/* Load history from file. The history file is just a plain text file
|
||||
* where entries are separated by newlines. */
|
||||
linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
|
||||
|
||||
/* Now this is the main loop of the typical linenoise-based application.
|
||||
* The call to linenoise() will block as long as the user types something
|
||||
* and presses enter.
|
||||
*
|
||||
* The typed string is returned as a malloc() allocated string by
|
||||
* linenoise, so the user needs to free() it. */
|
||||
while((line = linenoise("hello> ")) != NULL) {
|
||||
/* Do something with the string. */
|
||||
if (line[0] != '\0' && line[0] != '/') {
|
||||
if (line[0] != '\0') {
|
||||
printf("echo: '%s'\n", line);
|
||||
linenoiseHistoryAdd(line); /* Add to the history. */
|
||||
linenoiseHistorySave("history.txt"); /* Save the history on disk. */
|
||||
} else if (!strncmp(line,"/historylen",11)) {
|
||||
/* The "/historylen" command will change the history len. */
|
||||
int len = atoi(line+11);
|
||||
linenoiseHistorySetMaxLen(len);
|
||||
} else if (line[0] == '/') {
|
||||
printf("Unreconized command: %s\n", line);
|
||||
linenoiseHistoryAdd(line);
|
||||
linenoiseHistorySave("history.txt"); /* Save every new entry */
|
||||
}
|
||||
free(line);
|
||||
}
|
||||
|
||||
Vendored
+32
-47
@@ -2,7 +2,7 @@
|
||||
* line editing lib needs to be 20,000 lines of C code.
|
||||
*
|
||||
* You can find the latest source code at:
|
||||
*
|
||||
*
|
||||
* http://github.com/antirez/linenoise
|
||||
*
|
||||
* Does a number of crazy assumptions that happen to be true in 99.9999% of
|
||||
@@ -14,18 +14,18 @@
|
||||
* Copyright (c) 2010-2013, Pieter Noordhuis <pcnoordhuis 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.
|
||||
*
|
||||
*
|
||||
* 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
|
||||
@@ -37,7 +37,7 @@
|
||||
* 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.
|
||||
*
|
||||
*
|
||||
* ------------------------------------------------------------------------
|
||||
*
|
||||
* References:
|
||||
@@ -56,6 +56,10 @@
|
||||
* flickering effect with some slow terminal, but the lesser sequences
|
||||
* the more compatible.
|
||||
*
|
||||
* CHA (Cursor Horizontal Absolute)
|
||||
* Sequence: ESC [ n G
|
||||
* Effect: moves cursor to column n
|
||||
*
|
||||
* EL (Erase Line)
|
||||
* Sequence: ESC [ n K
|
||||
* Effect: if n is 0 or missing, clear from cursor to end of line
|
||||
@@ -64,19 +68,7 @@
|
||||
*
|
||||
* CUF (CUrsor Forward)
|
||||
* Sequence: ESC [ n C
|
||||
* Effect: moves cursor forward n chars
|
||||
*
|
||||
* CUB (CUrsor Backward)
|
||||
* Sequence: ESC [ n D
|
||||
* Effect: moves cursor backward n chars
|
||||
*
|
||||
* The following is used to get the terminal width if getting
|
||||
* the width with the TIOCGWINSZ ioctl fails
|
||||
*
|
||||
* DSR (Device Status Report)
|
||||
* Sequence: ESC [ 6 n
|
||||
* Effect: reports the current cusor position as ESC [ n ; m R
|
||||
* where n is the row and m is the column
|
||||
* Effect: moves cursor forward of n chars
|
||||
*
|
||||
* When multi line mode is enabled, we also use an additional escape
|
||||
* sequence. However multi line editing is disabled by default.
|
||||
@@ -89,18 +81,17 @@
|
||||
* Sequence: ESC [ n B
|
||||
* Effect: moves cursor down of n chars.
|
||||
*
|
||||
* When linenoiseClearScreen() is called, two additional escape sequences
|
||||
* are used in order to clear the screen and position the cursor at home
|
||||
* position.
|
||||
* The following are used to clear the screen: ESC [ H ESC [ 2 J
|
||||
* This is actually composed of two sequences:
|
||||
*
|
||||
* CUP (Cursor position)
|
||||
* cursorhome
|
||||
* Sequence: ESC [ H
|
||||
* Effect: moves the cursor to upper left corner
|
||||
*
|
||||
* ED (Erase display)
|
||||
* ED2 (Clear entire screen)
|
||||
* Sequence: ESC [ 2 J
|
||||
* Effect: clear the whole screen
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
#include <termios.h>
|
||||
@@ -341,7 +332,7 @@ static void freeCompletions(linenoiseCompletions *lc) {
|
||||
/* This is an helper function for linenoiseEdit() and is called when the
|
||||
* user types the <tab> key in order to complete the string currently in the
|
||||
* input.
|
||||
*
|
||||
*
|
||||
* The state of the editing is encapsulated into the pointed linenoiseState
|
||||
* structure as described in the structure definition. */
|
||||
static int completeLine(struct linenoiseState *ls) {
|
||||
@@ -468,7 +459,7 @@ static void refreshSingleLine(struct linenoiseState *l) {
|
||||
size_t len = l->len;
|
||||
size_t pos = l->pos;
|
||||
struct abuf ab;
|
||||
|
||||
|
||||
while((plen+pos) >= l->cols) {
|
||||
buf++;
|
||||
len--;
|
||||
@@ -480,7 +471,7 @@ static void refreshSingleLine(struct linenoiseState *l) {
|
||||
|
||||
abInit(&ab);
|
||||
/* Cursor to left edge */
|
||||
snprintf(seq,64,"\r");
|
||||
snprintf(seq,64,"\x1b[0G");
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
/* Write the prompt and the current buffer content */
|
||||
abAppend(&ab,l->prompt,strlen(l->prompt));
|
||||
@@ -489,7 +480,7 @@ static void refreshSingleLine(struct linenoiseState *l) {
|
||||
snprintf(seq,64,"\x1b[0K");
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
/* Move cursor to original position. */
|
||||
snprintf(seq,64,"\r\x1b[%dC", (int)(pos+plen));
|
||||
snprintf(seq,64,"\x1b[0G\x1b[%dC", (int)(pos+plen));
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
if (write(fd,ab.b,ab.len) == -1) {} /* Can't recover from write error. */
|
||||
abFree(&ab);
|
||||
@@ -505,7 +496,6 @@ static void refreshMultiLine(struct linenoiseState *l) {
|
||||
int rows = (plen+l->len+l->cols-1)/l->cols; /* rows used by current buf. */
|
||||
int rpos = (plen+l->oldpos+l->cols)/l->cols; /* cursor relative row. */
|
||||
int rpos2; /* rpos after refresh. */
|
||||
int col; /* colum position, zero-based. */
|
||||
int old_rows = l->maxrows;
|
||||
int fd = l->ofd, j;
|
||||
struct abuf ab;
|
||||
@@ -525,15 +515,15 @@ static void refreshMultiLine(struct linenoiseState *l) {
|
||||
/* Now for every row clear it, go up. */
|
||||
for (j = 0; j < old_rows-1; j++) {
|
||||
lndebug("clear+up");
|
||||
snprintf(seq,64,"\r\x1b[0K\x1b[1A");
|
||||
snprintf(seq,64,"\x1b[0G\x1b[0K\x1b[1A");
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
}
|
||||
|
||||
/* Clean the top line. */
|
||||
lndebug("clear");
|
||||
snprintf(seq,64,"\r\x1b[0K");
|
||||
snprintf(seq,64,"\x1b[0G\x1b[0K");
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
|
||||
|
||||
/* Write the prompt and the current buffer content */
|
||||
abAppend(&ab,l->prompt,strlen(l->prompt));
|
||||
abAppend(&ab,l->buf,l->len);
|
||||
@@ -546,7 +536,7 @@ static void refreshMultiLine(struct linenoiseState *l) {
|
||||
{
|
||||
lndebug("<newline>");
|
||||
abAppend(&ab,"\n",1);
|
||||
snprintf(seq,64,"\r");
|
||||
snprintf(seq,64,"\x1b[0G");
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
rows++;
|
||||
if (rows > (int)l->maxrows) l->maxrows = rows;
|
||||
@@ -564,12 +554,8 @@ static void refreshMultiLine(struct linenoiseState *l) {
|
||||
}
|
||||
|
||||
/* Set column. */
|
||||
col = (plen+(int)l->pos) % (int)l->cols;
|
||||
lndebug("set col %d", 1+col);
|
||||
if (col)
|
||||
snprintf(seq,64,"\r\x1b[%dC", col);
|
||||
else
|
||||
snprintf(seq,64,"\r");
|
||||
lndebug("set col %d", 1+((plen+(int)l->pos) % (int)l->cols));
|
||||
snprintf(seq,64,"\x1b[%dG", 1+((plen+(int)l->pos) % (int)l->cols));
|
||||
abAppend(&ab,seq,strlen(seq));
|
||||
|
||||
lndebug("\n");
|
||||
@@ -746,7 +732,7 @@ static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen,
|
||||
/* The latest history entry is always our current buffer, that
|
||||
* initially is just an empty string. */
|
||||
linenoiseHistoryAdd("");
|
||||
|
||||
|
||||
if (write(l.ofd,prompt,l.plen) == -1) return -1;
|
||||
while(1) {
|
||||
char c;
|
||||
@@ -771,7 +757,6 @@ static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen,
|
||||
case ENTER: /* enter */
|
||||
history_len--;
|
||||
free(history[history_len]);
|
||||
if (mlmode) linenoiseEditMoveEnd(&l);
|
||||
return (int)l.len;
|
||||
case CTRL_C: /* ctrl-c */
|
||||
errno = EAGAIN;
|
||||
@@ -780,8 +765,8 @@ static int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, size_t buflen,
|
||||
case 8: /* ctrl-h */
|
||||
linenoiseEditBackspace(&l);
|
||||
break;
|
||||
case CTRL_D: /* ctrl-d, remove char at right of cursor, or if the
|
||||
line is empty, act as end-of-file. */
|
||||
case CTRL_D: /* ctrl-d, remove char at right of cursor, or of the
|
||||
line is empty, act as end-of-file. */
|
||||
if (l.len > 0) {
|
||||
linenoiseEditDelete(&l);
|
||||
} else {
|
||||
@@ -919,7 +904,7 @@ void linenoisePrintKeyCodes(void) {
|
||||
|
||||
printf("'%c' %02x (%d) (type quit to exit)\n",
|
||||
isprint(c) ? c : '?', (int)c, (int)c);
|
||||
printf("\r"); /* Go left edge manually, we are in raw mode. */
|
||||
printf("\x1b[0G"); /* Go left edge manually, we are in raw mode. */
|
||||
fflush(stdout);
|
||||
}
|
||||
disableRawMode(STDIN_FILENO);
|
||||
@@ -1073,7 +1058,7 @@ int linenoiseHistorySetMaxLen(int len) {
|
||||
int linenoiseHistorySave(const char *filename) {
|
||||
FILE *fp = fopen(filename,"w");
|
||||
int j;
|
||||
|
||||
|
||||
if (fp == NULL) return -1;
|
||||
for (j = 0; j < history_len; j++)
|
||||
fprintf(fp,"%s\n",history[j]);
|
||||
@@ -1089,12 +1074,12 @@ int linenoiseHistorySave(const char *filename) {
|
||||
int linenoiseHistoryLoad(const char *filename) {
|
||||
FILE *fp = fopen(filename,"r");
|
||||
char buf[LINENOISE_MAX_LINE];
|
||||
|
||||
|
||||
if (fp == NULL) return -1;
|
||||
|
||||
while (fgets(buf,LINENOISE_MAX_LINE,fp) != NULL) {
|
||||
char *p;
|
||||
|
||||
|
||||
p = strchr(buf,'\r');
|
||||
if (!p) p = strchr(buf,'\n');
|
||||
if (p) *p = '\0';
|
||||
|
||||
Vendored
+3
-3
@@ -9,18 +9,18 @@
|
||||
* Copyright (c) 2010, Pieter Noordhuis <pcnoordhuis 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.
|
||||
*
|
||||
*
|
||||
* 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
|
||||
|
||||
Vendored
+2
-3
@@ -25,10 +25,9 @@ PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
|
||||
LUA_A= liblua.a
|
||||
CORE_O= lapi.o lcode.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o \
|
||||
lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o \
|
||||
lundump.o lvm.o lzio.o strbuf.o fpconv.o
|
||||
lundump.o lvm.o lzio.o strbuf.o
|
||||
LIB_O= lauxlib.o lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o \
|
||||
lstrlib.o loadlib.o linit.o lua_cjson.o lua_struct.o lua_cmsgpack.o \
|
||||
lua_bit.o
|
||||
lstrlib.o loadlib.o linit.o lua_cjson.o lua_struct.o lua_cmsgpack.o
|
||||
|
||||
LUA_T= lua
|
||||
LUA_O= lua.o
|
||||
|
||||
Vendored
-205
@@ -1,205 +0,0 @@
|
||||
/* fpconv - Floating point conversion routines
|
||||
*
|
||||
* Copyright (c) 2011-2012 Mark Pulford <mark@kyne.com.au>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/* JSON uses a '.' decimal separator. strtod() / sprintf() under C libraries
|
||||
* with locale support will break when the decimal separator is a comma.
|
||||
*
|
||||
* fpconv_* will around these issues with a translation buffer if required.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "fpconv.h"
|
||||
|
||||
/* Lua CJSON assumes the locale is the same for all threads within a
|
||||
* process and doesn't change after initialisation.
|
||||
*
|
||||
* This avoids the need for per thread storage or expensive checks
|
||||
* for call. */
|
||||
static char locale_decimal_point = '.';
|
||||
|
||||
/* In theory multibyte decimal_points are possible, but
|
||||
* Lua CJSON only supports UTF-8 and known locales only have
|
||||
* single byte decimal points ([.,]).
|
||||
*
|
||||
* localconv() may not be thread safe (=>crash), and nl_langinfo() is
|
||||
* not supported on some platforms. Use sprintf() instead - if the
|
||||
* locale does change, at least Lua CJSON won't crash. */
|
||||
static void fpconv_update_locale()
|
||||
{
|
||||
char buf[8];
|
||||
|
||||
snprintf(buf, sizeof(buf), "%g", 0.5);
|
||||
|
||||
/* Failing this test might imply the platform has a buggy dtoa
|
||||
* implementation or wide characters */
|
||||
if (buf[0] != '0' || buf[2] != '5' || buf[3] != 0) {
|
||||
fprintf(stderr, "Error: wide characters found or printf() bug.");
|
||||
abort();
|
||||
}
|
||||
|
||||
locale_decimal_point = buf[1];
|
||||
}
|
||||
|
||||
/* Check for a valid number character: [-+0-9a-yA-Y.]
|
||||
* Eg: -0.6e+5, infinity, 0xF0.F0pF0
|
||||
*
|
||||
* Used to find the probable end of a number. It doesn't matter if
|
||||
* invalid characters are counted - strtod() will find the valid
|
||||
* number if it exists. The risk is that slightly more memory might
|
||||
* be allocated before a parse error occurs. */
|
||||
static inline int valid_number_character(char ch)
|
||||
{
|
||||
char lower_ch;
|
||||
|
||||
if ('0' <= ch && ch <= '9')
|
||||
return 1;
|
||||
if (ch == '-' || ch == '+' || ch == '.')
|
||||
return 1;
|
||||
|
||||
/* Hex digits, exponent (e), base (p), "infinity",.. */
|
||||
lower_ch = ch | 0x20;
|
||||
if ('a' <= lower_ch && lower_ch <= 'y')
|
||||
return 1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Calculate the size of the buffer required for a strtod locale
|
||||
* conversion. */
|
||||
static int strtod_buffer_size(const char *s)
|
||||
{
|
||||
const char *p = s;
|
||||
|
||||
while (valid_number_character(*p))
|
||||
p++;
|
||||
|
||||
return p - s;
|
||||
}
|
||||
|
||||
/* Similar to strtod(), but must be passed the current locale's decimal point
|
||||
* character. Guaranteed to be called at the start of any valid number in a string */
|
||||
double fpconv_strtod(const char *nptr, char **endptr)
|
||||
{
|
||||
char localbuf[FPCONV_G_FMT_BUFSIZE];
|
||||
char *buf, *endbuf, *dp;
|
||||
int buflen;
|
||||
double value;
|
||||
|
||||
/* System strtod() is fine when decimal point is '.' */
|
||||
if (locale_decimal_point == '.')
|
||||
return strtod(nptr, endptr);
|
||||
|
||||
buflen = strtod_buffer_size(nptr);
|
||||
if (!buflen) {
|
||||
/* No valid characters found, standard strtod() return */
|
||||
*endptr = (char *)nptr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Duplicate number into buffer */
|
||||
if (buflen >= FPCONV_G_FMT_BUFSIZE) {
|
||||
/* Handle unusually large numbers */
|
||||
buf = malloc(buflen + 1);
|
||||
if (!buf) {
|
||||
fprintf(stderr, "Out of memory");
|
||||
abort();
|
||||
}
|
||||
} else {
|
||||
/* This is the common case.. */
|
||||
buf = localbuf;
|
||||
}
|
||||
memcpy(buf, nptr, buflen);
|
||||
buf[buflen] = 0;
|
||||
|
||||
/* Update decimal point character if found */
|
||||
dp = strchr(buf, '.');
|
||||
if (dp)
|
||||
*dp = locale_decimal_point;
|
||||
|
||||
value = strtod(buf, &endbuf);
|
||||
*endptr = (char *)&nptr[endbuf - buf];
|
||||
if (buflen >= FPCONV_G_FMT_BUFSIZE)
|
||||
free(buf);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
/* "fmt" must point to a buffer of at least 6 characters */
|
||||
static void set_number_format(char *fmt, int precision)
|
||||
{
|
||||
int d1, d2, i;
|
||||
|
||||
assert(1 <= precision && precision <= 14);
|
||||
|
||||
/* Create printf format (%.14g) from precision */
|
||||
d1 = precision / 10;
|
||||
d2 = precision % 10;
|
||||
fmt[0] = '%';
|
||||
fmt[1] = '.';
|
||||
i = 2;
|
||||
if (d1) {
|
||||
fmt[i++] = '0' + d1;
|
||||
}
|
||||
fmt[i++] = '0' + d2;
|
||||
fmt[i++] = 'g';
|
||||
fmt[i] = 0;
|
||||
}
|
||||
|
||||
/* Assumes there is always at least 32 characters available in the target buffer */
|
||||
int fpconv_g_fmt(char *str, double num, int precision)
|
||||
{
|
||||
char buf[FPCONV_G_FMT_BUFSIZE];
|
||||
char fmt[6];
|
||||
int len;
|
||||
char *b;
|
||||
|
||||
set_number_format(fmt, precision);
|
||||
|
||||
/* Pass through when decimal point character is dot. */
|
||||
if (locale_decimal_point == '.')
|
||||
return snprintf(str, FPCONV_G_FMT_BUFSIZE, fmt, num);
|
||||
|
||||
/* snprintf() to a buffer then translate for other decimal point characters */
|
||||
len = snprintf(buf, FPCONV_G_FMT_BUFSIZE, fmt, num);
|
||||
|
||||
/* Copy into target location. Translate decimal point if required */
|
||||
b = buf;
|
||||
do {
|
||||
*str++ = (*b == locale_decimal_point ? '.' : *b);
|
||||
} while(*b++);
|
||||
|
||||
return len;
|
||||
}
|
||||
|
||||
void fpconv_init()
|
||||
{
|
||||
fpconv_update_locale();
|
||||
}
|
||||
|
||||
/* vi:ai et sw=4 ts=4:
|
||||
*/
|
||||
Vendored
-22
@@ -1,22 +0,0 @@
|
||||
/* Lua CJSON floating point conversion routines */
|
||||
|
||||
/* Buffer required to store the largest string representation of a double.
|
||||
*
|
||||
* Longest double printed with %.14g is 21 characters long:
|
||||
* -1.7976931348623e+308 */
|
||||
# define FPCONV_G_FMT_BUFSIZE 32
|
||||
|
||||
#ifdef USE_INTERNAL_FPCONV
|
||||
static inline void fpconv_init()
|
||||
{
|
||||
/* Do nothing - not required */
|
||||
}
|
||||
#else
|
||||
extern void fpconv_init();
|
||||
#endif
|
||||
|
||||
extern int fpconv_g_fmt(char*, double, int);
|
||||
extern double fpconv_strtod(const char*, char**);
|
||||
|
||||
/* vi:ai et sw=4 ts=4:
|
||||
*/
|
||||
Vendored
+1
-1
@@ -495,7 +495,7 @@ static void f_parser (lua_State *L, void *ud) {
|
||||
struct SParser *p = cast(struct SParser *, ud);
|
||||
int c = luaZ_lookahead(p->z);
|
||||
luaC_checkGC(L);
|
||||
tf = (luaY_parser)(L, p->z,
|
||||
tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z,
|
||||
&p->buff, p->name);
|
||||
cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
|
||||
cl->l.p = tf;
|
||||
|
||||
Vendored
-189
@@ -1,189 +0,0 @@
|
||||
/*
|
||||
** Lua BitOp -- a bit operations library for Lua 5.1/5.2.
|
||||
** http://bitop.luajit.org/
|
||||
**
|
||||
** Copyright (C) 2008-2012 Mike Pall. All rights reserved.
|
||||
**
|
||||
** Permission is hereby granted, free of charge, to any person obtaining
|
||||
** a copy of this software and associated documentation files (the
|
||||
** "Software"), to deal in the Software without restriction, including
|
||||
** without limitation the rights to use, copy, modify, merge, publish,
|
||||
** distribute, sublicense, and/or sell copies of the Software, and to
|
||||
** permit persons to whom the Software is furnished to do so, subject to
|
||||
** the following conditions:
|
||||
**
|
||||
** The above copyright notice and this permission notice shall be
|
||||
** included in all copies or substantial portions of the Software.
|
||||
**
|
||||
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
**
|
||||
** [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
|
||||
*/
|
||||
|
||||
#define LUA_BITOP_VERSION "1.0.2"
|
||||
|
||||
#define LUA_LIB
|
||||
#include "lua.h"
|
||||
#include "lauxlib.h"
|
||||
|
||||
#ifdef _MSC_VER
|
||||
/* MSVC is stuck in the last century and doesn't have C99's stdint.h. */
|
||||
typedef __int32 int32_t;
|
||||
typedef unsigned __int32 uint32_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
|
||||
typedef int32_t SBits;
|
||||
typedef uint32_t UBits;
|
||||
|
||||
typedef union {
|
||||
lua_Number n;
|
||||
#ifdef LUA_NUMBER_DOUBLE
|
||||
uint64_t b;
|
||||
#else
|
||||
UBits b;
|
||||
#endif
|
||||
} BitNum;
|
||||
|
||||
/* Convert argument to bit type. */
|
||||
static UBits barg(lua_State *L, int idx)
|
||||
{
|
||||
BitNum bn;
|
||||
UBits b;
|
||||
#if LUA_VERSION_NUM < 502
|
||||
bn.n = lua_tonumber(L, idx);
|
||||
#else
|
||||
bn.n = luaL_checknumber(L, idx);
|
||||
#endif
|
||||
#if defined(LUA_NUMBER_DOUBLE)
|
||||
bn.n += 6755399441055744.0; /* 2^52+2^51 */
|
||||
#ifdef SWAPPED_DOUBLE
|
||||
b = (UBits)(bn.b >> 32);
|
||||
#else
|
||||
b = (UBits)bn.b;
|
||||
#endif
|
||||
#elif defined(LUA_NUMBER_INT) || defined(LUA_NUMBER_LONG) || \
|
||||
defined(LUA_NUMBER_LONGLONG) || defined(LUA_NUMBER_LONG_LONG) || \
|
||||
defined(LUA_NUMBER_LLONG)
|
||||
if (sizeof(UBits) == sizeof(lua_Number))
|
||||
b = bn.b;
|
||||
else
|
||||
b = (UBits)(SBits)bn.n;
|
||||
#elif defined(LUA_NUMBER_FLOAT)
|
||||
#error "A 'float' lua_Number type is incompatible with this library"
|
||||
#else
|
||||
#error "Unknown number type, check LUA_NUMBER_* in luaconf.h"
|
||||
#endif
|
||||
#if LUA_VERSION_NUM < 502
|
||||
if (b == 0 && !lua_isnumber(L, idx)) {
|
||||
luaL_typerror(L, idx, "number");
|
||||
}
|
||||
#endif
|
||||
return b;
|
||||
}
|
||||
|
||||
/* Return bit type. */
|
||||
#define BRET(b) lua_pushnumber(L, (lua_Number)(SBits)(b)); return 1;
|
||||
|
||||
static int bit_tobit(lua_State *L) { BRET(barg(L, 1)) }
|
||||
static int bit_bnot(lua_State *L) { BRET(~barg(L, 1)) }
|
||||
|
||||
#define BIT_OP(func, opr) \
|
||||
static int func(lua_State *L) { int i; UBits b = barg(L, 1); \
|
||||
for (i = lua_gettop(L); i > 1; i--) b opr barg(L, i); BRET(b) }
|
||||
BIT_OP(bit_band, &=)
|
||||
BIT_OP(bit_bor, |=)
|
||||
BIT_OP(bit_bxor, ^=)
|
||||
|
||||
#define bshl(b, n) (b << n)
|
||||
#define bshr(b, n) (b >> n)
|
||||
#define bsar(b, n) ((SBits)b >> n)
|
||||
#define brol(b, n) ((b << n) | (b >> (32-n)))
|
||||
#define bror(b, n) ((b << (32-n)) | (b >> n))
|
||||
#define BIT_SH(func, fn) \
|
||||
static int func(lua_State *L) { \
|
||||
UBits b = barg(L, 1); UBits n = barg(L, 2) & 31; BRET(fn(b, n)) }
|
||||
BIT_SH(bit_lshift, bshl)
|
||||
BIT_SH(bit_rshift, bshr)
|
||||
BIT_SH(bit_arshift, bsar)
|
||||
BIT_SH(bit_rol, brol)
|
||||
BIT_SH(bit_ror, bror)
|
||||
|
||||
static int bit_bswap(lua_State *L)
|
||||
{
|
||||
UBits b = barg(L, 1);
|
||||
b = (b >> 24) | ((b >> 8) & 0xff00) | ((b & 0xff00) << 8) | (b << 24);
|
||||
BRET(b)
|
||||
}
|
||||
|
||||
static int bit_tohex(lua_State *L)
|
||||
{
|
||||
UBits b = barg(L, 1);
|
||||
SBits n = lua_isnone(L, 2) ? 8 : (SBits)barg(L, 2);
|
||||
const char *hexdigits = "0123456789abcdef";
|
||||
char buf[8];
|
||||
int i;
|
||||
if (n < 0) { n = -n; hexdigits = "0123456789ABCDEF"; }
|
||||
if (n > 8) n = 8;
|
||||
for (i = (int)n; --i >= 0; ) { buf[i] = hexdigits[b & 15]; b >>= 4; }
|
||||
lua_pushlstring(L, buf, (size_t)n);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static const struct luaL_Reg bit_funcs[] = {
|
||||
{ "tobit", bit_tobit },
|
||||
{ "bnot", bit_bnot },
|
||||
{ "band", bit_band },
|
||||
{ "bor", bit_bor },
|
||||
{ "bxor", bit_bxor },
|
||||
{ "lshift", bit_lshift },
|
||||
{ "rshift", bit_rshift },
|
||||
{ "arshift", bit_arshift },
|
||||
{ "rol", bit_rol },
|
||||
{ "ror", bit_ror },
|
||||
{ "bswap", bit_bswap },
|
||||
{ "tohex", bit_tohex },
|
||||
{ NULL, NULL }
|
||||
};
|
||||
|
||||
/* Signed right-shifts are implementation-defined per C89/C99.
|
||||
** But the de facto standard are arithmetic right-shifts on two's
|
||||
** complement CPUs. This behaviour is required here, so test for it.
|
||||
*/
|
||||
#define BAD_SAR (bsar(-8, 2) != (SBits)-2)
|
||||
|
||||
LUALIB_API int luaopen_bit(lua_State *L)
|
||||
{
|
||||
UBits b;
|
||||
lua_pushnumber(L, (lua_Number)1437217655L);
|
||||
b = barg(L, -1);
|
||||
if (b != (UBits)1437217655L || BAD_SAR) { /* Perform a simple self-test. */
|
||||
const char *msg = "compiled with incompatible luaconf.h";
|
||||
#ifdef LUA_NUMBER_DOUBLE
|
||||
#ifdef _WIN32
|
||||
if (b == (UBits)1610612736L)
|
||||
msg = "use D3DCREATE_FPU_PRESERVE with DirectX";
|
||||
#endif
|
||||
if (b == (UBits)1127743488L)
|
||||
msg = "not compiled with SWAPPED_DOUBLE";
|
||||
#endif
|
||||
if (BAD_SAR)
|
||||
msg = "arithmetic right-shift broken";
|
||||
luaL_error(L, "bit library self-test failed (%s)", msg);
|
||||
}
|
||||
#if LUA_VERSION_NUM < 502
|
||||
luaL_register(L, "bit", bit_funcs);
|
||||
#else
|
||||
luaL_newlib(L, bit_funcs);
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
|
||||
Vendored
+310
-438
File diff suppressed because it is too large
Load Diff
Vendored
+127
-368
@@ -7,38 +7,14 @@
|
||||
#include "lua.h"
|
||||
#include "lauxlib.h"
|
||||
|
||||
#define LUACMSGPACK_NAME "cmsgpack"
|
||||
#define LUACMSGPACK_SAFE_NAME "cmsgpack_safe"
|
||||
#define LUACMSGPACK_VERSION "lua-cmsgpack 0.4.0"
|
||||
#define LUACMSGPACK_VERSION "lua-cmsgpack 0.3.0"
|
||||
#define LUACMSGPACK_COPYRIGHT "Copyright (C) 2012, Salvatore Sanfilippo"
|
||||
#define LUACMSGPACK_DESCRIPTION "MessagePack C implementation for Lua"
|
||||
|
||||
/* Allows a preprocessor directive to override MAX_NESTING */
|
||||
#ifndef LUACMSGPACK_MAX_NESTING
|
||||
#define LUACMSGPACK_MAX_NESTING 16 /* Max tables nesting. */
|
||||
#endif
|
||||
#define LUACMSGPACK_MAX_NESTING 16 /* Max tables nesting. */
|
||||
|
||||
/* Check if float or double can be an integer without loss of precision */
|
||||
#define IS_INT_TYPE_EQUIVALENT(x, T) (!isinf(x) && (T)(x) == (x))
|
||||
|
||||
#define IS_INT64_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int64_t)
|
||||
#define IS_INT_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int)
|
||||
|
||||
/* If size of pointer is equal to a 4 byte integer, we're on 32 bits. */
|
||||
#if UINTPTR_MAX == UINT_MAX
|
||||
#define BITS_32 1
|
||||
#else
|
||||
#define BITS_32 0
|
||||
#endif
|
||||
|
||||
#if BITS_32
|
||||
#define lua_pushunsigned(L, n) lua_pushnumber(L, n)
|
||||
#else
|
||||
#define lua_pushunsigned(L, n) lua_pushinteger(L, n)
|
||||
#endif
|
||||
|
||||
/* =============================================================================
|
||||
* MessagePack implementation and bindings for Lua 5.1/5.2.
|
||||
/* ==============================================================================
|
||||
* MessagePack implementation and bindings for Lua 5.1.
|
||||
* Copyright(C) 2012 Salvatore Sanfilippo <antirez@gmail.com>
|
||||
*
|
||||
* http://github.com/antirez/lua-cmsgpack
|
||||
@@ -53,27 +29,23 @@
|
||||
* 20-Feb-2012 (ver 0.2.0): Tables encoding improved.
|
||||
* 20-Feb-2012 (ver 0.2.1): Minor bug fixing.
|
||||
* 20-Feb-2012 (ver 0.3.0): Module renamed lua-cmsgpack (was lua-msgpack).
|
||||
* 04-Apr-2014 (ver 0.3.1): Lua 5.2 support and minor bug fix.
|
||||
* 07-Apr-2014 (ver 0.4.0): Multiple pack/unpack, lua allocator, efficiency.
|
||||
* ========================================================================== */
|
||||
* ============================================================================ */
|
||||
|
||||
/* -------------------------- Endian conversion --------------------------------
|
||||
* We use it only for floats and doubles, all the other conversions performed
|
||||
/* --------------------------- Endian conversion --------------------------------
|
||||
* We use it only for floats and doubles, all the other conversions are performed
|
||||
* in an endian independent fashion. So the only thing we need is a function
|
||||
* that swaps a binary string if arch is little endian (and left it untouched
|
||||
* that swaps a binary string if the arch is little endian (and left it untouched
|
||||
* otherwise). */
|
||||
|
||||
/* Reverse memory bytes if arch is little endian. Given the conceptual
|
||||
* simplicity of the Lua build system we prefer check for endianess at runtime.
|
||||
* simplicity of the Lua build system we prefer to check for endianess at runtime.
|
||||
* The performance difference should be acceptable. */
|
||||
void memrevifle(void *ptr, size_t len) {
|
||||
unsigned char *p = (unsigned char *)ptr,
|
||||
*e = (unsigned char *)p+len-1,
|
||||
aux;
|
||||
static void memrevifle(void *ptr, size_t len) {
|
||||
unsigned char *p = ptr, *e = p+len-1, aux;
|
||||
int test = 1;
|
||||
unsigned char *testp = (unsigned char*) &test;
|
||||
|
||||
if (testp[0] == 0) return; /* Big endian, nothing to do. */
|
||||
if (testp[0] == 0) return; /* Big endian, nothign to do. */
|
||||
len /= 2;
|
||||
while(len--) {
|
||||
aux = *p;
|
||||
@@ -84,34 +56,20 @@ void memrevifle(void *ptr, size_t len) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------- String buffer ----------------------------------
|
||||
* This is a simple implementation of string buffers. The only operation
|
||||
/* ----------------------------- String buffer ----------------------------------
|
||||
* This is a simple implementation of string buffers. The only opereation
|
||||
* supported is creating empty buffers and appending bytes to it.
|
||||
* The string buffer uses 2x preallocation on every realloc for O(N) append
|
||||
* behavior. */
|
||||
|
||||
typedef struct mp_buf {
|
||||
lua_State *L;
|
||||
unsigned char *b;
|
||||
size_t len, free;
|
||||
} mp_buf;
|
||||
|
||||
void *mp_realloc(lua_State *L, void *target, size_t osize,size_t nsize) {
|
||||
void *(*local_realloc) (void *, void *, size_t osize, size_t nsize) = NULL;
|
||||
void *ud;
|
||||
|
||||
local_realloc = lua_getallocf(L, &ud);
|
||||
|
||||
return local_realloc(ud, target, osize, nsize);
|
||||
}
|
||||
|
||||
mp_buf *mp_buf_new(lua_State *L) {
|
||||
mp_buf *buf = NULL;
|
||||
|
||||
/* Old size = 0; new size = sizeof(*buf) */
|
||||
buf = (mp_buf*)mp_realloc(L, NULL, 0, sizeof(*buf));
|
||||
|
||||
buf->L = L;
|
||||
static mp_buf *mp_buf_new(void) {
|
||||
mp_buf *buf = malloc(sizeof(*buf));
|
||||
|
||||
buf->b = NULL;
|
||||
buf->len = buf->free = 0;
|
||||
return buf;
|
||||
@@ -121,7 +79,7 @@ void mp_buf_append(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
if (buf->free < len) {
|
||||
size_t newlen = buf->len+len;
|
||||
|
||||
buf->b = (unsigned char*)mp_realloc(buf->L, buf->b, buf->len, newlen*2);
|
||||
buf->b = realloc(buf->b,newlen*2);
|
||||
buf->free = newlen;
|
||||
}
|
||||
memcpy(buf->b+buf->len,s,len);
|
||||
@@ -130,11 +88,11 @@ void mp_buf_append(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
}
|
||||
|
||||
void mp_buf_free(mp_buf *buf) {
|
||||
mp_realloc(buf->L, buf->b, buf->len, 0); /* realloc to 0 = free */
|
||||
mp_realloc(buf->L, buf, sizeof(*buf), 0);
|
||||
free(buf->b);
|
||||
free(buf);
|
||||
}
|
||||
|
||||
/* ---------------------------- String cursor ----------------------------------
|
||||
/* ------------------------------ String cursor ----------------------------------
|
||||
* This simple data structure is used for parsing. Basically you create a cursor
|
||||
* using a string pointer and a length, then it is possible to access the
|
||||
* current string position with cursor->p, check the remaining length
|
||||
@@ -144,7 +102,7 @@ void mp_buf_free(mp_buf *buf) {
|
||||
* be used to report errors. */
|
||||
|
||||
#define MP_CUR_ERROR_NONE 0
|
||||
#define MP_CUR_ERROR_EOF 1 /* Not enough data to complete operation. */
|
||||
#define MP_CUR_ERROR_EOF 1 /* Not enough data to complete the opereation. */
|
||||
#define MP_CUR_ERROR_BADFMT 2 /* Bad data format */
|
||||
|
||||
typedef struct mp_cur {
|
||||
@@ -153,15 +111,22 @@ typedef struct mp_cur {
|
||||
int err;
|
||||
} mp_cur;
|
||||
|
||||
void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
|
||||
static mp_cur *mp_cur_new(const unsigned char *s, size_t len) {
|
||||
mp_cur *cursor = malloc(sizeof(*cursor));
|
||||
|
||||
cursor->p = s;
|
||||
cursor->left = len;
|
||||
cursor->err = MP_CUR_ERROR_NONE;
|
||||
return cursor;
|
||||
}
|
||||
|
||||
static void mp_cur_free(mp_cur *cursor) {
|
||||
free(cursor);
|
||||
}
|
||||
|
||||
#define mp_cur_consume(_c,_len) do { _c->p += _len; _c->left -= _len; } while(0)
|
||||
|
||||
/* When there is not enough room we set an error in the cursor and return. This
|
||||
/* When there is not enough room we set an error in the cursor and return, this
|
||||
* is very common across the code so we have a macro to make the code look
|
||||
* a bit simpler. */
|
||||
#define mp_cur_need(_c,_len) do { \
|
||||
@@ -171,19 +136,15 @@ void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
|
||||
} \
|
||||
} while(0)
|
||||
|
||||
/* ------------------------- Low level MP encoding -------------------------- */
|
||||
/* --------------------------- Low level MP encoding -------------------------- */
|
||||
|
||||
void mp_encode_bytes(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
static void mp_encode_bytes(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
unsigned char hdr[5];
|
||||
int hdrlen;
|
||||
|
||||
if (len < 32) {
|
||||
hdr[0] = 0xa0 | (len&0xff); /* fix raw */
|
||||
hdrlen = 1;
|
||||
} else if (len <= 0xff) {
|
||||
hdr[0] = 0xd9;
|
||||
hdr[1] = len;
|
||||
hdrlen = 2;
|
||||
} else if (len <= 0xffff) {
|
||||
hdr[0] = 0xda;
|
||||
hdr[1] = (len&0xff00)>>8;
|
||||
@@ -202,7 +163,7 @@ void mp_encode_bytes(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
}
|
||||
|
||||
/* we assume IEEE 754 internal format for single and double precision floats. */
|
||||
void mp_encode_double(mp_buf *buf, double d) {
|
||||
static void mp_encode_double(mp_buf *buf, double d) {
|
||||
unsigned char b[9];
|
||||
float f = d;
|
||||
|
||||
@@ -220,7 +181,7 @@ void mp_encode_double(mp_buf *buf, double d) {
|
||||
}
|
||||
}
|
||||
|
||||
void mp_encode_int(mp_buf *buf, int64_t n) {
|
||||
static void mp_encode_int(mp_buf *buf, int64_t n) {
|
||||
unsigned char b[9];
|
||||
int enclen;
|
||||
|
||||
@@ -258,7 +219,7 @@ void mp_encode_int(mp_buf *buf, int64_t n) {
|
||||
}
|
||||
} else {
|
||||
if (n >= -32) {
|
||||
b[0] = ((signed char)n); /* negative fixnum */
|
||||
b[0] = ((char)n); /* negative fixnum */
|
||||
enclen = 1;
|
||||
} else if (n >= -128) {
|
||||
b[0] = 0xd0; /* int 8 */
|
||||
@@ -292,7 +253,7 @@ void mp_encode_int(mp_buf *buf, int64_t n) {
|
||||
mp_buf_append(buf,b,enclen);
|
||||
}
|
||||
|
||||
void mp_encode_array(mp_buf *buf, int64_t n) {
|
||||
static void mp_encode_array(mp_buf *buf, int64_t n) {
|
||||
unsigned char b[5];
|
||||
int enclen;
|
||||
|
||||
@@ -315,7 +276,7 @@ void mp_encode_array(mp_buf *buf, int64_t n) {
|
||||
mp_buf_append(buf,b,enclen);
|
||||
}
|
||||
|
||||
void mp_encode_map(mp_buf *buf, int64_t n) {
|
||||
static void mp_encode_map(mp_buf *buf, int64_t n) {
|
||||
unsigned char b[5];
|
||||
int enclen;
|
||||
|
||||
@@ -338,9 +299,9 @@ void mp_encode_map(mp_buf *buf, int64_t n) {
|
||||
mp_buf_append(buf,b,enclen);
|
||||
}
|
||||
|
||||
/* --------------------------- Lua types encoding --------------------------- */
|
||||
/* ----------------------------- Lua types encoding --------------------------- */
|
||||
|
||||
void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
|
||||
static void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
|
||||
size_t len;
|
||||
const char *s;
|
||||
|
||||
@@ -348,43 +309,26 @@ void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
|
||||
mp_encode_bytes(buf,(const unsigned char*)s,len);
|
||||
}
|
||||
|
||||
void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
|
||||
static void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
|
||||
unsigned char b = lua_toboolean(L,-1) ? 0xc3 : 0xc2;
|
||||
mp_buf_append(buf,&b,1);
|
||||
}
|
||||
|
||||
/* Lua 5.3 has a built in 64-bit integer type */
|
||||
void mp_encode_lua_integer(lua_State *L, mp_buf *buf) {
|
||||
#if (LUA_VERSION_NUM < 503) && BITS_32
|
||||
lua_Number i = lua_tonumber(L,-1);
|
||||
#else
|
||||
lua_Integer i = lua_tointeger(L,-1);
|
||||
#endif
|
||||
mp_encode_int(buf, (int64_t)i);
|
||||
}
|
||||
|
||||
/* Lua 5.2 and lower only has 64-bit doubles, so we need to
|
||||
* detect if the double may be representable as an int
|
||||
* for Lua < 5.3 */
|
||||
void mp_encode_lua_number(lua_State *L, mp_buf *buf) {
|
||||
static void mp_encode_lua_number(lua_State *L, mp_buf *buf) {
|
||||
lua_Number n = lua_tonumber(L,-1);
|
||||
|
||||
if (IS_INT64_EQUIVALENT(n)) {
|
||||
mp_encode_lua_integer(L, buf);
|
||||
} else {
|
||||
if (floor(n) != n) {
|
||||
mp_encode_double(buf,(double)n);
|
||||
} else {
|
||||
mp_encode_int(buf,(int64_t)n);
|
||||
}
|
||||
}
|
||||
|
||||
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
|
||||
static void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
|
||||
|
||||
/* Convert a lua table into a message pack list. */
|
||||
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
|
||||
#if LUA_VERSION_NUM < 502
|
||||
static void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
|
||||
size_t len = lua_objlen(L,-1), j;
|
||||
#else
|
||||
size_t len = lua_rawlen(L,-1), j;
|
||||
#endif
|
||||
|
||||
mp_encode_array(buf,len);
|
||||
for (j = 1; j <= len; j++) {
|
||||
@@ -395,13 +339,13 @@ void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
|
||||
}
|
||||
|
||||
/* Convert a lua table into a message pack key-value map. */
|
||||
void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
|
||||
static void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
|
||||
size_t len = 0;
|
||||
|
||||
/* First step: count keys into table. No other way to do it with the
|
||||
* Lua API, we need to iterate a first time. Note that an alternative
|
||||
* would be to do a single run, and then hack the buffer to insert the
|
||||
* map opcodes for message pack. Too hackish for this lib. */
|
||||
* map opcodes for message pack. Too hachish for this lib. */
|
||||
lua_pushnil(L);
|
||||
while(lua_next(L,-2)) {
|
||||
lua_pop(L,1); /* remove value, keep key for next iteration. */
|
||||
@@ -422,131 +366,80 @@ void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
|
||||
/* Returns true if the Lua table on top of the stack is exclusively composed
|
||||
* of keys from numerical keys from 1 up to N, with N being the total number
|
||||
* of elements, without any hole in the middle. */
|
||||
int table_is_an_array(lua_State *L) {
|
||||
int count = 0, max = 0;
|
||||
#if LUA_VERSION_NUM < 503
|
||||
static int table_is_an_array(lua_State *L) {
|
||||
long count = 0, max = 0, idx = 0;
|
||||
lua_Number n;
|
||||
#else
|
||||
lua_Integer n;
|
||||
#endif
|
||||
|
||||
/* Stack top on function entry */
|
||||
int stacktop;
|
||||
|
||||
stacktop = lua_gettop(L);
|
||||
|
||||
lua_pushnil(L);
|
||||
while(lua_next(L,-2)) {
|
||||
/* Stack: ... key value */
|
||||
lua_pop(L,1); /* Stack: ... key */
|
||||
/* The <= 0 check is valid here because we're comparing indexes. */
|
||||
#if LUA_VERSION_NUM < 503
|
||||
if ((LUA_TNUMBER != lua_type(L,-1)) || (n = lua_tonumber(L, -1)) <= 0 ||
|
||||
!IS_INT_EQUIVALENT(n))
|
||||
#else
|
||||
if (!lua_isinteger(L,-1) || (n = lua_tointeger(L, -1)) <= 0)
|
||||
#endif
|
||||
{
|
||||
lua_settop(L, stacktop);
|
||||
return 0;
|
||||
}
|
||||
max = (n > max ? n : max);
|
||||
if (lua_type(L,-1) != LUA_TNUMBER) goto not_array;
|
||||
n = lua_tonumber(L,-1);
|
||||
idx = n;
|
||||
if (idx != n || idx < 1) goto not_array;
|
||||
count++;
|
||||
max = idx;
|
||||
}
|
||||
/* We have the total number of elements in "count". Also we have
|
||||
* the max index encountered in "max". We can't reach this code
|
||||
* the max index encountered in "idx". We can't reach this code
|
||||
* if there are indexes <= 0. If you also note that there can not be
|
||||
* repeated keys into a table, you have that if max==count you are sure
|
||||
* repeated keys into a table, you have that if idx==count you are sure
|
||||
* that there are all the keys form 1 to count (both included). */
|
||||
lua_settop(L, stacktop);
|
||||
return max == count;
|
||||
return idx == count;
|
||||
|
||||
not_array:
|
||||
lua_pop(L,1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* If the length operator returns non-zero, that is, there is at least
|
||||
* an object at key '1', we serialize to message pack list. Otherwise
|
||||
* we use a map. */
|
||||
void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
|
||||
static void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
|
||||
if (table_is_an_array(L))
|
||||
mp_encode_lua_table_as_array(L,buf,level);
|
||||
else
|
||||
mp_encode_lua_table_as_map(L,buf,level);
|
||||
}
|
||||
|
||||
void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
|
||||
static void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
|
||||
unsigned char b[1];
|
||||
(void)L;
|
||||
|
||||
b[0] = 0xc0;
|
||||
mp_buf_append(buf,b,1);
|
||||
}
|
||||
|
||||
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level) {
|
||||
static void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level) {
|
||||
int t = lua_type(L,-1);
|
||||
|
||||
/* Limit the encoding of nested tables to a specified maximum depth, so that
|
||||
/* Limit the encoding of nested tables to a specfiied maximum depth, so that
|
||||
* we survive when called against circular references in tables. */
|
||||
if (t == LUA_TTABLE && level == LUACMSGPACK_MAX_NESTING) t = LUA_TNIL;
|
||||
switch(t) {
|
||||
case LUA_TSTRING: mp_encode_lua_string(L,buf); break;
|
||||
case LUA_TBOOLEAN: mp_encode_lua_bool(L,buf); break;
|
||||
case LUA_TNUMBER:
|
||||
#if LUA_VERSION_NUM < 503
|
||||
mp_encode_lua_number(L,buf); break;
|
||||
#else
|
||||
if (lua_isinteger(L, -1)) {
|
||||
mp_encode_lua_integer(L, buf);
|
||||
} else {
|
||||
mp_encode_lua_number(L, buf);
|
||||
}
|
||||
break;
|
||||
#endif
|
||||
case LUA_TNUMBER: mp_encode_lua_number(L,buf); break;
|
||||
case LUA_TTABLE: mp_encode_lua_table(L,buf,level); break;
|
||||
default: mp_encode_lua_null(L,buf); break;
|
||||
}
|
||||
lua_pop(L,1);
|
||||
}
|
||||
|
||||
/*
|
||||
* Packs all arguments as a stream for multiple upacking later.
|
||||
* Returns error if no arguments provided.
|
||||
*/
|
||||
int mp_pack(lua_State *L) {
|
||||
int nargs = lua_gettop(L);
|
||||
int i;
|
||||
mp_buf *buf;
|
||||
static int mp_pack(lua_State *L) {
|
||||
mp_buf *buf = mp_buf_new();
|
||||
|
||||
if (nargs == 0)
|
||||
return luaL_argerror(L, 0, "MessagePack pack needs input.");
|
||||
|
||||
buf = mp_buf_new(L);
|
||||
for(i = 1; i <= nargs; i++) {
|
||||
/* Copy argument i to top of stack for _encode processing;
|
||||
* the encode function pops it from the stack when complete. */
|
||||
lua_pushvalue(L, i);
|
||||
|
||||
mp_encode_lua_type(L,buf,0);
|
||||
|
||||
lua_pushlstring(L,(char*)buf->b,buf->len);
|
||||
|
||||
/* Reuse the buffer for the next operation by
|
||||
* setting its free count to the total buffer size
|
||||
* and the current position to zero. */
|
||||
buf->free += buf->len;
|
||||
buf->len = 0;
|
||||
}
|
||||
mp_encode_lua_type(L,buf,0);
|
||||
lua_pushlstring(L,(char*)buf->b,buf->len);
|
||||
mp_buf_free(buf);
|
||||
|
||||
/* Concatenate all nargs buffers together */
|
||||
lua_concat(L, nargs);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------- Decoding --------------------------------- */
|
||||
/* --------------------------------- Decoding --------------------------------- */
|
||||
|
||||
void mp_decode_to_lua_type(lua_State *L, mp_cur *c);
|
||||
|
||||
void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
|
||||
assert(len <= UINT_MAX);
|
||||
int index = 1;
|
||||
|
||||
lua_newtable(L);
|
||||
@@ -559,7 +452,6 @@ void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
|
||||
}
|
||||
|
||||
void mp_decode_to_lua_hash(lua_State *L, mp_cur *c, size_t len) {
|
||||
assert(len <= UINT_MAX);
|
||||
lua_newtable(L);
|
||||
while(len--) {
|
||||
mp_decode_to_lua_type(L,c); /* key */
|
||||
@@ -574,44 +466,34 @@ void mp_decode_to_lua_hash(lua_State *L, mp_cur *c, size_t len) {
|
||||
* a Lua type, that is left as the only result on the stack. */
|
||||
void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
mp_cur_need(c,1);
|
||||
|
||||
/* If we return more than 18 elements, we must resize the stack to
|
||||
* fit all our return values. But, there is no way to
|
||||
* determine how many objects a msgpack will unpack to up front, so
|
||||
* we request a +1 larger stack on each iteration (noop if stack is
|
||||
* big enough, and when stack does require resize it doubles in size) */
|
||||
luaL_checkstack(L, 1,
|
||||
"too many return values at once; "
|
||||
"use unpack_one or unpack_limit instead.");
|
||||
|
||||
switch(c->p[0]) {
|
||||
case 0xcc: /* uint 8 */
|
||||
mp_cur_need(c,2);
|
||||
lua_pushunsigned(L,c->p[1]);
|
||||
lua_pushnumber(L,c->p[1]);
|
||||
mp_cur_consume(c,2);
|
||||
break;
|
||||
case 0xd0: /* int 8 */
|
||||
mp_cur_need(c,2);
|
||||
lua_pushinteger(L,(signed char)c->p[1]);
|
||||
lua_pushnumber(L,(char)c->p[1]);
|
||||
mp_cur_consume(c,2);
|
||||
break;
|
||||
case 0xcd: /* uint 16 */
|
||||
mp_cur_need(c,3);
|
||||
lua_pushunsigned(L,
|
||||
lua_pushnumber(L,
|
||||
(c->p[1] << 8) |
|
||||
c->p[2]);
|
||||
mp_cur_consume(c,3);
|
||||
break;
|
||||
case 0xd1: /* int 16 */
|
||||
mp_cur_need(c,3);
|
||||
lua_pushinteger(L,(int16_t)
|
||||
lua_pushnumber(L,(int16_t)
|
||||
(c->p[1] << 8) |
|
||||
c->p[2]);
|
||||
mp_cur_consume(c,3);
|
||||
break;
|
||||
case 0xce: /* uint 32 */
|
||||
mp_cur_need(c,5);
|
||||
lua_pushunsigned(L,
|
||||
lua_pushnumber(L,
|
||||
((uint32_t)c->p[1] << 24) |
|
||||
((uint32_t)c->p[2] << 16) |
|
||||
((uint32_t)c->p[3] << 8) |
|
||||
@@ -620,7 +502,7 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
break;
|
||||
case 0xd2: /* int 32 */
|
||||
mp_cur_need(c,5);
|
||||
lua_pushinteger(L,
|
||||
lua_pushnumber(L,
|
||||
((int32_t)c->p[1] << 24) |
|
||||
((int32_t)c->p[2] << 16) |
|
||||
((int32_t)c->p[3] << 8) |
|
||||
@@ -629,7 +511,7 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
break;
|
||||
case 0xcf: /* uint 64 */
|
||||
mp_cur_need(c,9);
|
||||
lua_pushunsigned(L,
|
||||
lua_pushnumber(L,
|
||||
((uint64_t)c->p[1] << 56) |
|
||||
((uint64_t)c->p[2] << 48) |
|
||||
((uint64_t)c->p[3] << 40) |
|
||||
@@ -642,11 +524,7 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
break;
|
||||
case 0xd3: /* int 64 */
|
||||
mp_cur_need(c,9);
|
||||
#if LUA_VERSION_NUM < 503
|
||||
lua_pushnumber(L,
|
||||
#else
|
||||
lua_pushinteger(L,
|
||||
#endif
|
||||
((int64_t)c->p[1] << 56) |
|
||||
((int64_t)c->p[2] << 48) |
|
||||
((int64_t)c->p[3] << 40) |
|
||||
@@ -691,15 +569,6 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
mp_cur_consume(c,9);
|
||||
}
|
||||
break;
|
||||
case 0xd9: /* raw 8 */
|
||||
mp_cur_need(c,2);
|
||||
{
|
||||
size_t l = c->p[1];
|
||||
mp_cur_need(c,2+l);
|
||||
lua_pushlstring(L,(char*)c->p+2,l);
|
||||
mp_cur_consume(c,2+l);
|
||||
}
|
||||
break;
|
||||
case 0xda: /* raw 16 */
|
||||
mp_cur_need(c,3);
|
||||
{
|
||||
@@ -712,14 +581,13 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
case 0xdb: /* raw 32 */
|
||||
mp_cur_need(c,5);
|
||||
{
|
||||
size_t l = ((size_t)c->p[1] << 24) |
|
||||
((size_t)c->p[2] << 16) |
|
||||
((size_t)c->p[3] << 8) |
|
||||
(size_t)c->p[4];
|
||||
mp_cur_consume(c,5);
|
||||
mp_cur_need(c,l);
|
||||
lua_pushlstring(L,(char*)c->p,l);
|
||||
mp_cur_consume(c,l);
|
||||
size_t l = (c->p[1] << 24) |
|
||||
(c->p[2] << 16) |
|
||||
(c->p[3] << 8) |
|
||||
c->p[4];
|
||||
mp_cur_need(c,5+l);
|
||||
lua_pushlstring(L,(char*)c->p+5,l);
|
||||
mp_cur_consume(c,5+l);
|
||||
}
|
||||
break;
|
||||
case 0xdc: /* array 16 */
|
||||
@@ -733,10 +601,10 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
case 0xdd: /* array 32 */
|
||||
mp_cur_need(c,5);
|
||||
{
|
||||
size_t l = ((size_t)c->p[1] << 24) |
|
||||
((size_t)c->p[2] << 16) |
|
||||
((size_t)c->p[3] << 8) |
|
||||
(size_t)c->p[4];
|
||||
size_t l = (c->p[1] << 24) |
|
||||
(c->p[2] << 16) |
|
||||
(c->p[3] << 8) |
|
||||
c->p[4];
|
||||
mp_cur_consume(c,5);
|
||||
mp_decode_to_lua_array(L,c,l);
|
||||
}
|
||||
@@ -752,20 +620,20 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
case 0xdf: /* map 32 */
|
||||
mp_cur_need(c,5);
|
||||
{
|
||||
size_t l = ((size_t)c->p[1] << 24) |
|
||||
((size_t)c->p[2] << 16) |
|
||||
((size_t)c->p[3] << 8) |
|
||||
(size_t)c->p[4];
|
||||
size_t l = (c->p[1] << 24) |
|
||||
(c->p[2] << 16) |
|
||||
(c->p[3] << 8) |
|
||||
c->p[4];
|
||||
mp_cur_consume(c,5);
|
||||
mp_decode_to_lua_hash(L,c,l);
|
||||
}
|
||||
break;
|
||||
default: /* types that can't be idenitified by first byte value. */
|
||||
if ((c->p[0] & 0x80) == 0) { /* positive fixnum */
|
||||
lua_pushunsigned(L,c->p[0]);
|
||||
lua_pushnumber(L,c->p[0]);
|
||||
mp_cur_consume(c,1);
|
||||
} else if ((c->p[0] & 0xe0) == 0xe0) { /* negative fixnum */
|
||||
lua_pushinteger(L,(signed char)c->p[0]);
|
||||
lua_pushnumber(L,(signed char)c->p[0]);
|
||||
mp_cur_consume(c,1);
|
||||
} else if ((c->p[0] & 0xe0) == 0xa0) { /* fix raw */
|
||||
size_t l = c->p[0] & 0x1f;
|
||||
@@ -786,163 +654,54 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
}
|
||||
}
|
||||
|
||||
int mp_unpack_full(lua_State *L, int limit, int offset) {
|
||||
static int mp_unpack(lua_State *L) {
|
||||
size_t len;
|
||||
const char *s;
|
||||
mp_cur c;
|
||||
int cnt; /* Number of objects unpacked */
|
||||
int decode_all = (!limit && !offset);
|
||||
const unsigned char *s;
|
||||
mp_cur *c;
|
||||
|
||||
s = luaL_checklstring(L,1,&len); /* if no match, exits */
|
||||
|
||||
if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */
|
||||
return luaL_error(L,
|
||||
"Invalid request to unpack with offset of %d and limit of %d.",
|
||||
offset, len);
|
||||
else if (offset > len)
|
||||
return luaL_error(L,
|
||||
"Start offset %d greater than input length %d.", offset, len);
|
||||
|
||||
if (decode_all) limit = INT_MAX;
|
||||
|
||||
mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);
|
||||
|
||||
/* We loop over the decode because this could be a stream
|
||||
* of multiple top-level values serialized together */
|
||||
for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {
|
||||
mp_decode_to_lua_type(L,&c);
|
||||
|
||||
if (c.err == MP_CUR_ERROR_EOF) {
|
||||
return luaL_error(L,"Missing bytes in input.");
|
||||
} else if (c.err == MP_CUR_ERROR_BADFMT) {
|
||||
return luaL_error(L,"Bad data format in input.");
|
||||
}
|
||||
if (!lua_isstring(L,-1)) {
|
||||
lua_pushstring(L,"MessagePack decoding needs a string as input.");
|
||||
lua_error(L);
|
||||
}
|
||||
|
||||
if (!decode_all) {
|
||||
/* c->left is the remaining size of the input buffer.
|
||||
* subtract the entire buffer size from the unprocessed size
|
||||
* to get our next start offset */
|
||||
int offset = len - c.left;
|
||||
/* Return offset -1 when we have have processed the entire buffer. */
|
||||
lua_pushinteger(L, c.left == 0 ? -1 : offset);
|
||||
/* Results are returned with the arg elements still
|
||||
* in place. Lua takes care of only returning
|
||||
* elements above the args for us.
|
||||
* In this case, we have one arg on the stack
|
||||
* for this function, so we insert our first return
|
||||
* value at position 2. */
|
||||
lua_insert(L, 2);
|
||||
cnt += 1; /* increase return count by one to make room for offset */
|
||||
s = (const unsigned char*) lua_tolstring(L,-1,&len);
|
||||
c = mp_cur_new(s,len);
|
||||
mp_decode_to_lua_type(L,c);
|
||||
|
||||
if (c->err == MP_CUR_ERROR_EOF) {
|
||||
mp_cur_free(c);
|
||||
lua_pushstring(L,"Missing bytes in input.");
|
||||
lua_error(L);
|
||||
} else if (c->err == MP_CUR_ERROR_BADFMT) {
|
||||
mp_cur_free(c);
|
||||
lua_pushstring(L,"Bad data format in input.");
|
||||
lua_error(L);
|
||||
} else if (c->left != 0) {
|
||||
mp_cur_free(c);
|
||||
lua_pushstring(L,"Extra bytes in input.");
|
||||
lua_error(L);
|
||||
}
|
||||
|
||||
return cnt;
|
||||
mp_cur_free(c);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int mp_unpack(lua_State *L) {
|
||||
return mp_unpack_full(L, 0, 0);
|
||||
}
|
||||
/* ---------------------------------------------------------------------------- */
|
||||
|
||||
int mp_unpack_one(lua_State *L) {
|
||||
int offset = luaL_optinteger(L, 2, 0);
|
||||
/* Variable pop because offset may not exist */
|
||||
lua_pop(L, lua_gettop(L)-1);
|
||||
return mp_unpack_full(L, 1, offset);
|
||||
}
|
||||
|
||||
int mp_unpack_limit(lua_State *L) {
|
||||
int limit = luaL_checkinteger(L, 2);
|
||||
int offset = luaL_optinteger(L, 3, 0);
|
||||
/* Variable pop because offset may not exist */
|
||||
lua_pop(L, lua_gettop(L)-1);
|
||||
|
||||
return mp_unpack_full(L, limit, offset);
|
||||
}
|
||||
|
||||
int mp_safe(lua_State *L) {
|
||||
int argc, err, total_results;
|
||||
|
||||
argc = lua_gettop(L);
|
||||
|
||||
/* This adds our function to the bottom of the stack
|
||||
* (the "call this function" position) */
|
||||
lua_pushvalue(L, lua_upvalueindex(1));
|
||||
lua_insert(L, 1);
|
||||
|
||||
err = lua_pcall(L, argc, LUA_MULTRET, 0);
|
||||
total_results = lua_gettop(L);
|
||||
|
||||
if (!err) {
|
||||
return total_results;
|
||||
} else {
|
||||
lua_pushnil(L);
|
||||
lua_insert(L,-2);
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
const struct luaL_Reg cmds[] = {
|
||||
static const struct luaL_reg thislib[] = {
|
||||
{"pack", mp_pack},
|
||||
{"unpack", mp_unpack},
|
||||
{"unpack_one", mp_unpack_one},
|
||||
{"unpack_limit", mp_unpack_limit},
|
||||
{0}
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
int luaopen_create(lua_State *L) {
|
||||
int i;
|
||||
/* Manually construct our module table instead of
|
||||
* relying on _register or _newlib */
|
||||
lua_newtable(L);
|
||||
LUALIB_API int luaopen_cmsgpack (lua_State *L) {
|
||||
luaL_register(L, "cmsgpack", thislib);
|
||||
|
||||
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
|
||||
lua_pushcfunction(L, cmds[i].func);
|
||||
lua_setfield(L, -2, cmds[i].name);
|
||||
}
|
||||
|
||||
/* Add metadata */
|
||||
lua_pushliteral(L, LUACMSGPACK_NAME);
|
||||
lua_setfield(L, -2, "_NAME");
|
||||
lua_pushliteral(L, LUACMSGPACK_VERSION);
|
||||
lua_setfield(L, -2, "_VERSION");
|
||||
lua_pushliteral(L, LUACMSGPACK_COPYRIGHT);
|
||||
lua_setfield(L, -2, "_COPYRIGHT");
|
||||
lua_pushliteral(L, LUACMSGPACK_DESCRIPTION);
|
||||
lua_setfield(L, -2, "_DESCRIPTION");
|
||||
return 1;
|
||||
}
|
||||
|
||||
LUALIB_API int luaopen_cmsgpack(lua_State *L) {
|
||||
luaopen_create(L);
|
||||
|
||||
#if LUA_VERSION_NUM < 502
|
||||
/* Register name globally for 5.1 */
|
||||
lua_pushvalue(L, -1);
|
||||
lua_setglobal(L, LUACMSGPACK_NAME);
|
||||
#endif
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
LUALIB_API int luaopen_cmsgpack_safe(lua_State *L) {
|
||||
int i;
|
||||
|
||||
luaopen_cmsgpack(L);
|
||||
|
||||
/* Wrap all functions in the safe handler */
|
||||
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
|
||||
lua_getfield(L, -1, cmds[i].name);
|
||||
lua_pushcclosure(L, mp_safe, 1);
|
||||
lua_setfield(L, -2, cmds[i].name);
|
||||
}
|
||||
|
||||
#if LUA_VERSION_NUM < 502
|
||||
/* Register name globally for 5.1 */
|
||||
lua_pushvalue(L, -1);
|
||||
lua_setglobal(L, LUACMSGPACK_SAFE_NAME);
|
||||
#endif
|
||||
|
||||
lua_setfield(L, -2, "_DESCRIPTION");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+3
-3
@@ -1,6 +1,6 @@
|
||||
/* strbuf - String buffer routines
|
||||
/* strbuf - string buffer routines
|
||||
*
|
||||
* Copyright (c) 2010-2012 Mark Pulford <mark@kyne.com.au>
|
||||
* Copyright (c) 2010-2011 Mark Pulford <mark@kyne.com.au>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
@@ -29,7 +29,7 @@
|
||||
|
||||
#include "strbuf.h"
|
||||
|
||||
static void die(const char *fmt, ...)
|
||||
void die(const char *fmt, ...)
|
||||
{
|
||||
va_list arg;
|
||||
|
||||
|
||||
Vendored
+2
-14
@@ -1,6 +1,6 @@
|
||||
/* strbuf - String buffer routines
|
||||
*
|
||||
* Copyright (c) 2010-2012 Mark Pulford <mark@kyne.com.au>
|
||||
* Copyright (c) 2010-2011 Mark Pulford <mark@kyne.com.au>
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
@@ -62,9 +62,7 @@ extern void strbuf_resize(strbuf_t *s, int len);
|
||||
static int strbuf_empty_length(strbuf_t *s);
|
||||
static int strbuf_length(strbuf_t *s);
|
||||
static char *strbuf_string(strbuf_t *s, int *len);
|
||||
static void strbuf_ensure_empty_length(strbuf_t *s, int len);
|
||||
static char *strbuf_empty_ptr(strbuf_t *s);
|
||||
static void strbuf_extend_length(strbuf_t *s, int len);
|
||||
static void strbuf_ensure_empty_length(strbuf_t *s, int len);
|
||||
|
||||
/* Update */
|
||||
extern void strbuf_append_fmt(strbuf_t *s, int len, const char *fmt, ...);
|
||||
@@ -98,16 +96,6 @@ static inline void strbuf_ensure_empty_length(strbuf_t *s, int len)
|
||||
strbuf_resize(s, s->length + len);
|
||||
}
|
||||
|
||||
static inline char *strbuf_empty_ptr(strbuf_t *s)
|
||||
{
|
||||
return s->buf + s->length;
|
||||
}
|
||||
|
||||
static inline void strbuf_extend_length(strbuf_t *s, int len)
|
||||
{
|
||||
s->length += len;
|
||||
}
|
||||
|
||||
static inline int strbuf_length(strbuf_t *s)
|
||||
{
|
||||
return s->length;
|
||||
|
||||
+40
-139
@@ -1,9 +1,4 @@
|
||||
# Redis configuration file example.
|
||||
#
|
||||
# Note that in order to read the configuration file, Redis must be
|
||||
# started with the file path as first argument:
|
||||
#
|
||||
# ./redis-server /path/to/redis.conf
|
||||
# Redis configuration file example
|
||||
|
||||
# Note on units: when memory size is needed, it is possible to specify
|
||||
# it in the usual form of 1k 5GB 4M and so forth:
|
||||
@@ -20,7 +15,7 @@
|
||||
################################## INCLUDES ###################################
|
||||
|
||||
# Include one or more other config files here. This is useful if you
|
||||
# have a standard template that goes to all Redis servers but also need
|
||||
# have a standard template that goes to all Redis server but also need
|
||||
# to customize a few per-server settings. Include files can include
|
||||
# other files, so use this wisely.
|
||||
#
|
||||
@@ -73,7 +68,7 @@ tcp-backlog 511
|
||||
# on a unix socket when not specified.
|
||||
#
|
||||
# unixsocket /tmp/redis.sock
|
||||
# unixsocketperm 700
|
||||
# unixsocketperm 755
|
||||
|
||||
# Close the connection after a client is idle for N seconds (0 to disable)
|
||||
timeout 0
|
||||
@@ -136,7 +131,7 @@ databases 16
|
||||
# after 300 sec (5 min) if at least 10 keys changed
|
||||
# after 60 sec if at least 10000 keys changed
|
||||
#
|
||||
# Note: you can disable saving completely by commenting out all "save" lines.
|
||||
# Note: you can disable saving at all commenting all the "save" lines.
|
||||
#
|
||||
# It is also possible to remove all the previously configured save
|
||||
# points by adding a save directive with a single empty string argument
|
||||
@@ -185,27 +180,18 @@ dbfilename dump.rdb
|
||||
#
|
||||
# The DB will be written inside this directory, with the filename specified
|
||||
# above using the 'dbfilename' configuration directive.
|
||||
#
|
||||
#
|
||||
# The Append Only File will also be created inside this directory.
|
||||
#
|
||||
#
|
||||
# Note that you must specify a directory here, not a file name.
|
||||
dir ./
|
||||
|
||||
################################# REPLICATION #################################
|
||||
|
||||
# Master-Slave replication. Use slaveof to make a Redis instance a copy of
|
||||
# another Redis server. A few things to understand ASAP about Redis replication.
|
||||
#
|
||||
# 1) Redis replication is asynchronous, but you can configure a master to
|
||||
# stop accepting writes if it appears to be not connected with at least
|
||||
# a given number of slaves.
|
||||
# 2) Redis slaves are able to perform a partial resynchronization with the
|
||||
# master if the replication link is lost for a relatively small amount of
|
||||
# time. You may want to configure the replication backlog size (see the next
|
||||
# sections of this file) with a sensible value depending on your needs.
|
||||
# 3) Replication is automatic and does not need user intervention. After a
|
||||
# network partition slaves automatically try to reconnect to masters
|
||||
# and resynchronize with them.
|
||||
# another Redis server. Note that the configuration is local to the slave
|
||||
# so for example it is possible to configure the slave to save the DB with a
|
||||
# different interval, or to listen to another port, and so on.
|
||||
#
|
||||
# slaveof <masterip> <masterport>
|
||||
|
||||
@@ -245,49 +231,6 @@ slave-serve-stale-data yes
|
||||
# administrative / dangerous commands.
|
||||
slave-read-only yes
|
||||
|
||||
# Replication SYNC strategy: disk or socket.
|
||||
#
|
||||
# -------------------------------------------------------
|
||||
# WARNING: DISKLESS REPLICATION IS EXPERIMENTAL CURRENTLY
|
||||
# -------------------------------------------------------
|
||||
#
|
||||
# New slaves and reconnecting slaves that are not able to continue the replication
|
||||
# process just receiving differences, need to do what is called a "full
|
||||
# synchronization". An RDB file is transmitted from the master to the slaves.
|
||||
# The transmission can happen in two different ways:
|
||||
#
|
||||
# 1) Disk-backed: The Redis master creates a new process that writes the RDB
|
||||
# file on disk. Later the file is transferred by the parent
|
||||
# process to the slaves incrementally.
|
||||
# 2) Diskless: The Redis master creates a new process that directly writes the
|
||||
# RDB file to slave sockets, without touching the disk at all.
|
||||
#
|
||||
# With disk-backed replication, while the RDB file is generated, more slaves
|
||||
# can be queued and served with the RDB file as soon as the current child producing
|
||||
# the RDB file finishes its work. With diskless replication instead once
|
||||
# the transfer starts, new slaves arriving will be queued and a new transfer
|
||||
# will start when the current one terminates.
|
||||
#
|
||||
# When diskless replication is used, the master waits a configurable amount of
|
||||
# time (in seconds) before starting the transfer in the hope that multiple slaves
|
||||
# will arrive and the transfer can be parallelized.
|
||||
#
|
||||
# With slow disks and fast (large bandwidth) networks, diskless replication
|
||||
# works better.
|
||||
repl-diskless-sync no
|
||||
|
||||
# When diskless replication is enabled, it is possible to configure the delay
|
||||
# the server waits in order to spawn the child that transfers the RDB via socket
|
||||
# to the slaves.
|
||||
#
|
||||
# This is important since once the transfer starts, it is not possible to serve
|
||||
# new slaves arriving, that will be queued for the next RDB transfer, so the server
|
||||
# waits a delay in order to let more slaves arrive.
|
||||
#
|
||||
# The delay is specified in seconds, and by default is 5 seconds. To disable
|
||||
# it entirely just set it to 0 seconds and the transfer will start ASAP.
|
||||
repl-diskless-sync-delay 5
|
||||
|
||||
# Slaves send PINGs to server in a predefined interval. It's possible to change
|
||||
# this interval with the repl_ping_slave_period option. The default value is 10
|
||||
# seconds.
|
||||
@@ -327,7 +270,7 @@ repl-disable-tcp-nodelay no
|
||||
# resync is enough, just passing the portion of data the slave missed while
|
||||
# disconnected.
|
||||
#
|
||||
# The bigger the replication backlog, the longer the time the slave can be
|
||||
# The biggest the replication backlog, the longer the time the slave can be
|
||||
# disconnected and later be able to perform a partial resynchronization.
|
||||
#
|
||||
# The backlog is only allocated once there is at least a slave connected.
|
||||
@@ -366,7 +309,7 @@ slave-priority 100
|
||||
# The lag in seconds, that must be <= the specified value, is calculated from
|
||||
# the last ping received from the slave, that is usually sent every second.
|
||||
#
|
||||
# This option does not GUARANTEE that N replicas will accept the write, but
|
||||
# This option does not GUARANTEES that N replicas will accept the write, but
|
||||
# will limit the window of exposure for lost writes in case not enough slaves
|
||||
# are available, to the specified number of seconds.
|
||||
#
|
||||
@@ -388,7 +331,7 @@ slave-priority 100
|
||||
#
|
||||
# This should stay commented out for backward compatibility and because most
|
||||
# people do not need auth (e.g. they run their own servers).
|
||||
#
|
||||
#
|
||||
# Warning: since Redis is pretty fast an outside user can try up to
|
||||
# 150k passwords per second against a good box. This means that you should
|
||||
# use a very strong password otherwise it will be very easy to break.
|
||||
@@ -454,18 +397,18 @@ slave-priority 100
|
||||
|
||||
# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory
|
||||
# is reached. You can select among five behaviors:
|
||||
#
|
||||
#
|
||||
# volatile-lru -> remove the key with an expire set using an LRU algorithm
|
||||
# allkeys-lru -> remove any key according to the LRU algorithm
|
||||
# allkeys-lru -> remove any key accordingly to the LRU algorithm
|
||||
# volatile-random -> remove a random key with an expire set
|
||||
# allkeys-random -> remove a random key, any key
|
||||
# volatile-ttl -> remove the key with the nearest expire time (minor TTL)
|
||||
# noeviction -> don't expire at all, just return an error on write operations
|
||||
#
|
||||
#
|
||||
# Note: with any of the above policies, Redis will return an error on write
|
||||
# operations, when there are no suitable keys for eviction.
|
||||
# operations, when there are not suitable keys for eviction.
|
||||
#
|
||||
# At the date of writing these commands are: set setnx setex append
|
||||
# At the date of writing this commands are: set setnx setex append
|
||||
# incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
|
||||
# sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
|
||||
# zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
|
||||
@@ -513,13 +456,13 @@ appendonly no
|
||||
appendfilename "appendonly.aof"
|
||||
|
||||
# The fsync() call tells the Operating System to actually write data on disk
|
||||
# instead of waiting for more data in the output buffer. Some OS will really flush
|
||||
# instead to wait for more data in the output buffer. Some OS will really flush
|
||||
# data on disk, some other OS will just try to do it ASAP.
|
||||
#
|
||||
# Redis supports three different modes:
|
||||
#
|
||||
# no: don't fsync, just let the OS flush the data when it wants. Faster.
|
||||
# always: fsync after every write to the append only log. Slow, Safest.
|
||||
# always: fsync after every write to the append only log . Slow, Safest.
|
||||
# everysec: fsync only one time every second. Compromise.
|
||||
#
|
||||
# The default is "everysec", as that's usually the right compromise between
|
||||
@@ -554,7 +497,7 @@ appendfsync everysec
|
||||
# the same as "appendfsync none". In practical terms, this means that it is
|
||||
# possible to lose up to 30 seconds of log in the worst scenario (with the
|
||||
# default Linux settings).
|
||||
#
|
||||
#
|
||||
# If you have latency problems turn this to "yes". Otherwise leave it as
|
||||
# "no" that is the safest pick from the point of view of durability.
|
||||
|
||||
@@ -563,7 +506,7 @@ no-appendfsync-on-rewrite no
|
||||
# Automatic rewrite of the append only file.
|
||||
# Redis is able to automatically rewrite the log file implicitly calling
|
||||
# BGREWRITEAOF when the AOF log size grows by the specified percentage.
|
||||
#
|
||||
#
|
||||
# This is how it works: Redis remembers the size of the AOF file after the
|
||||
# latest rewrite (if no rewrite has happened since the restart, the size of
|
||||
# the AOF at startup is used).
|
||||
@@ -580,30 +523,6 @@ no-appendfsync-on-rewrite no
|
||||
auto-aof-rewrite-percentage 100
|
||||
auto-aof-rewrite-min-size 64mb
|
||||
|
||||
# An AOF file may be found to be truncated at the end during the Redis
|
||||
# startup process, when the AOF data gets loaded back into memory.
|
||||
# This may happen when the system where Redis is running
|
||||
# crashes, especially when an ext4 filesystem is mounted without the
|
||||
# data=ordered option (however this can't happen when Redis itself
|
||||
# crashes or aborts but the operating system still works correctly).
|
||||
#
|
||||
# Redis can either exit with an error when this happens, or load as much
|
||||
# data as possible (the default now) and start if the AOF file is found
|
||||
# to be truncated at the end. The following option controls this behavior.
|
||||
#
|
||||
# If aof-load-truncated is set to yes, a truncated AOF file is loaded and
|
||||
# the Redis server starts emitting a log to inform the user of the event.
|
||||
# Otherwise if the option is set to no, the server aborts with an error
|
||||
# and refuses to start. When the option is set to no, the user requires
|
||||
# to fix the AOF file using the "redis-check-aof" utility before to restart
|
||||
# the server.
|
||||
#
|
||||
# Note that if the AOF file will be found to be corrupted in the middle
|
||||
# the server will still exit with an error. This option only applies when
|
||||
# Redis will try to read more data from the AOF file but not enough bytes
|
||||
# will be found.
|
||||
aof-load-truncated yes
|
||||
|
||||
################################ LUA SCRIPTING ###############################
|
||||
|
||||
# Max execution time of a Lua script in milliseconds.
|
||||
@@ -612,11 +531,11 @@ aof-load-truncated yes
|
||||
# still in execution after the maximum allowed time and will start to
|
||||
# reply to queries with an error.
|
||||
#
|
||||
# When a long running script exceeds the maximum execution time only the
|
||||
# When a long running script exceed the maximum execution time only the
|
||||
# SCRIPT KILL and SHUTDOWN NOSAVE commands are available. The first can be
|
||||
# used to stop a script that did not yet called write commands. The second
|
||||
# is the only way to shut down the server in the case a write command was
|
||||
# already issued by the script but the user doesn't want to wait for the natural
|
||||
# is the only way to shut down the server in the case a write commands was
|
||||
# already issue by the script but the user don't want to wait for the natural
|
||||
# termination of the script.
|
||||
#
|
||||
# Set it to 0 or a negative value for unlimited execution without warnings.
|
||||
@@ -624,12 +543,6 @@ 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:
|
||||
@@ -639,12 +552,12 @@ lua-time-limit 5000
|
||||
# Every cluster node has a cluster configuration file. This file is not
|
||||
# intended to be edited by hand. It is created and updated by Redis nodes.
|
||||
# Every Redis Cluster node requires a different cluster configuration file.
|
||||
# Make sure that instances running in the same system do not have
|
||||
# Make sure that instances running in the same system does not have
|
||||
# overlapping cluster configuration file names.
|
||||
#
|
||||
# cluster-config-file nodes-6379.conf
|
||||
|
||||
# Cluster node timeout is the amount of milliseconds a node must be unreachable
|
||||
# Cluster node timeout is the amount of milliseconds a node must be unreachable
|
||||
# for it to be considered in failure state.
|
||||
# Most other internal time limits are multiple of the node timeout.
|
||||
#
|
||||
@@ -714,19 +627,6 @@ lua-time-limit 5000
|
||||
#
|
||||
# cluster-migration-barrier 1
|
||||
|
||||
# By default Redis Cluster nodes stop accepting queries if they detect there
|
||||
# is at least an hash slot uncovered (no available node is serving it).
|
||||
# This way if the cluster is partially down (for example a range of hash slots
|
||||
# are no longer covered) all the cluster becomes, eventually, unavailable.
|
||||
# It automatically returns available as soon as all the slots are covered again.
|
||||
#
|
||||
# However sometimes you want the subset of the cluster which is working,
|
||||
# to continue to accept queries for the part of the key space that is still
|
||||
# covered. In order to do so, just set the cluster-require-full-coverage
|
||||
# option to no.
|
||||
#
|
||||
# cluster-require-full-coverage yes
|
||||
|
||||
# In order to setup your cluster make sure to read the documentation
|
||||
# available at http://redis.io web site.
|
||||
|
||||
@@ -738,7 +638,7 @@ lua-time-limit 5000
|
||||
# but just the time needed to actually execute the command (this is the only
|
||||
# stage of command execution where the thread is blocked and can not serve
|
||||
# other requests in the meantime).
|
||||
#
|
||||
#
|
||||
# You can configure the slow log with two parameters: one tells Redis
|
||||
# what is the execution time, in microseconds, to exceed in order for the
|
||||
# command to get logged, and the other parameter is the length of the
|
||||
@@ -771,15 +671,15 @@ slowlog-max-len 128
|
||||
# By default latency monitoring is disabled since it is mostly not needed
|
||||
# if you don't have latency issues, and collecting data has a performance
|
||||
# impact, that while very small, can be measured under big load. Latency
|
||||
# monitoring can easily be enabled at runtime using the command
|
||||
# monitoring can easily be enalbed at runtime using the command
|
||||
# "CONFIG SET latency-monitor-threshold <milliseconds>" if needed.
|
||||
latency-monitor-threshold 0
|
||||
|
||||
############################# EVENT NOTIFICATION ##############################
|
||||
############################# Event notification ##############################
|
||||
|
||||
# Redis can notify Pub/Sub clients about events happening in the key space.
|
||||
# This feature is documented at http://redis.io/topics/notifications
|
||||
#
|
||||
# This feature is documented at http://redis.io/topics/keyspace-events
|
||||
#
|
||||
# For instance if keyspace events notification is enabled, and a client
|
||||
# performs a DEL operation on key "foo" stored in the Database 0, two
|
||||
# messages will be published via Pub/Sub:
|
||||
@@ -803,8 +703,8 @@ latency-monitor-threshold 0
|
||||
# A Alias for g$lshzxe, so that the "AKE" string means all the events.
|
||||
#
|
||||
# The "notify-keyspace-events" takes as argument a string that is composed
|
||||
# of zero or multiple characters. The empty string means that notifications
|
||||
# are disabled.
|
||||
# by zero or multiple characters. The empty string means that notifications
|
||||
# are disabled at all.
|
||||
#
|
||||
# Example: to enable list and generic events, from the point of view of the
|
||||
# event name, use:
|
||||
@@ -836,7 +736,7 @@ list-max-ziplist-entries 512
|
||||
list-max-ziplist-value 64
|
||||
|
||||
# Sets have a special encoding in just one case: when a set is composed
|
||||
# of just strings that happen to be integers in radix 10 in the range
|
||||
# of just strings that happens to be integers in radix 10 in the range
|
||||
# of 64 bit signed integers.
|
||||
# The following configuration setting sets the limit in the size of the
|
||||
# set in order to use this special memory saving encoding.
|
||||
@@ -854,7 +754,7 @@ zset-max-ziplist-value 64
|
||||
#
|
||||
# A value greater than 16000 is totally useless, since at that point the
|
||||
# dense representation is more memory efficient.
|
||||
#
|
||||
#
|
||||
# The suggested value is ~ 3000 in order to have the benefits of
|
||||
# the space efficient encoding without slowing down too much PFADD,
|
||||
# which is O(N) with the sparse encoding. The value can be raised to
|
||||
@@ -869,13 +769,13 @@ hll-sparse-max-bytes 3000
|
||||
# that is rehashing, the more rehashing "steps" are performed, so if the
|
||||
# server is idle the rehashing is never complete and some more memory is used
|
||||
# by the hash table.
|
||||
#
|
||||
#
|
||||
# The default is to use this millisecond 10 times every second in order to
|
||||
# actively rehash the main dictionaries, freeing memory when possible.
|
||||
# active rehashing the main dictionaries, freeing memory when possible.
|
||||
#
|
||||
# If unsure:
|
||||
# use "activerehashing no" if you have hard latency requirements and it is
|
||||
# not a good thing in your environment that Redis can reply from time to time
|
||||
# not a good thing in your environment that Redis can reply form time to time
|
||||
# to queries with 2 milliseconds delay.
|
||||
#
|
||||
# use "activerehashing yes" if you don't have such hard requirements but
|
||||
@@ -924,7 +824,7 @@ client-output-buffer-limit pubsub 32mb 8mb 60
|
||||
# never requested, and so forth.
|
||||
#
|
||||
# Not all tasks are performed with the same frequency, but Redis checks for
|
||||
# tasks to perform according to the specified "hz" value.
|
||||
# tasks to perform accordingly to the specified "hz" value.
|
||||
#
|
||||
# By default "hz" is set to 10. Raising the value will use more CPU when
|
||||
# Redis is idle, but at the same time will make Redis more responsive when
|
||||
@@ -941,3 +841,4 @@ hz 10
|
||||
# in order to commit the file to the disk more incrementally and avoid
|
||||
# big latency spikes.
|
||||
aof-rewrite-incremental-fsync yes
|
||||
|
||||
|
||||
+1
-23
@@ -4,32 +4,10 @@
|
||||
# The port that this sentinel instance will run on
|
||||
port 26379
|
||||
|
||||
# sentinel announce-ip <ip>
|
||||
# sentinel announce-port <port>
|
||||
#
|
||||
# The above two configuration directives are useful in environments where,
|
||||
# because of NAT, Sentinel is reachable from outside via a non-local address.
|
||||
#
|
||||
# When announce-ip is provided, the Sentinel will claim the specified IP address
|
||||
# in HELLO messages used to gossip its presence, instead of auto-detecting the
|
||||
# local address as it usually does.
|
||||
#
|
||||
# Similarly when announce-port is provided and is valid and non-zero, Sentinel
|
||||
# will announce the specified TCP port.
|
||||
#
|
||||
# The two options don't need to be used together, if only announce-ip is
|
||||
# provided, the Sentinel will announce the specified IP and the server port
|
||||
# as specified by the "port" option. If only announce-port is provided, the
|
||||
# Sentinel will announce the auto-detected local IP and the specified port.
|
||||
#
|
||||
# Example:
|
||||
#
|
||||
# sentinel announce-ip 1.2.3.4
|
||||
|
||||
# dir <working-directory>
|
||||
# Every long running process should have a well-defined working directory.
|
||||
# For Redis Sentinel to chdir to /tmp at startup is the simplest thing
|
||||
# for the process to don't interfere with administrative tasks such as
|
||||
# for the process to don't interferer with administrative tasks such as
|
||||
# unmounting filesystems.
|
||||
dir /tmp
|
||||
|
||||
|
||||
+4
-11
@@ -19,7 +19,7 @@ DEPENDENCY_TARGETS=hiredis linenoise lua
|
||||
|
||||
# Default settings
|
||||
STD=-std=c99 -pedantic
|
||||
WARN=-Wall -W
|
||||
WARN=-Wall
|
||||
OPT=$(OPTIMIZATION)
|
||||
|
||||
PREFIX?=/usr/local
|
||||
@@ -58,23 +58,17 @@ ifeq ($(uname_S),SunOS)
|
||||
# SunOS
|
||||
INSTALL=cp -pf
|
||||
FINAL_CFLAGS+= -D__EXTENSIONS__ -D_XPG6
|
||||
FINAL_LIBS+= -ldl -lnsl -lsocket -lresolv -lpthread -lrt
|
||||
FINAL_LIBS+= -ldl -lnsl -lsocket -lpthread
|
||||
else
|
||||
ifeq ($(uname_S),Darwin)
|
||||
# Darwin (nothing to do)
|
||||
else
|
||||
ifeq ($(uname_S),AIX)
|
||||
# AIX
|
||||
FINAL_LDFLAGS+= -Wl,-bexpall
|
||||
FINAL_LIBS+= -pthread -lcrypt -lbsd
|
||||
|
||||
else
|
||||
# All the other OSes (notably Linux)
|
||||
FINAL_LDFLAGS+= -rdynamic
|
||||
FINAL_LIBS+= -pthread
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
# Include paths to dependencies
|
||||
FINAL_CFLAGS+= -I../deps/hiredis -I../deps/linenoise -I../deps/lua/src
|
||||
|
||||
@@ -125,7 +119,7 @@ REDIS_CHECK_AOF_OBJ=redis-check-aof.o
|
||||
|
||||
all: $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_DUMP_NAME) $(REDIS_CHECK_AOF_NAME)
|
||||
@echo ""
|
||||
@echo "Hint: It's a good idea to run 'make test' ;)"
|
||||
@echo "Hint: To run 'make test' is a good idea ;)"
|
||||
@echo ""
|
||||
|
||||
.PHONY: all
|
||||
@@ -251,4 +245,3 @@ install: all
|
||||
$(REDIS_INSTALL) $(REDIS_CLI_NAME) $(INSTALL_BIN)
|
||||
$(REDIS_INSTALL) $(REDIS_CHECK_DUMP_NAME) $(INSTALL_BIN)
|
||||
$(REDIS_INSTALL) $(REDIS_CHECK_AOF_NAME) $(INSTALL_BIN)
|
||||
@ln -sf $(REDIS_SERVER_NAME) $(INSTALL_BIN)/$(REDIS_SENTINEL_NAME)
|
||||
|
||||
+1
-1
@@ -71,7 +71,7 @@ void listRelease(list *list)
|
||||
zfree(list);
|
||||
}
|
||||
|
||||
/* Add a new node to the list, to head, containing the specified 'value'
|
||||
/* Add a new node to the list, to head, contaning the specified 'value'
|
||||
* pointer as value.
|
||||
*
|
||||
* On error, NULL is returned and no operation is performed (i.e. the
|
||||
|
||||
@@ -156,9 +156,8 @@ void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
|
||||
{
|
||||
if (fd >= eventLoop->setsize) return;
|
||||
aeFileEvent *fe = &eventLoop->events[fd];
|
||||
if (fe->mask == AE_NONE) return;
|
||||
|
||||
aeApiDelEvent(eventLoop, fd, mask);
|
||||
if (fe->mask == AE_NONE) return;
|
||||
fe->mask = fe->mask & (~mask);
|
||||
if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
|
||||
/* Update the max fd */
|
||||
@@ -168,6 +167,7 @@ void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
|
||||
if (eventLoop->events[j].mask != AE_NONE) break;
|
||||
eventLoop->maxfd = j;
|
||||
}
|
||||
aeApiDelEvent(eventLoop, fd, mask);
|
||||
}
|
||||
|
||||
int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
|
||||
|
||||
+17
-81
@@ -34,7 +34,6 @@
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/time.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <arpa/inet.h>
|
||||
@@ -58,37 +57,24 @@ static void anetSetError(char *err, const char *fmt, ...)
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
int anetSetBlock(char *err, int fd, int non_block) {
|
||||
int anetNonBlock(char *err, int fd)
|
||||
{
|
||||
int flags;
|
||||
|
||||
/* Set the socket blocking (if non_block is zero) or non-blocking.
|
||||
/* Set the socket non-blocking.
|
||||
* Note that fcntl(2) for F_GETFL and F_SETFL can't be
|
||||
* interrupted by a signal. */
|
||||
if ((flags = fcntl(fd, F_GETFL)) == -1) {
|
||||
anetSetError(err, "fcntl(F_GETFL): %s", strerror(errno));
|
||||
return ANET_ERR;
|
||||
}
|
||||
|
||||
if (non_block)
|
||||
flags |= O_NONBLOCK;
|
||||
else
|
||||
flags &= ~O_NONBLOCK;
|
||||
|
||||
if (fcntl(fd, F_SETFL, flags) == -1) {
|
||||
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
|
||||
anetSetError(err, "fcntl(F_SETFL,O_NONBLOCK): %s", strerror(errno));
|
||||
return ANET_ERR;
|
||||
}
|
||||
return ANET_OK;
|
||||
}
|
||||
|
||||
int anetNonBlock(char *err, int fd) {
|
||||
return anetSetBlock(err,fd,1);
|
||||
}
|
||||
|
||||
int anetBlock(char *err, int fd) {
|
||||
return anetSetBlock(err,fd,0);
|
||||
}
|
||||
|
||||
/* Set TCP keep alive option to detect dead peers. The interval option
|
||||
* is only used for Linux as we are using Linux-specific APIs to set
|
||||
* the probe send time, interval, and count. */
|
||||
@@ -131,8 +117,6 @@ int anetKeepAlive(char *err, int fd, int interval)
|
||||
anetSetError(err, "setsockopt TCP_KEEPCNT: %s\n", strerror(errno));
|
||||
return ANET_ERR;
|
||||
}
|
||||
#else
|
||||
((void) interval); /* Avoid unused var warning for non Linux systems. */
|
||||
#endif
|
||||
|
||||
return ANET_OK;
|
||||
@@ -179,20 +163,6 @@ int anetTcpKeepAlive(char *err, int fd)
|
||||
return ANET_OK;
|
||||
}
|
||||
|
||||
/* Set the socket send timeout (SO_SNDTIMEO socket option) to the specified
|
||||
* number of milliseconds, or disable it if the 'ms' argument is zero. */
|
||||
int anetSendTimeout(char *err, int fd, long long ms) {
|
||||
struct timeval tv;
|
||||
|
||||
tv.tv_sec = ms/1000;
|
||||
tv.tv_usec = (ms%1000)*1000;
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) == -1) {
|
||||
anetSetError(err, "setsockopt SO_SNDTIMEO: %s", strerror(errno));
|
||||
return ANET_ERR;
|
||||
}
|
||||
return ANET_OK;
|
||||
}
|
||||
|
||||
/* anetGenericResolve() is called by anetResolve() and anetResolveIP() to
|
||||
* do the actual work. It resolves the hostname "host" and set the string
|
||||
* representation of the IP address into the buffer pointed by "ipbuf".
|
||||
@@ -264,7 +234,6 @@ static int anetCreateSocket(char *err, int domain) {
|
||||
|
||||
#define ANET_CONNECT_NONE 0
|
||||
#define ANET_CONNECT_NONBLOCK 1
|
||||
#define ANET_CONNECT_BE_BINDING 2 /* Best effort binding. */
|
||||
static int anetTcpGenericConnect(char *err, char *addr, int port,
|
||||
char *source_addr, int flags)
|
||||
{
|
||||
@@ -293,10 +262,9 @@ static int anetTcpGenericConnect(char *err, char *addr, int port,
|
||||
if (source_addr) {
|
||||
int bound = 0;
|
||||
/* Using getaddrinfo saves us from self-determining IPv4 vs IPv6 */
|
||||
if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0)
|
||||
{
|
||||
if ((rv = getaddrinfo(source_addr, NULL, &hints, &bservinfo)) != 0) {
|
||||
anetSetError(err, "%s", gai_strerror(rv));
|
||||
goto error;
|
||||
goto end;
|
||||
}
|
||||
for (b = bservinfo; b != NULL; b = b->ai_next) {
|
||||
if (bind(s,b->ai_addr,b->ai_addrlen) != -1) {
|
||||
@@ -304,10 +272,9 @@ static int anetTcpGenericConnect(char *err, char *addr, int port,
|
||||
break;
|
||||
}
|
||||
}
|
||||
freeaddrinfo(bservinfo);
|
||||
if (!bound) {
|
||||
anetSetError(err, "bind: %s", strerror(errno));
|
||||
goto error;
|
||||
goto end;
|
||||
}
|
||||
}
|
||||
if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {
|
||||
@@ -332,17 +299,9 @@ error:
|
||||
close(s);
|
||||
s = ANET_ERR;
|
||||
}
|
||||
|
||||
end:
|
||||
freeaddrinfo(servinfo);
|
||||
|
||||
/* Handle best effort binding: if a binding address was used, but it is
|
||||
* not possible to create a socket, try again without a binding address. */
|
||||
if (s == ANET_ERR && source_addr && (flags & ANET_CONNECT_BE_BINDING)) {
|
||||
return anetTcpGenericConnect(err,addr,port,NULL,flags);
|
||||
} else {
|
||||
return s;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
int anetTcpConnect(char *err, char *addr, int port)
|
||||
@@ -355,18 +314,9 @@ int anetTcpNonBlockConnect(char *err, char *addr, int port)
|
||||
return anetTcpGenericConnect(err,addr,port,NULL,ANET_CONNECT_NONBLOCK);
|
||||
}
|
||||
|
||||
int anetTcpNonBlockBindConnect(char *err, char *addr, int port,
|
||||
char *source_addr)
|
||||
int anetTcpNonBlockBindConnect(char *err, char *addr, int port, char *source_addr)
|
||||
{
|
||||
return anetTcpGenericConnect(err,addr,port,source_addr,
|
||||
ANET_CONNECT_NONBLOCK);
|
||||
}
|
||||
|
||||
int anetTcpNonBlockBestEffortBindConnect(char *err, char *addr, int port,
|
||||
char *source_addr)
|
||||
{
|
||||
return anetTcpGenericConnect(err,addr,port,source_addr,
|
||||
ANET_CONNECT_NONBLOCK|ANET_CONNECT_BE_BINDING);
|
||||
return anetTcpGenericConnect(err,addr,port,source_addr,ANET_CONNECT_NONBLOCK);
|
||||
}
|
||||
|
||||
int anetUnixGenericConnect(char *err, char *path, int flags)
|
||||
@@ -575,36 +525,22 @@ int anetPeerToString(int fd, char *ip, size_t ip_len, int *port) {
|
||||
struct sockaddr_storage sa;
|
||||
socklen_t salen = sizeof(sa);
|
||||
|
||||
if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) goto error;
|
||||
if (ip_len == 0) goto error;
|
||||
|
||||
if (getpeername(fd,(struct sockaddr*)&sa,&salen) == -1) {
|
||||
if (port) *port = 0;
|
||||
ip[0] = '?';
|
||||
ip[1] = '\0';
|
||||
return -1;
|
||||
}
|
||||
if (sa.ss_family == AF_INET) {
|
||||
struct sockaddr_in *s = (struct sockaddr_in *)&sa;
|
||||
if (ip) inet_ntop(AF_INET,(void*)&(s->sin_addr),ip,ip_len);
|
||||
if (port) *port = ntohs(s->sin_port);
|
||||
} else if (sa.ss_family == AF_INET6) {
|
||||
} else {
|
||||
struct sockaddr_in6 *s = (struct sockaddr_in6 *)&sa;
|
||||
if (ip) inet_ntop(AF_INET6,(void*)&(s->sin6_addr),ip,ip_len);
|
||||
if (port) *port = ntohs(s->sin6_port);
|
||||
} else if (sa.ss_family == AF_UNIX) {
|
||||
if (ip) strncpy(ip,"/unixsocket",ip_len);
|
||||
if (port) *port = 0;
|
||||
} else {
|
||||
goto error;
|
||||
}
|
||||
return 0;
|
||||
|
||||
error:
|
||||
if (ip) {
|
||||
if (ip_len >= 2) {
|
||||
ip[0] = '?';
|
||||
ip[1] = '\0';
|
||||
} else if (ip_len == 1) {
|
||||
ip[0] = '\0';
|
||||
}
|
||||
}
|
||||
if (port) *port = 0;
|
||||
return -1;
|
||||
}
|
||||
|
||||
int anetSockName(int fd, char *ip, size_t ip_len, int *port) {
|
||||
|
||||
+1
-8
@@ -39,18 +39,13 @@
|
||||
#define ANET_NONE 0
|
||||
#define ANET_IP_ONLY (1<<0)
|
||||
|
||||
#if defined(__sun) || defined(_AIX)
|
||||
#if defined(__sun)
|
||||
#define AF_LOCAL AF_UNIX
|
||||
#endif
|
||||
|
||||
#ifdef _AIX
|
||||
#undef ip_len
|
||||
#endif
|
||||
|
||||
int anetTcpConnect(char *err, char *addr, int port);
|
||||
int anetTcpNonBlockConnect(char *err, char *addr, int port);
|
||||
int anetTcpNonBlockBindConnect(char *err, char *addr, int port, char *source_addr);
|
||||
int anetTcpNonBlockBestEffortBindConnect(char *err, char *addr, int port, char *source_addr);
|
||||
int anetUnixConnect(char *err, char *path);
|
||||
int anetUnixNonBlockConnect(char *err, char *path);
|
||||
int anetRead(int fd, char *buf, int count);
|
||||
@@ -63,11 +58,9 @@ int anetTcpAccept(char *err, int serversock, char *ip, size_t ip_len, int *port)
|
||||
int anetUnixAccept(char *err, int serversock);
|
||||
int anetWrite(int fd, char *buf, int count);
|
||||
int anetNonBlock(char *err, int fd);
|
||||
int anetBlock(char *err, int fd);
|
||||
int anetEnableTcpNoDelay(char *err, int fd);
|
||||
int anetDisableTcpNoDelay(char *err, int fd);
|
||||
int anetTcpKeepAlive(char *err, int fd);
|
||||
int anetSendTimeout(char *err, int fd, long long ms);
|
||||
int anetPeerToString(int fd, char *ip, size_t ip_len, int *port);
|
||||
int anetKeepAlive(char *err, int fd, int interval);
|
||||
int anetSockName(int fd, char *ip, size_t ip_len, int *port);
|
||||
|
||||
@@ -74,7 +74,7 @@ void aofRewriteBufferReset(void) {
|
||||
listSetFreeMethod(server.aof_rewrite_buf_blocks,zfree);
|
||||
}
|
||||
|
||||
/* Return the current size of the AOF rewrite buffer. */
|
||||
/* Return the current size of the AOF rerwite buffer. */
|
||||
unsigned long aofRewriteBufferSize(void) {
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
@@ -95,10 +95,6 @@ void aofChildWriteDiffData(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
listNode *ln;
|
||||
aofrwblock *block;
|
||||
ssize_t nwritten;
|
||||
REDIS_NOTUSED(el);
|
||||
REDIS_NOTUSED(fd);
|
||||
REDIS_NOTUSED(privdata);
|
||||
REDIS_NOTUSED(mask);
|
||||
|
||||
while(1) {
|
||||
ln = listFirst(server.aof_rewrite_buf_blocks);
|
||||
@@ -181,7 +177,7 @@ ssize_t aofRewriteBufferWrite(int fd) {
|
||||
|
||||
if (block->used) {
|
||||
nwritten = write(fd,block->buf,block->used);
|
||||
if (nwritten != (ssize_t)block->used) {
|
||||
if (nwritten != block->used) {
|
||||
if (nwritten == 0) errno = EIO;
|
||||
return -1;
|
||||
}
|
||||
@@ -245,7 +241,7 @@ int startAppendOnly(void) {
|
||||
redisLog(REDIS_WARNING,"Redis needs to enable the AOF but can't trigger a background AOF rewrite operation. Check the above logs for more info about the error.");
|
||||
return REDIS_ERR;
|
||||
}
|
||||
/* We correctly switched on AOF, now wait for the rewrite to be complete
|
||||
/* We correctly switched on AOF, now wait for the rerwite to be complete
|
||||
* in order to append data on disk. */
|
||||
server.aof_state = REDIS_AOF_WAIT_REWRITE;
|
||||
return REDIS_OK;
|
||||
@@ -286,7 +282,7 @@ void flushAppendOnlyFile(int force) {
|
||||
* the write for a couple of seconds. */
|
||||
if (sync_in_progress) {
|
||||
if (server.aof_flush_postponed_start == 0) {
|
||||
/* No previous write postponing, remember that we are
|
||||
/* No previous write postponinig, remember that we are
|
||||
* postponing the flush and return. */
|
||||
server.aof_flush_postponed_start = server.unixtime;
|
||||
return;
|
||||
@@ -337,7 +333,7 @@ void flushAppendOnlyFile(int force) {
|
||||
last_write_error_log = server.unixtime;
|
||||
}
|
||||
|
||||
/* Log the AOF write error and record the error code. */
|
||||
/* Lof the AOF write error and record the error code. */
|
||||
if (nwritten == -1) {
|
||||
if (can_log) {
|
||||
redisLog(REDIS_WARNING,"Error writing to the AOF file: %s",
|
||||
@@ -361,7 +357,7 @@ void flushAppendOnlyFile(int force) {
|
||||
"ftruncate: %s", strerror(errno));
|
||||
}
|
||||
} else {
|
||||
/* If the ftruncate() succeeded we can set nwritten to
|
||||
/* If the ftrunacate() succeeded we can set nwritten to
|
||||
* -1 since there is no longer partial data into the AOF. */
|
||||
nwritten = -1;
|
||||
}
|
||||
@@ -373,7 +369,7 @@ void flushAppendOnlyFile(int force) {
|
||||
/* We can't recover when the fsync policy is ALWAYS since the
|
||||
* reply for the client is already in the output buffers, and we
|
||||
* have the contract with the user that on acknowledged write data
|
||||
* is synced on disk. */
|
||||
* is synched on disk. */
|
||||
redisLog(REDIS_WARNING,"Can't recover from AOF write error when the AOF fsync policy is 'always'. Exiting...");
|
||||
exit(1);
|
||||
} else {
|
||||
@@ -468,7 +464,7 @@ sds catAppendOnlyExpireAtCommand(sds buf, struct redisCommand *cmd, robj *key, r
|
||||
long long when;
|
||||
robj *argv[3];
|
||||
|
||||
/* Make sure we can use strtoll */
|
||||
/* Make sure we can use strtol */
|
||||
seconds = getDecodedObject(seconds);
|
||||
when = strtoll(seconds->ptr,NULL,10);
|
||||
/* Convert argument into milliseconds for EXPIRE, SETEX, EXPIREAT */
|
||||
@@ -499,7 +495,7 @@ void feedAppendOnlyFile(struct redisCommand *cmd, int dictid, robj **argv, int a
|
||||
robj *tmpargv[3];
|
||||
|
||||
/* The DB this command was targeting is not the same as the last command
|
||||
* we appended. To issue a SELECT command is needed. */
|
||||
* we appendend. To issue a SELECT command is needed. */
|
||||
if (dictid != server.aof_selected_db) {
|
||||
char seldb[64];
|
||||
|
||||
@@ -577,14 +573,6 @@ struct redisClient *createFakeClient(void) {
|
||||
return c;
|
||||
}
|
||||
|
||||
void freeFakeClientArgv(struct redisClient *c) {
|
||||
int j;
|
||||
|
||||
for (j = 0; j < c->argc; j++)
|
||||
decrRefCount(c->argv[j]);
|
||||
zfree(c->argv);
|
||||
}
|
||||
|
||||
void freeFakeClient(struct redisClient *c) {
|
||||
sdsfree(c->querybuf);
|
||||
listRelease(c->reply);
|
||||
@@ -593,7 +581,7 @@ void freeFakeClient(struct redisClient *c) {
|
||||
zfree(c);
|
||||
}
|
||||
|
||||
/* Replay the append log file. On success REDIS_OK is returned. On non fatal
|
||||
/* Replay the append log file. On error REDIS_OK is returned. On non fatal
|
||||
* error (the append only file is zero-length) REDIS_ERR is returned. On
|
||||
* fatal error an error message is logged and the program exists. */
|
||||
int loadAppendOnlyFile(char *filename) {
|
||||
@@ -602,7 +590,6 @@ int loadAppendOnlyFile(char *filename) {
|
||||
struct redis_stat sb;
|
||||
int old_aof_state = server.aof_state;
|
||||
long loops = 0;
|
||||
off_t valid_up_to = 0; /* Offset of the latest well-formed command loaded. */
|
||||
|
||||
if (fp && redis_fstat(fileno(fp),&sb) != -1 && sb.st_size == 0) {
|
||||
server.aof_current_size = 0;
|
||||
@@ -643,35 +630,18 @@ int loadAppendOnlyFile(char *filename) {
|
||||
goto readerr;
|
||||
}
|
||||
if (buf[0] != '*') goto fmterr;
|
||||
if (buf[1] == '\0') goto readerr;
|
||||
argc = atoi(buf+1);
|
||||
if (argc < 1) goto fmterr;
|
||||
|
||||
argv = zmalloc(sizeof(robj*)*argc);
|
||||
fakeClient->argc = argc;
|
||||
fakeClient->argv = argv;
|
||||
|
||||
for (j = 0; j < argc; j++) {
|
||||
if (fgets(buf,sizeof(buf),fp) == NULL) {
|
||||
fakeClient->argc = j; /* Free up to j-1. */
|
||||
freeFakeClientArgv(fakeClient);
|
||||
goto readerr;
|
||||
}
|
||||
if (fgets(buf,sizeof(buf),fp) == NULL) goto readerr;
|
||||
if (buf[0] != '$') goto fmterr;
|
||||
len = strtol(buf+1,NULL,10);
|
||||
argsds = sdsnewlen(NULL,len);
|
||||
if (len && fread(argsds,len,1,fp) == 0) {
|
||||
sdsfree(argsds);
|
||||
fakeClient->argc = j; /* Free up to j-1. */
|
||||
freeFakeClientArgv(fakeClient);
|
||||
goto readerr;
|
||||
}
|
||||
if (len && fread(argsds,len,1,fp) == 0) goto fmterr;
|
||||
argv[j] = createObject(REDIS_STRING,argsds);
|
||||
if (fread(buf,2,1,fp) == 0) {
|
||||
fakeClient->argc = j+1; /* Free up to j. */
|
||||
freeFakeClientArgv(fakeClient);
|
||||
goto readerr; /* discard CRLF */
|
||||
}
|
||||
if (fread(buf,2,1,fp) == 0) goto fmterr; /* discard CRLF */
|
||||
}
|
||||
|
||||
/* Command lookup */
|
||||
@@ -680,8 +650,9 @@ int loadAppendOnlyFile(char *filename) {
|
||||
redisLog(REDIS_WARNING,"Unknown command '%s' reading the append only file", (char*)argv[0]->ptr);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* Run the command in the context of a fake client */
|
||||
fakeClient->argc = argc;
|
||||
fakeClient->argv = argv;
|
||||
cmd->proc(fakeClient);
|
||||
|
||||
/* The fake client should not have a reply */
|
||||
@@ -691,15 +662,15 @@ int loadAppendOnlyFile(char *filename) {
|
||||
|
||||
/* Clean up. Command code may have changed argv/argc so we use the
|
||||
* argv/argc of the client instead of the local variables. */
|
||||
freeFakeClientArgv(fakeClient);
|
||||
if (server.aof_load_truncated) valid_up_to = ftello(fp);
|
||||
for (j = 0; j < fakeClient->argc; j++)
|
||||
decrRefCount(fakeClient->argv[j]);
|
||||
zfree(fakeClient->argv);
|
||||
}
|
||||
|
||||
/* This point can only be reached when EOF is reached without errors.
|
||||
* If the client is in the middle of a MULTI/EXEC, log error and quit. */
|
||||
if (fakeClient->flags & REDIS_MULTI) goto uxeof;
|
||||
if (fakeClient->flags & REDIS_MULTI) goto readerr;
|
||||
|
||||
loaded_ok: /* DB loaded, cleanup and return REDIS_OK to the caller. */
|
||||
fclose(fp);
|
||||
freeFakeClient(fakeClient);
|
||||
server.aof_state = old_aof_state;
|
||||
@@ -708,41 +679,14 @@ loaded_ok: /* DB loaded, cleanup and return REDIS_OK to the caller. */
|
||||
server.aof_rewrite_base_size = server.aof_current_size;
|
||||
return REDIS_OK;
|
||||
|
||||
readerr: /* Read error. If feof(fp) is true, fall through to unexpected EOF. */
|
||||
if (!feof(fp)) {
|
||||
readerr:
|
||||
if (feof(fp)) {
|
||||
redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file");
|
||||
} else {
|
||||
redisLog(REDIS_WARNING,"Unrecoverable error reading the append only file: %s", strerror(errno));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
uxeof: /* Unexpected AOF end of file. */
|
||||
if (server.aof_load_truncated) {
|
||||
redisLog(REDIS_WARNING,"!!! Warning: short read while loading the AOF file !!!");
|
||||
redisLog(REDIS_WARNING,"!!! Truncating the AOF at offset %llu !!!",
|
||||
(unsigned long long) valid_up_to);
|
||||
if (valid_up_to == -1 || truncate(filename,valid_up_to) == -1) {
|
||||
if (valid_up_to == -1) {
|
||||
redisLog(REDIS_WARNING,"Last valid command offset is invalid");
|
||||
} else {
|
||||
redisLog(REDIS_WARNING,"Error truncating the AOF file: %s",
|
||||
strerror(errno));
|
||||
}
|
||||
} else {
|
||||
/* Make sure the AOF file descriptor points to the end of the
|
||||
* file after the truncate call. */
|
||||
if (server.aof_fd != -1 && lseek(server.aof_fd,0,SEEK_END) == -1) {
|
||||
redisLog(REDIS_WARNING,"Can't seek the end of the AOF file: %s",
|
||||
strerror(errno));
|
||||
} else {
|
||||
redisLog(REDIS_WARNING,
|
||||
"AOF loaded anyway because aof-load-truncated is enabled");
|
||||
goto loaded_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
redisLog(REDIS_WARNING,"Unexpected end of file reading the append only file. You can: 1) Make a backup of your AOF file, then use ./redis-check-aof --fix <filename>. 2) Alternatively you can set the 'aof-load-truncated' configuration option to yes and restart the server.");
|
||||
exit(1);
|
||||
|
||||
fmterr: /* Format error. */
|
||||
fmterr:
|
||||
redisLog(REDIS_WARNING,"Bad file format reading the append only file: make a backup of your AOF file, then use ./redis-check-aof --fix <filename>");
|
||||
exit(1);
|
||||
}
|
||||
@@ -1000,7 +944,7 @@ int rewriteHashObject(rio *r, robj *key, robj *o) {
|
||||
* the difference accumulated from the parent into a buffer, that is
|
||||
* concatenated at the end of the rewrite. */
|
||||
ssize_t aofReadDiffFromParent(void) {
|
||||
char buf[65536]; /* Default pipe buffer size on most Linux systems. */
|
||||
char buf[65536]; /* Default pipe buffer size on most Linux sytems. */
|
||||
ssize_t nread, total = 0;
|
||||
|
||||
while ((nread =
|
||||
@@ -1105,7 +1049,6 @@ int rewriteAppendOnlyFile(char *filename) {
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
di = NULL;
|
||||
}
|
||||
|
||||
/* Do an initial slow fsync here while the parent is still sending
|
||||
@@ -1115,7 +1058,7 @@ int rewriteAppendOnlyFile(char *filename) {
|
||||
|
||||
/* Read again a few times to get more data from the parent.
|
||||
* We can't read forever (the server may receive data from clients
|
||||
* faster than it is able to send data to the child), so we try to read
|
||||
* fater than it is able to send data to the child), so we try to read
|
||||
* some more data in a loop as soon as there is a good chance more data
|
||||
* will come. If it looks like we are wasting time, we abort (this
|
||||
* happens after 20 ms without new data). */
|
||||
@@ -1169,9 +1112,9 @@ int rewriteAppendOnlyFile(char *filename) {
|
||||
return REDIS_OK;
|
||||
|
||||
werr:
|
||||
redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
|
||||
fclose(fp);
|
||||
unlink(tmpfile);
|
||||
redisLog(REDIS_WARNING,"Write error writing append only file on disk: %s", strerror(errno));
|
||||
if (di) dictReleaseIterator(di);
|
||||
return REDIS_ERR;
|
||||
}
|
||||
@@ -1185,9 +1128,6 @@ werr:
|
||||
* parent sends a '!' as well to acknowledge. */
|
||||
void aofChildPipeReadable(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
char byte;
|
||||
REDIS_NOTUSED(el);
|
||||
REDIS_NOTUSED(privdata);
|
||||
REDIS_NOTUSED(mask);
|
||||
|
||||
if (read(fd,&byte,1) == 1 && byte == '!') {
|
||||
redisLog(REDIS_NOTICE,"AOF rewrite child asks to stop sending diffs.");
|
||||
@@ -1251,7 +1191,7 @@ void aofClosePipes(void) {
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
* AOF background rewrite
|
||||
* AOF backgorund rewrite
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
/* This is how rewriting of the append only file in background works:
|
||||
@@ -1340,7 +1280,7 @@ void aofRemoveTempFile(pid_t childpid) {
|
||||
unlink(tmpfile);
|
||||
}
|
||||
|
||||
/* Update the server.aof_current_size field explicitly using stat(2)
|
||||
/* Update the server.aof_current_size filed explicitly using stat(2)
|
||||
* to check the size of the file. This is useful after a rewrite or after
|
||||
* a restart, normally the size is updated just adding the write length
|
||||
* to the current length, that is much faster. */
|
||||
@@ -1393,7 +1333,7 @@ void backgroundRewriteDoneHandler(int exitcode, int bysignal) {
|
||||
latencyAddSampleIfNeeded("aof-rewrite-diff-write",latency);
|
||||
|
||||
redisLog(REDIS_NOTICE,
|
||||
"Residual parent diff successfully flushed to the rewritten AOF (%.2f MB)", (double) aofRewriteBufferSize() / (1024*1024));
|
||||
"Redidual parent diff successfully flushed to the rewritten AOF (%.2f MB)", (double) aofRewriteBufferSize() / (1024*1024));
|
||||
|
||||
/* The only remaining thing to do is to rename the temporary file to
|
||||
* the configured file and switch the file descriptor used to do AOF
|
||||
|
||||
@@ -152,7 +152,6 @@ void *bioProcessBackgroundJobs(void *arg) {
|
||||
* receive the watchdog signal. */
|
||||
sigemptyset(&sigset);
|
||||
sigaddset(&sigset, SIGALRM);
|
||||
sigaddset(&sigset, SIGCHLD);
|
||||
if (pthread_sigmask(SIG_BLOCK, &sigset, NULL))
|
||||
redisLog(REDIS_WARNING,
|
||||
"Warning: can't mask SIGALRM in bio.c thread: %s", strerror(errno));
|
||||
|
||||
+18
-32
@@ -70,19 +70,16 @@ size_t redisPopcount(void *s, long count) {
|
||||
count--;
|
||||
}
|
||||
|
||||
/* Count bits 28 bytes at a time */
|
||||
/* Count bits 16 bytes at a time */
|
||||
p4 = (uint32_t*)p;
|
||||
while(count>=28) {
|
||||
uint32_t aux1, aux2, aux3, aux4, aux5, aux6, aux7;
|
||||
while(count>=16) {
|
||||
uint32_t aux1, aux2, aux3, aux4;
|
||||
|
||||
aux1 = *p4++;
|
||||
aux2 = *p4++;
|
||||
aux3 = *p4++;
|
||||
aux4 = *p4++;
|
||||
aux5 = *p4++;
|
||||
aux6 = *p4++;
|
||||
aux7 = *p4++;
|
||||
count -= 28;
|
||||
count -= 16;
|
||||
|
||||
aux1 = aux1 - ((aux1 >> 1) & 0x55555555);
|
||||
aux1 = (aux1 & 0x33333333) + ((aux1 >> 2) & 0x33333333);
|
||||
@@ -92,19 +89,10 @@ size_t redisPopcount(void *s, long count) {
|
||||
aux3 = (aux3 & 0x33333333) + ((aux3 >> 2) & 0x33333333);
|
||||
aux4 = aux4 - ((aux4 >> 1) & 0x55555555);
|
||||
aux4 = (aux4 & 0x33333333) + ((aux4 >> 2) & 0x33333333);
|
||||
aux5 = aux5 - ((aux5 >> 1) & 0x55555555);
|
||||
aux5 = (aux5 & 0x33333333) + ((aux5 >> 2) & 0x33333333);
|
||||
aux6 = aux6 - ((aux6 >> 1) & 0x55555555);
|
||||
aux6 = (aux6 & 0x33333333) + ((aux6 >> 2) & 0x33333333);
|
||||
aux7 = aux7 - ((aux7 >> 1) & 0x55555555);
|
||||
aux7 = (aux7 & 0x33333333) + ((aux7 >> 2) & 0x33333333);
|
||||
bits += ((((aux1 + (aux1 >> 4)) & 0x0F0F0F0F) +
|
||||
((aux2 + (aux2 >> 4)) & 0x0F0F0F0F) +
|
||||
((aux3 + (aux3 >> 4)) & 0x0F0F0F0F) +
|
||||
((aux4 + (aux4 >> 4)) & 0x0F0F0F0F) +
|
||||
((aux5 + (aux5 >> 4)) & 0x0F0F0F0F) +
|
||||
((aux6 + (aux6 >> 4)) & 0x0F0F0F0F) +
|
||||
((aux7 + (aux7 >> 4)) & 0x0F0F0F0F))* 0x01010101) >> 24;
|
||||
bits += ((((aux1 + (aux1 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24) +
|
||||
((((aux2 + (aux2 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24) +
|
||||
((((aux3 + (aux3 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24) +
|
||||
((((aux4 + (aux4 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24);
|
||||
}
|
||||
/* Count the remaining bytes. */
|
||||
p = (unsigned char*)p4;
|
||||
@@ -119,12 +107,12 @@ 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(void *s, long count, int bit) {
|
||||
unsigned long *l;
|
||||
unsigned char *c;
|
||||
unsigned long skipval, word = 0, one;
|
||||
long pos = 0; /* Position of bit, to return to the caller. */
|
||||
unsigned long j;
|
||||
int j;
|
||||
|
||||
/* Process whole words first, seeking for first word that is not
|
||||
* all ones or all zeros respectively if we are lookig for zeros
|
||||
@@ -288,12 +276,11 @@ void getbitCommand(redisClient *c) {
|
||||
void bitopCommand(redisClient *c) {
|
||||
char *opname = c->argv[1]->ptr;
|
||||
robj *o, *targetkey = c->argv[2];
|
||||
unsigned long op, j, numkeys;
|
||||
long op, j, numkeys;
|
||||
robj **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. */
|
||||
unsigned long minlen = 0; /* Min len among the input keys. */
|
||||
long *len, maxlen = 0; /* Array of length of src strings, and max len. */
|
||||
long minlen = 0; /* Min len among the input keys. */
|
||||
unsigned char *res = NULL; /* Resulting string. */
|
||||
|
||||
/* Parse the operation name. */
|
||||
@@ -333,10 +320,9 @@ void bitopCommand(redisClient *c) {
|
||||
}
|
||||
/* Return an error if one of the keys is not a string. */
|
||||
if (checkType(c,o,REDIS_STRING)) {
|
||||
unsigned long i;
|
||||
for (i = 0; i < j; i++) {
|
||||
if (objects[i])
|
||||
decrRefCount(objects[i]);
|
||||
for (j = j-1; j >= 0; j--) {
|
||||
if (objects[j])
|
||||
decrRefCount(objects[j]);
|
||||
}
|
||||
zfree(src);
|
||||
zfree(len);
|
||||
@@ -354,13 +340,13 @@ void bitopCommand(redisClient *c) {
|
||||
if (maxlen) {
|
||||
res = (unsigned char*) sdsnewlen(NULL,maxlen);
|
||||
unsigned char output, byte;
|
||||
unsigned long i;
|
||||
long i;
|
||||
|
||||
/* 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. */
|
||||
j = 0;
|
||||
if (minlen >= sizeof(unsigned long)*4 && numkeys <= 16) {
|
||||
if (minlen && numkeys <= 16) {
|
||||
unsigned long *lp[16];
|
||||
unsigned long *lres = (unsigned long*) res;
|
||||
|
||||
|
||||
+1
-26
@@ -59,8 +59,6 @@
|
||||
* When implementing a new type of blocking opeation, the implementation
|
||||
* should modify unblockClient() and replyToBlockedClientTimedOut() in order
|
||||
* to handle the btype-specific behavior of this two functions.
|
||||
* If the blocking operation waits for certain keys to change state, the
|
||||
* clusterRedirectBlockedClientIfNeeded() function should also be updated.
|
||||
*/
|
||||
|
||||
#include "redis.h"
|
||||
@@ -116,6 +114,7 @@ void processUnblockedClients(void) {
|
||||
c = ln->value;
|
||||
listDelNode(server.unblocked_clients,ln);
|
||||
c->flags &= ~REDIS_UNBLOCKED;
|
||||
c->btype = REDIS_BLOCKED_NONE;
|
||||
|
||||
/* Process remaining data in the input buffer. */
|
||||
if (c->querybuf && sdslen(c->querybuf) > 0) {
|
||||
@@ -157,27 +156,3 @@ void replyToBlockedClientTimedOut(redisClient *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.
|
||||
*
|
||||
* The semantics is to send an -UNBLOCKED error to the client, disconnecting
|
||||
* it at the same time. */
|
||||
void disconnectAllBlockedClients(void) {
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
|
||||
listRewind(server.clients,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
redisClient *c = listNodeValue(ln);
|
||||
|
||||
if (c->flags & REDIS_BLOCKED) {
|
||||
addReplySds(c,sdsnew(
|
||||
"-UNBLOCKED force unblock from blocking operation, "
|
||||
"instance state changed (master -> slave?)\r\n"));
|
||||
unblockClient(c);
|
||||
c->flags |= REDIS_CLOSE_AFTER_REPLY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+271
-691
File diff suppressed because it is too large
Load Diff
+15
-34
@@ -11,11 +11,10 @@
|
||||
#define REDIS_CLUSTER_NAMELEN 40 /* sha1 hex length */
|
||||
#define REDIS_CLUSTER_PORT_INCR 10000 /* Cluster port = baseport + PORT_INCR */
|
||||
|
||||
/* The following defines are amount of time, sometimes expressed as
|
||||
/* The following defines are amunt of time, sometimes expressed as
|
||||
* multiplicators of the node timeout value (when ending with MULT). */
|
||||
#define REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT 15000
|
||||
#define REDIS_CLUSTER_DEFAULT_SLAVE_VALIDITY 10 /* Slave max data age factor. */
|
||||
#define REDIS_CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE 1
|
||||
#define REDIS_CLUSTER_FAIL_REPORT_VALIDITY_MULT 2 /* Fail report validity. */
|
||||
#define REDIS_CLUSTER_FAIL_UNDO_TIME_MULT 2 /* Undo fail if master is back. */
|
||||
#define REDIS_CLUSTER_FAIL_UNDO_TIME_ADD 10 /* Some additional time. */
|
||||
@@ -26,12 +25,10 @@
|
||||
|
||||
/* Redirection errors returned by getNodeByQuery(). */
|
||||
#define REDIS_CLUSTER_REDIR_NONE 0 /* Node can serve the request. */
|
||||
#define REDIS_CLUSTER_REDIR_CROSS_SLOT 1 /* -CROSSSLOT request. */
|
||||
#define REDIS_CLUSTER_REDIR_UNSTABLE 2 /* -TRYAGAIN redirection required */
|
||||
#define REDIS_CLUSTER_REDIR_CROSS_SLOT 1 /* Keys in different slots. */
|
||||
#define REDIS_CLUSTER_REDIR_UNSTABLE 2 /* Keys in slot resharding. */
|
||||
#define REDIS_CLUSTER_REDIR_ASK 3 /* -ASK redirection required. */
|
||||
#define REDIS_CLUSTER_REDIR_MOVED 4 /* -MOVED redirection required. */
|
||||
#define REDIS_CLUSTER_REDIR_DOWN_STATE 5 /* -CLUSTERDOWN, global state. */
|
||||
#define REDIS_CLUSTER_REDIR_DOWN_UNBOUND 6 /* -CLUSTERDOWN, unbound slot. */
|
||||
|
||||
struct clusterNode;
|
||||
|
||||
@@ -53,7 +50,7 @@ typedef struct clusterLink {
|
||||
#define REDIS_NODE_HANDSHAKE 32 /* We have still to exchange the first ping */
|
||||
#define REDIS_NODE_NOADDR 64 /* We don't know the address of this node */
|
||||
#define REDIS_NODE_MEET 128 /* Send a MEET message to this node */
|
||||
#define REDIS_NODE_PROMOTED 256 /* Master was a slave promoted by failover */
|
||||
#define REDIS_NODE_PROMOTED 256 /* Master was a slave propoted by failover */
|
||||
#define REDIS_NODE_NULL_NAME "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
|
||||
|
||||
#define nodeIsMaster(n) ((n)->flags & REDIS_NODE_MASTER)
|
||||
@@ -64,21 +61,13 @@ typedef struct clusterLink {
|
||||
#define nodeTimedOut(n) ((n)->flags & REDIS_NODE_PFAIL)
|
||||
#define nodeFailed(n) ((n)->flags & REDIS_NODE_FAIL)
|
||||
|
||||
/* Reasons why a slave is not able to failover. */
|
||||
#define REDIS_CLUSTER_CANT_FAILOVER_NONE 0
|
||||
#define REDIS_CLUSTER_CANT_FAILOVER_DATA_AGE 1
|
||||
#define REDIS_CLUSTER_CANT_FAILOVER_WAITING_DELAY 2
|
||||
#define REDIS_CLUSTER_CANT_FAILOVER_EXPIRED 3
|
||||
#define REDIS_CLUSTER_CANT_FAILOVER_WAITING_VOTES 4
|
||||
#define REDIS_CLUSTER_CANT_FAILOVER_RELOG_PERIOD (60*5) /* seconds. */
|
||||
|
||||
/* This structure represent elements of node->fail_reports. */
|
||||
typedef struct clusterNodeFailReport {
|
||||
struct clusterNodeFailReport {
|
||||
struct clusterNode *node; /* Node reporting the failure condition. */
|
||||
mstime_t time; /* Time of the last report from this node. */
|
||||
} clusterNodeFailReport;
|
||||
} typedef clusterNodeFailReport;
|
||||
|
||||
typedef struct clusterNode {
|
||||
struct clusterNode {
|
||||
mstime_t ctime; /* Node object creation time. */
|
||||
char name[REDIS_CLUSTER_NAMELEN]; /* Node name, hex string, sha1-size */
|
||||
int flags; /* REDIS_NODE_... */
|
||||
@@ -98,7 +87,8 @@ typedef struct clusterNode {
|
||||
int port; /* Latest known port of this node */
|
||||
clusterLink *link; /* TCP/IP link with this node */
|
||||
list *fail_reports; /* List of nodes signaling this as failing */
|
||||
} clusterNode;
|
||||
};
|
||||
typedef struct clusterNode clusterNode;
|
||||
|
||||
typedef struct clusterState {
|
||||
clusterNode *myself; /* This node */
|
||||
@@ -117,8 +107,6 @@ typedef struct clusterState {
|
||||
int failover_auth_sent; /* True if we already asked for votes. */
|
||||
int failover_auth_rank; /* This slave rank for current auth request. */
|
||||
uint64_t failover_auth_epoch; /* Epoch of the current election. */
|
||||
int cant_failover_reason; /* Why a slave is currently not able to
|
||||
failover. See the CANT_FAILOVER_* macros. */
|
||||
/* Manual failover state in common. */
|
||||
mstime_t mf_end; /* Manual failover time limit (ms unixtime).
|
||||
It is zero if there is no MF in progress. */
|
||||
@@ -129,7 +117,7 @@ typedef struct clusterState {
|
||||
or zero if stil not received. */
|
||||
int mf_can_start; /* If non-zero signal that the manual failover
|
||||
can start requesting masters vote. */
|
||||
/* The followign fields are used by masters to take state on elections. */
|
||||
/* The followign fields are uesd by masters to take state on elections. */
|
||||
uint64_t lastVoteEpoch; /* Epoch of the last vote granted. */
|
||||
int todo_before_sleep; /* Things to do in clusterBeforeSleep(). */
|
||||
long long stats_bus_messages_sent; /* Num of msg sent via cluster bus. */
|
||||
@@ -165,11 +153,10 @@ typedef struct {
|
||||
char nodename[REDIS_CLUSTER_NAMELEN];
|
||||
uint32_t ping_sent;
|
||||
uint32_t pong_received;
|
||||
char ip[REDIS_IP_STR_LEN]; /* IP address last time it was seen */
|
||||
uint16_t port; /* port last time it was seen */
|
||||
uint16_t flags; /* node->flags copy */
|
||||
uint16_t notused1; /* Some room for future improvements. */
|
||||
uint32_t notused2;
|
||||
char ip[REDIS_IP_STR_LEN]; /* IP address last time it was seen */
|
||||
uint16_t port; /* port last time it was seen */
|
||||
uint16_t flags;
|
||||
uint32_t notused; /* for 64 bit alignment */
|
||||
} clusterMsgDataGossip;
|
||||
|
||||
typedef struct {
|
||||
@@ -179,10 +166,7 @@ typedef struct {
|
||||
typedef struct {
|
||||
uint32_t channel_len;
|
||||
uint32_t message_len;
|
||||
/* We can't reclare bulk_data as bulk_data[] since this structure is
|
||||
* nested. The 8 bytes are removed from the count during the message
|
||||
* length computation. */
|
||||
unsigned char bulk_data[8];
|
||||
unsigned char bulk_data[8]; /* defined as 8 just for alignment concerns. */
|
||||
} clusterMsgDataPublish;
|
||||
|
||||
typedef struct {
|
||||
@@ -214,7 +198,6 @@ union clusterMsgData {
|
||||
} update;
|
||||
};
|
||||
|
||||
#define CLUSTER_PROTO_VER 0 /* Cluster bus protocol version. */
|
||||
|
||||
typedef struct {
|
||||
char sig[4]; /* Siganture "RCmb" (Redis Cluster message bus). */
|
||||
@@ -250,7 +233,5 @@ typedef struct {
|
||||
|
||||
/* ---------------------- API exported outside cluster.c -------------------- */
|
||||
clusterNode *getNodeByQuery(redisClient *c, struct redisCommand *cmd, robj **argv, int argc, int *hashslot, int *ask);
|
||||
int clusterRedirectBlockedClientIfNeeded(redisClient *c);
|
||||
void clusterRedirectClient(redisClient *c, clusterNode *n, int hashslot, int error_code);
|
||||
|
||||
#endif /* __REDIS_CLUSTER_H */
|
||||
|
||||
+12
-70
@@ -73,7 +73,7 @@ void appendServerSaveParams(time_t seconds, int changes) {
|
||||
server.saveparamslen++;
|
||||
}
|
||||
|
||||
void resetServerSaveParams(void) {
|
||||
void resetServerSaveParams() {
|
||||
zfree(server.saveparams);
|
||||
server.saveparams = NULL;
|
||||
server.saveparamslen = 0;
|
||||
@@ -270,16 +270,6 @@ void loadServerConfigFromString(char *config) {
|
||||
if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) {
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"repl-diskless-sync") && argc==2) {
|
||||
if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) {
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"repl-diskless-sync-delay") && argc==2) {
|
||||
server.repl_diskless_sync_delay = atoi(argv[1]);
|
||||
if (server.repl_diskless_sync_delay < 0) {
|
||||
err = "repl-diskless-sync-delay can't be negative";
|
||||
goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) {
|
||||
long long size = memtoll(argv[1],NULL);
|
||||
if (size <= 0) {
|
||||
@@ -294,7 +284,7 @@ void loadServerConfigFromString(char *config) {
|
||||
goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"masterauth") && argc == 2) {
|
||||
server.masterauth = zstrdup(argv[1]);
|
||||
server.masterauth = zstrdup(argv[1]);
|
||||
} else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) {
|
||||
if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) {
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
@@ -368,12 +358,7 @@ void loadServerConfigFromString(char *config) {
|
||||
} else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") &&
|
||||
argc == 2)
|
||||
{
|
||||
if ((server.aof_rewrite_incremental_fsync =
|
||||
yesnotoi(argv[1])) == -1) {
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"aof-load-truncated") && argc == 2) {
|
||||
if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) {
|
||||
if ((server.aof_rewrite_incremental_fsync = yesnotoi(argv[1])) == -1) {
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"requirepass") && argc == 2) {
|
||||
@@ -439,13 +424,6 @@ void loadServerConfigFromString(char *config) {
|
||||
} else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) {
|
||||
zfree(server.cluster_configfile);
|
||||
server.cluster_configfile = zstrdup(argv[1]);
|
||||
} else if (!strcasecmp(argv[0],"cluster-require-full-coverage") &&
|
||||
argc == 2)
|
||||
{
|
||||
if ((server.cluster_require_full_coverage = yesnotoi(argv[1])) == -1)
|
||||
{
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) {
|
||||
server.cluster_node_timeout = strtoll(argv[1],NULL,10);
|
||||
if (server.cluster_node_timeout <= 0) {
|
||||
@@ -609,7 +587,6 @@ void loadServerConfig(char *filename, char *options) {
|
||||
void configSetCommand(redisClient *c) {
|
||||
robj *o;
|
||||
long long ll;
|
||||
int err;
|
||||
redisAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2]));
|
||||
redisAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3]));
|
||||
o = c->argv[3];
|
||||
@@ -629,8 +606,8 @@ void configSetCommand(redisClient *c) {
|
||||
zfree(server.masterauth);
|
||||
server.masterauth = ((char*)o->ptr)[0] ? zstrdup(o->ptr) : NULL;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"maxmemory")) {
|
||||
ll = memtoll(o->ptr,&err);
|
||||
if (err || ll < 0) goto badfmt;
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
|
||||
ll < 0) goto badfmt;
|
||||
server.maxmemory = ll;
|
||||
if (server.maxmemory) {
|
||||
if (server.maxmemory < zmalloc_used_memory()) {
|
||||
@@ -652,7 +629,7 @@ void configSetCommand(redisClient *c) {
|
||||
server.maxclients = orig_value;
|
||||
return;
|
||||
}
|
||||
if ((unsigned int) aeGetSetSize(server.el) <
|
||||
if (aeGetSetSize(server.el) <
|
||||
server.maxclients + REDIS_EVENTLOOP_FDSET_INCR)
|
||||
{
|
||||
if (aeResizeSetSize(server.el,
|
||||
@@ -736,11 +713,6 @@ void configSetCommand(redisClient *c) {
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.aof_rewrite_incremental_fsync = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"aof-load-truncated")) {
|
||||
int yn = yesnotoi(o->ptr);
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.aof_load_truncated = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"save")) {
|
||||
int vlen, j;
|
||||
sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen);
|
||||
@@ -785,11 +757,6 @@ void configSetCommand(redisClient *c) {
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.repl_slave_ro = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"activerehashing")) {
|
||||
int yn = yesnotoi(o->ptr);
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.activerehashing = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"dir")) {
|
||||
if (chdir((char*)o->ptr) == -1) {
|
||||
addReplyErrorFormat(c,"Changing directory: %s", strerror(errno));
|
||||
@@ -857,6 +824,7 @@ void configSetCommand(redisClient *c) {
|
||||
* whole configuration string or accept it all, even if a single
|
||||
* error in a single client class is present. */
|
||||
for (j = 0; j < vlen; j++) {
|
||||
char *eptr;
|
||||
long val;
|
||||
|
||||
if ((j % 4) == 0) {
|
||||
@@ -865,8 +833,8 @@ void configSetCommand(redisClient *c) {
|
||||
goto badfmt;
|
||||
}
|
||||
} else {
|
||||
val = memtoll(v[j], &err);
|
||||
if (err || val < 0) {
|
||||
val = strtoll(v[j], &eptr, 10);
|
||||
if (eptr[0] != '\0' || val < 0) {
|
||||
sdsfreesplitres(v,vlen);
|
||||
goto badfmt;
|
||||
}
|
||||
@@ -900,8 +868,7 @@ void configSetCommand(redisClient *c) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
|
||||
server.repl_timeout = ll;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-size")) {
|
||||
ll = memtoll(o->ptr,&err);
|
||||
if (err || ll < 0) goto badfmt;
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll <= 0) goto badfmt;
|
||||
resizeReplicationBacklog(ll);
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"repl-backlog-ttl")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
|
||||
@@ -927,15 +894,6 @@ void configSetCommand(redisClient *c) {
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.repl_disable_tcp_nodelay = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"repl-diskless-sync")) {
|
||||
int yn = yesnotoi(o->ptr);
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.repl_diskless_sync = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"repl-diskless-sync-delay")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
|
||||
ll < 0) goto badfmt;
|
||||
server.repl_diskless_sync_delay = ll;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"slave-priority")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
|
||||
ll < 0) goto badfmt;
|
||||
@@ -950,11 +908,6 @@ void configSetCommand(redisClient *c) {
|
||||
ll < 0) goto badfmt;
|
||||
server.repl_min_slaves_max_lag = ll;
|
||||
refreshGoodSlavesCount();
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"cluster-require-full-coverage")) {
|
||||
int yn = yesnotoi(o->ptr);
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.cluster_require_full_coverage = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"cluster-node-timeout")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR ||
|
||||
ll <= 0) goto badfmt;
|
||||
@@ -1074,11 +1027,8 @@ void configGetCommand(redisClient *c) {
|
||||
config_get_numerical_field("cluster-node-timeout",server.cluster_node_timeout);
|
||||
config_get_numerical_field("cluster-migration-barrier",server.cluster_migration_barrier);
|
||||
config_get_numerical_field("cluster-slave-validity-factor",server.cluster_slave_validity_factor);
|
||||
config_get_numerical_field("repl-diskless-sync-delay",server.repl_diskless_sync_delay);
|
||||
|
||||
/* Bool (yes/no) values */
|
||||
config_get_bool_field("cluster-require-full-coverage",
|
||||
server.cluster_require_full_coverage);
|
||||
config_get_bool_field("no-appendfsync-on-rewrite",
|
||||
server.aof_no_fsync_on_rewrite);
|
||||
config_get_bool_field("slave-serve-stale-data",
|
||||
@@ -1093,12 +1043,8 @@ void configGetCommand(redisClient *c) {
|
||||
config_get_bool_field("activerehashing", server.activerehashing);
|
||||
config_get_bool_field("repl-disable-tcp-nodelay",
|
||||
server.repl_disable_tcp_nodelay);
|
||||
config_get_bool_field("repl-diskless-sync",
|
||||
server.repl_diskless_sync);
|
||||
config_get_bool_field("aof-rewrite-incremental-fsync",
|
||||
server.aof_rewrite_incremental_fsync);
|
||||
config_get_bool_field("aof-load-truncated",
|
||||
server.aof_load_truncated);
|
||||
|
||||
/* Everything we can't handle with macros follows. */
|
||||
|
||||
@@ -1469,7 +1415,7 @@ void rewriteConfigStringOption(struct rewriteConfigState *state, char *option, c
|
||||
return;
|
||||
}
|
||||
|
||||
/* Set force to zero if the value is set to its default. */
|
||||
/* Compare the strings as sds strings to have a binary safe comparison. */
|
||||
if (defvalue && strcmp(value,defvalue) == 0) force = 0;
|
||||
|
||||
line = sdsnew(option);
|
||||
@@ -1521,7 +1467,7 @@ void rewriteConfigEnumOption(struct rewriteConfigState *state, char *option, int
|
||||
rewriteConfigRewriteLine(state,option,line,force);
|
||||
}
|
||||
|
||||
/* Rewrite the syslog-facility option. */
|
||||
/* Rewrite the syslog-fability option. */
|
||||
void rewriteConfigSyslogfacilityOption(struct rewriteConfigState *state) {
|
||||
int value = server.syslog_facility, j;
|
||||
int force = value != LOG_LOCAL0;
|
||||
@@ -1820,8 +1766,6 @@ int rewriteConfig(char *path) {
|
||||
rewriteConfigBytesOption(state,"repl-backlog-size",server.repl_backlog_size,REDIS_DEFAULT_REPL_BACKLOG_SIZE);
|
||||
rewriteConfigBytesOption(state,"repl-backlog-ttl",server.repl_backlog_time_limit,REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT);
|
||||
rewriteConfigYesNoOption(state,"repl-disable-tcp-nodelay",server.repl_disable_tcp_nodelay,REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY);
|
||||
rewriteConfigYesNoOption(state,"repl-diskless-sync",server.repl_diskless_sync,REDIS_DEFAULT_REPL_DISKLESS_SYNC);
|
||||
rewriteConfigNumericalOption(state,"repl-diskless-sync-delay",server.repl_diskless_sync_delay,REDIS_DEFAULT_REPL_DISKLESS_SYNC_DELAY);
|
||||
rewriteConfigNumericalOption(state,"slave-priority",server.slave_priority,REDIS_DEFAULT_SLAVE_PRIORITY);
|
||||
rewriteConfigNumericalOption(state,"min-slaves-to-write",server.repl_min_slaves_to_write,REDIS_DEFAULT_MIN_SLAVES_TO_WRITE);
|
||||
rewriteConfigNumericalOption(state,"min-slaves-max-lag",server.repl_min_slaves_max_lag,REDIS_DEFAULT_MIN_SLAVES_MAX_LAG);
|
||||
@@ -1850,7 +1794,6 @@ int rewriteConfig(char *path) {
|
||||
rewriteConfigNumericalOption(state,"lua-time-limit",server.lua_time_limit,REDIS_LUA_TIME_LIMIT);
|
||||
rewriteConfigYesNoOption(state,"cluster-enabled",server.cluster_enabled,0);
|
||||
rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,REDIS_DEFAULT_CLUSTER_CONFIG_FILE);
|
||||
rewriteConfigYesNoOption(state,"cluster-require-full-coverage",server.cluster_require_full_coverage,REDIS_CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE);
|
||||
rewriteConfigNumericalOption(state,"cluster-node-timeout",server.cluster_node_timeout,REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT);
|
||||
rewriteConfigNumericalOption(state,"cluster-migration-barrier",server.cluster_migration_barrier,REDIS_CLUSTER_DEFAULT_MIGRATION_BARRIER);
|
||||
rewriteConfigNumericalOption(state,"cluster-slave-validity-factor",server.cluster_slave_validity_factor,REDIS_CLUSTER_DEFAULT_SLAVE_VALIDITY);
|
||||
@@ -1870,7 +1813,6 @@ int rewriteConfig(char *path) {
|
||||
rewriteConfigClientoutputbufferlimitOption(state);
|
||||
rewriteConfigNumericalOption(state,"hz",server.hz,REDIS_DEFAULT_HZ);
|
||||
rewriteConfigYesNoOption(state,"aof-rewrite-incremental-fsync",server.aof_rewrite_incremental_fsync,REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC);
|
||||
rewriteConfigYesNoOption(state,"aof-load-truncated",server.aof_load_truncated,REDIS_DEFAULT_AOF_LOAD_TRUNCATED);
|
||||
if (server.sentinel_mode) rewriteConfigSentinelOption(state);
|
||||
|
||||
/* Step 3: remove all the orphaned lines in the old file, that is, lines
|
||||
|
||||
+5
-14
@@ -34,11 +34,6 @@
|
||||
#include <AvailabilityMacros.h>
|
||||
#endif
|
||||
|
||||
#ifdef __linux__
|
||||
#include <linux/version.h>
|
||||
#include <features.h>
|
||||
#endif
|
||||
|
||||
/* Define redis_fstat to fstat or fstat64() */
|
||||
#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
|
||||
#define redis_fstat fstat64
|
||||
@@ -53,7 +48,6 @@
|
||||
#define HAVE_PROC_STAT 1
|
||||
#define HAVE_PROC_MAPS 1
|
||||
#define HAVE_PROC_SMAPS 1
|
||||
#define HAVE_PROC_SOMAXCONN 1
|
||||
#endif
|
||||
|
||||
/* Test for task_info() */
|
||||
@@ -62,7 +56,7 @@
|
||||
#endif
|
||||
|
||||
/* Test for backtrace() */
|
||||
#if defined(__APPLE__) || (defined(__linux__) && defined(__GLIBC__))
|
||||
#if defined(__APPLE__) || defined(__linux__)
|
||||
#define HAVE_BACKTRACE 1
|
||||
#endif
|
||||
|
||||
@@ -92,6 +86,8 @@
|
||||
/* Define rdb_fsync_range to sync_file_range() on Linux, otherwise we use
|
||||
* the plain fsync() call. */
|
||||
#ifdef __linux__
|
||||
#include <linux/version.h>
|
||||
#include <features.h>
|
||||
#if defined(__GLIBC__) && defined(__GLIBC_PREREQ)
|
||||
#if (LINUX_VERSION_CODE >= 0x020611 && __GLIBC_PREREQ(2, 6))
|
||||
#define HAVE_SYNC_FILE_RANGE 1
|
||||
@@ -116,7 +112,7 @@
|
||||
#define USE_SETPROCTITLE
|
||||
#endif
|
||||
|
||||
#if ((defined __linux && defined(__GLIBC__)) || defined __APPLE__)
|
||||
#if (defined __linux || defined __APPLE__)
|
||||
#define USE_SETPROCTITLE
|
||||
#define INIT_SETPROCTITLE_REPLACEMENT
|
||||
void spt_init(int argc, char *argv[]);
|
||||
@@ -191,14 +187,9 @@ void setproctitle(const char *fmt, ...);
|
||||
|
||||
#if (__i386 || __amd64 || __powerpc__) && __GNUC__
|
||||
#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
|
||||
#if defined(__clang__)
|
||||
#if (GNUC_VERSION >= 40100) || defined(__clang__)
|
||||
#define HAVE_ATOMIC
|
||||
#endif
|
||||
#if (defined(__GLIBC__) && defined(__GLIBC_PREREQ))
|
||||
#if (GNUC_VERSION >= 40100 && __GLIBC_PREREQ(2, 6))
|
||||
#define HAVE_ATOMIC
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
@@ -293,17 +293,13 @@ void delCommand(redisClient *c) {
|
||||
addReplyLongLong(c,deleted);
|
||||
}
|
||||
|
||||
/* EXISTS key1 key2 ... key_N.
|
||||
* Return value is the number of keys existing. */
|
||||
void existsCommand(redisClient *c) {
|
||||
long long count = 0;
|
||||
int j;
|
||||
|
||||
for (j = 1; j < c->argc; j++) {
|
||||
expireIfNeeded(c->db,c->argv[j]);
|
||||
if (dbExists(c->db,c->argv[j])) count++;
|
||||
expireIfNeeded(c->db,c->argv[1]);
|
||||
if (dbExists(c->db,c->argv[1])) {
|
||||
addReply(c, shared.cone);
|
||||
} else {
|
||||
addReply(c, shared.czero);
|
||||
}
|
||||
addReplyLongLong(c,count);
|
||||
}
|
||||
|
||||
void selectCommand(redisClient *c) {
|
||||
@@ -385,7 +381,7 @@ void scanCallback(void *privdata, const dictEntry *de) {
|
||||
} else if (o->type == REDIS_ZSET) {
|
||||
key = dictGetKey(de);
|
||||
incrRefCount(key);
|
||||
val = createStringObjectFromLongDouble(*(double*)dictGetVal(de),0);
|
||||
val = createStringObjectFromLongDouble(*(double*)dictGetVal(de));
|
||||
} else {
|
||||
redisPanic("Type not handled in SCAN callback.");
|
||||
}
|
||||
@@ -425,7 +421,9 @@ int parseScanCursorOrReply(redisClient *c, robj *o, unsigned long *cursor) {
|
||||
* In the case of a Hash object the function returns both the field and value
|
||||
* of every element on the Hash. */
|
||||
void scanGenericCommand(redisClient *c, robj *o, unsigned long cursor) {
|
||||
int rv;
|
||||
int i, j;
|
||||
char buf[REDIS_LONGSTR_SIZE];
|
||||
list *keys = listCreate();
|
||||
listNode *node, *nextnode;
|
||||
long count = 10;
|
||||
@@ -497,11 +495,6 @@ void scanGenericCommand(redisClient *c, robj *o, unsigned long cursor) {
|
||||
|
||||
if (ht) {
|
||||
void *privdata[2];
|
||||
/* We set the max number of iterations to ten times the specified
|
||||
* COUNT, so if the hash table is in a pathological state (very
|
||||
* sparsely populated) we avoid to block too much time at the cost
|
||||
* of returning no or very few elements. */
|
||||
long maxiterations = count*10;
|
||||
|
||||
/* We pass two pointers to the callback: the list to which it will
|
||||
* add new elements, and the object containing the dictionary so that
|
||||
@@ -510,9 +503,7 @@ void scanGenericCommand(redisClient *c, robj *o, unsigned long cursor) {
|
||||
privdata[1] = o;
|
||||
do {
|
||||
cursor = dictScan(ht, cursor, scanCallback, privdata);
|
||||
} while (cursor &&
|
||||
maxiterations-- &&
|
||||
listLength(keys) < (unsigned long)count);
|
||||
} while (cursor && listLength(keys) < count);
|
||||
} else if (o->type == REDIS_SET) {
|
||||
int pos = 0;
|
||||
int64_t ll;
|
||||
@@ -586,7 +577,9 @@ void scanGenericCommand(redisClient *c, robj *o, unsigned long cursor) {
|
||||
|
||||
/* Step 4: Reply to the client. */
|
||||
addReplyMultiBulkLen(c, 2);
|
||||
addReplyBulkLongLong(c,cursor);
|
||||
rv = snprintf(buf, sizeof(buf), "%lu", cursor);
|
||||
redisAssert(rv < sizeof(buf));
|
||||
addReplyBulkCBuffer(c, buf, rv);
|
||||
|
||||
addReplyMultiBulkLen(c, listLength(keys));
|
||||
while ((node = listFirst(keys)) != NULL) {
|
||||
@@ -714,7 +707,6 @@ void moveCommand(redisClient *c) {
|
||||
robj *o;
|
||||
redisDb *src, *dst;
|
||||
int srcid;
|
||||
long long dbid, expire;
|
||||
|
||||
if (server.cluster_enabled) {
|
||||
addReplyError(c,"MOVE is not allowed in cluster mode");
|
||||
@@ -724,11 +716,7 @@ void moveCommand(redisClient *c) {
|
||||
/* Obtain source and target DB pointers */
|
||||
src = c->db;
|
||||
srcid = c->db->id;
|
||||
|
||||
if (getLongLongFromObject(c->argv[2],&dbid) == REDIS_ERR ||
|
||||
dbid < INT_MIN || dbid > INT_MAX ||
|
||||
selectDb(c,dbid) == REDIS_ERR)
|
||||
{
|
||||
if (selectDb(c,atoi(c->argv[2]->ptr)) == REDIS_ERR) {
|
||||
addReply(c,shared.outofrangeerr);
|
||||
return;
|
||||
}
|
||||
@@ -748,7 +736,6 @@ void moveCommand(redisClient *c) {
|
||||
addReply(c,shared.czero);
|
||||
return;
|
||||
}
|
||||
expire = getExpire(c->db,c->argv[1]);
|
||||
|
||||
/* Return zero if the key already exists in the target DB */
|
||||
if (lookupKeyWrite(dst,c->argv[1]) != NULL) {
|
||||
@@ -756,7 +743,6 @@ void moveCommand(redisClient *c) {
|
||||
return;
|
||||
}
|
||||
dbAdd(dst,c->argv[1],o);
|
||||
if (expire != -1) setExpire(dst,c->argv[1],expire);
|
||||
incrRefCount(o);
|
||||
|
||||
/* OK! key moved, free the entry in the source DB */
|
||||
@@ -1090,7 +1076,7 @@ int *evalGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys)
|
||||
* follow in SQL-alike style. Here we parse just the minimum in order to
|
||||
* correctly identify keys in the "STORE" option. */
|
||||
int *sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys) {
|
||||
int i, j, num, *keys, found_store = 0;
|
||||
int i, j, num, *keys;
|
||||
REDIS_NOTUSED(cmd);
|
||||
|
||||
num = 0;
|
||||
@@ -1121,13 +1107,12 @@ int *sortGetKeys(struct redisCommand *cmd, robj **argv, int argc, int *numkeys)
|
||||
/* Note: we don't increment "num" here and continue the loop
|
||||
* to be sure to process the *last* "STORE" option if multiple
|
||||
* ones are provided. This is same behavior as SORT. */
|
||||
found_store = 1;
|
||||
keys[num] = i+1; /* <store-key> */
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
*numkeys = num + found_store;
|
||||
*numkeys = num;
|
||||
return keys;
|
||||
}
|
||||
|
||||
|
||||
+4
-6
@@ -301,7 +301,7 @@ void debugCommand(redisClient *c) {
|
||||
"lru:%d lru_seconds_idle:%llu",
|
||||
(void*)val, val->refcount,
|
||||
strenc, (long long) rdbSavedObjectLen(val),
|
||||
val->lru, estimateObjectIdleTime(val)/1000);
|
||||
val->lru, estimateObjectIdleTime(val));
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"sdslen") && c->argc == 3) {
|
||||
dictEntry *de;
|
||||
robj *val;
|
||||
@@ -325,8 +325,7 @@ void debugCommand(redisClient *c) {
|
||||
(long long) sdslen(val->ptr),
|
||||
(long long) sdsavail(val->ptr));
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"populate") &&
|
||||
(c->argc == 3 || c->argc == 4)) {
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"populate") && c->argc == 3) {
|
||||
long keys, j;
|
||||
robj *key, *val;
|
||||
char buf[128];
|
||||
@@ -335,8 +334,7 @@ void debugCommand(redisClient *c) {
|
||||
return;
|
||||
dictExpand(c->db->dict,keys);
|
||||
for (j = 0; j < keys; j++) {
|
||||
snprintf(buf,sizeof(buf),"%s:%lu",
|
||||
(c->argc == 3) ? "key" : (char*)c->argv[3]->ptr, j);
|
||||
snprintf(buf,sizeof(buf),"key:%lu",j);
|
||||
key = createStringObject(buf,strlen(buf));
|
||||
if (lookupKeyRead(c->db,key) != NULL) {
|
||||
decrRefCount(key);
|
||||
@@ -852,7 +850,7 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
|
||||
redisLog(REDIS_WARNING,
|
||||
"\n=== REDIS 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"
|
||||
" Please report the crash opening an issue on github:\n\n"
|
||||
" http://github.com/antirez/redis/issues\n\n"
|
||||
" Suspect RAM error? Use redis-server --test-memory to verify it.\n\n"
|
||||
);
|
||||
|
||||
+74
-123
@@ -79,6 +79,12 @@ unsigned int dictIntHashFunction(unsigned int key)
|
||||
return key;
|
||||
}
|
||||
|
||||
/* Identity hash function for integer keys */
|
||||
unsigned int dictIdentityHashFunction(unsigned int key)
|
||||
{
|
||||
return key;
|
||||
}
|
||||
|
||||
static uint32_t dict_hash_function_seed = 5381;
|
||||
|
||||
void dictSetHashFunctionSeed(uint32_t seed) {
|
||||
@@ -211,9 +217,6 @@ int dictExpand(dict *d, unsigned long size)
|
||||
if (dictIsRehashing(d) || d->ht[0].used > size)
|
||||
return DICT_ERR;
|
||||
|
||||
/* Rehashing to the same table size is not useful. */
|
||||
if (realsize == d->ht[0].size) return DICT_ERR;
|
||||
|
||||
/* Allocate the new hash table and initialize all pointers to NULL */
|
||||
n.size = realsize;
|
||||
n.sizemask = realsize-1;
|
||||
@@ -235,27 +238,27 @@ int dictExpand(dict *d, unsigned long size)
|
||||
|
||||
/* Performs N steps of incremental rehashing. Returns 1 if there are still
|
||||
* keys to move from the old to the new hash table, otherwise 0 is returned.
|
||||
*
|
||||
* Note that a rehashing step consists in moving a bucket (that may have more
|
||||
* than one key as we use chaining) from the old to the new hash table, however
|
||||
* since part of the hash table may be composed of empty spaces, it is not
|
||||
* guaranteed that this function will rehash even a single bucket, since it
|
||||
* will visit at max N*10 empty buckets in total, otherwise the amount of
|
||||
* work it does would be unbound and the function may block for a long time. */
|
||||
* than one key as we use chaining) from the old to the new hash table. */
|
||||
int dictRehash(dict *d, int n) {
|
||||
int empty_visits = n*10; /* Max number of empty buckets to visit. */
|
||||
if (!dictIsRehashing(d)) return 0;
|
||||
|
||||
while(n-- && d->ht[0].used != 0) {
|
||||
while(n--) {
|
||||
dictEntry *de, *nextde;
|
||||
|
||||
/* Check if we already rehashed the whole table... */
|
||||
if (d->ht[0].used == 0) {
|
||||
zfree(d->ht[0].table);
|
||||
d->ht[0] = d->ht[1];
|
||||
_dictReset(&d->ht[1]);
|
||||
d->rehashidx = -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Note that rehashidx can't overflow as we are sure there are more
|
||||
* elements because ht[0].used != 0 */
|
||||
assert(d->ht[0].size > (unsigned long)d->rehashidx);
|
||||
while(d->ht[0].table[d->rehashidx] == NULL) {
|
||||
d->rehashidx++;
|
||||
if (--empty_visits == 0) return 1;
|
||||
}
|
||||
assert(d->ht[0].size > (unsigned)d->rehashidx);
|
||||
while(d->ht[0].table[d->rehashidx] == NULL) d->rehashidx++;
|
||||
de = d->ht[0].table[d->rehashidx];
|
||||
/* Move all the keys in this bucket from the old to the new hash HT */
|
||||
while(de) {
|
||||
@@ -273,17 +276,6 @@ int dictRehash(dict *d, int n) {
|
||||
d->ht[0].table[d->rehashidx] = NULL;
|
||||
d->rehashidx++;
|
||||
}
|
||||
|
||||
/* Check if we already rehashed the whole table... */
|
||||
if (d->ht[0].used == 0) {
|
||||
zfree(d->ht[0].table);
|
||||
d->ht[0] = d->ht[1];
|
||||
_dictReset(&d->ht[1]);
|
||||
d->rehashidx = -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* More to rehash... */
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -584,7 +576,7 @@ dictEntry *dictNext(dictIterator *iter)
|
||||
iter->fingerprint = dictFingerprint(iter->d);
|
||||
}
|
||||
iter->index++;
|
||||
if (iter->index >= (long) ht->size) {
|
||||
if (iter->index >= (signed) ht->size) {
|
||||
if (dictIsRehashing(iter->d) && iter->table == 0) {
|
||||
iter->table++;
|
||||
iter->index = 0;
|
||||
@@ -630,11 +622,7 @@ dictEntry *dictGetRandomKey(dict *d)
|
||||
if (dictIsRehashing(d)) _dictRehashStep(d);
|
||||
if (dictIsRehashing(d)) {
|
||||
do {
|
||||
/* We are sure there are no elements in indexes from 0
|
||||
* to rehashidx-1 */
|
||||
h = d->rehashidx + (random() % (d->ht[0].size +
|
||||
d->ht[1].size -
|
||||
d->rehashidx));
|
||||
h = random() % (d->ht[0].size+d->ht[1].size);
|
||||
he = (h >= d->ht[0].size) ? d->ht[1].table[h - d->ht[0].size] :
|
||||
d->ht[0].table[h];
|
||||
} while(he == NULL);
|
||||
@@ -661,12 +649,9 @@ dictEntry *dictGetRandomKey(dict *d)
|
||||
return he;
|
||||
}
|
||||
|
||||
/* This function samples the dictionary to return a few keys from random
|
||||
* locations.
|
||||
*
|
||||
* It does not guarantee to return all the keys specified in 'count', nor
|
||||
* it does guarantee to return non-duplicated elements, however it will make
|
||||
* some effort to do both things.
|
||||
/* This is a version of dictGetRandomKey() that is modified in order to
|
||||
* return multiple entries by jumping at a random place of the hash table
|
||||
* and scanning linearly for entries.
|
||||
*
|
||||
* Returned pointers to hash table entries are stored into 'des' that
|
||||
* points to an array of dictEntry pointers. The array must have room for
|
||||
@@ -675,65 +660,28 @@ dictEntry *dictGetRandomKey(dict *d)
|
||||
*
|
||||
* The function returns the number of items stored into 'des', that may
|
||||
* be less than 'count' if the hash table has less than 'count' elements
|
||||
* inside, or if not enough elements were found in a reasonable amount of
|
||||
* steps.
|
||||
* inside.
|
||||
*
|
||||
* Note that this function is not suitable when you need a good distribution
|
||||
* of the returned items, but only when you need to "sample" a given number
|
||||
* of continuous elements to run some kind of algorithm or to produce
|
||||
* statistics. However the function is much faster than dictGetRandomKey()
|
||||
* at producing N elements. */
|
||||
unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count) {
|
||||
unsigned int j; /* internal hash table id, 0 or 1. */
|
||||
unsigned int tables; /* 1 or 2 tables? */
|
||||
unsigned int stored = 0, maxsizemask;
|
||||
unsigned int maxsteps;
|
||||
* at producing N elements, and the elements are guaranteed to be non
|
||||
* repeating. */
|
||||
int dictGetRandomKeys(dict *d, dictEntry **des, int count) {
|
||||
int j; /* internal hash table id, 0 or 1. */
|
||||
int stored = 0;
|
||||
|
||||
if (dictSize(d) < count) count = dictSize(d);
|
||||
maxsteps = count*10;
|
||||
while(stored < count) {
|
||||
for (j = 0; j < 2; j++) {
|
||||
/* Pick a random point inside the hash table 0 or 1. */
|
||||
unsigned int i = random() & d->ht[j].sizemask;
|
||||
int size = d->ht[j].size;
|
||||
|
||||
/* Try to do a rehashing work proportional to 'count'. */
|
||||
for (j = 0; j < count; j++) {
|
||||
if (dictIsRehashing(d))
|
||||
_dictRehashStep(d);
|
||||
else
|
||||
break;
|
||||
}
|
||||
|
||||
tables = dictIsRehashing(d) ? 2 : 1;
|
||||
maxsizemask = d->ht[0].sizemask;
|
||||
if (tables > 1 && maxsizemask < d->ht[1].sizemask)
|
||||
maxsizemask = d->ht[1].sizemask;
|
||||
|
||||
/* Pick a random point inside the larger table. */
|
||||
unsigned int i = random() & maxsizemask;
|
||||
unsigned int emptylen = 0; /* Continuous empty entries so far. */
|
||||
while(stored < count && maxsteps--) {
|
||||
for (j = 0; j < tables; j++) {
|
||||
/* Invariant of the dict.c rehashing: up to the indexes already
|
||||
* visited in ht[0] during the rehashing, there are no populated
|
||||
* buckets, so we can skip ht[0] for indexes between 0 and idx-1. */
|
||||
if (tables == 2 && j == 0 && i < (unsigned int) d->rehashidx) {
|
||||
/* Moreover, if we are currently out of range in the second
|
||||
* table, there will be no elements in both tables up to
|
||||
* the current rehashing index, so we jump if possible.
|
||||
* (this happens when going from big to small table). */
|
||||
if (i >= d->ht[1].size) i = d->rehashidx;
|
||||
continue;
|
||||
}
|
||||
if (i >= d->ht[j].size) continue; /* Out of range for this table. */
|
||||
dictEntry *he = d->ht[j].table[i];
|
||||
|
||||
/* Count contiguous empty buckets, and jump to other
|
||||
* locations if they reach 'count' (with a minimum of 5). */
|
||||
if (he == NULL) {
|
||||
emptylen++;
|
||||
if (emptylen >= 5 && emptylen > count) {
|
||||
i = random() & maxsizemask;
|
||||
emptylen = 0;
|
||||
}
|
||||
} else {
|
||||
emptylen = 0;
|
||||
/* Make sure to visit every bucket by iterating 'size' times. */
|
||||
while(size--) {
|
||||
dictEntry *he = d->ht[j].table[i];
|
||||
while (he) {
|
||||
/* Collect all the elements of the buckets found non
|
||||
* empty while iterating. */
|
||||
@@ -743,11 +691,14 @@ unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count) {
|
||||
stored++;
|
||||
if (stored == count) return stored;
|
||||
}
|
||||
i = (i+1) & d->ht[j].sizemask;
|
||||
}
|
||||
/* If there is only one table and we iterated it all, we should
|
||||
* already have 'count' elements. Assert this condition. */
|
||||
assert(dictIsRehashing(d) != 0);
|
||||
}
|
||||
i = (i+1) & maxsizemask;
|
||||
}
|
||||
return stored;
|
||||
return stored; /* Never reached. */
|
||||
}
|
||||
|
||||
/* Function to reverse bits. Algorithm from:
|
||||
@@ -764,72 +715,72 @@ static unsigned long rev(unsigned long v) {
|
||||
|
||||
/* dictScan() is used to iterate over the elements of a dictionary.
|
||||
*
|
||||
* Iterating works the following way:
|
||||
* Iterating works in the following way:
|
||||
*
|
||||
* 1) Initially you call the function using a cursor (v) value of 0.
|
||||
* 2) The function performs one step of the iteration, and returns the
|
||||
* new cursor value you must use in the next call.
|
||||
* new cursor value that you must use in the next call.
|
||||
* 3) When the returned cursor is 0, the iteration is complete.
|
||||
*
|
||||
* The function guarantees all elements present in the
|
||||
* dictionary get returned between the start and end of the iteration.
|
||||
* However it is possible some elements get returned multiple times.
|
||||
* The function guarantees that all the elements that are present in the
|
||||
* dictionary from the start to the end of the iteration are returned.
|
||||
* However it is possible that some element is returned multiple time.
|
||||
*
|
||||
* For every element returned, the callback argument 'fn' is
|
||||
* called with 'privdata' as first argument and the dictionary entry
|
||||
* For every element returned, the callback 'fn' passed as argument is
|
||||
* called, with 'privdata' as first argument and the dictionar entry
|
||||
* 'de' as second argument.
|
||||
*
|
||||
* HOW IT WORKS.
|
||||
*
|
||||
* The iteration algorithm was designed by Pieter Noordhuis.
|
||||
* The algorithm used in the iteration was designed by Pieter Noordhuis.
|
||||
* The main idea is to increment a cursor starting from the higher order
|
||||
* bits. That is, instead of incrementing the cursor normally, the bits
|
||||
* bits, that is, instead of incrementing the cursor normally, the bits
|
||||
* of the cursor are reversed, then the cursor is incremented, and finally
|
||||
* the bits are reversed again.
|
||||
*
|
||||
* This strategy is needed because the hash table may be resized between
|
||||
* iteration calls.
|
||||
* This strategy is needed because the hash table may be resized from one
|
||||
* call to the other call of the same iteration.
|
||||
*
|
||||
* dict.c hash tables are always power of two in size, and they
|
||||
* use chaining, so the position of an element in a given table is given
|
||||
* by computing the bitwise AND between Hash(key) and SIZE-1
|
||||
* always by computing the bitwise AND between Hash(key) and SIZE-1
|
||||
* (where SIZE-1 is always the mask that is equivalent to taking the rest
|
||||
* of the division between the Hash of the key and SIZE).
|
||||
*
|
||||
* For example if the current hash table size is 16, the mask is
|
||||
* (in binary) 1111. The position of a key in the hash table will always be
|
||||
* (in binary) 1111. The position of a key in the hash table will be always
|
||||
* the last four bits of the hash output, and so forth.
|
||||
*
|
||||
* WHAT HAPPENS IF THE TABLE CHANGES IN SIZE?
|
||||
*
|
||||
* If the hash table grows, elements can go anywhere in one multiple of
|
||||
* the old bucket: for example let's say we already iterated with
|
||||
* a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16).
|
||||
* If the hash table grows, elements can go anyway in one multiple of
|
||||
* the old bucket: for example let's say that we already iterated with
|
||||
* a 4 bit cursor 1100, since the mask is 1111 (hash table size = 16).
|
||||
*
|
||||
* If the hash table will be resized to 64 elements, then the new mask will
|
||||
* be 111111. The new buckets you obtain by substituting in ??1100
|
||||
* with either 0 or 1 can be targeted only by keys we already visited
|
||||
* If the hash table will be resized to 64 elements, and the new mask will
|
||||
* be 111111, the new buckets that you obtain substituting in ??1100
|
||||
* either 0 or 1, can be targeted only by keys that we already visited
|
||||
* when scanning the bucket 1100 in the smaller hash table.
|
||||
*
|
||||
* By iterating the higher bits first, because of the inverted counter, the
|
||||
* cursor does not need to restart if the table size gets bigger. It will
|
||||
* continue iterating using cursors without '1100' at the end, and also
|
||||
* without any other combination of the final 4 bits already explored.
|
||||
* cursor does not need to restart if the table size gets bigger, and will
|
||||
* just continue iterating with cursors that don't have '1100' at the end,
|
||||
* nor any other combination of final 4 bits already explored.
|
||||
*
|
||||
* Similarly when the table size shrinks over time, for example going from
|
||||
* 16 to 8, if a combination of the lower three bits (the mask for size 8
|
||||
* is 111) were already completely explored, it would not be visited again
|
||||
* because we are sure we tried, for example, both 0111 and 1111 (all the
|
||||
* 16 to 8, If a combination of the lower three bits (the mask for size 8
|
||||
* is 111) was already completely explored, it will not be visited again
|
||||
* as we are sure that, we tried for example, both 0111 and 1111 (all the
|
||||
* variations of the higher bit) so we don't need to test it again.
|
||||
*
|
||||
* WAIT... YOU HAVE *TWO* TABLES DURING REHASHING!
|
||||
*
|
||||
* Yes, this is true, but we always iterate the smaller table first, then
|
||||
* we test all the expansions of the current cursor into the larger
|
||||
* table. For example if the current cursor is 101 and we also have a
|
||||
* Yes, this is true, but we always iterate the smaller one of the tables,
|
||||
* testing also all the expansions of the current cursor into the larger
|
||||
* table. So for example if the current cursor is 101 and we also have a
|
||||
* larger table of size 16, we also test (0)101 and (1)101 inside the larger
|
||||
* table. This reduces the problem back to having only one table, where
|
||||
* the larger one, if it exists, is just an expansion of the smaller one.
|
||||
* the larger one, if exists, is just an expansion of the smaller one.
|
||||
*
|
||||
* LIMITATIONS
|
||||
*
|
||||
@@ -838,11 +789,11 @@ static unsigned long rev(unsigned long v) {
|
||||
*
|
||||
* The disadvantages resulting from this design are:
|
||||
*
|
||||
* 1) It is possible we return elements more than once. However this is usually
|
||||
* 1) It is possible that we return duplicated elements. However this is usually
|
||||
* easy to deal with in the application level.
|
||||
* 2) The iterator must return multiple elements per call, as it needs to always
|
||||
* return all the keys chained in a given bucket, and all the expansions, so
|
||||
* we are sure we don't miss keys moving during rehashing.
|
||||
* we are sure we don't miss keys moving.
|
||||
* 3) The reverse cursor is somewhat hard to understand at first, but this
|
||||
* comment is supposed to help.
|
||||
*/
|
||||
|
||||
+5
-12
@@ -50,7 +50,6 @@ typedef struct dictEntry {
|
||||
void *val;
|
||||
uint64_t u64;
|
||||
int64_t s64;
|
||||
double d;
|
||||
} v;
|
||||
struct dictEntry *next;
|
||||
} dictEntry;
|
||||
@@ -77,7 +76,7 @@ typedef struct dict {
|
||||
dictType *type;
|
||||
void *privdata;
|
||||
dictht ht[2];
|
||||
long rehashidx; /* rehashing not in progress if rehashidx == -1 */
|
||||
int rehashidx; /* rehashing not in progress if rehashidx == -1 */
|
||||
int iterators; /* number of iterators currently running */
|
||||
} dict;
|
||||
|
||||
@@ -87,11 +86,9 @@ typedef struct dict {
|
||||
* should be called while iterating. */
|
||||
typedef struct dictIterator {
|
||||
dict *d;
|
||||
long index;
|
||||
int table, safe;
|
||||
int table, index, safe;
|
||||
dictEntry *entry, *nextEntry;
|
||||
/* unsafe iterator fingerprint for misuse detection. */
|
||||
long long fingerprint;
|
||||
long long fingerprint; /* unsafe iterator fingerprint for misuse detection */
|
||||
} dictIterator;
|
||||
|
||||
typedef void (dictScanFunction)(void *privdata, const dictEntry *de);
|
||||
@@ -117,9 +114,6 @@ typedef void (dictScanFunction)(void *privdata, const dictEntry *de);
|
||||
#define dictSetUnsignedIntegerVal(entry, _val_) \
|
||||
do { entry->v.u64 = _val_; } while(0)
|
||||
|
||||
#define dictSetDoubleVal(entry, _val_) \
|
||||
do { entry->v.d = _val_; } while(0)
|
||||
|
||||
#define dictFreeKey(d, entry) \
|
||||
if ((d)->type->keyDestructor) \
|
||||
(d)->type->keyDestructor((d)->privdata, (entry)->key)
|
||||
@@ -141,10 +135,9 @@ typedef void (dictScanFunction)(void *privdata, const dictEntry *de);
|
||||
#define dictGetVal(he) ((he)->v.val)
|
||||
#define dictGetSignedIntegerVal(he) ((he)->v.s64)
|
||||
#define dictGetUnsignedIntegerVal(he) ((he)->v.u64)
|
||||
#define dictGetDoubleVal(he) ((he)->v.d)
|
||||
#define dictSlots(d) ((d)->ht[0].size+(d)->ht[1].size)
|
||||
#define dictSize(d) ((d)->ht[0].used+(d)->ht[1].used)
|
||||
#define dictIsRehashing(d) ((d)->rehashidx != -1)
|
||||
#define dictIsRehashing(ht) ((ht)->rehashidx != -1)
|
||||
|
||||
/* API */
|
||||
dict *dictCreate(dictType *type, void *privDataPtr);
|
||||
@@ -164,7 +157,7 @@ dictIterator *dictGetSafeIterator(dict *d);
|
||||
dictEntry *dictNext(dictIterator *iter);
|
||||
void dictReleaseIterator(dictIterator *iter);
|
||||
dictEntry *dictGetRandomKey(dict *d);
|
||||
unsigned int dictGetSomeKeys(dict *d, dictEntry **des, unsigned int count);
|
||||
int dictGetRandomKeys(dict *d, dictEntry **des, int count);
|
||||
void dictPrintStats(dict *d);
|
||||
unsigned int dictGenHashFunction(const void *key, int len);
|
||||
unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len);
|
||||
|
||||
@@ -34,11 +34,6 @@
|
||||
|
||||
#if defined(__linux__)
|
||||
#define _GNU_SOURCE
|
||||
#define _DEFAULT_SOURCE
|
||||
#endif
|
||||
|
||||
#if defined(_AIX)
|
||||
#define _ALL_SOURCE
|
||||
#endif
|
||||
|
||||
#if defined(__linux__) || defined(__OpenBSD__)
|
||||
|
||||
+8
-180
@@ -1,4 +1,4 @@
|
||||
/* Automatically generated by generate-command-help.rb, do not edit. */
|
||||
/* Automatically generated by utils/generate-command-help.rb, do not edit. */
|
||||
|
||||
#ifndef __REDIS_HELP_H
|
||||
#define __REDIS_HELP_H
|
||||
@@ -15,9 +15,7 @@ static char *commandGroups[] = {
|
||||
"connection",
|
||||
"server",
|
||||
"scripting",
|
||||
"hyperloglog",
|
||||
"cluster",
|
||||
"geo"
|
||||
"hyperloglog"
|
||||
};
|
||||
|
||||
struct commandHelp {
|
||||
@@ -48,7 +46,7 @@ struct commandHelp {
|
||||
9,
|
||||
"1.0.0" },
|
||||
{ "BITCOUNT",
|
||||
"key [start end]",
|
||||
"key [start] [end]",
|
||||
"Count set bits in a string",
|
||||
1,
|
||||
"2.6.0" },
|
||||
@@ -83,7 +81,7 @@ struct commandHelp {
|
||||
9,
|
||||
"2.6.9" },
|
||||
{ "CLIENT KILL",
|
||||
"[ip:port] [ID client-id] [TYPE normal|slave|pubsub] [ADDR ip:port] [SKIPME yes/no]",
|
||||
"ip:port",
|
||||
"Kill the connection of a client",
|
||||
9,
|
||||
"2.4.0" },
|
||||
@@ -102,116 +100,6 @@ struct commandHelp {
|
||||
"Set the current connection name",
|
||||
9,
|
||||
"2.6.9" },
|
||||
{ "CLUSTER ADDSLOTS",
|
||||
"slot [slot ...]",
|
||||
"Assign new hash slots to receiving node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER COUNT-FAILURE-REPORTS",
|
||||
"node-id",
|
||||
"Return the number of failure reports active for a given node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER COUNTKEYSINSLOT",
|
||||
"slot",
|
||||
"Return the number of local keys in the specified hash slot",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER DELSLOTS",
|
||||
"slot [slot ...]",
|
||||
"Set hash slots as unbound in receiving node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER FAILOVER",
|
||||
"[FORCE|TAKEOVER]",
|
||||
"Forces a slave to perform a manual failover of its master.",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER FORGET",
|
||||
"node-id",
|
||||
"Remove a node from the nodes table",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER GETKEYSINSLOT",
|
||||
"slot count",
|
||||
"Return local key names in the specified hash slot",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER INFO",
|
||||
"-",
|
||||
"Provides info about Redis Cluster node state",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER KEYSLOT",
|
||||
"key",
|
||||
"Returns the hash slot of the specified key",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER MEET",
|
||||
"ip port",
|
||||
"Force a node cluster to handshake with another node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER NODES",
|
||||
"-",
|
||||
"Get Cluster config for the node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER REPLICATE",
|
||||
"node-id",
|
||||
"Reconfigure a node as a slave of the specified master node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER RESET",
|
||||
"[HARD|SOFT]",
|
||||
"Reset a Redis Cluster node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER SAVECONFIG",
|
||||
"-",
|
||||
"Forces the node to save cluster state on disk",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER SET-CONFIG-EPOCH",
|
||||
"config-epoch",
|
||||
"Set the configuration epoch in a new node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER SETSLOT",
|
||||
"slot IMPORTING|MIGRATING|STABLE|NODE [node-id]",
|
||||
"Bind an hash slot to a specific node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER SLAVES",
|
||||
"node-id",
|
||||
"List slave nodes of the specified master node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "CLUSTER SLOTS",
|
||||
"-",
|
||||
"Get array of Cluster slot to node mappings",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "COMMAND",
|
||||
"-",
|
||||
"Get array of Redis command details",
|
||||
9,
|
||||
"2.8.13" },
|
||||
{ "COMMAND COUNT",
|
||||
"-",
|
||||
"Get total number of Redis commands",
|
||||
9,
|
||||
"2.8.13" },
|
||||
{ "COMMAND GETKEYS",
|
||||
"-",
|
||||
"Extract keys given a full Redis command",
|
||||
9,
|
||||
"2.8.13" },
|
||||
{ "COMMAND INFO",
|
||||
"command-name [command-name ...]",
|
||||
"Get array of specific Redis command details",
|
||||
9,
|
||||
"2.8.13" },
|
||||
{ "CONFIG GET",
|
||||
"parameter",
|
||||
"Get the value of a configuration parameter",
|
||||
@@ -293,7 +181,7 @@ struct commandHelp {
|
||||
7,
|
||||
"1.2.0" },
|
||||
{ "EXISTS",
|
||||
"key [key ...]",
|
||||
"key",
|
||||
"Determine if a key exists",
|
||||
0,
|
||||
"1.0.0" },
|
||||
@@ -317,36 +205,6 @@ struct commandHelp {
|
||||
"Remove all keys from the current database",
|
||||
9,
|
||||
"1.0.0" },
|
||||
{ "GEOADD",
|
||||
"key longitude latitude member [longitude latitude member ...]",
|
||||
"Add one or more geospatial items in the geospatial index represented using a sorted set",
|
||||
13,
|
||||
"" },
|
||||
{ "GEODIST",
|
||||
"key member1 member2 [unit]",
|
||||
"Returns the distance between two members of a geospatial index",
|
||||
13,
|
||||
"" },
|
||||
{ "GEOHASH",
|
||||
"key member [member ...]",
|
||||
"Returns members of a geospatial index as standard geohash strings",
|
||||
13,
|
||||
"" },
|
||||
{ "GEOPOS",
|
||||
"key member [member ...]",
|
||||
"Returns longitude and latitude of members of a geospatial index",
|
||||
13,
|
||||
"" },
|
||||
{ "GEORADIUS",
|
||||
"key longitude latitude radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count]",
|
||||
"Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a point",
|
||||
13,
|
||||
"" },
|
||||
{ "GEORADIUSBYMEMBER",
|
||||
"key member radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count]",
|
||||
"Query a sorted set representing a geospatial index to fetch members matching a given maximum distance from a member",
|
||||
13,
|
||||
"" },
|
||||
{ "GET",
|
||||
"key",
|
||||
"Get the value of a key",
|
||||
@@ -432,11 +290,6 @@ struct commandHelp {
|
||||
"Set the value of a hash field, only if the field does not exist",
|
||||
5,
|
||||
"2.0.0" },
|
||||
{ "HSTRLEN",
|
||||
"key field",
|
||||
"Get the length of the value of a hash field",
|
||||
5,
|
||||
"3.2.0" },
|
||||
{ "HVALS",
|
||||
"key",
|
||||
"Get all the values in a hash",
|
||||
@@ -637,16 +490,6 @@ struct commandHelp {
|
||||
"Return a random key from the keyspace",
|
||||
0,
|
||||
"1.0.0" },
|
||||
{ "READONLY",
|
||||
"-",
|
||||
"Enables read queries for a connection to a cluster slave node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "READWRITE",
|
||||
"-",
|
||||
"Disables read queries for a connection to a cluster slave node",
|
||||
12,
|
||||
"3.0.0" },
|
||||
{ "RENAME",
|
||||
"key newkey",
|
||||
"Rename a key",
|
||||
@@ -658,15 +501,10 @@ struct commandHelp {
|
||||
0,
|
||||
"1.0.0" },
|
||||
{ "RESTORE",
|
||||
"key ttl serialized-value [REPLACE]",
|
||||
"key ttl serialized-value",
|
||||
"Create a key using the provided serialized value, previously obtained using DUMP.",
|
||||
0,
|
||||
"2.6.0" },
|
||||
{ "ROLE",
|
||||
"-",
|
||||
"Return the role of the instance in the context of replication",
|
||||
9,
|
||||
"2.8.12" },
|
||||
{ "RPOP",
|
||||
"key",
|
||||
"Remove and get the last element in a list",
|
||||
@@ -674,7 +512,7 @@ struct commandHelp {
|
||||
"1.0.0" },
|
||||
{ "RPOPLPUSH",
|
||||
"source destination",
|
||||
"Remove the last element in a list, prepend it to another list and return it",
|
||||
"Remove the last element in a list, append it to another list and return it",
|
||||
2,
|
||||
"1.2.0" },
|
||||
{ "RPUSH",
|
||||
@@ -882,18 +720,13 @@ struct commandHelp {
|
||||
"Forget about all watched keys",
|
||||
7,
|
||||
"2.2.0" },
|
||||
{ "WAIT",
|
||||
"numslaves timeout",
|
||||
"Wait for the synchronous replication of all the write commands sent in the context of the current connection",
|
||||
0,
|
||||
"3.0.0" },
|
||||
{ "WATCH",
|
||||
"key [key ...]",
|
||||
"Watch the given keys to determine execution of the MULTI/EXEC block",
|
||||
7,
|
||||
"2.2.0" },
|
||||
{ "ZADD",
|
||||
"key [NX|XX] [CH] [INCR] score member [score member ...]",
|
||||
"key score member [score member ...]",
|
||||
"Add one or more members to a sorted set, or update its score if it already exists",
|
||||
4,
|
||||
"1.2.0" },
|
||||
@@ -967,11 +800,6 @@ struct commandHelp {
|
||||
"Return a range of members in a sorted set, by index, with scores ordered from high to low",
|
||||
4,
|
||||
"1.2.0" },
|
||||
{ "ZREVRANGEBYLEX",
|
||||
"key max min [LIMIT offset count]",
|
||||
"Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings.",
|
||||
4,
|
||||
"2.8.9" },
|
||||
{ "ZREVRANGEBYSCORE",
|
||||
"key max min [WITHSCORES] [LIMIT offset count]",
|
||||
"Return a range of members in a sorted set, by score, with scores ordered from high to low",
|
||||
|
||||
+4
-12
@@ -1213,7 +1213,7 @@ void pfcountCommand(redisClient *c) {
|
||||
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.*/
|
||||
if (o == NULL) continue; /* Assume empty HLL for non existing var. */
|
||||
if (isHLLObjectOrReply(c,o) != REDIS_OK) return;
|
||||
|
||||
/* Merge with this HLL with our 'max' HHL by setting max[i]
|
||||
@@ -1349,7 +1349,7 @@ void pfmergeCommand(redisClient *c) {
|
||||
* Something that is not easy to test from within the outside. */
|
||||
#define HLL_TEST_CYCLES 1000
|
||||
void pfselftestCommand(redisClient *c) {
|
||||
unsigned int j, i;
|
||||
int j, i;
|
||||
sds bitcounters = sdsnewlen(NULL,HLL_DENSE_SIZE);
|
||||
struct hllhdr *hdr = (struct hllhdr*) bitcounters, *hdr2;
|
||||
robj *o = NULL;
|
||||
@@ -1386,7 +1386,7 @@ void pfselftestCommand(redisClient *c) {
|
||||
* The test adds unique elements and check that the estimated value
|
||||
* is always reasonable bounds.
|
||||
*
|
||||
* We check that the error is smaller than a few times than the expected
|
||||
* We check that the error is smaller than 4 times than the expected
|
||||
* standard error, to make it very unlikely for the test to fail because
|
||||
* of a "bad" run.
|
||||
*
|
||||
@@ -1422,16 +1422,8 @@ void pfselftestCommand(redisClient *c) {
|
||||
/* Check error. */
|
||||
if (j == checkpoint) {
|
||||
int64_t abserr = checkpoint - (int64_t)hllCount(hdr,NULL);
|
||||
uint64_t maxerr = ceil(relerr*6*checkpoint);
|
||||
|
||||
/* Adjust the max error we expect for cardinality 10
|
||||
* since from time to time it is statistically likely to get
|
||||
* much higher error due to collision, resulting into a false
|
||||
* positive. */
|
||||
if (j == 10) maxerr = 1;
|
||||
|
||||
if (abserr < 0) abserr = -abserr;
|
||||
if (abserr > (int64_t)maxerr) {
|
||||
if (abserr > (uint64_t)(relerr*4*checkpoint)) {
|
||||
addReplyErrorFormat(c,
|
||||
"TESTFAILED Too big error. card:%llu abserr:%llu",
|
||||
(unsigned long long) checkpoint,
|
||||
|
||||
+1
-1
@@ -133,7 +133,7 @@ static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) {
|
||||
}
|
||||
|
||||
while(max >= min) {
|
||||
mid = ((unsigned int)min + (unsigned int)max) >> 1;
|
||||
mid = (min+max)/2;
|
||||
cur = _intsetGet(is,mid);
|
||||
if (value > cur) {
|
||||
min = mid+1;
|
||||
|
||||
+10
-59
@@ -37,7 +37,6 @@
|
||||
|
||||
/* Dictionary type for latency events. */
|
||||
int dictStringKeyCompare(void *privdata, const void *key1, const void *key2) {
|
||||
REDIS_NOTUSED(privdata);
|
||||
return strcmp(key1,key2) == 0;
|
||||
}
|
||||
|
||||
@@ -56,32 +55,6 @@ dictType latencyTimeSeriesDictType = {
|
||||
dictVanillaFree /* val destructor */
|
||||
};
|
||||
|
||||
/* ------------------------- Utility functions ------------------------------ */
|
||||
|
||||
#ifdef __linux__
|
||||
/* Returns 1 if Transparent Huge Pages support is enabled in the kernel.
|
||||
* Otherwise (or if we are unable to check) 0 is returned. */
|
||||
int THPIsEnabled(void) {
|
||||
char buf[1024];
|
||||
|
||||
FILE *fp = fopen("/sys/kernel/mm/transparent_hugepage/enabled","r");
|
||||
if (!fp) return 0;
|
||||
if (fgets(buf,sizeof(buf),fp) == NULL) {
|
||||
fclose(fp);
|
||||
return 0;
|
||||
}
|
||||
fclose(fp);
|
||||
return (strstr(buf,"[never]") == NULL) ? 1 : 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Report the amount of AnonHugePages in smap, in bytes. If the return
|
||||
* value of the function is non-zero, the process is being targeted by
|
||||
* THP support, and is likely to have memory usage / latency issues. */
|
||||
int THPGetAnonHugePagesSize(void) {
|
||||
return zmalloc_get_smap_bytes_by_field("AnonHugePages:");
|
||||
}
|
||||
|
||||
/* ---------------------------- Latency API --------------------------------- */
|
||||
|
||||
/* Latency monitor initialization. We just need to create the dictionary
|
||||
@@ -228,9 +201,7 @@ sds createLatencyReport(void) {
|
||||
int advise_write_load_info = 0; /* Print info about AOF and write load. */
|
||||
int advise_hz = 0; /* Use higher HZ. */
|
||||
int advise_large_objects = 0; /* Deletion of large objects. */
|
||||
int advise_mass_eviction = 0; /* Avoid mass eviction of keys. */
|
||||
int advise_relax_fsync_policy = 0; /* appendfsync always is slow. */
|
||||
int advise_disable_thp = 0; /* AnonHugePages detected. */
|
||||
int advices = 0;
|
||||
|
||||
/* Return ASAP if the latency engine is disabled and it looks like it
|
||||
@@ -248,7 +219,7 @@ sds createLatencyReport(void) {
|
||||
dictEntry *de;
|
||||
int eventnum = 0;
|
||||
|
||||
di = dictGetSafeIterator(server.latency_events);
|
||||
di = dictGetIterator(server.latency_events);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
char *event = dictGetKey(de);
|
||||
struct latencyTimeSeries *ts = dictGetVal(de);
|
||||
@@ -365,13 +336,8 @@ sds createLatencyReport(void) {
|
||||
}
|
||||
|
||||
/* Eviction cycle. */
|
||||
if (!strcasecmp(event,"eviction-del")) {
|
||||
advise_large_objects = 1;
|
||||
advices++;
|
||||
}
|
||||
|
||||
if (!strcasecmp(event,"eviction-cycle")) {
|
||||
advise_mass_eviction = 1;
|
||||
advise_large_objects = 1;
|
||||
advices++;
|
||||
}
|
||||
|
||||
@@ -379,15 +345,9 @@ sds createLatencyReport(void) {
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
/* Add non event based advices. */
|
||||
if (THPGetAnonHugePagesSize() > 0) {
|
||||
advise_disable_thp = 1;
|
||||
advices++;
|
||||
}
|
||||
|
||||
if (eventnum == 0 && advices == 0) {
|
||||
if (eventnum == 0) {
|
||||
report = sdscat(report,"Dave, no latency spike was observed during the lifetime of this Redis instance, not in the slightest bit. I honestly think you ought to sit down calmly, take a stress pill, and think things over.\n");
|
||||
} else if (eventnum > 0 && advices == 0) {
|
||||
} else if (advices == 0) {
|
||||
report = sdscat(report,"\nWhile there are latency events logged, I'm not able to suggest any easy fix. Please use the Redis community to get some help, providing this report in your help request.\n");
|
||||
} else {
|
||||
/* Add all the suggestions accumulated so far. */
|
||||
@@ -408,7 +368,7 @@ sds createLatencyReport(void) {
|
||||
}
|
||||
|
||||
if (advise_slowlog_inspect) {
|
||||
report = sdscat(report,"- Check your Slow Log to understand what are the commands you are running which are too slow to execute. Please check http://redis.io/commands/slowlog for more information.\n");
|
||||
report = sdscat(report,"- Check your Slow Log to understand what are the commads you are running which are too slow to execute. Please check http://redis.io/commands/slowlog for more information.\n");
|
||||
}
|
||||
|
||||
/* Intrinsic latency. */
|
||||
@@ -457,14 +417,6 @@ sds createLatencyReport(void) {
|
||||
if (advise_large_objects) {
|
||||
report = sdscat(report,"- Deleting, expiring or evicting (because of maxmemory policy) large objects is a blocking operation. If you have very large objects that are often deleted, expired, or evicted, try to fragment those objects into multiple smaller objects.\n");
|
||||
}
|
||||
|
||||
if (advise_mass_eviction) {
|
||||
report = sdscat(report,"- Sudden changes to the 'maxmemory' setting via 'CONFIG SET', or allocation of large objects via sets or sorted sets intersections, STORE option of SORT, Redis Cluster large keys migrations (RESTORE command), may create sudden memory pressure forcing the server to block trying to evict keys. \n");
|
||||
}
|
||||
|
||||
if (advise_disable_thp) {
|
||||
report = sdscat(report,"- I detected a non zero amount of anonymous huge pages used by your process. This creates very serious latency events in different conditions, especially when Redis is persisting on disk. To disable THP support use the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled', make sure to also add it into /etc/rc.local so that the command will be executed again after a reboot. Note that even if you have already disabled THP, you still need to restart the Redis process to get rid of the huge pages already created.\n");
|
||||
}
|
||||
}
|
||||
|
||||
return report;
|
||||
@@ -522,6 +474,7 @@ sds latencyCommandGenSparkeline(char *event, struct latencyTimeSeries *ts) {
|
||||
for (j = 0; j < LATENCY_TS_LEN; j++) {
|
||||
int i = (ts->idx + j) % LATENCY_TS_LEN;
|
||||
int elapsed;
|
||||
char *label;
|
||||
char buf[64];
|
||||
|
||||
if (ts->samples[i].time == 0) continue;
|
||||
@@ -543,7 +496,8 @@ sds latencyCommandGenSparkeline(char *event, struct latencyTimeSeries *ts) {
|
||||
snprintf(buf,sizeof(buf),"%dh",elapsed/3600);
|
||||
else
|
||||
snprintf(buf,sizeof(buf),"%dd",elapsed/(3600*24));
|
||||
sparklineSequenceAddSample(seq,ts->samples[i].latency,buf);
|
||||
label = zstrdup(buf);
|
||||
sparklineSequenceAddSample(seq,ts->samples[i].latency,label);
|
||||
}
|
||||
|
||||
graph = sdscatprintf(graph,
|
||||
@@ -570,11 +524,8 @@ void latencyCommand(redisClient *c) {
|
||||
if (!strcasecmp(c->argv[1]->ptr,"history") && c->argc == 3) {
|
||||
/* LATENCY HISTORY <event> */
|
||||
ts = dictFetchValue(server.latency_events,c->argv[2]->ptr);
|
||||
if (ts == NULL) {
|
||||
addReplyMultiBulkLen(c,0);
|
||||
} else {
|
||||
latencyCommandReplyWithSamples(c,ts);
|
||||
}
|
||||
if (ts == NULL) goto nodataerr;
|
||||
latencyCommandReplyWithSamples(c,ts);
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"graph") && c->argc == 3) {
|
||||
/* LATENCY GRAPH <event> */
|
||||
sds graph;
|
||||
|
||||
@@ -63,7 +63,6 @@ struct latencyStats {
|
||||
|
||||
void latencyMonitorInit(void);
|
||||
void latencyAddSample(char *event, mstime_t latency);
|
||||
int THPIsEnabled(void);
|
||||
|
||||
/* Latency monitoring macros. */
|
||||
|
||||
@@ -86,8 +85,4 @@ int THPIsEnabled(void);
|
||||
(var) >= server.latency_monitor_threshold) \
|
||||
latencyAddSample((event),(var));
|
||||
|
||||
/* Remove time from a nested event. */
|
||||
#define latencyRemoveNestedEvent(event_var,nested_var) \
|
||||
event_var += nested_var;
|
||||
|
||||
#endif /* __LATENCY_H */
|
||||
|
||||
@@ -35,9 +35,6 @@
|
||||
#include <errno.h>
|
||||
#include <termios.h>
|
||||
#include <sys/ioctl.h>
|
||||
#if defined(__sun)
|
||||
#include <stropts.h>
|
||||
#endif
|
||||
#include "config.h"
|
||||
|
||||
#if (ULONG_MAX == 4294967295UL)
|
||||
@@ -240,7 +237,6 @@ void memtest_test(size_t megabytes, int passes) {
|
||||
memtest_progress_end();
|
||||
memtest_compare_times(m,bytes,pass,4);
|
||||
}
|
||||
free(m);
|
||||
}
|
||||
|
||||
void memtest_non_destructive_invert(void *addr, size_t size) {
|
||||
|
||||
+1
-1
@@ -72,7 +72,7 @@ void queueMultiCommand(redisClient *c) {
|
||||
void discardTransaction(redisClient *c) {
|
||||
freeClientMultiState(c);
|
||||
initClientMultiState(c);
|
||||
c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS|REDIS_DIRTY_EXEC);
|
||||
c->flags &= ~(REDIS_MULTI|REDIS_DIRTY_CAS|REDIS_DIRTY_EXEC);;
|
||||
unwatchAllKeys(c);
|
||||
}
|
||||
|
||||
|
||||
+38
-63
@@ -100,12 +100,10 @@ redisClient *createClient(int fd) {
|
||||
c->ctime = c->lastinteraction = server.unixtime;
|
||||
c->authenticated = 0;
|
||||
c->replstate = REDIS_REPL_NONE;
|
||||
c->repl_put_online_on_ack = 0;
|
||||
c->reploff = 0;
|
||||
c->repl_ack_off = 0;
|
||||
c->repl_ack_time = 0;
|
||||
c->slave_listening_port = 0;
|
||||
c->slave_capa = SLAVE_CAPA_NONE;
|
||||
c->reply = listCreate();
|
||||
c->reply_bytes = 0;
|
||||
c->obuf_soft_limit_reached_time = 0;
|
||||
@@ -136,49 +134,23 @@ redisClient *createClient(int fd) {
|
||||
* returns REDIS_OK, and make sure to install the write handler in our event
|
||||
* loop so that when the socket is writable new data gets written.
|
||||
*
|
||||
* If the client should not receive new data, because it is a fake client
|
||||
* (used to load AOF in memory), a master or because the setup of the write
|
||||
* handler failed, the function returns REDIS_ERR.
|
||||
*
|
||||
* The function may return REDIS_OK without actually installing the write
|
||||
* event handler in the following cases:
|
||||
*
|
||||
* 1) The event handler should already be installed since the output buffer
|
||||
* already contained something.
|
||||
* 2) The client is a slave but not yet online, so we want to just accumulate
|
||||
* writes in the buffer but not actually sending them yet.
|
||||
* If the client should not receive new data, because it is a fake client,
|
||||
* a master, a slave not yet online, or because the setup of the write handler
|
||||
* failed, the function returns REDIS_ERR.
|
||||
*
|
||||
* Typically gets called every time a reply is built, before adding more
|
||||
* data to the clients output buffers. If the function returns REDIS_ERR no
|
||||
* data should be appended to the output buffers. */
|
||||
int prepareClientToWrite(redisClient *c) {
|
||||
/* If it's the Lua client we always return ok without installing any
|
||||
* handler since there is no socket at all. */
|
||||
if (c->flags & REDIS_LUA_CLIENT) return REDIS_OK;
|
||||
|
||||
/* Masters don't receive replies, unless REDIS_MASTER_FORCE_REPLY flag
|
||||
* is set. */
|
||||
if ((c->flags & REDIS_MASTER) &&
|
||||
!(c->flags & REDIS_MASTER_FORCE_REPLY)) return REDIS_ERR;
|
||||
|
||||
if (c->fd <= 0) return REDIS_ERR; /* Fake client for AOF loading. */
|
||||
|
||||
/* Only install the handler if not already installed and, in case of
|
||||
* slaves, if the client can actually receive writes. */
|
||||
if (c->fd <= 0) return REDIS_ERR; /* Fake client */
|
||||
if (c->bufpos == 0 && listLength(c->reply) == 0 &&
|
||||
(c->replstate == REDIS_REPL_NONE ||
|
||||
(c->replstate == REDIS_REPL_ONLINE && !c->repl_put_online_on_ack)))
|
||||
{
|
||||
/* Try to install the write handler. */
|
||||
if (aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
|
||||
sendReplyToClient, c) == AE_ERR)
|
||||
{
|
||||
freeClientAsync(c);
|
||||
return REDIS_ERR;
|
||||
}
|
||||
}
|
||||
|
||||
/* Authorize the caller to queue in the output buffer of this client. */
|
||||
c->replstate == REDIS_REPL_ONLINE) &&
|
||||
aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
|
||||
sendReplyToClient, c) == AE_ERR) return REDIS_ERR;
|
||||
return REDIS_OK;
|
||||
}
|
||||
|
||||
@@ -667,6 +639,20 @@ void disconnectSlaves(void) {
|
||||
}
|
||||
}
|
||||
|
||||
/* This function is called when the slave lose the connection with the
|
||||
* master into an unexpected way. */
|
||||
void replicationHandleMasterDisconnection(void) {
|
||||
server.master = NULL;
|
||||
server.repl_state = REDIS_REPL_CONNECT;
|
||||
server.repl_down_since = server.unixtime;
|
||||
/* We lost connection with our master, force our slaves to resync
|
||||
* with us as well to load the new data set.
|
||||
*
|
||||
* If server.masterhost is NULL the user called SLAVEOF NO ONE so
|
||||
* slave resync is not needed. */
|
||||
if (server.masterhost != NULL) disconnectSlaves();
|
||||
}
|
||||
|
||||
void freeClient(redisClient *c) {
|
||||
listNode *ln;
|
||||
|
||||
@@ -692,8 +678,12 @@ void freeClient(redisClient *c) {
|
||||
|
||||
/* Log link disconnection with slave */
|
||||
if ((c->flags & REDIS_SLAVE) && !(c->flags & REDIS_MONITOR)) {
|
||||
redisLog(REDIS_WARNING,"Connection with slave %s lost.",
|
||||
replicationGetSlaveName(c));
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
|
||||
if (anetPeerToString(c->fd,ip,sizeof(ip),NULL) != -1) {
|
||||
redisLog(REDIS_WARNING,"Connection with slave %s:%d lost.",
|
||||
ip, c->slave_listening_port);
|
||||
}
|
||||
}
|
||||
|
||||
/* Free the query buffer */
|
||||
@@ -784,7 +774,7 @@ void freeClient(redisClient *c) {
|
||||
* a context where calling freeClient() is not possible, because the client
|
||||
* should be valid for the continuation of the flow of the program. */
|
||||
void freeClientAsync(redisClient *c) {
|
||||
if (c->flags & REDIS_CLOSE_ASAP || c->flags & REDIS_LUA_CLIENT) return;
|
||||
if (c->flags & REDIS_CLOSE_ASAP) return;
|
||||
c->flags |= REDIS_CLOSE_ASAP;
|
||||
listAddNodeTail(server.clients_to_close,c);
|
||||
}
|
||||
@@ -852,7 +842,6 @@ void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
*
|
||||
* However if we are over the maxmemory limit we ignore that and
|
||||
* just deliver as much data as it is possible to deliver. */
|
||||
server.stat_net_output_bytes += totwritten;
|
||||
if (totwritten > REDIS_MAX_WRITE_PER_EVENT &&
|
||||
(server.maxmemory == 0 ||
|
||||
zmalloc_used_memory() < server.maxmemory)) break;
|
||||
@@ -940,10 +929,8 @@ int processInlineBuffer(redisClient *c) {
|
||||
sdsrange(c->querybuf,querylen+2,-1);
|
||||
|
||||
/* Setup argv array on client structure */
|
||||
if (argc) {
|
||||
if (c->argv) zfree(c->argv);
|
||||
c->argv = zmalloc(sizeof(robj*)*argc);
|
||||
}
|
||||
if (c->argv) zfree(c->argv);
|
||||
c->argv = zmalloc(sizeof(robj*)*argc);
|
||||
|
||||
/* Create redis objects for all arguments. */
|
||||
for (c->argc = 0, j = 0; j < argc; j++) {
|
||||
@@ -961,7 +948,7 @@ int processInlineBuffer(redisClient *c) {
|
||||
/* Helper function. Trims query buffer to make the function that processes
|
||||
* multi bulk requests idempotent. */
|
||||
static void setProtocolError(redisClient *c, int pos) {
|
||||
if (server.verbosity <= REDIS_VERBOSE) {
|
||||
if (server.verbosity >= REDIS_VERBOSE) {
|
||||
sds client = catClientInfoString(sdsempty(),c);
|
||||
redisLog(REDIS_VERBOSE,
|
||||
"Protocol error from client: %s", client);
|
||||
@@ -1064,7 +1051,7 @@ int processMultibulkBuffer(redisClient *c) {
|
||||
qblen = sdslen(c->querybuf);
|
||||
/* Hint the sds library about the amount of bytes this string is
|
||||
* going to contain. */
|
||||
if (qblen < (size_t)ll+2)
|
||||
if (qblen < ll+2)
|
||||
c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2-qblen);
|
||||
}
|
||||
c->bulklen = ll;
|
||||
@@ -1195,7 +1182,6 @@ void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
sdsIncrLen(c->querybuf,nread);
|
||||
c->lastinteraction = server.unixtime;
|
||||
if (c->flags & REDIS_MASTER) c->reploff += nread;
|
||||
server.stat_net_input_bytes += nread;
|
||||
} else {
|
||||
server.current_client = NULL;
|
||||
return;
|
||||
@@ -1244,9 +1230,9 @@ void formatPeerId(char *peerid, size_t peerid_len, char *ip, int port) {
|
||||
}
|
||||
|
||||
/* A Redis "Peer ID" is a colon separated ip:port pair.
|
||||
* For IPv4 it's in the form x.y.z.k:port, example: "127.0.0.1:1234".
|
||||
* For IPv4 it's in the form x.y.z.k:pork, example: "127.0.0.1:1234".
|
||||
* For IPv6 addresses we use [] around the IP part, like in "[::1]:1234".
|
||||
* For Unix sockets we use path:0, like in "/tmp/redis:0".
|
||||
* For Unix socekts we use path:0, like in "/tmp/redis:0".
|
||||
*
|
||||
* A Peer ID always fits inside a buffer of REDIS_PEER_ID_LEN bytes, including
|
||||
* the null term.
|
||||
@@ -1273,7 +1259,7 @@ int genClientPeerId(redisClient *client, char *peerid, size_t peerid_len) {
|
||||
}
|
||||
|
||||
/* This function returns the client peer id, by creating and caching it
|
||||
* if client->peerid is NULL, otherwise returning the cached value.
|
||||
* if client->perrid is NULL, otherwise returning the cached value.
|
||||
* The Peer ID never changes during the life of the client, however it
|
||||
* is expensive to compute. */
|
||||
char *getClientPeerId(redisClient *c) {
|
||||
@@ -1575,7 +1561,7 @@ unsigned long getClientOutputBufferMemoryUsage(redisClient *c) {
|
||||
int getClientType(redisClient *c) {
|
||||
if ((c->flags & REDIS_SLAVE) && !(c->flags & REDIS_MONITOR))
|
||||
return REDIS_CLIENT_TYPE_SLAVE;
|
||||
if (c->flags & REDIS_PUBSUB)
|
||||
if (dictSize(c->pubsub_channels) || listLength(c->pubsub_patterns))
|
||||
return REDIS_CLIENT_TYPE_PUBSUB;
|
||||
return REDIS_CLIENT_TYPE_NORMAL;
|
||||
}
|
||||
@@ -1666,12 +1652,6 @@ void flushSlavesOutputBuffers(void) {
|
||||
redisClient *slave = listNodeValue(ln);
|
||||
int events;
|
||||
|
||||
/* Note that the following will not flush output buffers of slaves
|
||||
* in STATE_ONLINE but having put_online_on_ack set to true: in this
|
||||
* case the writable event is never installed, since the purpose
|
||||
* of put_online_on_ack is to postpone the moment it is installed.
|
||||
* This is what we want since slaves in this state should not receive
|
||||
* writes before the first ACK. */
|
||||
events = aeGetFileEvents(server.el,slave->fd);
|
||||
if (events & AE_WRITABLE &&
|
||||
slave->replstate == REDIS_REPL_ONLINE &&
|
||||
@@ -1708,9 +1688,7 @@ void pauseClients(mstime_t end) {
|
||||
/* Return non-zero if clients are currently paused. As a side effect the
|
||||
* function checks if the pause time was reached and clear it. */
|
||||
int clientsArePaused(void) {
|
||||
if (server.clients_paused &&
|
||||
server.clients_pause_end_time < server.mstime)
|
||||
{
|
||||
if (server.clients_paused && server.clients_pause_end_time < server.mstime) {
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
redisClient *c;
|
||||
@@ -1723,10 +1701,7 @@ int clientsArePaused(void) {
|
||||
while ((ln = listNext(&li)) != NULL) {
|
||||
c = listNodeValue(ln);
|
||||
|
||||
/* Don't touch slaves and blocked clients. The latter pending
|
||||
* requests be processed when unblocked. */
|
||||
if (c->flags & (REDIS_SLAVE|REDIS_BLOCKED)) continue;
|
||||
c->flags |= REDIS_UNBLOCKED;
|
||||
if (c->flags & REDIS_SLAVE) continue;
|
||||
listAddNodeTail(server.unblocked_clients,c);
|
||||
}
|
||||
}
|
||||
|
||||
+18
-38
@@ -109,44 +109,26 @@ robj *createStringObjectFromLongLong(long long value) {
|
||||
return o;
|
||||
}
|
||||
|
||||
/* Create a string object from a long double. If humanfriendly is non-zero
|
||||
* it does not use exponential format and trims trailing zeroes at the end,
|
||||
* however this results in loss of precision. Otherwise exp format is used
|
||||
* and the output of snprintf() is not modified.
|
||||
*
|
||||
* The 'humanfriendly' option is used for INCRBYFLOAT and HINCRBYFLOAT. */
|
||||
robj *createStringObjectFromLongDouble(long double value, int humanfriendly) {
|
||||
/* Note: this function is defined into object.c since here it is where it
|
||||
* belongs but it is actually designed to be used just for INCRBYFLOAT */
|
||||
robj *createStringObjectFromLongDouble(long double value) {
|
||||
char buf[256];
|
||||
int len;
|
||||
|
||||
if (isinf(value)) {
|
||||
/* Libc in odd systems (Hi Solaris!) will format infinite in a
|
||||
* different way, so better to handle it in an explicit way. */
|
||||
if (value > 0) {
|
||||
memcpy(buf,"inf",3);
|
||||
len = 3;
|
||||
} else {
|
||||
memcpy(buf,"-inf",4);
|
||||
len = 4;
|
||||
/* We use 17 digits precision since with 128 bit floats that precision
|
||||
* after rounding is able to represent most small decimal numbers in a way
|
||||
* that is "non surprising" for the user (that is, most small decimal
|
||||
* numbers will be represented in a way that when converted back into
|
||||
* a string are exactly the same as what the user typed.) */
|
||||
len = snprintf(buf,sizeof(buf),"%.17Lf", value);
|
||||
/* Now remove trailing zeroes after the '.' */
|
||||
if (strchr(buf,'.') != NULL) {
|
||||
char *p = buf+len-1;
|
||||
while(*p == '0') {
|
||||
p--;
|
||||
len--;
|
||||
}
|
||||
} else if (humanfriendly) {
|
||||
/* We use 17 digits precision since with 128 bit floats that precision
|
||||
* after rounding is able to represent most small decimal numbers in a
|
||||
* way that is "non surprising" for the user (that is, most small
|
||||
* decimal numbers will be represented in a way that when converted
|
||||
* back into a string are exactly the same as what the user typed.) */
|
||||
len = snprintf(buf,sizeof(buf),"%.17Lf", value);
|
||||
/* Now remove trailing zeroes after the '.' */
|
||||
if (strchr(buf,'.') != NULL) {
|
||||
char *p = buf+len-1;
|
||||
while(*p == '0') {
|
||||
p--;
|
||||
len--;
|
||||
}
|
||||
if (*p == '.') len--;
|
||||
}
|
||||
} else {
|
||||
len = snprintf(buf,sizeof(buf),"%.17Lg", value);
|
||||
if (*p == '.') len--;
|
||||
}
|
||||
return createStringObject(buf,len);
|
||||
}
|
||||
@@ -391,9 +373,7 @@ 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 != REDIS_MAXMEMORY_VOLATILE_LRU &&
|
||||
server.maxmemory_policy != REDIS_MAXMEMORY_ALLKEYS_LRU)) &&
|
||||
if (server.maxmemory == 0 &&
|
||||
value >= 0 &&
|
||||
value < REDIS_SHARED_INTEGERS)
|
||||
{
|
||||
@@ -716,7 +696,7 @@ robj *objectCommandLookupOrReply(redisClient *c, robj *key, robj *reply) {
|
||||
}
|
||||
|
||||
/* Object command allows to inspect the internals of an Redis Object.
|
||||
* Usage: OBJECT <refcount|encoding|idletime> <key> */
|
||||
* Usage: OBJECT <verb> ... arguments ... */
|
||||
void objectCommand(redisClient *c) {
|
||||
robj *o;
|
||||
|
||||
|
||||
+4
-14
@@ -47,12 +47,6 @@ int listMatchPubsubPattern(void *a, void *b) {
|
||||
(equalStringObjects(pa->pattern,pb->pattern));
|
||||
}
|
||||
|
||||
/* Return the number of channels + patterns a client is subscribed to. */
|
||||
int clientSubscriptionsCount(redisClient *c) {
|
||||
return dictSize(c->pubsub_channels)+
|
||||
listLength(c->pubsub_patterns);
|
||||
}
|
||||
|
||||
/* 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(redisClient *c, robj *channel) {
|
||||
@@ -79,7 +73,7 @@ int pubsubSubscribeChannel(redisClient *c, robj *channel) {
|
||||
addReply(c,shared.mbulkhdr[3]);
|
||||
addReply(c,shared.subscribebulk);
|
||||
addReplyBulk(c,channel);
|
||||
addReplyLongLong(c,clientSubscriptionsCount(c));
|
||||
addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
|
||||
return retval;
|
||||
}
|
||||
|
||||
@@ -141,7 +135,7 @@ int pubsubSubscribePattern(redisClient *c, robj *pattern) {
|
||||
addReply(c,shared.mbulkhdr[3]);
|
||||
addReply(c,shared.psubscribebulk);
|
||||
addReplyBulk(c,pattern);
|
||||
addReplyLongLong(c,clientSubscriptionsCount(c));
|
||||
addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
|
||||
return retval;
|
||||
}
|
||||
|
||||
@@ -174,7 +168,7 @@ int pubsubUnsubscribePattern(redisClient *c, robj *pattern, int notify) {
|
||||
}
|
||||
|
||||
/* Unsubscribe from all the channels. Return the number of channels the
|
||||
* client was subscribed to. */
|
||||
* client was subscribed from. */
|
||||
int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
|
||||
dictIterator *di = dictGetSafeIterator(c->pubsub_channels);
|
||||
dictEntry *de;
|
||||
@@ -279,7 +273,6 @@ void subscribeCommand(redisClient *c) {
|
||||
|
||||
for (j = 1; j < c->argc; j++)
|
||||
pubsubSubscribeChannel(c,c->argv[j]);
|
||||
c->flags |= REDIS_PUBSUB;
|
||||
}
|
||||
|
||||
void unsubscribeCommand(redisClient *c) {
|
||||
@@ -291,7 +284,6 @@ void unsubscribeCommand(redisClient *c) {
|
||||
for (j = 1; j < c->argc; j++)
|
||||
pubsubUnsubscribeChannel(c,c->argv[j],1);
|
||||
}
|
||||
if (clientSubscriptionsCount(c) == 0) c->flags &= ~REDIS_PUBSUB;
|
||||
}
|
||||
|
||||
void psubscribeCommand(redisClient *c) {
|
||||
@@ -299,7 +291,6 @@ void psubscribeCommand(redisClient *c) {
|
||||
|
||||
for (j = 1; j < c->argc; j++)
|
||||
pubsubSubscribePattern(c,c->argv[j]);
|
||||
c->flags |= REDIS_PUBSUB;
|
||||
}
|
||||
|
||||
void punsubscribeCommand(redisClient *c) {
|
||||
@@ -311,7 +302,6 @@ void punsubscribeCommand(redisClient *c) {
|
||||
for (j = 1; j < c->argc; j++)
|
||||
pubsubUnsubscribePattern(c,c->argv[j],1);
|
||||
}
|
||||
if (clientSubscriptionsCount(c) == 0) c->flags &= ~REDIS_PUBSUB;
|
||||
}
|
||||
|
||||
void publishCommand(redisClient *c) {
|
||||
@@ -358,7 +348,7 @@ void pubsubCommand(redisClient *c) {
|
||||
list *l = dictFetchValue(server.pubsub_channels,c->argv[j]);
|
||||
|
||||
addReplyBulk(c,c->argv[j]);
|
||||
addReplyLongLong(c,l ? listLength(l) : 0);
|
||||
addReplyBulkLongLong(c,l ? listLength(l) : 0);
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"numpat") && c->argc == 2) {
|
||||
/* PUBSUB NUMPAT */
|
||||
|
||||
+2
-2
@@ -66,7 +66,7 @@
|
||||
#define HI_BIT (1L << (2 * N - 1))
|
||||
|
||||
static uint32_t x[3] = { X0, X1, X2 }, a[3] = { A0, A1, A2 }, c = C;
|
||||
static void next(void);
|
||||
static void next();
|
||||
|
||||
int32_t redisLrand48() {
|
||||
next();
|
||||
@@ -77,7 +77,7 @@ void redisSrand48(int32_t seedval) {
|
||||
SEED(X0, LOW(seedval), HIGH(seedval));
|
||||
}
|
||||
|
||||
static void next(void) {
|
||||
static void next() {
|
||||
uint32_t p[2], q[2], r[2], carry0, carry1;
|
||||
|
||||
MUL(a[0], x[0], p);
|
||||
|
||||
@@ -333,7 +333,7 @@ int rdbSaveStringObject(rio *rdb, robj *obj) {
|
||||
robj *rdbGenericLoadStringObject(rio *rdb, int encode) {
|
||||
int isencoded;
|
||||
uint32_t len;
|
||||
robj *o;
|
||||
sds val;
|
||||
|
||||
len = rdbLoadLen(rdb,&isencoded);
|
||||
if (isencoded) {
|
||||
@@ -350,13 +350,12 @@ robj *rdbGenericLoadStringObject(rio *rdb, int encode) {
|
||||
}
|
||||
|
||||
if (len == REDIS_RDB_LENERR) return NULL;
|
||||
o = encode ? createStringObject(NULL,len) :
|
||||
createRawStringObject(NULL,len);
|
||||
if (len && rioRead(rdb,o->ptr,len) == 0) {
|
||||
decrRefCount(o);
|
||||
val = sdsnewlen(NULL,len);
|
||||
if (len && rioRead(rdb,val,len) == 0) {
|
||||
sdsfree(val);
|
||||
return NULL;
|
||||
}
|
||||
return o;
|
||||
return createObject(REDIS_STRING,val);
|
||||
}
|
||||
|
||||
robj *rdbLoadStringObject(rio *rdb) {
|
||||
@@ -475,7 +474,7 @@ int rdbLoadObjectType(rio *rdb) {
|
||||
return type;
|
||||
}
|
||||
|
||||
/* Save a Redis object. Returns -1 on error, number of bytes written on success. */
|
||||
/* Save a Redis object. Returns -1 on error, 0 on success. */
|
||||
int rdbSaveObject(rio *rdb, robj *o) {
|
||||
int n, nwritten = 0;
|
||||
|
||||
@@ -627,100 +626,17 @@ int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val,
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Produces a dump of the database in RDB format sending it to the specified
|
||||
* Redis I/O channel. On success REDIS_OK is returned, otherwise REDIS_ERR
|
||||
* is returned and part of the output, or all the output, can be
|
||||
* missing because of I/O errors.
|
||||
*
|
||||
* When the function returns REDIS_ERR and if 'error' is not NULL, the
|
||||
* integer pointed by 'error' is set to the value of errno just after the I/O
|
||||
* error. */
|
||||
int rdbSaveRio(rio *rdb, int *error) {
|
||||
/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success */
|
||||
int rdbSave(char *filename) {
|
||||
dictIterator *di = NULL;
|
||||
dictEntry *de;
|
||||
char tmpfile[256];
|
||||
char magic[10];
|
||||
int j;
|
||||
long long now = mstime();
|
||||
uint64_t cksum;
|
||||
|
||||
if (server.rdb_checksum)
|
||||
rdb->update_cksum = rioGenericUpdateChecksum;
|
||||
snprintf(magic,sizeof(magic),"REDIS%04d",REDIS_RDB_VERSION);
|
||||
if (rdbWriteRaw(rdb,magic,9) == -1) goto werr;
|
||||
|
||||
for (j = 0; j < server.dbnum; j++) {
|
||||
redisDb *db = server.db+j;
|
||||
dict *d = db->dict;
|
||||
if (dictSize(d) == 0) continue;
|
||||
di = dictGetSafeIterator(d);
|
||||
if (!di) return REDIS_ERR;
|
||||
|
||||
/* Write the SELECT DB opcode */
|
||||
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_SELECTDB) == -1) goto werr;
|
||||
if (rdbSaveLen(rdb,j) == -1) goto werr;
|
||||
|
||||
/* Iterate this DB writing every entry */
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sds keystr = dictGetKey(de);
|
||||
robj key, *o = dictGetVal(de);
|
||||
long long expire;
|
||||
|
||||
initStaticStringObject(key,keystr);
|
||||
expire = getExpire(db,&key);
|
||||
if (rdbSaveKeyValuePair(rdb,&key,o,expire,now) == -1) goto werr;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
di = NULL; /* So that we don't release it again on error. */
|
||||
|
||||
/* EOF opcode */
|
||||
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_EOF) == -1) goto werr;
|
||||
|
||||
/* CRC64 checksum. It will be zero if checksum computation is disabled, the
|
||||
* loading code skips the check in this case. */
|
||||
cksum = rdb->cksum;
|
||||
memrev64ifbe(&cksum);
|
||||
if (rioWrite(rdb,&cksum,8) == 0) goto werr;
|
||||
return REDIS_OK;
|
||||
|
||||
werr:
|
||||
if (error) *error = errno;
|
||||
if (di) dictReleaseIterator(di);
|
||||
return REDIS_ERR;
|
||||
}
|
||||
|
||||
/* This is just a wrapper to rdbSaveRio() that additionally adds a prefix
|
||||
* and a suffix to the generated RDB dump. The prefix is:
|
||||
*
|
||||
* $EOF:<40 bytes unguessable hex string>\r\n
|
||||
*
|
||||
* While the suffix is the 40 bytes hex string we announced in the prefix.
|
||||
* This way processes receiving the payload can understand when it ends
|
||||
* without doing any processing of the content. */
|
||||
int rdbSaveRioWithEOFMark(rio *rdb, int *error) {
|
||||
char eofmark[REDIS_EOF_MARK_SIZE];
|
||||
|
||||
getRandomHexChars(eofmark,REDIS_EOF_MARK_SIZE);
|
||||
if (error) *error = 0;
|
||||
if (rioWrite(rdb,"$EOF:",5) == 0) goto werr;
|
||||
if (rioWrite(rdb,eofmark,REDIS_EOF_MARK_SIZE) == 0) goto werr;
|
||||
if (rioWrite(rdb,"\r\n",2) == 0) goto werr;
|
||||
if (rdbSaveRio(rdb,error) == REDIS_ERR) goto werr;
|
||||
if (rioWrite(rdb,eofmark,REDIS_EOF_MARK_SIZE) == 0) goto werr;
|
||||
return REDIS_OK;
|
||||
|
||||
werr: /* Write error. */
|
||||
/* Set 'error' only if not already set by rdbSaveRio() call. */
|
||||
if (error && *error == 0) *error = errno;
|
||||
return REDIS_ERR;
|
||||
}
|
||||
|
||||
/* Save the DB on disk. Return REDIS_ERR on error, REDIS_OK on success. */
|
||||
int rdbSave(char *filename) {
|
||||
char tmpfile[256];
|
||||
FILE *fp;
|
||||
rio rdb;
|
||||
int error;
|
||||
uint64_t cksum;
|
||||
|
||||
snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
|
||||
fp = fopen(tmpfile,"w");
|
||||
@@ -731,10 +647,47 @@ int rdbSave(char *filename) {
|
||||
}
|
||||
|
||||
rioInitWithFile(&rdb,fp);
|
||||
if (rdbSaveRio(&rdb,&error) == REDIS_ERR) {
|
||||
errno = error;
|
||||
goto werr;
|
||||
if (server.rdb_checksum)
|
||||
rdb.update_cksum = rioGenericUpdateChecksum;
|
||||
snprintf(magic,sizeof(magic),"REDIS%04d",REDIS_RDB_VERSION);
|
||||
if (rdbWriteRaw(&rdb,magic,9) == -1) goto werr;
|
||||
|
||||
for (j = 0; j < server.dbnum; j++) {
|
||||
redisDb *db = server.db+j;
|
||||
dict *d = db->dict;
|
||||
if (dictSize(d) == 0) continue;
|
||||
di = dictGetSafeIterator(d);
|
||||
if (!di) {
|
||||
fclose(fp);
|
||||
return REDIS_ERR;
|
||||
}
|
||||
|
||||
/* Write the SELECT DB opcode */
|
||||
if (rdbSaveType(&rdb,REDIS_RDB_OPCODE_SELECTDB) == -1) goto werr;
|
||||
if (rdbSaveLen(&rdb,j) == -1) goto werr;
|
||||
|
||||
/* Iterate this DB writing every entry */
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sds keystr = dictGetKey(de);
|
||||
robj key, *o = dictGetVal(de);
|
||||
long long expire;
|
||||
|
||||
initStaticStringObject(key,keystr);
|
||||
expire = getExpire(db,&key);
|
||||
if (rdbSaveKeyValuePair(&rdb,&key,o,expire,now) == -1) goto werr;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
di = NULL; /* So that we don't release it again on error. */
|
||||
|
||||
/* EOF opcode */
|
||||
if (rdbSaveType(&rdb,REDIS_RDB_OPCODE_EOF) == -1) goto werr;
|
||||
|
||||
/* CRC64 checksum. It will be zero if checksum computation is disabled, the
|
||||
* loading code skips the check in this case. */
|
||||
cksum = rdb.cksum;
|
||||
memrev64ifbe(&cksum);
|
||||
rioWrite(&rdb,&cksum,8);
|
||||
|
||||
/* Make sure data will not remain on the OS's output buffers */
|
||||
if (fflush(fp) == EOF) goto werr;
|
||||
@@ -755,9 +708,10 @@ int rdbSave(char *filename) {
|
||||
return REDIS_OK;
|
||||
|
||||
werr:
|
||||
redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
|
||||
fclose(fp);
|
||||
unlink(tmpfile);
|
||||
redisLog(REDIS_WARNING,"Write error saving DB on disk: %s", strerror(errno));
|
||||
if (di) dictReleaseIterator(di);
|
||||
return REDIS_ERR;
|
||||
}
|
||||
|
||||
@@ -802,7 +756,6 @@ int rdbSaveBackground(char *filename) {
|
||||
redisLog(REDIS_NOTICE,"Background saving started by pid %d",childpid);
|
||||
server.rdb_save_time_start = time(NULL);
|
||||
server.rdb_child_pid = childpid;
|
||||
server.rdb_child_type = REDIS_RDB_CHILD_TYPE_DISK;
|
||||
updateDictResizePolicy();
|
||||
return REDIS_OK;
|
||||
}
|
||||
@@ -812,7 +765,7 @@ int rdbSaveBackground(char *filename) {
|
||||
void rdbRemoveTempFile(pid_t childpid) {
|
||||
char tmpfile[256];
|
||||
|
||||
snprintf(tmpfile,sizeof(tmpfile),"temp-%d.rdb", (int) childpid);
|
||||
snprintf(tmpfile,256,"temp-%d.rdb", (int) childpid);
|
||||
unlink(tmpfile);
|
||||
}
|
||||
|
||||
@@ -989,7 +942,7 @@ robj *rdbLoadObject(int rdbtype, rio *rdb) {
|
||||
|
||||
/* Add pair to hash table */
|
||||
ret = dictAdd((dict*)o->ptr, field, value);
|
||||
redisAssert(ret == DICT_OK);
|
||||
redisAssert(ret == REDIS_OK);
|
||||
}
|
||||
|
||||
/* All pairs should be read by now */
|
||||
@@ -1087,9 +1040,8 @@ void startLoading(FILE *fp) {
|
||||
/* Load the DB */
|
||||
server.loading = 1;
|
||||
server.loading_start_time = time(NULL);
|
||||
server.loading_loaded_bytes = 0;
|
||||
if (fstat(fileno(fp), &sb) == -1) {
|
||||
server.loading_total_bytes = 0;
|
||||
server.loading_total_bytes = 1; /* just to avoid division by zero */
|
||||
} else {
|
||||
server.loading_total_bytes = sb.st_size;
|
||||
}
|
||||
@@ -1238,9 +1190,8 @@ eoferr: /* unexpected end of file is handled here with a fatal exit */
|
||||
return REDIS_ERR; /* Just to avoid warning */
|
||||
}
|
||||
|
||||
/* A background saving child (BGSAVE) terminated its work. Handle this.
|
||||
* This function covers the case of actual BGSAVEs. */
|
||||
void backgroundSaveDoneHandlerDisk(int exitcode, int bysignal) {
|
||||
/* A background saving child (BGSAVE) terminated its work. Handle this. */
|
||||
void backgroundSaveDoneHandler(int exitcode, int bysignal) {
|
||||
if (!bysignal && exitcode == 0) {
|
||||
redisLog(REDIS_NOTICE,
|
||||
"Background saving terminated with success");
|
||||
@@ -1265,276 +1216,11 @@ void backgroundSaveDoneHandlerDisk(int exitcode, int bysignal) {
|
||||
server.lastbgsave_status = REDIS_ERR;
|
||||
}
|
||||
server.rdb_child_pid = -1;
|
||||
server.rdb_child_type = REDIS_RDB_CHILD_TYPE_NONE;
|
||||
server.rdb_save_time_last = time(NULL)-server.rdb_save_time_start;
|
||||
server.rdb_save_time_start = -1;
|
||||
/* Possibly there are slaves waiting for a BGSAVE in order to be served
|
||||
* (the first stage of SYNC is a bulk transfer of dump.rdb) */
|
||||
updateSlavesWaitingBgsave((!bysignal && exitcode == 0) ? REDIS_OK : REDIS_ERR, REDIS_RDB_CHILD_TYPE_DISK);
|
||||
}
|
||||
|
||||
/* A background saving child (BGSAVE) terminated its work. Handle this.
|
||||
* This function covers the case of RDB -> Salves socket transfers for
|
||||
* diskless replication. */
|
||||
void backgroundSaveDoneHandlerSocket(int exitcode, int bysignal) {
|
||||
uint64_t *ok_slaves;
|
||||
|
||||
if (!bysignal && exitcode == 0) {
|
||||
redisLog(REDIS_NOTICE,
|
||||
"Background RDB transfer terminated with success");
|
||||
} else if (!bysignal && exitcode != 0) {
|
||||
redisLog(REDIS_WARNING, "Background transfer error");
|
||||
} else {
|
||||
redisLog(REDIS_WARNING,
|
||||
"Background transfer terminated by signal %d", bysignal);
|
||||
}
|
||||
server.rdb_child_pid = -1;
|
||||
server.rdb_child_type = REDIS_RDB_CHILD_TYPE_NONE;
|
||||
server.rdb_save_time_start = -1;
|
||||
|
||||
/* If the child returns an OK exit code, read the set of slave client
|
||||
* IDs and the associated status code. We'll terminate all the slaves
|
||||
* in error state.
|
||||
*
|
||||
* If the process returned an error, consider the list of slaves that
|
||||
* can continue to be emtpy, so that it's just a special case of the
|
||||
* normal code path. */
|
||||
ok_slaves = zmalloc(sizeof(uint64_t)); /* Make space for the count. */
|
||||
ok_slaves[0] = 0;
|
||||
if (!bysignal && exitcode == 0) {
|
||||
int readlen = sizeof(uint64_t);
|
||||
|
||||
if (read(server.rdb_pipe_read_result_from_child, ok_slaves, readlen) ==
|
||||
readlen)
|
||||
{
|
||||
readlen = ok_slaves[0]*sizeof(uint64_t)*2;
|
||||
|
||||
/* Make space for enough elements as specified by the first
|
||||
* uint64_t element in the array. */
|
||||
ok_slaves = zrealloc(ok_slaves,sizeof(uint64_t)+readlen);
|
||||
if (readlen &&
|
||||
read(server.rdb_pipe_read_result_from_child, ok_slaves+1,
|
||||
readlen) != readlen)
|
||||
{
|
||||
ok_slaves[0] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close(server.rdb_pipe_read_result_from_child);
|
||||
close(server.rdb_pipe_write_result_to_parent);
|
||||
|
||||
/* We can continue the replication process with all the slaves that
|
||||
* correctly received the full payload. Others are terminated. */
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
|
||||
listRewind(server.slaves,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
redisClient *slave = ln->value;
|
||||
|
||||
if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_END) {
|
||||
uint64_t j;
|
||||
int errorcode = 0;
|
||||
|
||||
/* Search for the slave ID in the reply. In order for a slave to
|
||||
* continue the replication process, we need to find it in the list,
|
||||
* and it must have an error code set to 0 (which means success). */
|
||||
for (j = 0; j < ok_slaves[0]; j++) {
|
||||
if (slave->id == ok_slaves[2*j+1]) {
|
||||
errorcode = ok_slaves[2*j+2];
|
||||
break; /* Found in slaves list. */
|
||||
}
|
||||
}
|
||||
if (j == ok_slaves[0] || errorcode != 0) {
|
||||
redisLog(REDIS_WARNING,
|
||||
"Closing slave %s: child->slave RDB transfer failed: %s",
|
||||
replicationGetSlaveName(slave),
|
||||
(errorcode == 0) ? "RDB transfer child aborted"
|
||||
: strerror(errorcode));
|
||||
freeClient(slave);
|
||||
} else {
|
||||
redisLog(REDIS_WARNING,
|
||||
"Slave %s correctly received the streamed RDB file.",
|
||||
replicationGetSlaveName(slave));
|
||||
/* Restore the socket as non-blocking. */
|
||||
anetNonBlock(NULL,slave->fd);
|
||||
anetSendTimeout(NULL,slave->fd,0);
|
||||
}
|
||||
}
|
||||
}
|
||||
zfree(ok_slaves);
|
||||
|
||||
updateSlavesWaitingBgsave((!bysignal && exitcode == 0) ? REDIS_OK : REDIS_ERR, REDIS_RDB_CHILD_TYPE_SOCKET);
|
||||
}
|
||||
|
||||
/* When a background RDB saving/transfer terminates, call the right handler. */
|
||||
void backgroundSaveDoneHandler(int exitcode, int bysignal) {
|
||||
switch(server.rdb_child_type) {
|
||||
case REDIS_RDB_CHILD_TYPE_DISK:
|
||||
backgroundSaveDoneHandlerDisk(exitcode,bysignal);
|
||||
break;
|
||||
case REDIS_RDB_CHILD_TYPE_SOCKET:
|
||||
backgroundSaveDoneHandlerSocket(exitcode,bysignal);
|
||||
break;
|
||||
default:
|
||||
redisPanic("Unknown RDB child type.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Spawn an RDB child that writes the RDB to the sockets of the slaves
|
||||
* that are currently in REDIS_REPL_WAIT_BGSAVE_START state. */
|
||||
int rdbSaveToSlavesSockets(void) {
|
||||
int *fds;
|
||||
uint64_t *clientids;
|
||||
int numfds;
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
pid_t childpid;
|
||||
long long start;
|
||||
int pipefds[2];
|
||||
|
||||
if (server.rdb_child_pid != -1) return REDIS_ERR;
|
||||
|
||||
/* Before to fork, create a pipe that will be used in order to
|
||||
* send back to the parent the IDs of the slaves that successfully
|
||||
* received all the writes. */
|
||||
if (pipe(pipefds) == -1) return REDIS_ERR;
|
||||
server.rdb_pipe_read_result_from_child = pipefds[0];
|
||||
server.rdb_pipe_write_result_to_parent = pipefds[1];
|
||||
|
||||
/* Collect the file descriptors of the slaves we want to transfer
|
||||
* the RDB to, which are i WAIT_BGSAVE_START state. */
|
||||
fds = zmalloc(sizeof(int)*listLength(server.slaves));
|
||||
/* We also allocate an array of corresponding client IDs. This will
|
||||
* be useful for the child process in order to build the report
|
||||
* (sent via unix pipe) that will be sent to the parent. */
|
||||
clientids = zmalloc(sizeof(uint64_t)*listLength(server.slaves));
|
||||
numfds = 0;
|
||||
|
||||
listRewind(server.slaves,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
redisClient *slave = ln->value;
|
||||
|
||||
if (slave->replstate == REDIS_REPL_WAIT_BGSAVE_START) {
|
||||
clientids[numfds] = slave->id;
|
||||
fds[numfds++] = slave->fd;
|
||||
replicationSetupSlaveForFullResync(slave,getPsyncInitialOffset());
|
||||
/* Put the socket in non-blocking mode to simplify RDB transfer.
|
||||
* We'll restore it when the children returns (since duped socket
|
||||
* will share the O_NONBLOCK attribute with the parent). */
|
||||
anetBlock(NULL,slave->fd);
|
||||
anetSendTimeout(NULL,slave->fd,server.repl_timeout*1000);
|
||||
}
|
||||
}
|
||||
|
||||
/* Create the child process. */
|
||||
start = ustime();
|
||||
if ((childpid = fork()) == 0) {
|
||||
/* Child */
|
||||
int retval;
|
||||
rio slave_sockets;
|
||||
|
||||
rioInitWithFdset(&slave_sockets,fds,numfds);
|
||||
zfree(fds);
|
||||
|
||||
closeListeningSockets(0);
|
||||
redisSetProcTitle("redis-rdb-to-slaves");
|
||||
|
||||
retval = rdbSaveRioWithEOFMark(&slave_sockets,NULL);
|
||||
if (retval == REDIS_OK && rioFlush(&slave_sockets) == 0)
|
||||
retval = REDIS_ERR;
|
||||
|
||||
if (retval == REDIS_OK) {
|
||||
size_t private_dirty = zmalloc_get_private_dirty();
|
||||
|
||||
if (private_dirty) {
|
||||
redisLog(REDIS_NOTICE,
|
||||
"RDB: %zu MB of memory used by copy-on-write",
|
||||
private_dirty/(1024*1024));
|
||||
}
|
||||
|
||||
/* If we are returning OK, at least one slave was served
|
||||
* with the RDB file as expected, so we need to send a report
|
||||
* to the parent via the pipe. The format of the message is:
|
||||
*
|
||||
* <len> <slave[0].id> <slave[0].error> ...
|
||||
*
|
||||
* len, slave IDs, and slave errors, are all uint64_t integers,
|
||||
* so basically the reply is composed of 64 bits for the len field
|
||||
* plus 2 additional 64 bit integers for each entry, for a total
|
||||
* of 'len' entries.
|
||||
*
|
||||
* The 'id' represents the slave's client ID, so that the master
|
||||
* can match the report with a specific slave, and 'error' is
|
||||
* set to 0 if the replication process terminated with a success
|
||||
* or the error code if an error occurred. */
|
||||
void *msg = zmalloc(sizeof(uint64_t)*(1+2*numfds));
|
||||
uint64_t *len = msg;
|
||||
uint64_t *ids = len+1;
|
||||
int j, msglen;
|
||||
|
||||
*len = numfds;
|
||||
for (j = 0; j < numfds; j++) {
|
||||
*ids++ = clientids[j];
|
||||
*ids++ = slave_sockets.io.fdset.state[j];
|
||||
}
|
||||
|
||||
/* Write the message to the parent. If we have no good slaves or
|
||||
* we are unable to transfer the message to the parent, we exit
|
||||
* with an error so that the parent will abort the replication
|
||||
* process with all the childre that were waiting. */
|
||||
msglen = sizeof(uint64_t)*(1+2*numfds);
|
||||
if (*len == 0 ||
|
||||
write(server.rdb_pipe_write_result_to_parent,msg,msglen)
|
||||
!= msglen)
|
||||
{
|
||||
retval = REDIS_ERR;
|
||||
}
|
||||
zfree(msg);
|
||||
}
|
||||
zfree(clientids);
|
||||
exitFromChild((retval == REDIS_OK) ? 0 : 1);
|
||||
} else {
|
||||
/* Parent */
|
||||
server.stat_fork_time = ustime()-start;
|
||||
server.stat_fork_rate = (double) zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024); /* GB per second. */
|
||||
latencyAddSampleIfNeeded("fork",server.stat_fork_time/1000);
|
||||
if (childpid == -1) {
|
||||
redisLog(REDIS_WARNING,"Can't save in background: fork: %s",
|
||||
strerror(errno));
|
||||
|
||||
/* Undo the state change. The caller will perform cleanup on
|
||||
* all the slaves in BGSAVE_START state, but an early call to
|
||||
* replicationSetupSlaveForFullResync() turned it into BGSAVE_END */
|
||||
listRewind(server.slaves,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
redisClient *slave = ln->value;
|
||||
int j;
|
||||
|
||||
for (j = 0; j < numfds; j++) {
|
||||
if (slave->id == clientids[j]) {
|
||||
slave->replstate = REDIS_REPL_WAIT_BGSAVE_START;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
close(pipefds[0]);
|
||||
close(pipefds[1]);
|
||||
} else {
|
||||
redisLog(REDIS_NOTICE,"Background RDB transfer started by pid %d",
|
||||
childpid);
|
||||
server.rdb_save_time_start = time(NULL);
|
||||
server.rdb_child_pid = childpid;
|
||||
server.rdb_child_type = REDIS_RDB_CHILD_TYPE_SOCKET;
|
||||
updateDictResizePolicy();
|
||||
}
|
||||
zfree(clientids);
|
||||
zfree(fds);
|
||||
return (childpid == -1) ? REDIS_ERR : REDIS_OK;
|
||||
}
|
||||
return REDIS_OK; /* Unreached. */
|
||||
updateSlavesWaitingBgsave(exitcode == 0 ? REDIS_OK : REDIS_ERR);
|
||||
}
|
||||
|
||||
void saveCommand(redisClient *c) {
|
||||
|
||||
@@ -101,7 +101,6 @@ int rdbSaveObjectType(rio *rdb, robj *o);
|
||||
int rdbLoadObjectType(rio *rdb);
|
||||
int rdbLoad(char *filename);
|
||||
int rdbSaveBackground(char *filename);
|
||||
int rdbSaveToSlavesSockets(void);
|
||||
void rdbRemoveTempFile(pid_t childpid);
|
||||
int rdbSave(char *filename);
|
||||
int rdbSaveObject(rio *rdb, robj *o);
|
||||
|
||||
+44
-56
@@ -77,7 +77,6 @@ static struct config {
|
||||
int dbnum;
|
||||
sds dbnumstr;
|
||||
char *tests;
|
||||
char *auth;
|
||||
} config;
|
||||
|
||||
typedef struct _client {
|
||||
@@ -90,10 +89,9 @@ typedef struct _client {
|
||||
long long start; /* Start time of a request */
|
||||
long long latency; /* Request latency */
|
||||
int pending; /* Number of pending requests (replies to consume) */
|
||||
int prefix_pending; /* If non-zero, number of pending prefix commands. Commands
|
||||
such as auth and select are prefixed to the pipeline of
|
||||
benchmark commands and discarded after the first send. */
|
||||
int prefixlen; /* Size in bytes of the pending prefix commands */
|
||||
int selectlen; /* If non-zero, a SELECT of 'selectlen' bytes is currently
|
||||
used as a prefix of the pipline of commands. This gets
|
||||
discarded the first time it's sent. */
|
||||
} *client;
|
||||
|
||||
/* Prototypes */
|
||||
@@ -213,21 +211,20 @@ static void readHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
}
|
||||
|
||||
freeReplyObject(reply);
|
||||
/* This is an OK for prefix commands such as auth and select.*/
|
||||
if (c->prefix_pending > 0) {
|
||||
c->prefix_pending--;
|
||||
|
||||
if (c->selectlen) {
|
||||
int j;
|
||||
|
||||
/* This is the OK from SELECT. Just discard the SELECT
|
||||
* from the buffer. */
|
||||
c->pending--;
|
||||
/* Discard prefix commands on first response.*/
|
||||
if (c->prefixlen > 0) {
|
||||
size_t j;
|
||||
sdsrange(c->obuf, c->prefixlen, -1);
|
||||
/* We also need to fix the pointers to the strings
|
||||
* we need to randomize. */
|
||||
for (j = 0; j < c->randlen; j++)
|
||||
c->randptr[j] -= c->prefixlen;
|
||||
c->prefixlen = 0;
|
||||
}
|
||||
continue;
|
||||
sdsrange(c->obuf,c->selectlen,-1);
|
||||
/* We also need to fix the pointers to the strings
|
||||
* we need to randomize. */
|
||||
for (j = 0; j < c->randlen; j++)
|
||||
c->randptr[j] -= c->selectlen;
|
||||
c->selectlen = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (config.requests_finished < config.requests)
|
||||
@@ -301,7 +298,8 @@ static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
* 2) The offsets of the __rand_int__ elements inside the command line, used
|
||||
* for arguments randomization.
|
||||
*
|
||||
* Even when cloning another client, prefix commands are applied if needed.*/
|
||||
* Even when cloning another client, the SELECT command is automatically prefixed
|
||||
* if needed. */
|
||||
static client createClient(char *cmd, size_t len, client from) {
|
||||
int j;
|
||||
client c = zmalloc(sizeof(struct _client));
|
||||
@@ -326,17 +324,6 @@ static client createClient(char *cmd, size_t len, client from) {
|
||||
* Queue N requests accordingly to the pipeline size, or simply clone
|
||||
* the example client buffer. */
|
||||
c->obuf = sdsempty();
|
||||
/* Prefix the request buffer with AUTH and/or SELECT commands, if applicable.
|
||||
* These commands are discarded after the first response, so if the client is
|
||||
* reused the commands will not be used again. */
|
||||
c->prefix_pending = 0;
|
||||
if (config.auth) {
|
||||
char *buf = NULL;
|
||||
int len = redisFormatCommand(&buf, "AUTH %s", config.auth);
|
||||
c->obuf = sdscatlen(c->obuf, buf, len);
|
||||
free(buf);
|
||||
c->prefix_pending++;
|
||||
}
|
||||
|
||||
/* If a DB number different than zero is selected, prefix our request
|
||||
* buffer with the SELECT command, that will be discarded the first
|
||||
@@ -345,23 +332,25 @@ static client createClient(char *cmd, size_t len, client from) {
|
||||
if (config.dbnum != 0) {
|
||||
c->obuf = sdscatprintf(c->obuf,"*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n",
|
||||
(int)sdslen(config.dbnumstr),config.dbnumstr);
|
||||
c->prefix_pending++;
|
||||
c->selectlen = sdslen(c->obuf);
|
||||
} else {
|
||||
c->selectlen = 0;
|
||||
}
|
||||
c->prefixlen = sdslen(c->obuf);
|
||||
|
||||
/* Append the request itself. */
|
||||
if (from) {
|
||||
c->obuf = sdscatlen(c->obuf,
|
||||
from->obuf+from->prefixlen,
|
||||
sdslen(from->obuf)-from->prefixlen);
|
||||
from->obuf+from->selectlen,
|
||||
sdslen(from->obuf)-from->selectlen);
|
||||
} else {
|
||||
for (j = 0; j < config.pipeline; j++)
|
||||
c->obuf = sdscatlen(c->obuf,cmd,len);
|
||||
}
|
||||
|
||||
c->written = 0;
|
||||
c->pending = config.pipeline+c->prefix_pending;
|
||||
c->pending = config.pipeline;
|
||||
c->randptr = NULL;
|
||||
c->randlen = 0;
|
||||
if (c->selectlen) c->pending++;
|
||||
|
||||
/* Find substrings in the output buffer that need to be randomized. */
|
||||
if (config.randomkeys) {
|
||||
@@ -370,10 +359,10 @@ static client createClient(char *cmd, size_t len, client from) {
|
||||
c->randfree = 0;
|
||||
c->randptr = zmalloc(sizeof(char*)*c->randlen);
|
||||
/* copy the offsets. */
|
||||
for (j = 0; j < (int)c->randlen; j++) {
|
||||
for (j = 0; j < c->randlen; j++) {
|
||||
c->randptr[j] = c->obuf + (from->randptr[j]-from->obuf);
|
||||
/* Adjust for the different select prefix length. */
|
||||
c->randptr[j] += c->prefixlen - from->prefixlen;
|
||||
c->randptr[j] += c->selectlen - from->selectlen;
|
||||
}
|
||||
} else {
|
||||
char *p = c->obuf;
|
||||
@@ -392,8 +381,7 @@ static client createClient(char *cmd, size_t len, client from) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (config.idlemode == 0)
|
||||
aeCreateFileEvent(config.el,c->context->fd,AE_WRITABLE,writeHandler,c);
|
||||
aeCreateFileEvent(config.el,c->context->fd,AE_WRITABLE,writeHandler,c);
|
||||
listAddNodeTail(config.clients,c);
|
||||
config.liveclients++;
|
||||
return c;
|
||||
@@ -401,6 +389,15 @@ static client createClient(char *cmd, size_t len, client from) {
|
||||
|
||||
static void createMissingClients(client c) {
|
||||
int n = 0;
|
||||
char *buf = c->obuf;
|
||||
size_t buflen = sdslen(c->obuf);
|
||||
|
||||
/* If we are cloning from a client with a SELECT prefix, skip it since the
|
||||
* client will be created with the prefixed SELECT if needed. */
|
||||
if (c->selectlen) {
|
||||
buf += c->selectlen;
|
||||
buflen -= c->selectlen;
|
||||
}
|
||||
|
||||
while(config.liveclients < config.numclients) {
|
||||
createClient(NULL,0,c);
|
||||
@@ -492,9 +489,6 @@ int parseOptions(int argc, const char **argv) {
|
||||
} else if (!strcmp(argv[i],"-s")) {
|
||||
if (lastarg) goto invalid;
|
||||
config.hostsocket = strdup(argv[++i]);
|
||||
} else if (!strcmp(argv[i],"-a") ) {
|
||||
if (lastarg) goto invalid;
|
||||
config.auth = strdup(argv[++i]);
|
||||
} else if (!strcmp(argv[i],"-d")) {
|
||||
if (lastarg) goto invalid;
|
||||
config.datasize = atoi(argv[++i]);
|
||||
@@ -556,9 +550,8 @@ usage:
|
||||
" -h <hostname> Server hostname (default 127.0.0.1)\n"
|
||||
" -p <port> Server port (default 6379)\n"
|
||||
" -s <socket> Server socket (overrides host and port)\n"
|
||||
" -a <password> Password for Redis Auth\n"
|
||||
" -c <clients> Number of parallel connections (default 50)\n"
|
||||
" -n <requests> Total number of requests (default 100000)\n"
|
||||
" -n <requests> Total number of requests (default 10000)\n"
|
||||
" -d <size> Data size of SET/GET value in bytes (default 2)\n"
|
||||
" -dbnum <db> SELECT the specified db number (default 0)\n"
|
||||
" -k <boolean> 1=keep alive 0=reconnect (default 1)\n"
|
||||
@@ -600,15 +593,11 @@ int showThroughput(struct aeEventLoop *eventLoop, long long id, void *clientData
|
||||
REDIS_NOTUSED(clientData);
|
||||
|
||||
if (config.liveclients == 0) {
|
||||
fprintf(stderr,"All clients disconnected... aborting.\n");
|
||||
fprintf(stderr,"All clients disconnected... aborting.");
|
||||
exit(1);
|
||||
}
|
||||
if (config.csv) return 250;
|
||||
if (config.idlemode == 1) {
|
||||
printf("clients: %d\r", config.liveclients);
|
||||
fflush(stdout);
|
||||
return 250;
|
||||
}
|
||||
|
||||
if (config.csv) return 250;
|
||||
float dt = (float)(mstime()-config.start)/1000.0;
|
||||
float rps = (float)config.requests_finished/dt;
|
||||
printf("%s: %.2f\r", config.title, rps);
|
||||
@@ -642,7 +631,7 @@ int main(int argc, const char **argv) {
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
|
||||
config.numclients = 50;
|
||||
config.requests = 100000;
|
||||
config.requests = 10000;
|
||||
config.liveclients = 0;
|
||||
config.el = aeCreateEventLoop(1024*10);
|
||||
aeCreateTimeEvent(config.el,1,showThroughput,NULL,NULL);
|
||||
@@ -662,7 +651,6 @@ int main(int argc, const char **argv) {
|
||||
config.hostsocket = NULL;
|
||||
config.tests = NULL;
|
||||
config.dbnum = 0;
|
||||
config.auth = NULL;
|
||||
|
||||
i = parseOptions(argc,argv);
|
||||
argc -= i;
|
||||
@@ -700,8 +688,8 @@ int main(int argc, const char **argv) {
|
||||
}
|
||||
|
||||
/* Run default benchmark suite. */
|
||||
data = zmalloc(config.datasize+1);
|
||||
do {
|
||||
data = zmalloc(config.datasize+1);
|
||||
memset(data,'x',config.datasize);
|
||||
data[config.datasize] = '\0';
|
||||
|
||||
|
||||
@@ -138,10 +138,8 @@ typedef struct {
|
||||
* at runtime to avoid strange compiler optimizations. */
|
||||
static double R_Zero, R_PosInf, R_NegInf, R_Nan;
|
||||
|
||||
#define MAX_TYPES_NUM 256
|
||||
#define MAX_TYPE_NAME_LEN 16
|
||||
/* store string types for output */
|
||||
static char types[MAX_TYPES_NUM][MAX_TYPE_NAME_LEN];
|
||||
static char types[256][16];
|
||||
|
||||
/* Return true if 't' is a valid object type. */
|
||||
int checkType(unsigned char t) {
|
||||
@@ -168,7 +166,7 @@ int readBytes(void *target, long num) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int processHeader(void) {
|
||||
int processHeader() {
|
||||
char buf[10] = "_________";
|
||||
int dump_version;
|
||||
|
||||
@@ -337,7 +335,6 @@ char* loadStringObject() {
|
||||
if (len == REDIS_RDB_LENERR) return NULL;
|
||||
|
||||
char *buf = malloc(sizeof(char) * (len+1));
|
||||
if (buf == NULL) return NULL;
|
||||
buf[len] = '\0';
|
||||
if (!readBytes(buf, len)) {
|
||||
free(buf);
|
||||
@@ -603,7 +600,7 @@ void printErrorStack(entry *e) {
|
||||
}
|
||||
}
|
||||
|
||||
void process(void) {
|
||||
void process() {
|
||||
uint64_t num_errors = 0, num_valid_ops = 0, num_valid_bytes = 0;
|
||||
entry entry;
|
||||
int dump_version = processHeader();
|
||||
@@ -614,7 +611,7 @@ void process(void) {
|
||||
printf("RDB version >= 5 but no room for checksum.\n");
|
||||
exit(1);
|
||||
}
|
||||
positions[0].size -= 8;
|
||||
positions[0].size -= 8;;
|
||||
}
|
||||
|
||||
level = 1;
|
||||
|
||||
+63
-408
@@ -44,7 +44,6 @@
|
||||
#include <assert.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "hiredis.h"
|
||||
#include "sds.h"
|
||||
@@ -61,19 +60,6 @@
|
||||
#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"
|
||||
|
||||
/* --latency-dist palettes. */
|
||||
int spectrum_palette_color_size = 19;
|
||||
int spectrum_palette_color[] = {0,233,234,235,237,239,241,243,245,247,144,143,142,184,226,214,208,202,196};
|
||||
|
||||
int spectrum_palette_mono_size = 13;
|
||||
int spectrum_palette_mono[] = {0,233,234,235,237,239,241,243,245,247,249,251,253};
|
||||
|
||||
/* The actual palette in use. */
|
||||
int *spectrum_palette;
|
||||
int spectrum_palette_size;
|
||||
|
||||
static redisContext *context;
|
||||
static struct config {
|
||||
@@ -88,10 +74,7 @@ static struct config {
|
||||
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;
|
||||
@@ -111,11 +94,10 @@ static struct config {
|
||||
sds mb_delim;
|
||||
char prompt[128];
|
||||
char *eval;
|
||||
int last_cmd_type;
|
||||
} config;
|
||||
|
||||
static volatile sig_atomic_t force_cancel_loop = 0;
|
||||
static void usage(void);
|
||||
static void usage();
|
||||
static void slaveMode(void);
|
||||
char *redisGitSHA1(void);
|
||||
char *redisGitDirty(void);
|
||||
@@ -149,36 +131,12 @@ static void cliRefreshPrompt(void) {
|
||||
strchr(config.hostip,':') ? "[%s]:%d" : "%s:%d",
|
||||
config.hostip, config.hostport);
|
||||
/* Add [dbnum] if needed */
|
||||
if (config.dbnum != 0 && config.last_cmd_type != REDIS_REPLY_ERROR)
|
||||
if (config.dbnum != 0)
|
||||
len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
|
||||
config.dbnum);
|
||||
snprintf(config.prompt+len,sizeof(config.prompt)-len,"> ");
|
||||
}
|
||||
|
||||
static sds getHistoryPath() {
|
||||
char *path = NULL;
|
||||
sds historyPath = NULL;
|
||||
|
||||
/* check the env for a histfile override */
|
||||
path = getenv(REDIS_CLI_HISTFILE_ENV);
|
||||
if (path != NULL && *path != '\0') {
|
||||
if (!strcmp("/dev/null", path)) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* if the env is set, return it */
|
||||
historyPath = sdscatprintf(sdsempty(), "%s", path);
|
||||
} else {
|
||||
char *home = getenv("HOME");
|
||||
if (home != NULL && *home != '\0') {
|
||||
/* otherwise, return the default */
|
||||
historyPath = sdscatprintf(sdsempty(), "%s/%s", home, REDIS_CLI_HISTFILE_DEFAULT);
|
||||
}
|
||||
}
|
||||
|
||||
return historyPath;
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
* Help functions
|
||||
*--------------------------------------------------------------------------- */
|
||||
@@ -199,7 +157,7 @@ typedef struct {
|
||||
static helpEntry *helpEntries;
|
||||
static int helpEntriesLen;
|
||||
|
||||
static sds cliVersion(void) {
|
||||
static sds cliVersion() {
|
||||
sds version;
|
||||
version = sdscatprintf(sdsempty(), "%s", REDIS_VERSION);
|
||||
|
||||
@@ -213,7 +171,7 @@ static sds cliVersion(void) {
|
||||
return version;
|
||||
}
|
||||
|
||||
static void cliInitHelp(void) {
|
||||
static void cliInitHelp() {
|
||||
int commandslen = sizeof(commandHelp)/sizeof(struct commandHelp);
|
||||
int groupslen = sizeof(commandGroups)/sizeof(char*);
|
||||
int i, len, pos = 0;
|
||||
@@ -252,7 +210,7 @@ static void cliOutputCommandHelp(struct commandHelp *help, int group) {
|
||||
}
|
||||
|
||||
/* Print generic help. */
|
||||
static void cliOutputGenericHelp(void) {
|
||||
static void cliOutputGenericHelp() {
|
||||
sds version = cliVersion();
|
||||
printf(
|
||||
"redis-cli %s\r\n"
|
||||
@@ -343,7 +301,7 @@ static void completionCallback(const char *buf, linenoiseCompletions *lc) {
|
||||
*--------------------------------------------------------------------------- */
|
||||
|
||||
/* Send AUTH command to the server */
|
||||
static int cliAuth(void) {
|
||||
static int cliAuth() {
|
||||
redisReply *reply;
|
||||
if (config.auth == NULL) return REDIS_OK;
|
||||
|
||||
@@ -356,16 +314,14 @@ static int cliAuth(void) {
|
||||
}
|
||||
|
||||
/* Send SELECT dbnum to the server */
|
||||
static int cliSelect(void) {
|
||||
static int cliSelect() {
|
||||
redisReply *reply;
|
||||
if (config.dbnum == 0) return REDIS_OK;
|
||||
|
||||
reply = redisCommand(context,"SELECT %d",config.dbnum);
|
||||
if (reply != NULL) {
|
||||
int result = REDIS_OK;
|
||||
if (reply->type == REDIS_REPLY_ERROR) result = REDIS_ERR;
|
||||
freeReplyObject(reply);
|
||||
return result;
|
||||
return REDIS_OK;
|
||||
}
|
||||
return REDIS_ERR;
|
||||
}
|
||||
@@ -409,7 +365,7 @@ static int cliConnect(int force) {
|
||||
return REDIS_OK;
|
||||
}
|
||||
|
||||
static void cliPrintContextError(void) {
|
||||
static void cliPrintContextError() {
|
||||
if (context == NULL) return;
|
||||
fprintf(stderr,"Error: %s\n",context->errstr);
|
||||
}
|
||||
@@ -534,7 +490,7 @@ static sds cliFormatReplyCSV(redisReply *r) {
|
||||
out = sdscatrepr(out,r->str,r->len);
|
||||
break;
|
||||
case REDIS_REPLY_NIL:
|
||||
out = sdscat(out,"NIL");
|
||||
out = sdscat(out,"NIL\n");
|
||||
break;
|
||||
case REDIS_REPLY_ARRAY:
|
||||
for (i = 0; i < r->elements; i++) {
|
||||
@@ -558,15 +514,11 @@ static int cliReadReply(int output_raw_strings) {
|
||||
int output = 1;
|
||||
|
||||
if (redisGetReply(context,&_reply) != REDIS_OK) {
|
||||
if (config.shutdown) {
|
||||
redisFree(context);
|
||||
context = NULL;
|
||||
if (config.shutdown)
|
||||
return REDIS_OK;
|
||||
}
|
||||
if (config.interactive) {
|
||||
/* Filter cases where we should reconnect */
|
||||
if (context->err == REDIS_ERR_IO &&
|
||||
(errno == ECONNRESET || errno == EPIPE))
|
||||
if (context->err == REDIS_ERR_IO && errno == ECONNRESET)
|
||||
return REDIS_ERR;
|
||||
if (context->err == REDIS_ERR_EOF)
|
||||
return REDIS_ERR;
|
||||
@@ -578,8 +530,6 @@ static int cliReadReply(int output_raw_strings) {
|
||||
|
||||
reply = (redisReply*)_reply;
|
||||
|
||||
config.last_cmd_type = reply->type;
|
||||
|
||||
/* Check if we need to connect to a different node and reissue the
|
||||
* request. */
|
||||
if (config.cluster_mode && reply->type == REDIS_REPLY_ERROR &&
|
||||
@@ -689,7 +639,6 @@ static int cliSendCommand(int argc, char **argv, int repeat) {
|
||||
printf("Entering slave output mode... (press Ctrl-C to quit)\n");
|
||||
slaveMode();
|
||||
config.slave_mode = 0;
|
||||
free(argvlen);
|
||||
return REDIS_ERR; /* Error = slaveMode lost connection to master */
|
||||
}
|
||||
|
||||
@@ -701,8 +650,6 @@ static int cliSendCommand(int argc, char **argv, int repeat) {
|
||||
if (!strcasecmp(command,"select") && argc == 2) {
|
||||
config.dbnum = atoi(argv[1]);
|
||||
cliRefreshPrompt();
|
||||
} else if (!strcasecmp(command,"auth") && argc == 2) {
|
||||
cliSelect();
|
||||
}
|
||||
}
|
||||
if (config.interval) usleep(config.interval);
|
||||
@@ -713,17 +660,16 @@ static int cliSendCommand(int argc, char **argv, int repeat) {
|
||||
return REDIS_OK;
|
||||
}
|
||||
|
||||
/* Send a command reconnecting the link if needed. */
|
||||
static redisReply *reconnectingRedisCommand(redisContext *c, const char *fmt, ...) {
|
||||
/* Send the INFO command, reconnecting the link if needed. */
|
||||
static redisReply *reconnectingInfo(void) {
|
||||
redisContext *c = context;
|
||||
redisReply *reply = NULL;
|
||||
int tries = 0;
|
||||
va_list ap;
|
||||
|
||||
assert(!c->err);
|
||||
while(reply == NULL) {
|
||||
while (c->err & (REDIS_ERR_IO | REDIS_ERR_EOF)) {
|
||||
printf("\r\x1b[0K"); /* Cursor to left edge + clear line. */
|
||||
printf("Reconnecting... %d\r", ++tries);
|
||||
printf("Reconnecting (%d)...\r", ++tries);
|
||||
fflush(stdout);
|
||||
|
||||
redisFree(c);
|
||||
@@ -731,15 +677,12 @@ static redisReply *reconnectingRedisCommand(redisContext *c, const char *fmt, ..
|
||||
usleep(1000000);
|
||||
}
|
||||
|
||||
va_start(ap,fmt);
|
||||
reply = redisvCommand(c,fmt,ap);
|
||||
va_end(ap);
|
||||
|
||||
reply = redisCommand(c,"INFO");
|
||||
if (c->err && !(c->err & (REDIS_ERR_IO | REDIS_ERR_EOF))) {
|
||||
fprintf(stderr, "Error: %s\n", c->errstr);
|
||||
exit(1);
|
||||
} else if (tries > 0) {
|
||||
printf("\r\x1b[0K"); /* Cursor to left edge + clear line. */
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -781,23 +724,13 @@ static int parseOptions(int argc, char **argv) {
|
||||
config.auth = argv[++i];
|
||||
} else if (!strcmp(argv[i],"--raw")) {
|
||||
config.output = OUTPUT_RAW;
|
||||
} else if (!strcmp(argv[i],"--no-raw")) {
|
||||
config.output = OUTPUT_STANDARD;
|
||||
} else if (!strcmp(argv[i],"--csv")) {
|
||||
config.output = OUTPUT_CSV;
|
||||
} else if (!strcmp(argv[i],"--latency")) {
|
||||
config.latency_mode = 1;
|
||||
} else if (!strcmp(argv[i],"--latency-dist")) {
|
||||
config.latency_dist_mode = 1;
|
||||
} else if (!strcmp(argv[i],"--mono")) {
|
||||
spectrum_palette = spectrum_palette_mono;
|
||||
spectrum_palette_size = spectrum_palette_mono_size;
|
||||
} else if (!strcmp(argv[i],"--latency-history")) {
|
||||
config.latency_mode = 1;
|
||||
config.latency_history = 1;
|
||||
} else if (!strcmp(argv[i],"--lru-test") && !lastarg) {
|
||||
config.lru_test_mode = 1;
|
||||
config.lru_test_sample_size = strtoll(argv[++i],NULL,10);
|
||||
} else if (!strcmp(argv[i],"--slave")) {
|
||||
config.slave_mode = 1;
|
||||
} else if (!strcmp(argv[i],"--stat")) {
|
||||
@@ -862,7 +795,7 @@ static sds readArgFromStdin(void) {
|
||||
return arg;
|
||||
}
|
||||
|
||||
static void usage(void) {
|
||||
static void usage() {
|
||||
sds version = cliVersion();
|
||||
fprintf(stderr,
|
||||
"redis-cli %s\n"
|
||||
@@ -881,15 +814,10 @@ static void usage(void) {
|
||||
" -c Enable cluster mode (follow -ASK and -MOVED redirections).\n"
|
||||
" --raw Use raw formatting for replies (default when STDOUT is\n"
|
||||
" not a tty).\n"
|
||||
" --no-raw Force formatted output even when STDOUT is not a tty.\n"
|
||||
" --csv Output in CSV format.\n"
|
||||
" --stat Print rolling stats about server: mem, clients, ...\n"
|
||||
" --latency Enter a special mode continuously sampling latency.\n"
|
||||
" --latency-history Like --latency but tracking latency changes over time.\n"
|
||||
" Default time interval is 15 sec. Change it using -i.\n"
|
||||
" --latency-dist Shows latency as a spectrum, requires xterm 256 colors.\n"
|
||||
" Default time interval is 1 sec. Change it using -i.\n"
|
||||
" --lru-test <keys> Simulate a cache workload with an 80-20 distribution.\n"
|
||||
" --slave Simulate a slave showing commands received from the master.\n"
|
||||
" --rdb <filename> Transfer an RDB dump from remote server to local file.\n"
|
||||
" --pipe Transfer raw Redis protocol from stdin to server.\n"
|
||||
@@ -934,34 +862,8 @@ static char **convertToSds(int count, char** args) {
|
||||
return sds;
|
||||
}
|
||||
|
||||
static int issueCommandRepeat(int argc, char **argv, long repeat) {
|
||||
while (1) {
|
||||
config.cluster_reissue_command = 0;
|
||||
if (cliSendCommand(argc,argv,repeat) != REDIS_OK) {
|
||||
cliConnect(1);
|
||||
|
||||
/* If we still cannot send the command print error.
|
||||
* We'll try to reconnect the next time. */
|
||||
if (cliSendCommand(argc,argv,repeat) != REDIS_OK) {
|
||||
cliPrintContextError();
|
||||
return REDIS_ERR;
|
||||
}
|
||||
}
|
||||
/* Issue the command again if we got redirected in cluster mode */
|
||||
if (config.cluster_mode && config.cluster_reissue_command) {
|
||||
cliConnect(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return REDIS_OK;
|
||||
}
|
||||
|
||||
static int issueCommand(int argc, char **argv) {
|
||||
return issueCommandRepeat(argc, argv, config.repeat);
|
||||
}
|
||||
|
||||
static void repl(void) {
|
||||
#define LINE_BUFLEN 4096
|
||||
static void repl() {
|
||||
sds historyfile = NULL;
|
||||
int history = 0;
|
||||
char *line;
|
||||
@@ -974,9 +876,10 @@ static void repl(void) {
|
||||
|
||||
/* Only use history when stdin is a tty. */
|
||||
if (isatty(fileno(stdin))) {
|
||||
historyfile = getHistoryPath();
|
||||
if (historyfile != NULL) {
|
||||
history = 1;
|
||||
history = 1;
|
||||
|
||||
if (getenv("HOME") != NULL) {
|
||||
historyfile = sdscatprintf(sdsempty(),"%s/.rediscli_history",getenv("HOME"));
|
||||
linenoiseHistoryLoad(historyfile);
|
||||
}
|
||||
}
|
||||
@@ -1016,8 +919,26 @@ static void repl(void) {
|
||||
repeat = 1;
|
||||
}
|
||||
|
||||
issueCommandRepeat(argc-skipargs, argv+skipargs, repeat);
|
||||
while (1) {
|
||||
config.cluster_reissue_command = 0;
|
||||
if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
|
||||
!= REDIS_OK)
|
||||
{
|
||||
cliConnect(1);
|
||||
|
||||
/* If we still cannot send the command print error.
|
||||
* We'll try to reconnect the next time. */
|
||||
if (cliSendCommand(argc-skipargs,argv+skipargs,repeat)
|
||||
!= REDIS_OK)
|
||||
cliPrintContextError();
|
||||
}
|
||||
/* Issue the command again if we got redirected in cluster mode */
|
||||
if (config.cluster_mode && config.cluster_reissue_command) {
|
||||
cliConnect(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
elapsed = mstime()-start_time;
|
||||
if (elapsed >= 500) {
|
||||
printf("(%.2fs)\n",(double)elapsed/1000);
|
||||
@@ -1038,9 +959,10 @@ static int noninteractive(int argc, char **argv) {
|
||||
if (config.stdinarg) {
|
||||
argv = zrealloc(argv, (argc+1)*sizeof(char*));
|
||||
argv[argc] = readArgFromStdin();
|
||||
retval = issueCommand(argc+1, argv);
|
||||
retval = cliSendCommand(argc+1, argv, config.repeat);
|
||||
} else {
|
||||
retval = issueCommand(argc, argv);
|
||||
/* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
|
||||
retval = cliSendCommand(argc, argv, config.repeat);
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
@@ -1084,7 +1006,7 @@ static int evalMode(int argc, char **argv) {
|
||||
argv2[2] = sdscatprintf(sdsempty(),"%d",keys);
|
||||
|
||||
/* Call it */
|
||||
return issueCommand(argc+3-got_comma, argv2);
|
||||
return cliSendCommand(argc+3-got_comma, argv2, config.repeat);
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
@@ -1105,7 +1027,7 @@ static void latencyMode(void) {
|
||||
if (!context) exit(1);
|
||||
while(1) {
|
||||
start = mstime();
|
||||
reply = reconnectingRedisCommand(context,"PING");
|
||||
reply = redisCommand(context,"PING");
|
||||
if (reply == NULL) {
|
||||
fprintf(stderr,"\nI/O error\n");
|
||||
exit(1);
|
||||
@@ -1135,148 +1057,6 @@ static void latencyMode(void) {
|
||||
}
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
* Latency distribution mode -- requires 256 colors xterm
|
||||
*--------------------------------------------------------------------------- */
|
||||
|
||||
#define LATENCY_DIST_DEFAULT_INTERVAL 1000 /* milliseconds. */
|
||||
|
||||
/* Structure to store samples distribution. */
|
||||
struct distsamples {
|
||||
long long max; /* Max latency to fit into this interval (usec). */
|
||||
long long count; /* Number of samples in this interval. */
|
||||
int character; /* Associated character in visualization. */
|
||||
};
|
||||
|
||||
/* Helper function for latencyDistMode(). Performs the spectrum visualization
|
||||
* of the collected samples targeting an xterm 256 terminal.
|
||||
*
|
||||
* Takes an array of distsamples structures, ordered from smaller to bigger
|
||||
* 'max' value. Last sample max must be 0, to mean that it olds all the
|
||||
* samples greater than the previous one, and is also the stop sentinel.
|
||||
*
|
||||
* "tot' is the total number of samples in the different buckets, so it
|
||||
* is the SUM(samples[i].conut) for i to 0 up to the max sample.
|
||||
*
|
||||
* As a side effect the function sets all the buckets count to 0. */
|
||||
void showLatencyDistSamples(struct distsamples *samples, long long tot) {
|
||||
int j;
|
||||
|
||||
/* We convert samples into a index inside the palette
|
||||
* proportional to the percentage a given bucket represents.
|
||||
* This way intensity of the different parts of the spectrum
|
||||
* don't change relative to the number of requests, which avoids to
|
||||
* pollute the visualization with non-latency related info. */
|
||||
printf("\033[38;5;0m"); /* Set foreground color to black. */
|
||||
for (j = 0; ; j++) {
|
||||
int coloridx =
|
||||
ceil((float) samples[j].count / tot * (spectrum_palette_size-1));
|
||||
int color = spectrum_palette[coloridx];
|
||||
printf("\033[48;5;%dm%c", (int)color, samples[j].character);
|
||||
samples[j].count = 0;
|
||||
if (samples[j].max == 0) break; /* Last sample. */
|
||||
}
|
||||
printf("\033[0m\n");
|
||||
fflush(stdout);
|
||||
}
|
||||
|
||||
/* Show the legend: different buckets values and colors meaning, so
|
||||
* that the spectrum is more easily readable. */
|
||||
void showLatencyDistLegend(void) {
|
||||
int j;
|
||||
|
||||
printf("---------------------------------------------\n");
|
||||
printf(". - * # .01 .125 .25 .5 milliseconds\n");
|
||||
printf("1,2,3,...,9 from 1 to 9 milliseconds\n");
|
||||
printf("A,B,C,D,E 10,20,30,40,50 milliseconds\n");
|
||||
printf("F,G,H,I,J .1,.2,.3,.4,.5 seconds\n");
|
||||
printf("K,L,M,N,O,P,Q,? 1,2,4,8,16,30,60,>60 seconds\n");
|
||||
printf("From 0 to 100%%: ");
|
||||
for (j = 0; j < spectrum_palette_size; j++) {
|
||||
printf("\033[48;5;%dm ", spectrum_palette[j]);
|
||||
}
|
||||
printf("\033[0m\n");
|
||||
printf("---------------------------------------------\n");
|
||||
}
|
||||
|
||||
static void latencyDistMode(void) {
|
||||
redisReply *reply;
|
||||
long long start, latency, count = 0;
|
||||
long long history_interval =
|
||||
config.interval ? config.interval/1000 :
|
||||
LATENCY_DIST_DEFAULT_INTERVAL;
|
||||
long long history_start = ustime();
|
||||
int j, outputs = 0;
|
||||
|
||||
struct distsamples samples[] = {
|
||||
/* We use a mostly logarithmic scale, with certain linear intervals
|
||||
* which are more interesting than others, like 1-10 milliseconds
|
||||
* range. */
|
||||
{10,0,'.'}, /* 0.01 ms */
|
||||
{125,0,'-'}, /* 0.125 ms */
|
||||
{250,0,'*'}, /* 0.25 ms */
|
||||
{500,0,'#'}, /* 0.5 ms */
|
||||
{1000,0,'1'}, /* 1 ms */
|
||||
{2000,0,'2'}, /* 2 ms */
|
||||
{3000,0,'3'}, /* 3 ms */
|
||||
{4000,0,'4'}, /* 4 ms */
|
||||
{5000,0,'5'}, /* 5 ms */
|
||||
{6000,0,'6'}, /* 6 ms */
|
||||
{7000,0,'7'}, /* 7 ms */
|
||||
{8000,0,'8'}, /* 8 ms */
|
||||
{9000,0,'9'}, /* 9 ms */
|
||||
{10000,0,'A'}, /* 10 ms */
|
||||
{20000,0,'B'}, /* 20 ms */
|
||||
{30000,0,'C'}, /* 30 ms */
|
||||
{40000,0,'D'}, /* 40 ms */
|
||||
{50000,0,'E'}, /* 50 ms */
|
||||
{100000,0,'F'}, /* 0.1 s */
|
||||
{200000,0,'G'}, /* 0.2 s */
|
||||
{300000,0,'H'}, /* 0.3 s */
|
||||
{400000,0,'I'}, /* 0.4 s */
|
||||
{500000,0,'J'}, /* 0.5 s */
|
||||
{1000000,0,'K'}, /* 1 s */
|
||||
{2000000,0,'L'}, /* 2 s */
|
||||
{4000000,0,'M'}, /* 4 s */
|
||||
{8000000,0,'N'}, /* 8 s */
|
||||
{16000000,0,'O'}, /* 16 s */
|
||||
{30000000,0,'P'}, /* 30 s */
|
||||
{60000000,0,'Q'}, /* 1 minute */
|
||||
{0,0,'?'}, /* > 1 minute */
|
||||
};
|
||||
|
||||
if (!context) exit(1);
|
||||
while(1) {
|
||||
start = ustime();
|
||||
reply = reconnectingRedisCommand(context,"PING");
|
||||
if (reply == NULL) {
|
||||
fprintf(stderr,"\nI/O error\n");
|
||||
exit(1);
|
||||
}
|
||||
latency = ustime()-start;
|
||||
freeReplyObject(reply);
|
||||
count++;
|
||||
|
||||
/* Populate the relevant bucket. */
|
||||
for (j = 0; ; j++) {
|
||||
if (samples[j].max == 0 || latency <= samples[j].max) {
|
||||
samples[j].count++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* From time to time show the spectrum. */
|
||||
if (count && (ustime()-history_start)/1000 > history_interval) {
|
||||
if ((outputs++ % 20) == 0)
|
||||
showLatencyDistLegend();
|
||||
showLatencyDistSamples(samples,count);
|
||||
history_start = ustime();
|
||||
count = 0;
|
||||
}
|
||||
usleep(LATENCY_SAMPLE_RATE * 1000);
|
||||
}
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
* Slave mode
|
||||
*--------------------------------------------------------------------------- */
|
||||
@@ -1397,7 +1177,6 @@ static void getRDB(void) {
|
||||
* Bulk import (pipe) mode
|
||||
*--------------------------------------------------------------------------- */
|
||||
|
||||
#define PIPEMODE_WRITE_LOOP_MAX_BYTES (128*1024)
|
||||
static void pipeMode(void) {
|
||||
int fd = context->fd;
|
||||
long long errors = 0, replies = 0, obuf_len = 0, obuf_pos = 0;
|
||||
@@ -1474,8 +1253,6 @@ static void pipeMode(void) {
|
||||
|
||||
/* Handle the writable state: we can send protocol to the server. */
|
||||
if (mask & AE_WRITABLE) {
|
||||
ssize_t loop_nwritten = 0;
|
||||
|
||||
while(1) {
|
||||
/* Transfer current buffer to server. */
|
||||
if (obuf_len != 0) {
|
||||
@@ -1492,7 +1269,6 @@ static void pipeMode(void) {
|
||||
}
|
||||
obuf_len -= nwritten;
|
||||
obuf_pos += nwritten;
|
||||
loop_nwritten += nwritten;
|
||||
if (obuf_len != 0) break; /* Can't accept more data. */
|
||||
}
|
||||
/* If buffer is empty, load from stdin. */
|
||||
@@ -1528,8 +1304,7 @@ static void pipeMode(void) {
|
||||
obuf_pos = 0;
|
||||
}
|
||||
}
|
||||
if ((obuf_len == 0 && eof) ||
|
||||
loop_nwritten > PIPEMODE_WRITE_LOOP_MAX_BYTES) break;
|
||||
if (obuf_len == 0 && eof) break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1587,7 +1362,7 @@ static redisReply *sendScan(unsigned long long *it) {
|
||||
assert(reply->element[1]->type == REDIS_REPLY_ARRAY);
|
||||
|
||||
/* Update iterator */
|
||||
*it = strtoull(reply->element[0]->str, NULL, 10);
|
||||
*it = atoi(reply->element[0]->str);
|
||||
|
||||
return reply;
|
||||
}
|
||||
@@ -1631,7 +1406,7 @@ static int toIntType(char *key, char *type) {
|
||||
|
||||
static void getKeyTypes(redisReply *keys, int *types) {
|
||||
redisReply *reply;
|
||||
unsigned int i;
|
||||
int i;
|
||||
|
||||
/* Pipeline TYPE commands */
|
||||
for(i=0;i<keys->elements;i++) {
|
||||
@@ -1660,7 +1435,7 @@ static void getKeySizes(redisReply *keys, int *types,
|
||||
{
|
||||
redisReply *reply;
|
||||
char *sizecmds[] = {"STRLEN","LLEN","SCARD","HLEN","ZCARD"};
|
||||
unsigned int i;
|
||||
int i;
|
||||
|
||||
/* Pipeline size commands */
|
||||
for(i=0;i<keys->elements;i++) {
|
||||
@@ -1707,8 +1482,7 @@ static void findBigKeys(void) {
|
||||
char *typename[] = {"string","list","set","hash","zset"};
|
||||
char *typeunit[] = {"bytes","items","members","fields","members"};
|
||||
redisReply *reply, *keys;
|
||||
unsigned int arrsize=0, i;
|
||||
int type, *types=NULL;
|
||||
int type, *types=NULL, arrsize=0, i;
|
||||
double pct;
|
||||
|
||||
/* Total keys pre scanning */
|
||||
@@ -1723,7 +1497,7 @@ static void findBigKeys(void) {
|
||||
for(i=0;i<TYPE_NONE; i++) {
|
||||
maxkeys[i] = sdsempty();
|
||||
if(!maxkeys[i]) {
|
||||
fprintf(stderr, "Failed to allocate memory for largest key names!\n");
|
||||
fprintf(stderr, "Failed to allocate memory for largest key names!");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1892,7 +1666,7 @@ void bytesToHuman(char *s, long long n) {
|
||||
}
|
||||
}
|
||||
|
||||
static void statMode(void) {
|
||||
static void statMode() {
|
||||
redisReply *reply;
|
||||
long aux, requests = 0;
|
||||
int i = 0;
|
||||
@@ -1901,7 +1675,7 @@ static void statMode(void) {
|
||||
char buf[64];
|
||||
int j;
|
||||
|
||||
reply = reconnectingRedisCommand(context,"INFO");
|
||||
reply = reconnectingInfo();
|
||||
if (reply->type == REDIS_REPLY_ERROR) {
|
||||
printf("ERROR: %s\n", reply->str);
|
||||
exit(1);
|
||||
@@ -1955,7 +1729,6 @@ static void statMode(void) {
|
||||
/* Children */
|
||||
aux = getLongInfoField(reply->str,"bgsave_in_progress");
|
||||
aux |= getLongInfoField(reply->str,"aof_rewrite_in_progress") << 1;
|
||||
aux |= getLongInfoField(reply->str,"loading") << 2;
|
||||
switch(aux) {
|
||||
case 0: break;
|
||||
case 1:
|
||||
@@ -1967,9 +1740,6 @@ static void statMode(void) {
|
||||
case 3:
|
||||
printf("SAVE+AOF");
|
||||
break;
|
||||
case 4:
|
||||
printf("LOAD");
|
||||
break;
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
@@ -1982,7 +1752,7 @@ static void statMode(void) {
|
||||
* Scan mode
|
||||
*--------------------------------------------------------------------------- */
|
||||
|
||||
static void scanMode(void) {
|
||||
static void scanMode() {
|
||||
redisReply *reply;
|
||||
unsigned long long cur = 0;
|
||||
|
||||
@@ -1999,7 +1769,7 @@ static void scanMode(void) {
|
||||
printf("ERROR: %s\n", reply->str);
|
||||
exit(1);
|
||||
} else {
|
||||
unsigned int j;
|
||||
int j;
|
||||
|
||||
cur = strtoull(reply->element[0]->str,NULL,10);
|
||||
for (j = 0; j < reply->element[1]->elements; j++)
|
||||
@@ -2011,94 +1781,6 @@ static void scanMode(void) {
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
* LRU test mode
|
||||
*--------------------------------------------------------------------------- */
|
||||
|
||||
/* Return an integer from min to max (both inclusive) using a power-law
|
||||
* distribution, depending on the value of alpha: the greater the alpha
|
||||
* the more bias towards lower values.
|
||||
*
|
||||
* With alpha = 6.2 the output follows the 80-20 rule where 20% of
|
||||
* the returned numbers will account for 80% of the frequency. */
|
||||
long long powerLawRand(long long min, long long max, double alpha) {
|
||||
double pl, r;
|
||||
|
||||
max += 1;
|
||||
r = ((double)rand()) / RAND_MAX;
|
||||
pl = pow(
|
||||
((pow(max,alpha+1) - pow(min,alpha+1))*r + pow(min,alpha+1)),
|
||||
(1.0/(alpha+1)));
|
||||
return (max-1-(long long)pl)+min;
|
||||
}
|
||||
|
||||
/* Generates a key name among a set of lru_test_sample_size keys, using
|
||||
* an 80-20 distribution. */
|
||||
void LRUTestGenKey(char *buf, size_t buflen) {
|
||||
snprintf(buf, buflen, "lru:%lld\n",
|
||||
powerLawRand(1, config.lru_test_sample_size, 6.2));
|
||||
}
|
||||
|
||||
#define LRU_CYCLE_PERIOD 1000 /* 1000 milliseconds. */
|
||||
#define LRU_CYCLE_PIPELINE_SIZE 250
|
||||
static void LRUTestMode(void) {
|
||||
redisReply *reply;
|
||||
char key[128];
|
||||
long long start_cycle;
|
||||
int j;
|
||||
|
||||
srand(time(NULL)^getpid());
|
||||
while(1) {
|
||||
/* Perform cycles of 1 second with 50% writes and 50% reads.
|
||||
* We use pipelining batching writes / reads N times per cycle in order
|
||||
* to fill the target instance easily. */
|
||||
start_cycle = mstime();
|
||||
long long hits = 0, misses = 0;
|
||||
while(mstime() - start_cycle < 1000) {
|
||||
/* Write cycle. */
|
||||
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) {
|
||||
LRUTestGenKey(key,sizeof(key));
|
||||
redisAppendCommand(context, "SET %s val",key);
|
||||
}
|
||||
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++)
|
||||
redisGetReply(context, (void**)&reply);
|
||||
|
||||
/* Read cycle. */
|
||||
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) {
|
||||
LRUTestGenKey(key,sizeof(key));
|
||||
redisAppendCommand(context, "GET %s",key);
|
||||
}
|
||||
for (j = 0; j < LRU_CYCLE_PIPELINE_SIZE; j++) {
|
||||
if (redisGetReply(context, (void**)&reply) == REDIS_OK) {
|
||||
switch(reply->type) {
|
||||
case REDIS_REPLY_ERROR:
|
||||
printf("%s\n", reply->str);
|
||||
break;
|
||||
case REDIS_REPLY_NIL:
|
||||
misses++;
|
||||
break;
|
||||
default:
|
||||
hits++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (context->err) {
|
||||
fprintf(stderr,"I/O error during LRU test\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
/* Print stats. */
|
||||
printf(
|
||||
"%lld Gets/sec | Hits: %lld (%.2f%%) | Misses: %lld (%.2f%%)\n",
|
||||
hits+misses,
|
||||
hits, (double)hits/(hits+misses)*100,
|
||||
misses, (double)misses/(hits+misses)*100);
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
* Intrisic latency mode.
|
||||
*
|
||||
@@ -2158,15 +1840,11 @@ static void intrinsicLatencyMode(void) {
|
||||
printf("Max latency so far: %lld microseconds.\n", max_latency);
|
||||
}
|
||||
|
||||
double avg_us = (double)run_time/runs;
|
||||
double avg_ns = avg_us * 10e3;
|
||||
if (force_cancel_loop || end > test_end) {
|
||||
printf("\n%lld total runs "
|
||||
"(avg latency: "
|
||||
"%.4f microseconds / %.2f nanoseconds per run).\n",
|
||||
runs, avg_us, avg_ns);
|
||||
printf("Worst run took %.0fx longer than the average latency.\n",
|
||||
max_latency / avg_us);
|
||||
printf("\n%lld total runs (avg %lld microseconds per run).\n",
|
||||
runs, run_time/runs);
|
||||
printf("Worst run took %.02fx times the average.\n",
|
||||
(double) max_latency / (run_time/runs));
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
@@ -2190,10 +1868,7 @@ int main(int argc, char **argv) {
|
||||
config.monitor_mode = 0;
|
||||
config.pubsub_mode = 0;
|
||||
config.latency_mode = 0;
|
||||
config.latency_dist_mode = 0;
|
||||
config.latency_history = 0;
|
||||
config.lru_test_mode = 0;
|
||||
config.lru_test_sample_size = 0;
|
||||
config.cluster_mode = 0;
|
||||
config.slave_mode = 0;
|
||||
config.getrdb_mode = 0;
|
||||
@@ -2208,11 +1883,6 @@ int main(int argc, char **argv) {
|
||||
config.stdinarg = 0;
|
||||
config.auth = NULL;
|
||||
config.eval = NULL;
|
||||
config.last_cmd_type = -1;
|
||||
|
||||
spectrum_palette = spectrum_palette_color;
|
||||
spectrum_palette_size = spectrum_palette_color_size;
|
||||
|
||||
if (!isatty(fileno(stdout)) && (getenv("FAKETTY") == NULL))
|
||||
config.output = OUTPUT_RAW;
|
||||
else
|
||||
@@ -2230,12 +1900,6 @@ int main(int argc, char **argv) {
|
||||
latencyMode();
|
||||
}
|
||||
|
||||
/* Latency distribution mode */
|
||||
if (config.latency_dist_mode) {
|
||||
if (cliConnect(0) == REDIS_ERR) exit(1);
|
||||
latencyDistMode();
|
||||
}
|
||||
|
||||
/* Slave mode */
|
||||
if (config.slave_mode) {
|
||||
if (cliConnect(0) == REDIS_ERR) exit(1);
|
||||
@@ -2273,20 +1937,11 @@ int main(int argc, char **argv) {
|
||||
scanMode();
|
||||
}
|
||||
|
||||
/* LRU test mode */
|
||||
if (config.lru_test_mode) {
|
||||
if (cliConnect(0) == REDIS_ERR) exit(1);
|
||||
LRUTestMode();
|
||||
}
|
||||
|
||||
/* Intrinsic latency mode */
|
||||
if (config.intrinsic_latency_mode) intrinsicLatencyMode();
|
||||
|
||||
/* Start interactive mode when no command is provided */
|
||||
if (argc == 0 && !config.eval) {
|
||||
/* Ignore SIGPIPE in interactive mode to force a reconnect */
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
|
||||
/* Note that in repl mode we don't abort on connection error.
|
||||
* A new attempt will be performed for every command send. */
|
||||
cliConnect(0);
|
||||
|
||||
+80
-177
@@ -50,16 +50,14 @@ end
|
||||
class ClusterNode
|
||||
def initialize(addr)
|
||||
s = addr.split(":")
|
||||
if s.length < 2
|
||||
puts "Invalid IP or Port (given as #{addr}) - use IP:Port format"
|
||||
exit 1
|
||||
if s.length != 2
|
||||
puts "Invalid node name #{addr}"
|
||||
exit 1
|
||||
end
|
||||
port = s.pop # removes port from split array
|
||||
ip = s.join(":") # if s.length > 1 here, it's IPv6, so restore address
|
||||
@r = nil
|
||||
@info = {}
|
||||
@info[:host] = ip
|
||||
@info[:port] = port
|
||||
@info[:host] = s[0]
|
||||
@info[:port] = s[1]
|
||||
@info[:slots] = {}
|
||||
@info[:migrating] = {}
|
||||
@info[:importing] = {}
|
||||
@@ -72,7 +70,7 @@ class ClusterNode
|
||||
@friends
|
||||
end
|
||||
|
||||
def slots
|
||||
def slots
|
||||
@info[:slots]
|
||||
end
|
||||
|
||||
@@ -154,7 +152,7 @@ class ClusterNode
|
||||
end
|
||||
} if slots
|
||||
@dirty = false
|
||||
@r.cluster("info").split("\n").each{|e|
|
||||
@r.cluster("info").split("\n").each{|e|
|
||||
k,v=e.split(":")
|
||||
k = k.to_sym
|
||||
v.chop!
|
||||
@@ -213,7 +211,7 @@ class ClusterNode
|
||||
#
|
||||
# Note: this could be easily written without side effects,
|
||||
# we use 'slots' just to split the computation into steps.
|
||||
|
||||
|
||||
# First step: we want an increasing array of integers
|
||||
# for instance: [1,2,3,4,5,8,9,20,21,22,23,24,25,30]
|
||||
slots = @info[:slots].keys.sort
|
||||
@@ -273,7 +271,7 @@ class ClusterNode
|
||||
def info
|
||||
@info
|
||||
end
|
||||
|
||||
|
||||
def is_dirty?
|
||||
@dirty
|
||||
end
|
||||
@@ -496,10 +494,6 @@ class RedisTrib
|
||||
# importing state in 1 slot. That's trivial to address.
|
||||
if migrating.length == 1 && importing.length == 1
|
||||
move_slot(migrating[0],importing[0],slot,:verbose=>true,:fix=>true)
|
||||
# Case 2: There are multiple nodes that claim the slot as importing,
|
||||
# they probably got keys about the slot after a restart so opened
|
||||
# the slot. In this case we just move all the keys to the owner
|
||||
# according to the configuration.
|
||||
elsif migrating.length == 0 && importing.length > 0
|
||||
xputs ">>> Moving all the #{slot} slot keys to its owner #{owner}"
|
||||
importing.each {|node|
|
||||
@@ -508,14 +502,8 @@ class RedisTrib
|
||||
xputs ">>> Setting #{slot} as STABLE in #{node}"
|
||||
node.r.cluster("setslot",slot,"stable")
|
||||
}
|
||||
# Case 3: There are no slots claiming to be in importing state, but
|
||||
# there is a migrating node that actually don't have any key. We
|
||||
# can just close the slot, probably a reshard interrupted in the middle.
|
||||
elsif importing.length == 0 && migrating.length == 1 &&
|
||||
migrating[0].r.cluster("getkeysinslot",slot,10).length == 0
|
||||
migrating[0].r.cluster("setslot",slot,"stable")
|
||||
else
|
||||
xputs "[ERR] Sorry, Redis-trib can't fix this slot yet (work in progress). Slot is set as migrating in #{migrating.join(",")}, as importing in #{importing.join(",")}, owner is #{owner}"
|
||||
xputs "[ERR] Sorry, Redis-trib can't fix this slot yet (work in progress)"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -550,6 +538,7 @@ class RedisTrib
|
||||
nodes_count = @nodes.length
|
||||
masters_count = @nodes.length / (@replicas+1)
|
||||
masters = []
|
||||
slaves = []
|
||||
|
||||
# The first step is to split instances by IP. This is useful as
|
||||
# we'll try to allocate master nodes in different physical machines
|
||||
@@ -567,31 +556,16 @@ class RedisTrib
|
||||
|
||||
# Select master instances
|
||||
puts "Using #{masters_count} masters:"
|
||||
interleaved = []
|
||||
stop = false
|
||||
while not stop do
|
||||
# Take one node from each IP until we run out of nodes
|
||||
# across every IP.
|
||||
ips.each do |ip,nodes|
|
||||
if nodes.empty?
|
||||
# if this IP has no remaining nodes, check for termination
|
||||
if interleaved.length == nodes_count
|
||||
# stop when 'interleaved' has accumulated all nodes
|
||||
stop = true
|
||||
next
|
||||
end
|
||||
else
|
||||
# else, move one node from this IP to 'interleaved'
|
||||
interleaved.push nodes.shift
|
||||
end
|
||||
end
|
||||
while masters.length < masters_count
|
||||
ips.each{|ip,nodes_list|
|
||||
next if nodes_list.length == 0
|
||||
masters << nodes_list.shift
|
||||
puts masters[-1]
|
||||
nodes_count -= 1
|
||||
break if masters.length == masters_count
|
||||
}
|
||||
end
|
||||
|
||||
masters = interleaved.slice!(0, masters_count)
|
||||
nodes_count -= masters.length
|
||||
|
||||
masters.each{|m| puts m}
|
||||
|
||||
# Alloc slots on masters
|
||||
slots_per_node = ClusterHashSlots.to_f / masters_count
|
||||
first = 0
|
||||
@@ -618,8 +592,8 @@ class RedisTrib
|
||||
# all nodes will be used.
|
||||
assignment_verbose = false
|
||||
|
||||
[:requested,:unused].each do |assign|
|
||||
masters.each do |m|
|
||||
[:requested,:unused].each{|assign|
|
||||
masters.each{|m|
|
||||
assigned_replicas = 0
|
||||
while assigned_replicas < @replicas
|
||||
break if nodes_count == 0
|
||||
@@ -633,33 +607,21 @@ class RedisTrib
|
||||
"role too (#{nodes_count} remaining)."
|
||||
end
|
||||
end
|
||||
|
||||
# Return the first node not matching our current master
|
||||
node = interleaved.find{|n| n.info[:host] != m.info[:host]}
|
||||
|
||||
# If we found a node, use it as a best-first match.
|
||||
# Otherwise, we didn't find a node on a different IP, so we
|
||||
# go ahead and use a same-IP replica.
|
||||
if node
|
||||
slave = node
|
||||
interleaved.delete node
|
||||
else
|
||||
slave = interleaved.shift
|
||||
end
|
||||
slave.set_as_replica(m.info[:name])
|
||||
nodes_count -= 1
|
||||
assigned_replicas += 1
|
||||
puts "Adding replica #{slave} to #{m}"
|
||||
|
||||
# If we are in the "assign extra nodes" loop,
|
||||
# we want to assign one extra replica to each
|
||||
# master before repeating masters.
|
||||
# This break lets us assign extra replicas to masters
|
||||
# in a round-robin way.
|
||||
break if assign == :unused
|
||||
ips.each{|ip,nodes_list|
|
||||
next if nodes_list.length == 0
|
||||
# Skip instances with the same IP as the master if we
|
||||
# have some more IPs available.
|
||||
next if ip == m.info[:host] && nodes_count > nodes_list.length
|
||||
slave = nodes_list.shift
|
||||
slave.set_as_replica(m.info[:name])
|
||||
nodes_count -= 1
|
||||
assigned_replicas += 1
|
||||
puts "Adding replica #{slave} to #{m}"
|
||||
break
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def flush_nodes_config
|
||||
@@ -724,13 +686,8 @@ class RedisTrib
|
||||
f[:flags].index("fail")
|
||||
fnode = ClusterNode.new(f[:addr])
|
||||
fnode.connect()
|
||||
next if !fnode.r
|
||||
begin
|
||||
fnode.load_info()
|
||||
add_node(fnode)
|
||||
rescue => e
|
||||
xputs "[ERR] Unable to load info for node #{fnode}"
|
||||
end
|
||||
fnode.load_info()
|
||||
add_node(fnode)
|
||||
}
|
||||
populate_nodes_replicas_info
|
||||
end
|
||||
@@ -799,7 +756,7 @@ class RedisTrib
|
||||
|
||||
# Move slots between source and target nodes using MIGRATE.
|
||||
#
|
||||
# Options:
|
||||
# Options:
|
||||
# :verbose -- Print a dot for every moved key.
|
||||
# :fix -- We are moving in the context of a fix. Use REPLACE.
|
||||
# :cold -- Move keys without opening / reconfiguring the nodes.
|
||||
@@ -822,7 +779,7 @@ class RedisTrib
|
||||
source.r.client.call(["migrate",target.info[:host],target.info[:port],key,0,15000])
|
||||
rescue => e
|
||||
if o[:fix] && e.to_s =~ /BUSYKEY/
|
||||
xputs "*** Target key #{key} exists. Replacing it for FIX."
|
||||
xputs "*** Target key #{key} exists. Replace it for FIX."
|
||||
source.r.client.call(["migrate",target.info[:host],target.info[:port],key,0,15000,:replace])
|
||||
else
|
||||
puts ""
|
||||
@@ -864,96 +821,50 @@ class RedisTrib
|
||||
puts "*** Please fix your cluster problems before resharding"
|
||||
exit 1
|
||||
end
|
||||
|
||||
# Get number of slots
|
||||
if opt['slots']
|
||||
numslots = opt['slots'].to_i
|
||||
else
|
||||
numslots = 0
|
||||
while numslots <= 0 or numslots > ClusterHashSlots
|
||||
print "How many slots do you want to move (from 1 to #{ClusterHashSlots})? "
|
||||
numslots = STDIN.gets.to_i
|
||||
end
|
||||
numslots = 0
|
||||
while numslots <= 0 or numslots > ClusterHashSlots
|
||||
print "How many slots do you want to move (from 1 to #{ClusterHashSlots})? "
|
||||
numslots = STDIN.gets.to_i
|
||||
end
|
||||
|
||||
# Get the target instance
|
||||
if opt['to']
|
||||
target = get_node_by_name(opt['to'])
|
||||
target = nil
|
||||
while not target
|
||||
print "What is the receiving node ID? "
|
||||
target = get_node_by_name(STDIN.gets.chop)
|
||||
if !target || target.has_flag?("slave")
|
||||
xputs "*** The specified node is not known or not a master, please retry."
|
||||
exit 1
|
||||
end
|
||||
else
|
||||
target = nil
|
||||
while not target
|
||||
print "What is the receiving node ID? "
|
||||
target = get_node_by_name(STDIN.gets.chop)
|
||||
if !target || target.has_flag?("slave")
|
||||
xputs "*** The specified node is not known or not a master, please retry."
|
||||
target = nil
|
||||
end
|
||||
target = nil
|
||||
end
|
||||
end
|
||||
|
||||
# Get the source instances
|
||||
sources = []
|
||||
if opt['from']
|
||||
opt['from'].split(',').each{|node_id|
|
||||
if node_id == "all"
|
||||
sources = "all"
|
||||
break
|
||||
end
|
||||
src = get_node_by_name(node_id)
|
||||
if !src || src.has_flag?("slave")
|
||||
xputs "*** The specified node is not known or is not a master, please retry."
|
||||
xputs "Please enter all the source node IDs."
|
||||
xputs " Type 'all' to use all the nodes as source nodes for the hash slots."
|
||||
xputs " Type 'done' once you entered all the source nodes IDs."
|
||||
while true
|
||||
print "Source node ##{sources.length+1}:"
|
||||
line = STDIN.gets.chop
|
||||
src = get_node_by_name(line)
|
||||
if line == "done"
|
||||
if sources.length == 0
|
||||
puts "No source nodes given, operation aborted"
|
||||
exit 1
|
||||
end
|
||||
sources << src
|
||||
}
|
||||
else
|
||||
xputs "Please enter all the source node IDs."
|
||||
xputs " Type 'all' to use all the nodes as source nodes for the hash slots."
|
||||
xputs " Type 'done' once you entered all the source nodes IDs."
|
||||
while true
|
||||
print "Source node ##{sources.length+1}:"
|
||||
line = STDIN.gets.chop
|
||||
src = get_node_by_name(line)
|
||||
if line == "done"
|
||||
break
|
||||
elsif line == "all"
|
||||
sources = "all"
|
||||
break
|
||||
elsif !src || src.has_flag?("slave")
|
||||
xputs "*** The specified node is not known or is not a master, please retry."
|
||||
elsif src.info[:name] == target.info[:name]
|
||||
xputs "*** It is not possible to use the target node as source node."
|
||||
else
|
||||
sources << src
|
||||
break
|
||||
end
|
||||
elsif line == "all"
|
||||
@nodes.each{|n|
|
||||
next if n.info[:name] == target.info[:name]
|
||||
next if n.has_flag?("slave")
|
||||
sources << n
|
||||
}
|
||||
break
|
||||
elsif !src || src.has_flag?("slave")
|
||||
xputs "*** The specified node is not known or is not a master, please retry."
|
||||
elsif src.info[:name] == target.info[:name]
|
||||
xputs "*** It is not possible to use the target node as source node."
|
||||
else
|
||||
sources << src
|
||||
end
|
||||
end
|
||||
|
||||
if sources.length == 0
|
||||
puts "*** No source nodes given, operation aborted"
|
||||
exit 1
|
||||
end
|
||||
|
||||
# Handle soures == all.
|
||||
if sources == "all"
|
||||
sources = []
|
||||
@nodes.each{|n|
|
||||
next if n.info[:name] == target.info[:name]
|
||||
next if n.has_flag?("slave")
|
||||
sources << n
|
||||
}
|
||||
end
|
||||
|
||||
# Check if the destination node is the same of any source nodes.
|
||||
if sources.index(target)
|
||||
xputs "*** Target node is also listed among the source nodes!"
|
||||
exit 1
|
||||
end
|
||||
|
||||
puts "\nReady to move #{numslots} slots."
|
||||
puts " Source nodes:"
|
||||
sources.each{|s| puts " "+s.info_string}
|
||||
@@ -962,11 +873,9 @@ class RedisTrib
|
||||
reshard_table = compute_reshard_table(sources,numslots)
|
||||
puts " Resharding plan:"
|
||||
show_reshard_table(reshard_table)
|
||||
if !opt['yes']
|
||||
print "Do you want to proceed with the proposed reshard plan (yes/no)? "
|
||||
yesno = STDIN.gets.chop
|
||||
exit(1) if (yesno != "yes")
|
||||
end
|
||||
print "Do you want to proceed with the proposed reshard plan (yes/no)? "
|
||||
yesno = STDIN.gets.chop
|
||||
exit(1) if (yesno != "yes")
|
||||
reshard_table.each{|e|
|
||||
move_slot(e[:source],target,e[:slot],:verbose=>true)
|
||||
}
|
||||
@@ -1149,9 +1058,7 @@ class RedisTrib
|
||||
def import_cluster_cmd(argv,opt)
|
||||
source_addr = opt['from']
|
||||
xputs ">>> Importing data from #{source_addr} to cluster #{argv[1]}"
|
||||
use_copy = opt['copy']
|
||||
use_replace = opt['replace']
|
||||
|
||||
|
||||
# Check the existing cluster.
|
||||
load_cluster_info_from_node(argv[0])
|
||||
check_cluster
|
||||
@@ -1177,7 +1084,7 @@ class RedisTrib
|
||||
# right node as needed.
|
||||
cursor = nil
|
||||
while cursor != 0
|
||||
cursor,keys = source.scan(cursor, :count => 1000)
|
||||
cursor,keys = source.scan(cursor,:count,1000)
|
||||
cursor = cursor.to_i
|
||||
keys.each{|k|
|
||||
# Migrate keys using the MIGRATE command.
|
||||
@@ -1186,10 +1093,7 @@ class RedisTrib
|
||||
print "Migrating #{k} to #{target}: "
|
||||
STDOUT.flush
|
||||
begin
|
||||
cmd = ["migrate",target.info[:host],target.info[:port],k,0,15000]
|
||||
cmd << :copy if use_copy
|
||||
cmd << :replace if use_replace
|
||||
source.client.call(cmd)
|
||||
source.client.call(["migrate",target.info[:host],target.info[:port],k,0,15000])
|
||||
rescue => e
|
||||
puts e
|
||||
else
|
||||
@@ -1247,7 +1151,7 @@ end
|
||||
|
||||
#################################################################################
|
||||
# Libraries
|
||||
#
|
||||
#
|
||||
# We try to don't depend on external libs since this is a critical part
|
||||
# of Redis Cluster.
|
||||
#################################################################################
|
||||
@@ -1349,8 +1253,7 @@ COMMANDS={
|
||||
ALLOWED_OPTIONS={
|
||||
"create" => {"replicas" => true},
|
||||
"add-node" => {"slave" => false, "master-id" => true},
|
||||
"import" => {"from" => :required, "copy" => false, "replace" => false},
|
||||
"reshard" => {"from" => true, "to" => true, "slots" => true, "yes" => false}
|
||||
"import" => {"from" => :required}
|
||||
}
|
||||
|
||||
def show_help
|
||||
|
||||
+131
-263
@@ -31,7 +31,6 @@
|
||||
#include "cluster.h"
|
||||
#include "slowlog.h"
|
||||
#include "bio.h"
|
||||
#include "latency.h"
|
||||
|
||||
#include <time.h>
|
||||
#include <signal.h>
|
||||
@@ -67,6 +66,7 @@ double R_Zero, R_PosInf, R_NegInf, R_Nan;
|
||||
|
||||
/* Global vars */
|
||||
struct redisServer server; /* server global state */
|
||||
struct redisCommand *commandTable;
|
||||
|
||||
/* Our command table.
|
||||
*
|
||||
@@ -129,7 +129,7 @@ struct redisCommand redisCommandTable[] = {
|
||||
{"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0},
|
||||
{"strlen",strlenCommand,2,"rF",0,NULL,1,1,1,0,0},
|
||||
{"del",delCommand,-2,"w",0,NULL,1,-1,1,0,0},
|
||||
{"exists",existsCommand,-2,"rF",0,NULL,1,-1,1,0,0},
|
||||
{"exists",existsCommand,2,"rF",0,NULL,1,1,1,0,0},
|
||||
{"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0},
|
||||
{"getbit",getbitCommand,3,"rF",0,NULL,1,1,1,0,0},
|
||||
{"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0},
|
||||
@@ -224,7 +224,7 @@ struct redisCommand redisCommandTable[] = {
|
||||
{"scan",scanCommand,-2,"rR",0,NULL,0,0,0,0,0},
|
||||
{"dbsize",dbsizeCommand,1,"rF",0,NULL,0,0,0,0,0},
|
||||
{"auth",authCommand,2,"rsltF",0,NULL,0,0,0,0,0},
|
||||
{"ping",pingCommand,-1,"rtF",0,NULL,0,0,0,0,0},
|
||||
{"ping",pingCommand,1,"rtF",0,NULL,0,0,0,0,0},
|
||||
{"echo",echoCommand,2,"rF",0,NULL,0,0,0,0,0},
|
||||
{"save",saveCommand,1,"ars",0,NULL,0,0,0,0,0},
|
||||
{"bgsave",bgsaveCommand,1,"ar",0,NULL,0,0,0,0,0},
|
||||
@@ -247,7 +247,7 @@ struct redisCommand redisCommandTable[] = {
|
||||
{"pttl",pttlCommand,2,"rF",0,NULL,1,1,1,0,0},
|
||||
{"persist",persistCommand,2,"wF",0,NULL,1,1,1,0,0},
|
||||
{"slaveof",slaveofCommand,3,"ast",0,NULL,0,0,0,0,0},
|
||||
{"role",roleCommand,1,"lst",0,NULL,0,0,0,0,0},
|
||||
{"role",roleCommand,1,"last",0,NULL,0,0,0,0,0},
|
||||
{"debug",debugCommand,-2,"as",0,NULL,0,0,0,0,0},
|
||||
{"config",configCommand,-2,"art",0,NULL,0,0,0,0,0},
|
||||
{"subscribe",subscribeCommand,-2,"rpslt",0,NULL,0,0,0,0,0},
|
||||
@@ -259,19 +259,19 @@ struct redisCommand redisCommandTable[] = {
|
||||
{"watch",watchCommand,-2,"rsF",0,NULL,1,-1,1,0,0},
|
||||
{"unwatch",unwatchCommand,1,"rsF",0,NULL,0,0,0,0,0},
|
||||
{"cluster",clusterCommand,-2,"ar",0,NULL,0,0,0,0,0},
|
||||
{"restore",restoreCommand,-4,"wm",0,NULL,1,1,1,0,0},
|
||||
{"restore-asking",restoreCommand,-4,"wmk",0,NULL,1,1,1,0,0},
|
||||
{"migrate",migrateCommand,-6,"w",0,NULL,3,3,1,0,0},
|
||||
{"restore",restoreCommand,-4,"awm",0,NULL,1,1,1,0,0},
|
||||
{"restore-asking",restoreCommand,-4,"awmk",0,NULL,1,1,1,0,0},
|
||||
{"migrate",migrateCommand,-6,"aw",0,NULL,0,0,0,0,0},
|
||||
{"asking",askingCommand,1,"r",0,NULL,0,0,0,0,0},
|
||||
{"readonly",readonlyCommand,1,"rF",0,NULL,0,0,0,0,0},
|
||||
{"readwrite",readwriteCommand,1,"rF",0,NULL,0,0,0,0,0},
|
||||
{"dump",dumpCommand,2,"r",0,NULL,1,1,1,0,0},
|
||||
{"object",objectCommand,3,"r",0,NULL,2,2,2,0,0},
|
||||
{"client",clientCommand,-2,"rs",0,NULL,0,0,0,0,0},
|
||||
{"dump",dumpCommand,2,"ar",0,NULL,1,1,1,0,0},
|
||||
{"object",objectCommand,-2,"r",0,NULL,2,2,2,0,0},
|
||||
{"client",clientCommand,-2,"ar",0,NULL,0,0,0,0,0},
|
||||
{"eval",evalCommand,-3,"s",0,evalGetKeys,0,0,0,0,0},
|
||||
{"evalsha",evalShaCommand,-3,"s",0,evalGetKeys,0,0,0,0,0},
|
||||
{"slowlog",slowlogCommand,-2,"r",0,NULL,0,0,0,0,0},
|
||||
{"script",scriptCommand,-2,"rs",0,NULL,0,0,0,0,0},
|
||||
{"script",scriptCommand,-2,"ras",0,NULL,0,0,0,0,0},
|
||||
{"time",timeCommand,1,"rRF",0,NULL,0,0,0,0,0},
|
||||
{"bitop",bitopCommand,-4,"wm",0,NULL,2,-1,1,0,0},
|
||||
{"bitcount",bitcountCommand,-2,"r",0,NULL,1,1,1,0,0},
|
||||
@@ -280,7 +280,7 @@ struct redisCommand redisCommandTable[] = {
|
||||
{"command",commandCommand,0,"rlt",0,NULL,0,0,0,0,0},
|
||||
{"pfselftest",pfselftestCommand,1,"r",0,NULL,0,0,0,0,0},
|
||||
{"pfadd",pfaddCommand,-2,"wmF",0,NULL,1,1,1,0,0},
|
||||
{"pfcount",pfcountCommand,-2,"r",0,NULL,1,-1,1,0,0},
|
||||
{"pfcount",pfcountCommand,-2,"w",0,NULL,1,1,1,0,0},
|
||||
{"pfmerge",pfmergeCommand,-2,"wm",0,NULL,1,-1,1,0,0},
|
||||
{"pfdebug",pfdebugCommand,-3,"w",0,NULL,0,0,0,0,0},
|
||||
{"latency",latencyCommand,-2,"arslt",0,NULL,0,0,0,0,0}
|
||||
@@ -408,7 +408,7 @@ void exitFromChild(int retcode) {
|
||||
/*====================== Hash table type implementation ==================== */
|
||||
|
||||
/* This is a hash table type that uses the SDS dynamic strings library as
|
||||
* keys and redis objects as values (objects can hold SDS strings,
|
||||
* keys and radis objects as values (objects can hold SDS strings,
|
||||
* lists, sets). */
|
||||
|
||||
void dictVanillaFree(void *privdata, void *val)
|
||||
@@ -760,8 +760,8 @@ void activeExpireCycle(int type) {
|
||||
static int timelimit_exit = 0; /* Time limit hit in previous call? */
|
||||
static long long last_fast_cycle = 0; /* When last fast cycle ran. */
|
||||
|
||||
int j, iteration = 0;
|
||||
int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL;
|
||||
unsigned int j, iteration = 0;
|
||||
unsigned int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL;
|
||||
long long start = ustime(), timelimit;
|
||||
|
||||
if (type == ACTIVE_EXPIRE_CYCLE_FAST) {
|
||||
@@ -876,44 +876,39 @@ unsigned int getLRUClock(void) {
|
||||
}
|
||||
|
||||
/* Add a sample to the operations per second array of samples. */
|
||||
void trackInstantaneousMetric(int metric, long long current_reading) {
|
||||
long long t = mstime() - server.inst_metric[metric].last_sample_time;
|
||||
long long ops = current_reading -
|
||||
server.inst_metric[metric].last_sample_count;
|
||||
void trackOperationsPerSecond(void) {
|
||||
long long t = mstime() - server.ops_sec_last_sample_time;
|
||||
long long ops = server.stat_numcommands - server.ops_sec_last_sample_ops;
|
||||
long long ops_sec;
|
||||
|
||||
ops_sec = t > 0 ? (ops*1000/t) : 0;
|
||||
|
||||
server.inst_metric[metric].samples[server.inst_metric[metric].idx] =
|
||||
ops_sec;
|
||||
server.inst_metric[metric].idx++;
|
||||
server.inst_metric[metric].idx %= REDIS_METRIC_SAMPLES;
|
||||
server.inst_metric[metric].last_sample_time = mstime();
|
||||
server.inst_metric[metric].last_sample_count = current_reading;
|
||||
server.ops_sec_samples[server.ops_sec_idx] = ops_sec;
|
||||
server.ops_sec_idx = (server.ops_sec_idx+1) % REDIS_OPS_SEC_SAMPLES;
|
||||
server.ops_sec_last_sample_time = mstime();
|
||||
server.ops_sec_last_sample_ops = server.stat_numcommands;
|
||||
}
|
||||
|
||||
/* Return the mean of all the samples. */
|
||||
long long getInstantaneousMetric(int metric) {
|
||||
long long getOperationsPerSecond(void) {
|
||||
int j;
|
||||
long long sum = 0;
|
||||
|
||||
for (j = 0; j < REDIS_METRIC_SAMPLES; j++)
|
||||
sum += server.inst_metric[metric].samples[j];
|
||||
return sum / REDIS_METRIC_SAMPLES;
|
||||
for (j = 0; j < REDIS_OPS_SEC_SAMPLES; j++)
|
||||
sum += server.ops_sec_samples[j];
|
||||
return sum / REDIS_OPS_SEC_SAMPLES;
|
||||
}
|
||||
|
||||
/* Check for timeouts. Returns non-zero if the client was terminated.
|
||||
* The function gets the current time in milliseconds as argument since
|
||||
* it gets called multiple times in a loop, so calling gettimeofday() for
|
||||
* each iteration would be costly without any actual gain. */
|
||||
int clientsCronHandleTimeout(redisClient *c, mstime_t now_ms) {
|
||||
time_t now = now_ms/1000;
|
||||
/* Check for timeouts. Returns non-zero if the client was terminated */
|
||||
int clientsCronHandleTimeout(redisClient *c) {
|
||||
time_t now = server.unixtime;
|
||||
|
||||
if (server.maxidletime &&
|
||||
!(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
|
||||
!(c->flags & REDIS_MASTER) && /* no timeout for masters */
|
||||
!(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */
|
||||
!(c->flags & REDIS_PUBSUB) && /* no timeout for Pub/Sub clients */
|
||||
dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
|
||||
listLength(c->pubsub_patterns) == 0 &&
|
||||
(now - c->lastinteraction > server.maxidletime))
|
||||
{
|
||||
redisLog(REDIS_VERBOSE,"Closing idle client");
|
||||
@@ -923,16 +918,11 @@ int clientsCronHandleTimeout(redisClient *c, mstime_t now_ms) {
|
||||
/* Blocked OPS timeout is handled with milliseconds resolution.
|
||||
* However note that the actual resolution is limited by
|
||||
* server.hz. */
|
||||
mstime_t now_ms = mstime();
|
||||
|
||||
if (c->bpop.timeout != 0 && c->bpop.timeout < now_ms) {
|
||||
/* Handle blocking operation specific timeout. */
|
||||
replyToBlockedClientTimedOut(c);
|
||||
unblockClient(c);
|
||||
} else if (server.cluster_enabled) {
|
||||
/* Cluster: handle unblock & redirect of clients blocked
|
||||
* into keys no longer served by this server. */
|
||||
if (clusterRedirectBlockedClientIfNeeded(c))
|
||||
unblockClient(c);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
@@ -964,23 +954,17 @@ int clientsCronResizeQueryBuffer(redisClient *c) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
#define CLIENTS_CRON_MIN_ITERATIONS 5
|
||||
void clientsCron(void) {
|
||||
/* Make sure to process at least numclients/server.hz of clients
|
||||
* per call. Since this function is called server.hz times per second
|
||||
* we are sure that in the worst case we process all the clients in 1
|
||||
* second. */
|
||||
/* Make sure to process at least 1/(server.hz*10) of clients per call.
|
||||
* Since this function is called server.hz times per second we are sure that
|
||||
* in the worst case we process all the clients in 10 seconds.
|
||||
* In normal conditions (a reasonable number of clients) we process
|
||||
* all the clients in a shorter time. */
|
||||
int numclients = listLength(server.clients);
|
||||
int iterations = numclients/server.hz;
|
||||
mstime_t now = mstime();
|
||||
|
||||
/* Process at least a few clients while we are at it, even if we need
|
||||
* to process less than CLIENTS_CRON_MIN_ITERATIONS to meet our contract
|
||||
* of processing each client once per second. */
|
||||
if (iterations < CLIENTS_CRON_MIN_ITERATIONS)
|
||||
iterations = (numclients < CLIENTS_CRON_MIN_ITERATIONS) ?
|
||||
numclients : CLIENTS_CRON_MIN_ITERATIONS;
|
||||
int iterations = numclients/(server.hz*10);
|
||||
|
||||
if (iterations < 50)
|
||||
iterations = (numclients < 50) ? numclients : 50;
|
||||
while(listLength(server.clients) && iterations--) {
|
||||
redisClient *c;
|
||||
listNode *head;
|
||||
@@ -994,7 +978,7 @@ void clientsCron(void) {
|
||||
/* The following functions do different service checks on the client.
|
||||
* The protocol is that they return non-zero if the client was
|
||||
* terminated. */
|
||||
if (clientsCronHandleTimeout(c,now)) continue;
|
||||
if (clientsCronHandleTimeout(c)) continue;
|
||||
if (clientsCronResizeQueryBuffer(c)) continue;
|
||||
}
|
||||
}
|
||||
@@ -1017,8 +1001,8 @@ void databasesCron(void) {
|
||||
* cron loop iteration. */
|
||||
static unsigned int resize_db = 0;
|
||||
static unsigned int rehash_db = 0;
|
||||
int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL;
|
||||
int j;
|
||||
unsigned int dbs_per_call = REDIS_DBCRON_DBS_PER_CALL;
|
||||
unsigned int j;
|
||||
|
||||
/* Don't test more DBs than we have. */
|
||||
if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum;
|
||||
@@ -1085,13 +1069,7 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
|
||||
/* Update the time cache. */
|
||||
updateCachedTime();
|
||||
|
||||
run_with_period(100) {
|
||||
trackInstantaneousMetric(REDIS_METRIC_COMMAND,server.stat_numcommands);
|
||||
trackInstantaneousMetric(REDIS_METRIC_NET_INPUT,
|
||||
server.stat_net_input_bytes);
|
||||
trackInstantaneousMetric(REDIS_METRIC_NET_OUTPUT,
|
||||
server.stat_net_output_bytes);
|
||||
}
|
||||
run_with_period(100) trackOperationsPerSecond();
|
||||
|
||||
/* We have just REDIS_LRU_BITS bits per object for LRU information.
|
||||
* So we use an (eventually wrapping) LRU clock.
|
||||
@@ -1172,13 +1150,7 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
|
||||
|
||||
if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc);
|
||||
|
||||
if (pid == -1) {
|
||||
redisLog(LOG_WARNING,"wait3() returned an error: %s. "
|
||||
"rdb_child_pid = %d, aof_child_pid = %d",
|
||||
strerror(errno),
|
||||
(int) server.rdb_child_pid,
|
||||
(int) server.aof_child_pid);
|
||||
} else if (pid == server.rdb_child_pid) {
|
||||
if (pid == server.rdb_child_pid) {
|
||||
backgroundSaveDoneHandler(exitcode,bysignal);
|
||||
} else if (pid == server.aof_child_pid) {
|
||||
backgroundRewriteDoneHandler(exitcode,bysignal);
|
||||
@@ -1277,12 +1249,6 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
|
||||
void beforeSleep(struct aeEventLoop *eventLoop) {
|
||||
REDIS_NOTUSED(eventLoop);
|
||||
|
||||
/* Call the Redis Cluster before sleep function. Note that this function
|
||||
* may change the state of Redis Cluster (from ok to fail or vice versa),
|
||||
* so it's a good idea to call it before serving the unblocked clients
|
||||
* later in this function. */
|
||||
if (server.cluster_enabled) clusterBeforeSleep();
|
||||
|
||||
/* Run a fast expire cycle (the called function will return
|
||||
* ASAP if a fast cycle is not needed). */
|
||||
if (server.active_expire_enabled && server.masterhost == NULL)
|
||||
@@ -1314,6 +1280,9 @@ void beforeSleep(struct aeEventLoop *eventLoop) {
|
||||
|
||||
/* Write the AOF buffer on disk */
|
||||
flushAppendOnlyFile(0);
|
||||
|
||||
/* Call the Redis Cluster before sleep function. */
|
||||
if (server.cluster_enabled) clusterBeforeSleep();
|
||||
}
|
||||
|
||||
/* =========================== Server initialization ======================== */
|
||||
@@ -1408,7 +1377,7 @@ void createSharedObjects(void) {
|
||||
shared.maxstring = createStringObject("maxstring",9);
|
||||
}
|
||||
|
||||
void initServerConfig(void) {
|
||||
void initServerConfig() {
|
||||
int j;
|
||||
|
||||
getRandomHexChars(server.runid,REDIS_RUN_ID_SIZE);
|
||||
@@ -1452,7 +1421,6 @@ void initServerConfig(void) {
|
||||
server.aof_selected_db = -1; /* Make sure the first time will not match */
|
||||
server.aof_flush_postponed_start = 0;
|
||||
server.aof_rewrite_incremental_fsync = REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC;
|
||||
server.aof_load_truncated = REDIS_DEFAULT_AOF_LOAD_TRUNCATED;
|
||||
server.pidfile = zstrdup(REDIS_DEFAULT_PID_FILE);
|
||||
server.rdb_filename = zstrdup(REDIS_DEFAULT_RDB_FILENAME);
|
||||
server.aof_filename = zstrdup(REDIS_DEFAULT_AOF_FILENAME);
|
||||
@@ -1484,7 +1452,6 @@ void initServerConfig(void) {
|
||||
server.cluster_node_timeout = REDIS_CLUSTER_DEFAULT_NODE_TIMEOUT;
|
||||
server.cluster_migration_barrier = REDIS_CLUSTER_DEFAULT_MIGRATION_BARRIER;
|
||||
server.cluster_slave_validity_factor = REDIS_CLUSTER_DEFAULT_SLAVE_VALIDITY;
|
||||
server.cluster_require_full_coverage = REDIS_CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE;
|
||||
server.cluster_configfile = zstrdup(REDIS_DEFAULT_CLUSTER_CONFIG_FILE);
|
||||
server.lua_caller = NULL;
|
||||
server.lua_time_limit = REDIS_LUA_TIME_LIMIT;
|
||||
@@ -1513,8 +1480,6 @@ void initServerConfig(void) {
|
||||
server.repl_slave_ro = REDIS_DEFAULT_SLAVE_READ_ONLY;
|
||||
server.repl_down_since = 0; /* Never connected, repl is down since EVER. */
|
||||
server.repl_disable_tcp_nodelay = REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY;
|
||||
server.repl_diskless_sync = REDIS_DEFAULT_REPL_DISKLESS_SYNC;
|
||||
server.repl_diskless_sync_delay = REDIS_DEFAULT_REPL_DISKLESS_SYNC_DELAY;
|
||||
server.slave_priority = REDIS_DEFAULT_SLAVE_PRIORITY;
|
||||
server.master_repl_offset = 0;
|
||||
|
||||
@@ -1586,33 +1551,33 @@ void adjustOpenFilesLimit(void) {
|
||||
/* Set the max number of files if the current limit is not enough
|
||||
* for our needs. */
|
||||
if (oldlimit < maxfiles) {
|
||||
rlim_t bestlimit;
|
||||
rlim_t f;
|
||||
int setrlimit_error = 0;
|
||||
|
||||
/* Try to set the file limit to match 'maxfiles' or at least
|
||||
* to the higher value supported less than maxfiles. */
|
||||
bestlimit = maxfiles;
|
||||
while(bestlimit > oldlimit) {
|
||||
rlim_t decr_step = 16;
|
||||
f = maxfiles;
|
||||
while(f > oldlimit) {
|
||||
int decr_step = 16;
|
||||
|
||||
limit.rlim_cur = bestlimit;
|
||||
limit.rlim_max = bestlimit;
|
||||
limit.rlim_cur = f;
|
||||
limit.rlim_max = f;
|
||||
if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break;
|
||||
setrlimit_error = errno;
|
||||
|
||||
/* We failed to set file limit to 'bestlimit'. Try with a
|
||||
/* We failed to set file limit to 'f'. Try with a
|
||||
* smaller limit decrementing by a few FDs per iteration. */
|
||||
if (bestlimit < decr_step) break;
|
||||
bestlimit -= decr_step;
|
||||
if (f < decr_step) break;
|
||||
f -= decr_step;
|
||||
}
|
||||
|
||||
/* Assume that the limit we get initially is still valid if
|
||||
* our last try was even lower. */
|
||||
if (bestlimit < oldlimit) bestlimit = oldlimit;
|
||||
if (f < oldlimit) f = oldlimit;
|
||||
|
||||
if (bestlimit < maxfiles) {
|
||||
if (f != maxfiles) {
|
||||
int old_maxclients = server.maxclients;
|
||||
server.maxclients = bestlimit-REDIS_MIN_RESERVED_FDS;
|
||||
server.maxclients = f-REDIS_MIN_RESERVED_FDS;
|
||||
if (server.maxclients < 1) {
|
||||
redisLog(REDIS_WARNING,"Your current 'ulimit -n' "
|
||||
"of %llu is not enough for Redis to start. "
|
||||
@@ -1633,7 +1598,7 @@ void adjustOpenFilesLimit(void) {
|
||||
"maxclients has been reduced to %d to compensate for "
|
||||
"low ulimit. "
|
||||
"If you need higher maxclients increase 'ulimit -n'.",
|
||||
(unsigned long long) bestlimit, server.maxclients);
|
||||
(unsigned long long) oldlimit, server.maxclients);
|
||||
} else {
|
||||
redisLog(REDIS_NOTICE,"Increased maximum number of open files "
|
||||
"to %llu (it was originally set to %llu).",
|
||||
@@ -1644,23 +1609,6 @@ void adjustOpenFilesLimit(void) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Check that server.tcp_backlog can be actually enforced in Linux according
|
||||
* to the value of /proc/sys/net/core/somaxconn, or warn about it. */
|
||||
void checkTcpBacklogSettings(void) {
|
||||
#ifdef HAVE_PROC_SOMAXCONN
|
||||
FILE *fp = fopen("/proc/sys/net/core/somaxconn","r");
|
||||
char buf[1024];
|
||||
if (!fp) return;
|
||||
if (fgets(buf,sizeof(buf),fp) != NULL) {
|
||||
int somaxconn = atoi(buf);
|
||||
if (somaxconn > 0 && somaxconn < server.tcp_backlog) {
|
||||
redisLog(REDIS_WARNING,"WARNING: The TCP backlog setting of %d cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of %d.", server.tcp_backlog, somaxconn);
|
||||
}
|
||||
}
|
||||
fclose(fp);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Initialize a set of file descriptors to listen to the specified 'port'
|
||||
* binding the addresses specified in the Redis server configuration.
|
||||
*
|
||||
@@ -1731,8 +1679,6 @@ int listenToPort(int port, int *fds, int *count) {
|
||||
* to reset via CONFIG RESETSTAT. The function is also used in order to
|
||||
* initialize these fields in initServer() at server startup. */
|
||||
void resetServerStats(void) {
|
||||
int j;
|
||||
|
||||
server.stat_numcommands = 0;
|
||||
server.stat_numconnections = 0;
|
||||
server.stat_expiredkeys = 0;
|
||||
@@ -1745,24 +1691,17 @@ void resetServerStats(void) {
|
||||
server.stat_sync_full = 0;
|
||||
server.stat_sync_partial_ok = 0;
|
||||
server.stat_sync_partial_err = 0;
|
||||
for (j = 0; j < REDIS_METRIC_COUNT; j++) {
|
||||
server.inst_metric[j].idx = 0;
|
||||
server.inst_metric[j].last_sample_time = mstime();
|
||||
server.inst_metric[j].last_sample_count = 0;
|
||||
memset(server.inst_metric[j].samples,0,
|
||||
sizeof(server.inst_metric[j].samples));
|
||||
}
|
||||
server.stat_net_input_bytes = 0;
|
||||
server.stat_net_output_bytes = 0;
|
||||
server.aof_delayed_fsync = 0;
|
||||
memset(server.ops_sec_samples,0,sizeof(server.ops_sec_samples));
|
||||
server.ops_sec_idx = 0;
|
||||
server.ops_sec_last_sample_time = mstime();
|
||||
server.ops_sec_last_sample_ops = 0;
|
||||
}
|
||||
|
||||
void initServer(void) {
|
||||
void initServer() {
|
||||
int j;
|
||||
|
||||
signal(SIGHUP, SIG_IGN);
|
||||
signal(SIGPIPE, SIG_IGN); /* No write(2) generated signals. */
|
||||
signal(SIGCHLD, SIG_DFL); /* We want zombies to queue for waitpid(). */
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
setupSignalHandlers();
|
||||
|
||||
if (server.syslog_enabled) {
|
||||
@@ -1799,7 +1738,7 @@ void initServer(void) {
|
||||
server.sofd = anetUnixServer(server.neterr,server.unixsocket,
|
||||
server.unixsocketperm, server.tcp_backlog);
|
||||
if (server.sofd == ANET_ERR) {
|
||||
redisLog(REDIS_WARNING, "Opening Unix socket: %s", server.neterr);
|
||||
redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
|
||||
exit(1);
|
||||
}
|
||||
anetNonBlock(NULL,server.sofd);
|
||||
@@ -1829,7 +1768,6 @@ void initServer(void) {
|
||||
server.cronloops = 0;
|
||||
server.rdb_child_pid = -1;
|
||||
server.aof_child_pid = -1;
|
||||
server.rdb_child_type = REDIS_RDB_CHILD_TYPE_NONE;
|
||||
aofRewriteBufferReset();
|
||||
server.aof_buf = sdsempty();
|
||||
server.lastsave = time(NULL); /* At startup we consider the DB saved. */
|
||||
@@ -2040,7 +1978,7 @@ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
|
||||
}
|
||||
|
||||
/* It is possible to call the function forceCommandPropagation() inside a
|
||||
* Redis command implementation in order to to force the propagation of a
|
||||
* Redis command implementaiton in order to to force the propagation of a
|
||||
* specific command execution into AOF / Replication. */
|
||||
void forceCommandPropagation(redisClient *c, int flags) {
|
||||
if (flags & REDIS_PROPAGATE_REPL) c->flags |= REDIS_FORCE_REPL;
|
||||
@@ -2056,7 +1994,7 @@ void call(redisClient *c, int flags) {
|
||||
* not generated from reading an AOF. */
|
||||
if (listLength(server.monitors) &&
|
||||
!server.loading &&
|
||||
!(c->cmd->flags & (REDIS_CMD_SKIP_MONITOR|REDIS_CMD_ADMIN)))
|
||||
!(c->cmd->flags & REDIS_CMD_SKIP_MONITOR))
|
||||
{
|
||||
replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc);
|
||||
}
|
||||
@@ -2069,7 +2007,6 @@ void call(redisClient *c, int flags) {
|
||||
c->cmd->proc(c);
|
||||
duration = ustime()-start;
|
||||
dirty = server.dirty-dirty;
|
||||
if (dirty < 0) dirty = 0;
|
||||
|
||||
/* When EVAL is called loading the AOF we don't want commands called
|
||||
* from Lua to go into the slowlog or to populate statistics. */
|
||||
@@ -2180,22 +2117,36 @@ int processCommand(redisClient *c) {
|
||||
* 2) The command has no key arguments. */
|
||||
if (server.cluster_enabled &&
|
||||
!(c->flags & REDIS_MASTER) &&
|
||||
!(c->flags & REDIS_LUA_CLIENT &&
|
||||
server.lua_caller->flags & REDIS_MASTER) &&
|
||||
!(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0))
|
||||
{
|
||||
int hashslot;
|
||||
|
||||
if (server.cluster->state != REDIS_CLUSTER_OK) {
|
||||
flagTransaction(c);
|
||||
clusterRedirectClient(c,NULL,0,REDIS_CLUSTER_REDIR_DOWN_STATE);
|
||||
addReplySds(c,sdsnew("-CLUSTERDOWN The cluster is down. Use CLUSTER INFO for more information\r\n"));
|
||||
return REDIS_OK;
|
||||
} else {
|
||||
int error_code;
|
||||
clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,&hashslot,&error_code);
|
||||
if (n == NULL || n != server.cluster->myself) {
|
||||
if (n == NULL) {
|
||||
flagTransaction(c);
|
||||
clusterRedirectClient(c,n,hashslot,error_code);
|
||||
if (error_code == REDIS_CLUSTER_REDIR_CROSS_SLOT) {
|
||||
addReplySds(c,sdsnew("-CROSSSLOT Keys in request don't hash to the same slot\r\n"));
|
||||
} else if (error_code == REDIS_CLUSTER_REDIR_UNSTABLE) {
|
||||
/* The request spawns mutliple keys in the same slot,
|
||||
* but the slot is not "stable" currently as there is
|
||||
* a migration or import in progress. */
|
||||
addReplySds(c,sdsnew("-TRYAGAIN Multiple keys request during rehashing of slot\r\n"));
|
||||
} else {
|
||||
redisPanic("getNodeByQuery() unknown error.");
|
||||
}
|
||||
return REDIS_OK;
|
||||
} else if (n != server.cluster->myself) {
|
||||
flagTransaction(c);
|
||||
addReplySds(c,sdscatprintf(sdsempty(),
|
||||
"-%s %d %s:%d\r\n",
|
||||
(error_code == REDIS_CLUSTER_REDIR_ASK) ? "ASK" : "MOVED",
|
||||
hashslot,n->ip,n->port));
|
||||
return REDIS_OK;
|
||||
}
|
||||
}
|
||||
@@ -2260,13 +2211,13 @@ int processCommand(redisClient *c) {
|
||||
}
|
||||
|
||||
/* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
|
||||
if (c->flags & REDIS_PUBSUB &&
|
||||
c->cmd->proc != pingCommand &&
|
||||
if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
|
||||
&&
|
||||
c->cmd->proc != subscribeCommand &&
|
||||
c->cmd->proc != unsubscribeCommand &&
|
||||
c->cmd->proc != psubscribeCommand &&
|
||||
c->cmd->proc != punsubscribeCommand) {
|
||||
addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context");
|
||||
addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
|
||||
return REDIS_OK;
|
||||
}
|
||||
|
||||
@@ -2409,9 +2360,9 @@ int time_independent_strcmp(char *a, char *b) {
|
||||
* a or b are fixed (our password) length, and the difference is only
|
||||
* relative to the length of the user provided string, so no information
|
||||
* leak is possible in the following two lines of code. */
|
||||
unsigned int alen = strlen(a);
|
||||
unsigned int blen = strlen(b);
|
||||
unsigned int j;
|
||||
int alen = strlen(a);
|
||||
int blen = strlen(b);
|
||||
int j;
|
||||
int diff = 0;
|
||||
|
||||
/* We can't compare strings longer than our static buffers.
|
||||
@@ -2448,29 +2399,8 @@ void authCommand(redisClient *c) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The PING command. It works in a different way if the client is in
|
||||
* in Pub/Sub mode. */
|
||||
void pingCommand(redisClient *c) {
|
||||
/* The command takes zero or one arguments. */
|
||||
if (c->argc > 2) {
|
||||
addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
|
||||
c->cmd->name);
|
||||
return;
|
||||
}
|
||||
|
||||
if (c->flags & REDIS_PUBSUB) {
|
||||
addReply(c,shared.mbulkhdr[2]);
|
||||
addReplyBulkCBuffer(c,"pong",4);
|
||||
if (c->argc == 1)
|
||||
addReplyBulkCBuffer(c,"",0);
|
||||
else
|
||||
addReplyBulk(c,c->argv[1]);
|
||||
} else {
|
||||
if (c->argc == 1)
|
||||
addReply(c,shared.pong);
|
||||
else
|
||||
addReplyBulk(c,c->argv[1]);
|
||||
}
|
||||
addReply(c,shared.pong);
|
||||
}
|
||||
|
||||
void echoCommand(redisClient *c) {
|
||||
@@ -2597,15 +2527,6 @@ void bytesToHuman(char *s, unsigned long long n) {
|
||||
} else if (n < (1024LL*1024*1024*1024)) {
|
||||
d = (double)n/(1024LL*1024*1024);
|
||||
sprintf(s,"%.2fG",d);
|
||||
} else if (n < (1024LL*1024*1024*1024*1024)) {
|
||||
d = (double)n/(1024LL*1024*1024*1024);
|
||||
sprintf(s,"%.2fT",d);
|
||||
} else if (n < (1024LL*1024*1024*1024*1024*1024)) {
|
||||
d = (double)n/(1024LL*1024*1024*1024*1024);
|
||||
sprintf(s,"%.2fP",d);
|
||||
} else {
|
||||
/* Let's hope we never need this */
|
||||
sprintf(s,"%lluB",n);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2621,9 +2542,10 @@ sds genRedisInfoString(char *section) {
|
||||
int allsections = 0, defsections = 0;
|
||||
int sections = 0;
|
||||
|
||||
if (section == NULL) section = "default";
|
||||
allsections = strcasecmp(section,"all") == 0;
|
||||
defsections = strcasecmp(section,"default") == 0;
|
||||
if (section) {
|
||||
allsections = strcasecmp(section,"all") == 0;
|
||||
defsections = strcasecmp(section,"default") == 0;
|
||||
}
|
||||
|
||||
getrusage(RUSAGE_SELF, &self_ru);
|
||||
getrusage(RUSAGE_CHILDREN, &c_ru);
|
||||
@@ -2801,14 +2723,14 @@ sds genRedisInfoString(char *section) {
|
||||
server.loading_loaded_bytes;
|
||||
|
||||
perc = ((double)server.loading_loaded_bytes /
|
||||
(server.loading_total_bytes+1)) * 100;
|
||||
server.loading_total_bytes) * 100;
|
||||
|
||||
elapsed = time(NULL)-server.loading_start_time;
|
||||
elapsed = server.unixtime-server.loading_start_time;
|
||||
if (elapsed == 0) {
|
||||
eta = 1; /* A fake 1 second figure if we don't have
|
||||
enough info */
|
||||
} else {
|
||||
eta = (elapsed*remaining_bytes)/(server.loading_loaded_bytes+1);
|
||||
eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
|
||||
}
|
||||
|
||||
info = sdscatprintf(info,
|
||||
@@ -2834,10 +2756,6 @@ sds genRedisInfoString(char *section) {
|
||||
"total_connections_received:%lld\r\n"
|
||||
"total_commands_processed:%lld\r\n"
|
||||
"instantaneous_ops_per_sec:%lld\r\n"
|
||||
"total_net_input_bytes:%lld\r\n"
|
||||
"total_net_output_bytes:%lld\r\n"
|
||||
"instantaneous_input_kbps:%.2f\r\n"
|
||||
"instantaneous_output_kbps:%.2f\r\n"
|
||||
"rejected_connections:%lld\r\n"
|
||||
"sync_full:%lld\r\n"
|
||||
"sync_partial_ok:%lld\r\n"
|
||||
@@ -2852,11 +2770,7 @@ sds genRedisInfoString(char *section) {
|
||||
"migrate_cached_sockets:%ld\r\n",
|
||||
server.stat_numconnections,
|
||||
server.stat_numcommands,
|
||||
getInstantaneousMetric(REDIS_METRIC_COMMAND),
|
||||
server.stat_net_input_bytes,
|
||||
server.stat_net_output_bytes,
|
||||
(float)getInstantaneousMetric(REDIS_METRIC_NET_INPUT)/1024,
|
||||
(float)getInstantaneousMetric(REDIS_METRIC_NET_OUTPUT)/1024,
|
||||
getOperationsPerSecond(),
|
||||
server.stat_rejected_conn,
|
||||
server.stat_sync_full,
|
||||
server.stat_sync_partial_ok,
|
||||
@@ -3147,7 +3061,13 @@ void evictionPoolPopulate(dict *sampledict, dict *keydict, struct evictionPoolEn
|
||||
samples = zmalloc(sizeof(samples[0])*server.maxmemory_samples);
|
||||
}
|
||||
|
||||
count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples);
|
||||
#if 1 /* Use bulk get by default. */
|
||||
count = dictGetRandomKeys(sampledict,samples,server.maxmemory_samples);
|
||||
#else
|
||||
count = server.maxmemory_samples;
|
||||
for (j = 0; j < count; j++) samples[j] = dictGetRandomKey(sampledict);
|
||||
#endif
|
||||
|
||||
for (j = 0; j < count; j++) {
|
||||
unsigned long long idle;
|
||||
sds key;
|
||||
@@ -3202,7 +3122,7 @@ void evictionPoolPopulate(dict *sampledict, dict *keydict, struct evictionPoolEn
|
||||
int freeMemoryIfNeeded(void) {
|
||||
size_t mem_used, mem_tofree, mem_freed;
|
||||
int slaves = listLength(server.slaves);
|
||||
mstime_t latency, eviction_latency;
|
||||
mstime_t latency;
|
||||
|
||||
/* Remove the size of slaves output buffers and AOF buffer from the
|
||||
* count of used memory. */
|
||||
@@ -3333,11 +3253,7 @@ int freeMemoryIfNeeded(void) {
|
||||
* AOF and Output buffer memory will be freed eventually so
|
||||
* we only care about memory used by the key space. */
|
||||
delta = (long long) zmalloc_used_memory();
|
||||
latencyStartMonitor(eviction_latency);
|
||||
dbDelete(db,keyobj);
|
||||
latencyEndMonitor(eviction_latency);
|
||||
latencyAddSampleIfNeeded("eviction-del",eviction_latency);
|
||||
latencyRemoveNestedEvent(latency,eviction_latency);
|
||||
delta -= (long long) zmalloc_used_memory();
|
||||
mem_freed += delta;
|
||||
server.stat_evictedkeys++;
|
||||
@@ -3381,13 +3297,10 @@ int linuxOvercommitMemoryValue(void) {
|
||||
return atoi(buf);
|
||||
}
|
||||
|
||||
void linuxMemoryWarnings(void) {
|
||||
void linuxOvercommitMemoryWarning(void) {
|
||||
if (linuxOvercommitMemoryValue() == 0) {
|
||||
redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
|
||||
}
|
||||
if (THPIsEnabled()) {
|
||||
redisLog(REDIS_WARNING,"WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.");
|
||||
}
|
||||
}
|
||||
#endif /* __linux__ */
|
||||
|
||||
@@ -3417,7 +3330,7 @@ void daemonize(void) {
|
||||
}
|
||||
}
|
||||
|
||||
void version(void) {
|
||||
void version() {
|
||||
printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d build=%llx\n",
|
||||
REDIS_VERSION,
|
||||
redisGitSHA1(),
|
||||
@@ -3428,7 +3341,7 @@ void version(void) {
|
||||
exit(0);
|
||||
}
|
||||
|
||||
void usage(void) {
|
||||
void usage() {
|
||||
fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n");
|
||||
fprintf(stderr," ./redis-server - (read config from stdin)\n");
|
||||
fprintf(stderr," ./redis-server -v or --version\n");
|
||||
@@ -3448,63 +3361,27 @@ void usage(void) {
|
||||
void redisAsciiArt(void) {
|
||||
#include "asciilogo.h"
|
||||
char *buf = zmalloc(1024*16);
|
||||
char *mode;
|
||||
char *mode = "stand alone";
|
||||
|
||||
if (server.cluster_enabled) mode = "cluster";
|
||||
else if (server.sentinel_mode) mode = "sentinel";
|
||||
else mode = "standalone";
|
||||
|
||||
if (server.syslog_enabled) {
|
||||
redisLog(REDIS_NOTICE,
|
||||
"Redis %s (%s/%d) %s bit, %s mode, port %d, pid %ld ready to start.",
|
||||
REDIS_VERSION,
|
||||
redisGitSHA1(),
|
||||
strtol(redisGitDirty(),NULL,10) > 0,
|
||||
(sizeof(long) == 8) ? "64" : "32",
|
||||
mode, server.port,
|
||||
(long) getpid()
|
||||
);
|
||||
} else {
|
||||
snprintf(buf,1024*16,ascii_logo,
|
||||
REDIS_VERSION,
|
||||
redisGitSHA1(),
|
||||
strtol(redisGitDirty(),NULL,10) > 0,
|
||||
(sizeof(long) == 8) ? "64" : "32",
|
||||
mode, server.port,
|
||||
(long) getpid()
|
||||
);
|
||||
redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
|
||||
}
|
||||
snprintf(buf,1024*16,ascii_logo,
|
||||
REDIS_VERSION,
|
||||
redisGitSHA1(),
|
||||
strtol(redisGitDirty(),NULL,10) > 0,
|
||||
(sizeof(long) == 8) ? "64" : "32",
|
||||
mode, server.port,
|
||||
(long) getpid()
|
||||
);
|
||||
redisLogRaw(REDIS_NOTICE|REDIS_LOG_RAW,buf);
|
||||
zfree(buf);
|
||||
}
|
||||
|
||||
static void sigShutdownHandler(int sig) {
|
||||
char *msg;
|
||||
static void sigtermHandler(int sig) {
|
||||
REDIS_NOTUSED(sig);
|
||||
|
||||
switch (sig) {
|
||||
case SIGINT:
|
||||
msg = "Received SIGINT scheduling shutdown...";
|
||||
break;
|
||||
case SIGTERM:
|
||||
msg = "Received SIGTERM scheduling shutdown...";
|
||||
break;
|
||||
default:
|
||||
msg = "Received shutdown signal, scheduling shutdown...";
|
||||
};
|
||||
|
||||
/* SIGINT is often delivered via Ctrl+C in an interactive session.
|
||||
* If we receive the signal the second time, we interpret this as
|
||||
* the user really wanting to quit ASAP without waiting to persist
|
||||
* on disk. */
|
||||
if (server.shutdown_asap && sig == SIGINT) {
|
||||
redisLogFromHandler(REDIS_WARNING, "You insist... exiting now.");
|
||||
rdbRemoveTempFile(getpid());
|
||||
exit(1); /* Exit with an error since this was not a clean shutdown. */
|
||||
} else if (server.loading) {
|
||||
exit(0);
|
||||
}
|
||||
|
||||
redisLogFromHandler(REDIS_WARNING, msg);
|
||||
redisLogFromHandler(REDIS_WARNING,"Received SIGTERM, scheduling shutdown...");
|
||||
server.shutdown_asap = 1;
|
||||
}
|
||||
|
||||
@@ -3515,9 +3392,8 @@ void setupSignalHandlers(void) {
|
||||
* Otherwise, sa_handler is used. */
|
||||
sigemptyset(&act.sa_mask);
|
||||
act.sa_flags = 0;
|
||||
act.sa_handler = sigShutdownHandler;
|
||||
act.sa_handler = sigtermHandler;
|
||||
sigaction(SIGTERM, &act, NULL);
|
||||
sigaction(SIGINT, &act, NULL);
|
||||
|
||||
#ifdef HAVE_BACKTRACE
|
||||
sigemptyset(&act.sa_mask);
|
||||
@@ -3648,13 +3524,6 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
j++;
|
||||
}
|
||||
if (server.sentinel_mode && configfile && *configfile == '-') {
|
||||
redisLog(REDIS_WARNING,
|
||||
"Sentinel config from STDIN not allowed.");
|
||||
redisLog(REDIS_WARNING,
|
||||
"Sentinel needs config file on disk to save state. Exiting...");
|
||||
exit(1);
|
||||
}
|
||||
if (configfile) server.configfile = getAbsolutePath(configfile);
|
||||
resetServerSaveParams();
|
||||
loadServerConfig(configfile,options);
|
||||
@@ -3667,13 +3536,12 @@ int main(int argc, char **argv) {
|
||||
if (server.daemonize) createPidFile();
|
||||
redisSetProcTitle(argv[0]);
|
||||
redisAsciiArt();
|
||||
checkTcpBacklogSettings();
|
||||
|
||||
if (!server.sentinel_mode) {
|
||||
/* Things not needed when running in Sentinel mode. */
|
||||
redisLog(REDIS_WARNING,"Server started, Redis version " REDIS_VERSION);
|
||||
#ifdef __linux__
|
||||
linuxMemoryWarnings();
|
||||
linuxOvercommitMemoryWarning();
|
||||
#endif
|
||||
loadDataFromDisk();
|
||||
if (server.cluster_enabled) {
|
||||
|
||||
+29
-82
@@ -32,7 +32,10 @@
|
||||
|
||||
#include "fmacros.h"
|
||||
#include "config.h"
|
||||
|
||||
#if defined(__sun)
|
||||
#include "solarisfixes.h"
|
||||
#endif
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -93,7 +96,7 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_REPL_TIMEOUT 60
|
||||
#define REDIS_REPL_PING_SLAVE_PERIOD 10
|
||||
#define REDIS_RUN_ID_SIZE 40
|
||||
#define REDIS_EOF_MARK_SIZE 40
|
||||
#define REDIS_OPS_SEC_SAMPLES 16
|
||||
#define REDIS_DEFAULT_REPL_BACKLOG_SIZE (1024*1024) /* 1mb */
|
||||
#define REDIS_DEFAULT_REPL_BACKLOG_TIME_LIMIT (60*60) /* 1 hour */
|
||||
#define REDIS_REPL_BACKLOG_MIN_SIZE (1024*16) /* 16k */
|
||||
@@ -110,8 +113,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_DEFAULT_RDB_COMPRESSION 1
|
||||
#define REDIS_DEFAULT_RDB_CHECKSUM 1
|
||||
#define REDIS_DEFAULT_RDB_FILENAME "dump.rdb"
|
||||
#define REDIS_DEFAULT_REPL_DISKLESS_SYNC 0
|
||||
#define REDIS_DEFAULT_REPL_DISKLESS_SYNC_DELAY 5
|
||||
#define REDIS_DEFAULT_SLAVE_SERVE_STALE_DATA 1
|
||||
#define REDIS_DEFAULT_SLAVE_READ_ONLY 1
|
||||
#define REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY 0
|
||||
@@ -119,12 +120,11 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_DEFAULT_MAXMEMORY_SAMPLES 5
|
||||
#define REDIS_DEFAULT_AOF_FILENAME "appendonly.aof"
|
||||
#define REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE 0
|
||||
#define REDIS_DEFAULT_AOF_LOAD_TRUNCATED 1
|
||||
#define REDIS_DEFAULT_ACTIVE_REHASHING 1
|
||||
#define REDIS_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC 1
|
||||
#define REDIS_DEFAULT_MIN_SLAVES_TO_WRITE 0
|
||||
#define REDIS_DEFAULT_MIN_SLAVES_MAX_LAG 10
|
||||
#define REDIS_IP_STR_LEN 46 /* INET6_ADDRSTRLEN is 46, but we need to be sure */
|
||||
#define REDIS_IP_STR_LEN INET6_ADDRSTRLEN
|
||||
#define REDIS_PEER_ID_LEN (REDIS_IP_STR_LEN+32) /* Must be enough for ip:port */
|
||||
#define REDIS_BINDADDR_MAX 16
|
||||
#define REDIS_MIN_RESERVED_FDS 32
|
||||
@@ -136,13 +136,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define ACTIVE_EXPIRE_CYCLE_SLOW 0
|
||||
#define ACTIVE_EXPIRE_CYCLE_FAST 1
|
||||
|
||||
/* Instantaneous metrics tracking. */
|
||||
#define REDIS_METRIC_SAMPLES 16 /* Number of samples per metric. */
|
||||
#define REDIS_METRIC_COMMAND 0 /* Number of commands executed. */
|
||||
#define REDIS_METRIC_NET_INPUT 1 /* Bytes read to network .*/
|
||||
#define REDIS_METRIC_NET_OUTPUT 2 /* Bytes written to network. */
|
||||
#define REDIS_METRIC_COUNT 3
|
||||
|
||||
/* Protocol and I/O related defines */
|
||||
#define REDIS_MAX_QUERYBUF_LEN (1024*1024*1024) /* 1GB max query buffer. */
|
||||
#define REDIS_IOBUF_LEN (1024*16) /* Generic I/O buffer size */
|
||||
@@ -248,7 +241,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_FORCE_REPL (1<<15) /* Force replication of current cmd. */
|
||||
#define REDIS_PRE_PSYNC (1<<16) /* Instance don't understand PSYNC. */
|
||||
#define REDIS_READONLY (1<<17) /* Cluster client is in read-only state. */
|
||||
#define REDIS_PUBSUB (1<<18) /* Client is in Pub/Sub mode. */
|
||||
|
||||
/* Client block type (btype field in client structure)
|
||||
* if REDIS_BLOCKED flag is set. */
|
||||
@@ -267,37 +259,22 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_CLIENT_TYPE_PUBSUB 2 /* Clients subscribed to PubSub channels. */
|
||||
#define REDIS_CLIENT_TYPE_COUNT 3
|
||||
|
||||
/* Slave replication state. Used in server.repl_state for slaves to remember
|
||||
* what to do next. */
|
||||
/* Slave replication state - from the point of view of the slave. */
|
||||
#define REDIS_REPL_NONE 0 /* No active replication */
|
||||
#define REDIS_REPL_CONNECT 1 /* Must connect to master */
|
||||
#define REDIS_REPL_CONNECTING 2 /* Connecting to master */
|
||||
/* --- Handshake states, must be ordered --- */
|
||||
#define REDIS_REPL_RECEIVE_PONG 3 /* Wait for PING reply */
|
||||
#define REDIS_REPL_SEND_AUTH 4 /* Send AUTH to master */
|
||||
#define REDIS_REPL_RECEIVE_AUTH 5 /* Wait for AUTH reply */
|
||||
#define REDIS_REPL_SEND_PORT 6 /* Send REPLCONF listening-port */
|
||||
#define REDIS_REPL_RECEIVE_PORT 7 /* Wait for REPLCONF reply */
|
||||
#define REDIS_REPL_SEND_CAPA 8 /* Send REPLCONF capa */
|
||||
#define REDIS_REPL_RECEIVE_CAPA 9 /* Wait for REPLCONF reply */
|
||||
#define REDIS_REPL_SEND_PSYNC 10 /* Send PSYNC */
|
||||
#define REDIS_REPL_RECEIVE_PSYNC 11 /* Wait for PSYNC reply */
|
||||
/* --- End of handshake states --- */
|
||||
#define REDIS_REPL_TRANSFER 12 /* Receiving .rdb from master */
|
||||
#define REDIS_REPL_CONNECTED 13 /* Connected to master */
|
||||
#define REDIS_REPL_TRANSFER 4 /* Receiving .rdb from master */
|
||||
#define REDIS_REPL_CONNECTED 5 /* Connected to master */
|
||||
|
||||
/* State of slaves from the POV of the master. Used in client->replstate.
|
||||
/* Slave replication state - from the point of view of the master.
|
||||
* In SEND_BULK and ONLINE state the slave receives new updates
|
||||
* in its output queue. In the WAIT_BGSAVE state instead the server is waiting
|
||||
* to start the next background saving in order to send updates to it. */
|
||||
#define REDIS_REPL_WAIT_BGSAVE_START 14 /* We need to produce a new RDB file. */
|
||||
#define REDIS_REPL_WAIT_BGSAVE_END 15 /* Waiting RDB file creation to finish. */
|
||||
#define REDIS_REPL_SEND_BULK 16 /* Sending RDB file to slave. */
|
||||
#define REDIS_REPL_ONLINE 17 /* RDB file transmitted, sending just updates. */
|
||||
|
||||
/* Slave capabilities. */
|
||||
#define SLAVE_CAPA_NONE 0
|
||||
#define SLAVE_CAPA_EOF (1<<0) /* Can parse the RDB EOF streaming format. */
|
||||
#define REDIS_REPL_WAIT_BGSAVE_START 6 /* We need to produce a new RDB file. */
|
||||
#define REDIS_REPL_WAIT_BGSAVE_END 7 /* Waiting RDB file creation to finish. */
|
||||
#define REDIS_REPL_SEND_BULK 8 /* Sending RDB file to slave. */
|
||||
#define REDIS_REPL_ONLINE 9 /* RDB file transmitted, sending just updates. */
|
||||
|
||||
/* Synchronous read timeout - slave side */
|
||||
#define REDIS_REPL_SYNCIO_TIMEOUT 5
|
||||
@@ -382,11 +359,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_PROPAGATE_AOF 1
|
||||
#define REDIS_PROPAGATE_REPL 2
|
||||
|
||||
/* RDB active child save type. */
|
||||
#define REDIS_RDB_CHILD_TYPE_NONE 0
|
||||
#define REDIS_RDB_CHILD_TYPE_DISK 1 /* RDB is written to disk. */
|
||||
#define REDIS_RDB_CHILD_TYPE_SOCKET 2 /* RDB is written to slave socket. */
|
||||
|
||||
/* Keyspace changes notification classes. Every class is associated with a
|
||||
* character for configuration purposes. */
|
||||
#define REDIS_NOTIFY_KEYSPACE (1<<0) /* K */
|
||||
@@ -525,7 +497,7 @@ typedef struct readyList {
|
||||
} readyList;
|
||||
|
||||
/* With multiplexing we need to take per-client state.
|
||||
* Clients are taken in a linked list. */
|
||||
* Clients are taken in a liked list. */
|
||||
typedef struct redisClient {
|
||||
uint64_t id; /* Client incremental unique ID. */
|
||||
int fd;
|
||||
@@ -550,7 +522,6 @@ typedef struct redisClient {
|
||||
int flags; /* REDIS_SLAVE | REDIS_MONITOR | REDIS_MULTI ... */
|
||||
int authenticated; /* when requirepass is non-NULL */
|
||||
int replstate; /* replication state if this is a slave */
|
||||
int repl_put_online_on_ack; /* Install slave write handler on ACK. */
|
||||
int repldbfd; /* replication DB file descriptor */
|
||||
off_t repldboff; /* replication DB file offset */
|
||||
off_t repldbsize; /* replication DB file size */
|
||||
@@ -558,12 +529,8 @@ typedef struct redisClient {
|
||||
long long reploff; /* replication offset if this is our master */
|
||||
long long repl_ack_off; /* replication ack offset, if this is a slave */
|
||||
long long repl_ack_time;/* replication ack time, if this is a slave */
|
||||
long long psync_initial_offset; /* FULLRESYNC reply offset other slaves
|
||||
copying this slave output buffer
|
||||
should use. */
|
||||
char replrunid[REDIS_RUN_ID_SIZE+1]; /* master run id if this is a master */
|
||||
int slave_listening_port; /* As configured with: SLAVECONF listening-port */
|
||||
int slave_capa; /* Slave capabilities: SLAVE_CAPA_* bitwise OR. */
|
||||
multiState mstate; /* MULTI/EXEC state */
|
||||
int btype; /* Type of blocking op if REDIS_BLOCKED. */
|
||||
blockingState bpop; /* blocking state */
|
||||
@@ -658,12 +625,6 @@ typedef struct redisOpArray {
|
||||
|
||||
struct clusterState;
|
||||
|
||||
/* AIX defines hz to __hz, we don't use this define and in order to allow
|
||||
* Redis build on AIX we need to undef it. */
|
||||
#ifdef _AIX
|
||||
#undef hz
|
||||
#endif
|
||||
|
||||
struct redisServer {
|
||||
/* General */
|
||||
pid_t pid; /* Main process pid. */
|
||||
@@ -732,16 +693,12 @@ struct redisServer {
|
||||
long long slowlog_log_slower_than; /* SLOWLOG time limit (to get logged) */
|
||||
unsigned long slowlog_max_len; /* SLOWLOG max number of items logged */
|
||||
size_t resident_set_size; /* RSS sampled in serverCron(). */
|
||||
long long stat_net_input_bytes; /* Bytes read from network. */
|
||||
long long stat_net_output_bytes; /* Bytes written to network. */
|
||||
/* The following two are used to track instantaneous metrics, like
|
||||
* number of operations per second, network traffic. */
|
||||
struct {
|
||||
long long last_sample_time; /* Timestamp of last sample in ms */
|
||||
long long last_sample_count;/* Count in last sample */
|
||||
long long samples[REDIS_METRIC_SAMPLES];
|
||||
int idx;
|
||||
} inst_metric[REDIS_METRIC_COUNT];
|
||||
/* The following two are used to track instantaneous "load" in terms
|
||||
* of operations per second. */
|
||||
long long ops_sec_last_sample_time; /* Timestamp of last sample (in ms) */
|
||||
long long ops_sec_last_sample_ops; /* numcommands in last sample */
|
||||
long long ops_sec_samples[REDIS_OPS_SEC_SAMPLES];
|
||||
int ops_sec_idx;
|
||||
/* Configuration */
|
||||
int verbosity; /* Loglevel in redis.conf */
|
||||
int maxidletime; /* Client timeout in seconds */
|
||||
@@ -775,7 +732,6 @@ struct redisServer {
|
||||
int aof_rewrite_incremental_fsync;/* fsync incrementally while rewriting? */
|
||||
int aof_last_write_status; /* REDIS_OK or REDIS_ERR */
|
||||
int aof_last_write_errno; /* Valid if aof_last_write_status is ERR */
|
||||
int aof_load_truncated; /* Don't stop on unexpected AOF EOF. */
|
||||
/* AOF pipes used to communicate between parent and child during rewrite. */
|
||||
int aof_pipe_write_data_to_child;
|
||||
int aof_pipe_read_data_from_parent;
|
||||
@@ -799,11 +755,8 @@ struct redisServer {
|
||||
time_t lastbgsave_try; /* Unix time of last attempted bgsave */
|
||||
time_t rdb_save_time_last; /* Time used by last RDB save run. */
|
||||
time_t rdb_save_time_start; /* Current RDB save start time. */
|
||||
int rdb_child_type; /* Type of save by active child. */
|
||||
int lastbgsave_status; /* REDIS_OK or REDIS_ERR */
|
||||
int stop_writes_on_bgsave_err; /* Don't allow writes if can't BGSAVE */
|
||||
int rdb_pipe_write_result_to_parent; /* RDB pipes used to return the state */
|
||||
int rdb_pipe_read_result_from_child; /* of each slave in diskless SYNC. */
|
||||
/* Propagation of commands in AOF / replication */
|
||||
redisOpArray also_propagate; /* Additional command to propagate. */
|
||||
/* Logging */
|
||||
@@ -828,8 +781,6 @@ struct redisServer {
|
||||
int repl_min_slaves_to_write; /* Min number of slaves to write. */
|
||||
int repl_min_slaves_max_lag; /* Max lag of <count> slaves to write. */
|
||||
int repl_good_slaves_count; /* Number of slaves with lag <= max_lag. */
|
||||
int repl_diskless_sync; /* Send RDB to slaves sockets directly. */
|
||||
int repl_diskless_sync_delay; /* Delay to start a diskless repl BGSAVE. */
|
||||
/* Replication (slave) */
|
||||
char *masterauth; /* AUTH with this password with master */
|
||||
char *masterhost; /* Hostname of master */
|
||||
@@ -856,12 +807,12 @@ struct redisServer {
|
||||
/* Replication script cache. */
|
||||
dict *repl_scriptcache_dict; /* SHA1 all slaves are aware of. */
|
||||
list *repl_scriptcache_fifo; /* First in, first out LRU eviction. */
|
||||
unsigned int repl_scriptcache_size; /* Max number of elements. */
|
||||
int repl_scriptcache_size; /* Max number of elements. */
|
||||
/* Synchronous replication. */
|
||||
list *clients_waiting_acks; /* Clients waiting in WAIT command. */
|
||||
int get_ack_from_slaves; /* If true we send REPLCONF GETACK. */
|
||||
/* Limits */
|
||||
unsigned int maxclients; /* Max number of simultaneous clients */
|
||||
int maxclients; /* Max number of simultaneous clients */
|
||||
unsigned long long maxmemory; /* Max number of memory bytes to use */
|
||||
int maxmemory_policy; /* Policy for key eviction */
|
||||
int maxmemory_samples; /* Pricision of random sampling */
|
||||
@@ -898,8 +849,6 @@ struct redisServer {
|
||||
struct clusterState *cluster; /* State of the cluster */
|
||||
int cluster_migration_barrier; /* Cluster replicas migration barrier. */
|
||||
int cluster_slave_validity_factor; /* Slave max data age for failover. */
|
||||
int cluster_require_full_coverage; /* If true, put the cluster down if
|
||||
there is at least an uncovered slot. */
|
||||
/* Scripting */
|
||||
lua_State *lua; /* The Lua interpreter. We use just one for all clients */
|
||||
redisClient *lua_client; /* The "fake client" to query Redis from Lua */
|
||||
@@ -1043,10 +992,11 @@ void freeClient(redisClient *c);
|
||||
void freeClientAsync(redisClient *c);
|
||||
void resetClient(redisClient *c);
|
||||
void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
void addReply(redisClient *c, robj *obj);
|
||||
void *addDeferredMultiBulkLength(redisClient *c);
|
||||
void setDeferredMultiBulkLength(redisClient *c, void *node, long length);
|
||||
void addReplySds(redisClient *c, sds s);
|
||||
void processInputBuffer(redisClient *c);
|
||||
void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
@@ -1054,6 +1004,7 @@ void addReplyBulk(redisClient *c, robj *obj);
|
||||
void addReplyBulkCString(redisClient *c, char *s);
|
||||
void addReplyBulkCBuffer(redisClient *c, void *p, size_t len);
|
||||
void addReplyBulkLongLong(redisClient *c, long long ll);
|
||||
void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask);
|
||||
void addReply(redisClient *c, robj *obj);
|
||||
void addReplySds(redisClient *c, sds s);
|
||||
void addReplyError(redisClient *c, char *err);
|
||||
@@ -1142,7 +1093,7 @@ robj *tryObjectEncoding(robj *o);
|
||||
robj *getDecodedObject(robj *o);
|
||||
size_t stringObjectLen(robj *o);
|
||||
robj *createStringObjectFromLongLong(long long value);
|
||||
robj *createStringObjectFromLongDouble(long double value, int humanfriendly);
|
||||
robj *createStringObjectFromLongDouble(long double value);
|
||||
robj *createListObject(void);
|
||||
robj *createZiplistObject(void);
|
||||
robj *createSetObject(void);
|
||||
@@ -1172,7 +1123,7 @@ ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout);
|
||||
/* Replication */
|
||||
void replicationFeedSlaves(list *slaves, int dictid, robj **argv, int argc);
|
||||
void replicationFeedMonitors(redisClient *c, list *monitors, int dictid, robj **argv, int argc);
|
||||
void updateSlavesWaitingBgsave(int bgsaveerr, int type);
|
||||
void updateSlavesWaitingBgsave(int bgsaveerr);
|
||||
void replicationCron(void);
|
||||
void replicationHandleMasterDisconnection(void);
|
||||
void replicationCacheMaster(redisClient *c);
|
||||
@@ -1189,9 +1140,6 @@ void unblockClientWaitingReplicas(redisClient *c);
|
||||
int replicationCountAcksByOffset(long long offset);
|
||||
void replicationSendNewlineToMaster(void);
|
||||
long long replicationGetSlaveOffset(void);
|
||||
char *replicationGetSlaveName(redisClient *c);
|
||||
long long getPsyncInitialOffset(void);
|
||||
int replicationSetupSlaveForFullResync(redisClient *slave, long long offset);
|
||||
|
||||
/* Generic persistence functions */
|
||||
void startLoading(FILE *fp);
|
||||
@@ -1261,7 +1209,7 @@ void redisLog(int level, const char *fmt, ...);
|
||||
#endif
|
||||
void redisLogRaw(int level, const char *msg);
|
||||
void redisLogFromHandler(int level, const char *msg);
|
||||
void usage(void);
|
||||
void usage();
|
||||
void updateDictResizePolicy(void);
|
||||
int htNeedsResize(dict *dict);
|
||||
void oom(const char *msg);
|
||||
@@ -1321,7 +1269,7 @@ sds keyspaceEventsFlagsToString(int flags);
|
||||
/* Configuration */
|
||||
void loadServerConfig(char *filename, char *options);
|
||||
void appendServerSaveParams(time_t seconds, int changes);
|
||||
void resetServerSaveParams(void);
|
||||
void resetServerSaveParams();
|
||||
struct rewriteConfigState; /* Forward declaration to export API. */
|
||||
void rewriteConfigRewriteLine(struct rewriteConfigState *state, char *option, sds line, int force);
|
||||
int rewriteConfig(char *path);
|
||||
@@ -1387,7 +1335,6 @@ void blockClient(redisClient *c, int btype);
|
||||
void unblockClient(redisClient *c);
|
||||
void replyToBlockedClientTimedOut(redisClient *c);
|
||||
int getTimeoutFromObjectOrReply(redisClient *c, robj *object, mstime_t *timeout, int unit);
|
||||
void disconnectAllBlockedClients(void);
|
||||
|
||||
/* Git SHA1 */
|
||||
char *redisGitSHA1(void);
|
||||
|
||||
+229
-696
File diff suppressed because it is too large
Load Diff
@@ -55,8 +55,6 @@
|
||||
#include "config.h"
|
||||
#include "redis.h"
|
||||
|
||||
/* ------------------------- Buffer I/O implementation ----------------------- */
|
||||
|
||||
/* Returns 1 or 0 for success/failure. */
|
||||
static size_t rioBufferWrite(rio *r, const void *buf, size_t len) {
|
||||
r->io.buffer.ptr = sdscatlen(r->io.buffer.ptr,(char*)buf,len);
|
||||
@@ -78,33 +76,6 @@ static off_t rioBufferTell(rio *r) {
|
||||
return r->io.buffer.pos;
|
||||
}
|
||||
|
||||
/* Flushes any buffer to target device if applicable. Returns 1 on success
|
||||
* and 0 on failures. */
|
||||
static int rioBufferFlush(rio *r) {
|
||||
REDIS_NOTUSED(r);
|
||||
return 1; /* Nothing to do, our write just appends to the buffer. */
|
||||
}
|
||||
|
||||
static const rio rioBufferIO = {
|
||||
rioBufferRead,
|
||||
rioBufferWrite,
|
||||
rioBufferTell,
|
||||
rioBufferFlush,
|
||||
NULL, /* update_checksum */
|
||||
0, /* current checksum */
|
||||
0, /* bytes read or written */
|
||||
0, /* read/write chunk size */
|
||||
{ { NULL, 0 } } /* union for io-specific vars */
|
||||
};
|
||||
|
||||
void rioInitWithBuffer(rio *r, sds s) {
|
||||
*r = rioBufferIO;
|
||||
r->io.buffer.ptr = s;
|
||||
r->io.buffer.pos = 0;
|
||||
}
|
||||
|
||||
/* --------------------- Stdio file pointer implementation ------------------- */
|
||||
|
||||
/* Returns 1 or 0 for success/failure. */
|
||||
static size_t rioFileWrite(rio *r, const void *buf, size_t len) {
|
||||
size_t retval;
|
||||
@@ -132,17 +103,21 @@ static off_t rioFileTell(rio *r) {
|
||||
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 (fflush(r->io.file.fp) == 0) ? 1 : 0;
|
||||
}
|
||||
static const rio rioBufferIO = {
|
||||
rioBufferRead,
|
||||
rioBufferWrite,
|
||||
rioBufferTell,
|
||||
NULL, /* update_checksum */
|
||||
0, /* current checksum */
|
||||
0, /* bytes read or written */
|
||||
0, /* read/write chunk size */
|
||||
{ { NULL, 0 } } /* union for io-specific vars */
|
||||
};
|
||||
|
||||
static const rio rioFileIO = {
|
||||
rioFileRead,
|
||||
rioFileWrite,
|
||||
rioFileTell,
|
||||
rioFileFlush,
|
||||
NULL, /* update_checksum */
|
||||
0, /* current checksum */
|
||||
0, /* bytes read or written */
|
||||
@@ -157,133 +132,12 @@ void rioInitWithFile(rio *r, FILE *fp) {
|
||||
r->io.file.autosync = 0;
|
||||
}
|
||||
|
||||
/* ------------------- File descriptors set implementation ------------------- */
|
||||
|
||||
/* Returns 1 or 0 for success/failure.
|
||||
* The function returns success as long as we are able to correctly write
|
||||
* to at least one file descriptor.
|
||||
*
|
||||
* When buf is NULL adn len is 0, the function performs a flush operation
|
||||
* if there is some pending buffer, so this function is also used in order
|
||||
* to implement rioFdsetFlush(). */
|
||||
static size_t rioFdsetWrite(rio *r, const void *buf, size_t len) {
|
||||
ssize_t retval;
|
||||
int j;
|
||||
unsigned char *p = (unsigned char*) buf;
|
||||
int doflush = (buf == NULL && len == 0);
|
||||
|
||||
/* To start we always append to our buffer. If it gets larger than
|
||||
* a given size, we actually write to the sockets. */
|
||||
if (len) {
|
||||
r->io.fdset.buf = sdscatlen(r->io.fdset.buf,buf,len);
|
||||
len = 0; /* Prevent entering the while belove if we don't flush. */
|
||||
if (sdslen(r->io.fdset.buf) > REDIS_IOBUF_LEN) doflush = 1;
|
||||
}
|
||||
|
||||
if (doflush) {
|
||||
p = (unsigned char*) r->io.fdset.buf;
|
||||
len = sdslen(r->io.fdset.buf);
|
||||
}
|
||||
|
||||
/* Write in little chunchs so that when there are big writes we
|
||||
* parallelize while the kernel is sending data in background to
|
||||
* the TCP socket. */
|
||||
while(len) {
|
||||
size_t count = len < 1024 ? len : 1024;
|
||||
int broken = 0;
|
||||
for (j = 0; j < r->io.fdset.numfds; j++) {
|
||||
if (r->io.fdset.state[j] != 0) {
|
||||
/* Skip FDs alraedy in error. */
|
||||
broken++;
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Make sure to write 'count' bytes to the socket regardless
|
||||
* of short writes. */
|
||||
size_t nwritten = 0;
|
||||
while(nwritten != count) {
|
||||
retval = write(r->io.fdset.fds[j],p+nwritten,count-nwritten);
|
||||
if (retval <= 0) {
|
||||
/* With blocking sockets, which is the sole user of this
|
||||
* rio target, EWOULDBLOCK is returned only because of
|
||||
* the SO_SNDTIMEO socket option, so we translate the error
|
||||
* into one more recognizable by the user. */
|
||||
if (retval == -1 && errno == EWOULDBLOCK) errno = ETIMEDOUT;
|
||||
break;
|
||||
}
|
||||
nwritten += retval;
|
||||
}
|
||||
|
||||
if (nwritten != count) {
|
||||
/* Mark this FD as broken. */
|
||||
r->io.fdset.state[j] = errno;
|
||||
if (r->io.fdset.state[j] == 0) r->io.fdset.state[j] = EIO;
|
||||
}
|
||||
}
|
||||
if (broken == r->io.fdset.numfds) return 0; /* All the FDs in error. */
|
||||
p += count;
|
||||
len -= count;
|
||||
r->io.fdset.pos += count;
|
||||
}
|
||||
|
||||
if (doflush) sdsclear(r->io.fdset.buf);
|
||||
return 1;
|
||||
void rioInitWithBuffer(rio *r, sds s) {
|
||||
*r = rioBufferIO;
|
||||
r->io.buffer.ptr = s;
|
||||
r->io.buffer.pos = 0;
|
||||
}
|
||||
|
||||
/* Returns 1 or 0 for success/failure. */
|
||||
static size_t rioFdsetRead(rio *r, void *buf, size_t len) {
|
||||
REDIS_NOTUSED(r);
|
||||
REDIS_NOTUSED(buf);
|
||||
REDIS_NOTUSED(len);
|
||||
return 0; /* Error, this target does not support reading. */
|
||||
}
|
||||
|
||||
/* Returns read/write position in file. */
|
||||
static off_t rioFdsetTell(rio *r) {
|
||||
return r->io.fdset.pos;
|
||||
}
|
||||
|
||||
/* Flushes any buffer to target device if applicable. Returns 1 on success
|
||||
* and 0 on failures. */
|
||||
static int rioFdsetFlush(rio *r) {
|
||||
/* Our flush is implemented by the write method, that recognizes a
|
||||
* buffer set to NULL with a count of zero as a flush request. */
|
||||
return rioFdsetWrite(r,NULL,0);
|
||||
}
|
||||
|
||||
static const rio rioFdsetIO = {
|
||||
rioFdsetRead,
|
||||
rioFdsetWrite,
|
||||
rioFdsetTell,
|
||||
rioFdsetFlush,
|
||||
NULL, /* update_checksum */
|
||||
0, /* current checksum */
|
||||
0, /* bytes read or written */
|
||||
0, /* read/write chunk size */
|
||||
{ { NULL, 0 } } /* union for io-specific vars */
|
||||
};
|
||||
|
||||
void rioInitWithFdset(rio *r, int *fds, int numfds) {
|
||||
int j;
|
||||
|
||||
*r = rioFdsetIO;
|
||||
r->io.fdset.fds = zmalloc(sizeof(int)*numfds);
|
||||
r->io.fdset.state = zmalloc(sizeof(int)*numfds);
|
||||
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;
|
||||
r->io.fdset.pos = 0;
|
||||
r->io.fdset.buf = sdsempty();
|
||||
}
|
||||
|
||||
void rioFreeFdset(rio *r) {
|
||||
zfree(r->io.fdset.fds);
|
||||
zfree(r->io.fdset.state);
|
||||
sdsfree(r->io.fdset.buf);
|
||||
}
|
||||
|
||||
/* ---------------------------- Generic functions ---------------------------- */
|
||||
|
||||
/* 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) {
|
||||
@@ -303,8 +157,7 @@ void rioSetAutoSync(rio *r, off_t bytes) {
|
||||
r->io.file.autosync = bytes;
|
||||
}
|
||||
|
||||
/* --------------------------- Higher level interface --------------------------
|
||||
*
|
||||
/* ------------------------------ Higher level interface ---------------------------
|
||||
* The following higher level functions use lower level rio.c functions to help
|
||||
* generating the Redis protocol for the Append Only File. */
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ struct _rio {
|
||||
size_t (*read)(struct _rio *, void *buf, size_t len);
|
||||
size_t (*write)(struct _rio *, const void *buf, size_t len);
|
||||
off_t (*tell)(struct _rio *);
|
||||
int (*flush)(struct _rio *);
|
||||
/* The update_cksum method if not NULL is used to compute the checksum of
|
||||
* all the data that was read or written so far. The method should be
|
||||
* designed so that can be called with the current checksum, and the buf
|
||||
@@ -62,25 +61,15 @@ struct _rio {
|
||||
|
||||
/* Backend-specific vars. */
|
||||
union {
|
||||
/* In-memory buffer target. */
|
||||
struct {
|
||||
sds ptr;
|
||||
off_t pos;
|
||||
} buffer;
|
||||
/* Stdio file pointer target. */
|
||||
struct {
|
||||
FILE *fp;
|
||||
off_t buffered; /* Bytes written since last fsync. */
|
||||
off_t autosync; /* fsync after 'autosync' bytes written. */
|
||||
} file;
|
||||
/* Multiple FDs target (used to write to N sockets). */
|
||||
struct {
|
||||
int *fds; /* File descriptors. */
|
||||
int *state; /* Error state of each fd. 0 (if ok) or errno. */
|
||||
int numfds;
|
||||
off_t pos;
|
||||
sds buf;
|
||||
} fdset;
|
||||
} io;
|
||||
};
|
||||
|
||||
@@ -120,13 +109,8 @@ static inline off_t rioTell(rio *r) {
|
||||
return r->tell(r);
|
||||
}
|
||||
|
||||
static inline int rioFlush(rio *r) {
|
||||
return r->flush(r);
|
||||
}
|
||||
|
||||
void rioInitWithFile(rio *r, FILE *fp);
|
||||
void rioInitWithBuffer(rio *r, sds s);
|
||||
void rioInitWithFdset(rio *r, int *fds, int numfds);
|
||||
|
||||
size_t rioWriteBulkCount(rio *r, char prefix, int count);
|
||||
size_t rioWriteBulkString(rio *r, const char *buf, size_t len);
|
||||
|
||||
+12
-56
@@ -30,7 +30,6 @@
|
||||
#include "redis.h"
|
||||
#include "sha1.h"
|
||||
#include "rand.h"
|
||||
#include "cluster.h"
|
||||
|
||||
#include <lua.h>
|
||||
#include <lauxlib.h>
|
||||
@@ -213,33 +212,19 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
static robj **argv = NULL;
|
||||
static int argv_size = 0;
|
||||
static robj *cached_objects[LUA_CMD_OBJCACHE_SIZE];
|
||||
static size_t cached_objects_len[LUA_CMD_OBJCACHE_SIZE];
|
||||
static int inuse = 0; /* Recursive calls detection. */
|
||||
|
||||
/* By using Lua debug hooks it is possible to trigger a recursive call
|
||||
* to luaRedisGenericCommand(), which normally should never happen.
|
||||
* To make this function reentrant is futile and makes it slower, but
|
||||
* we should at least detect such a misuse, and abort. */
|
||||
if (inuse) {
|
||||
char *recursion_warning =
|
||||
"luaRedisGenericCommand() recursive call detected. "
|
||||
"Are you doing funny stuff with Lua debug hooks?";
|
||||
redisLog(REDIS_WARNING,"%s",recursion_warning);
|
||||
luaPushError(lua,recursion_warning);
|
||||
return 1;
|
||||
}
|
||||
inuse++;
|
||||
static int cached_objects_len[LUA_CMD_OBJCACHE_SIZE];
|
||||
|
||||
/* Require at least one argument */
|
||||
if (argc == 0) {
|
||||
luaPushError(lua,
|
||||
"Please specify at least one argument for redis.call()");
|
||||
inuse--;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Build the arguments vector */
|
||||
if (argv_size < argc) {
|
||||
if (!argv) {
|
||||
argv = zmalloc(sizeof(robj*)*argc);
|
||||
} else if (argv_size < argc) {
|
||||
argv = zrealloc(argv,sizeof(robj*)*argc);
|
||||
argv_size = argc;
|
||||
}
|
||||
@@ -289,7 +274,6 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
}
|
||||
luaPushError(lua,
|
||||
"Lua redis() command arguments must be strings or integers");
|
||||
inuse--;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -309,7 +293,6 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
luaPushError(lua,"Unknown Redis command called from Lua script");
|
||||
goto cleanup;
|
||||
}
|
||||
c->cmd = cmd;
|
||||
|
||||
/* There are commands that are not allowed inside scripts. */
|
||||
if (cmd->flags & REDIS_CMD_NOSCRIPT) {
|
||||
@@ -356,24 +339,8 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
if (cmd->flags & REDIS_CMD_RANDOM) server.lua_random_dirty = 1;
|
||||
if (cmd->flags & REDIS_CMD_WRITE) server.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. */
|
||||
if (server.cluster_enabled && !(server.lua_caller->flags & REDIS_MASTER)) {
|
||||
/* Duplicate relevant flags in the lua client. */
|
||||
c->flags &= ~(REDIS_READONLY|REDIS_ASKING);
|
||||
c->flags |= server.lua_caller->flags & (REDIS_READONLY|REDIS_ASKING);
|
||||
if (getNodeByQuery(c,c->cmd,c->argv,c->argc,NULL,NULL) !=
|
||||
server.cluster->myself)
|
||||
{
|
||||
luaPushError(lua,
|
||||
"Lua script attempted to access a non local key in a "
|
||||
"cluster node");
|
||||
goto cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* Run the command */
|
||||
c->cmd = cmd;
|
||||
call(c,REDIS_CALL_SLOWLOG | REDIS_CALL_STATS);
|
||||
|
||||
/* Convert the result of the Redis command into a suitable Lua type.
|
||||
@@ -435,7 +402,6 @@ cleanup:
|
||||
if (c->argv != argv) {
|
||||
zfree(c->argv);
|
||||
argv = NULL;
|
||||
argv_size = 0;
|
||||
}
|
||||
|
||||
if (raise_error) {
|
||||
@@ -444,10 +410,8 @@ cleanup:
|
||||
* return the plain error. */
|
||||
lua_pushstring(lua,"err");
|
||||
lua_gettable(lua,-2);
|
||||
inuse--;
|
||||
return lua_error(lua);
|
||||
}
|
||||
inuse--;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -574,7 +538,6 @@ void luaLoadLib(lua_State *lua, const char *libname, lua_CFunction luafunc) {
|
||||
LUALIB_API int (luaopen_cjson) (lua_State *L);
|
||||
LUALIB_API int (luaopen_struct) (lua_State *L);
|
||||
LUALIB_API int (luaopen_cmsgpack) (lua_State *L);
|
||||
LUALIB_API int (luaopen_bit) (lua_State *L);
|
||||
|
||||
void luaLoadLibraries(lua_State *lua) {
|
||||
luaLoadLib(lua, "", luaopen_base);
|
||||
@@ -585,7 +548,6 @@ void luaLoadLibraries(lua_State *lua) {
|
||||
luaLoadLib(lua, "cjson", luaopen_cjson);
|
||||
luaLoadLib(lua, "struct", luaopen_struct);
|
||||
luaLoadLib(lua, "cmsgpack", luaopen_cmsgpack);
|
||||
luaLoadLib(lua, "bit", luaopen_bit);
|
||||
|
||||
#if 0 /* Stuff that we don't load currently, for sandboxing concerns. */
|
||||
luaLoadLib(lua, LUA_LOADLIBNAME, luaopen_package);
|
||||
@@ -612,12 +574,11 @@ void scriptingEnableGlobalsProtection(lua_State *lua) {
|
||||
|
||||
/* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html.
|
||||
* Modified to be adapted to Redis. */
|
||||
s[j++]="local dbg=debug\n";
|
||||
s[j++]="local mt = {}\n";
|
||||
s[j++]="setmetatable(_G, mt)\n";
|
||||
s[j++]="mt.__newindex = function (t, n, v)\n";
|
||||
s[j++]=" if dbg.getinfo(2) then\n";
|
||||
s[j++]=" local w = dbg.getinfo(2, \"S\").what\n";
|
||||
s[j++]=" if debug.getinfo(2) then\n";
|
||||
s[j++]=" local w = debug.getinfo(2, \"S\").what\n";
|
||||
s[j++]=" if w ~= \"main\" and w ~= \"C\" then\n";
|
||||
s[j++]=" error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n";
|
||||
s[j++]=" end\n";
|
||||
@@ -625,12 +586,11 @@ void scriptingEnableGlobalsProtection(lua_State *lua) {
|
||||
s[j++]=" rawset(t, n, v)\n";
|
||||
s[j++]="end\n";
|
||||
s[j++]="mt.__index = function (t, n)\n";
|
||||
s[j++]=" if dbg.getinfo(2) and dbg.getinfo(2, \"S\").what ~= \"C\" then\n";
|
||||
s[j++]=" if debug.getinfo(2) and debug.getinfo(2, \"S\").what ~= \"C\" then\n";
|
||||
s[j++]=" error(\"Script attempted to access unexisting global variable '\"..tostring(n)..\"'\", 2)\n";
|
||||
s[j++]=" end\n";
|
||||
s[j++]=" return rawget(t, n)\n";
|
||||
s[j++]="end\n";
|
||||
s[j++]="debug = nil\n";
|
||||
s[j++]=NULL;
|
||||
|
||||
for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j]));
|
||||
@@ -734,11 +694,10 @@ void scriptingInit(void) {
|
||||
* information about the caller, that's what makes sense from the point
|
||||
* of view of the user debugging a script. */
|
||||
{
|
||||
char *errh_func = "local dbg = debug\n"
|
||||
"function __redis__err__handler(err)\n"
|
||||
" local i = dbg.getinfo(2,'nSl')\n"
|
||||
char *errh_func = "function __redis__err__handler(err)\n"
|
||||
" local i = debug.getinfo(2,'nSl')\n"
|
||||
" if i and i.what == 'C' then\n"
|
||||
" i = dbg.getinfo(3,'nSl')\n"
|
||||
" i = debug.getinfo(3,'nSl')\n"
|
||||
" end\n"
|
||||
" if i then\n"
|
||||
" return i.source .. ':' .. i.currentline .. ': ' .. err\n"
|
||||
@@ -759,7 +718,7 @@ void scriptingInit(void) {
|
||||
server.lua_client->flags |= REDIS_LUA_CLIENT;
|
||||
}
|
||||
|
||||
/* Lua beginners often don't use "local", this is likely to introduce
|
||||
/* Lua beginners ofter 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);
|
||||
@@ -951,9 +910,6 @@ void evalGenericCommand(redisClient *c, int evalsha) {
|
||||
if (numkeys > (c->argc - 3)) {
|
||||
addReplyError(c,"Number of keys can't be greater than number of args");
|
||||
return;
|
||||
} else if (numkeys < 0) {
|
||||
addReplyError(c,"Number of keys can't be negative");
|
||||
return;
|
||||
}
|
||||
|
||||
/* We obtain the script SHA1, then check if this function is already
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
* The string is always null-termined (all the sds strings are, always) so
|
||||
* even if you create an sds string with:
|
||||
*
|
||||
* mystring = sdsnewlen("abc",3);
|
||||
* mystring = sdsnewlen("abc",3");
|
||||
*
|
||||
* You can print the string with printf() as there is an implicit \0 at the
|
||||
* end of the string. However the string is binary safe and can contain
|
||||
@@ -71,7 +71,7 @@ sds sdsempty(void) {
|
||||
return sdsnewlen("",0);
|
||||
}
|
||||
|
||||
/* Create a new sds string starting from a null terminated C string. */
|
||||
/* Create a new sds string starting from a null termined C string. */
|
||||
sds sdsnew(const char *init) {
|
||||
size_t initlen = (init == NULL) ? 0 : strlen(init);
|
||||
return sdsnewlen(init, initlen);
|
||||
@@ -109,7 +109,7 @@ void sdsupdatelen(sds s) {
|
||||
sh->len = reallen;
|
||||
}
|
||||
|
||||
/* Modify an sds string in-place to make it empty (zero length).
|
||||
/* Modify an sds string on-place to make it empty (zero length).
|
||||
* However all the existing buffer is not discarded but set as free space
|
||||
* so that next append operations will not require allocations up to the
|
||||
* number of bytes previously available. */
|
||||
@@ -200,12 +200,10 @@ size_t sdsAllocSize(sds s) {
|
||||
void sdsIncrLen(sds s, int incr) {
|
||||
struct sdshdr *sh = (void*) (s-(sizeof(struct sdshdr)));
|
||||
|
||||
if (incr >= 0)
|
||||
assert(sh->free >= (unsigned int)incr);
|
||||
else
|
||||
assert(sh->len >= (unsigned int)(-incr));
|
||||
assert(sh->free >= incr);
|
||||
sh->len += incr;
|
||||
sh->free -= incr;
|
||||
assert(sh->free >= 0);
|
||||
s[sh->len] = '\0';
|
||||
}
|
||||
|
||||
@@ -295,7 +293,7 @@ sds sdscpy(sds s, const char *t) {
|
||||
* conversion. 's' must point to a string with room for at least
|
||||
* SDS_LLSTR_SIZE bytes.
|
||||
*
|
||||
* The function returns the length of the null-terminated string
|
||||
* The function returns the lenght of the null-terminated string
|
||||
* representation stored at 's'. */
|
||||
#define SDS_LLSTR_SIZE 21
|
||||
int sdsll2str(char *s, long long value) {
|
||||
@@ -369,7 +367,7 @@ sds sdsfromlonglong(long long value) {
|
||||
return sdsnewlen(buf,len);
|
||||
}
|
||||
|
||||
/* Like sdscatprintf() but gets va_list instead of being variadic. */
|
||||
/* Like sdscatpritf() but gets va_list instead of being variadic. */
|
||||
sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
|
||||
va_list cpy;
|
||||
char staticbuf[1024], *buf = staticbuf, *t;
|
||||
@@ -390,7 +388,6 @@ sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
|
||||
buf[buflen-2] = '\0';
|
||||
va_copy(cpy,ap);
|
||||
vsnprintf(buf, buflen, fmt, cpy);
|
||||
va_end(cpy);
|
||||
if (buf[buflen-2] != '\0') {
|
||||
if (buf != staticbuf) zfree(buf);
|
||||
buflen *= 2;
|
||||
@@ -415,7 +412,7 @@ sds sdscatvprintf(sds s, const char *fmt, va_list ap) {
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* s = sdsnew("Sum is: ");
|
||||
* s = sdsempty("Sum is: ");
|
||||
* s = sdscatprintf(s,"%d+%d = %d",a,b,a+b).
|
||||
*
|
||||
* Often you need to create a string from scratch with the printf-alike
|
||||
@@ -460,7 +457,7 @@ sds sdscatfmt(sds s, char const *fmt, ...) {
|
||||
i = initlen; /* Position of the next byte to write to dest str. */
|
||||
while(*f) {
|
||||
char next, *str;
|
||||
unsigned int l;
|
||||
int l;
|
||||
long long num;
|
||||
unsigned long long unum;
|
||||
|
||||
@@ -557,7 +554,7 @@ sds sdscatfmt(sds s, char const *fmt, ...) {
|
||||
* Example:
|
||||
*
|
||||
* s = sdsnew("AA...AA.a.aa.aHelloWorld :::");
|
||||
* s = sdstrim(s,"Aa. :");
|
||||
* s = sdstrim(s,"A. :");
|
||||
* printf("%s\n", s);
|
||||
*
|
||||
* Output will be just "Hello World".
|
||||
@@ -643,8 +640,8 @@ void sdstoupper(sds s) {
|
||||
*
|
||||
* Return value:
|
||||
*
|
||||
* positive if s1 > s2.
|
||||
* negative if s1 < s2.
|
||||
* 1 if s1 > s2.
|
||||
* -1 if s1 < s2.
|
||||
* 0 if s1 and s2 are exactly the same binary string.
|
||||
*
|
||||
* If two strings share exactly the same prefix, but one of the two has
|
||||
@@ -1083,7 +1080,6 @@ int main(void) {
|
||||
int oldfree;
|
||||
|
||||
sdsfree(x);
|
||||
sdsfree(y);
|
||||
x = sdsnew("0");
|
||||
sh = (void*) (x-(sizeof(struct sdshdr)));
|
||||
test_cond("sdsnew() free/len buffers", sh->len == 1 && sh->free == 0);
|
||||
@@ -1096,8 +1092,6 @@ int main(void) {
|
||||
test_cond("sdsIncrLen() -- content", x[0] == '0' && x[1] == '1');
|
||||
test_cond("sdsIncrLen() -- len", sh->len == 2);
|
||||
test_cond("sdsIncrLen() -- free", sh->free == oldfree-1);
|
||||
|
||||
sdsfree(x);
|
||||
}
|
||||
}
|
||||
test_report()
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
typedef char *sds;
|
||||
|
||||
struct sdshdr {
|
||||
unsigned int len;
|
||||
unsigned int free;
|
||||
int len;
|
||||
int free;
|
||||
char buf[];
|
||||
};
|
||||
|
||||
|
||||
+26
-134
@@ -159,7 +159,7 @@ typedef struct sentinelRedisInstance {
|
||||
/* Master specific. */
|
||||
dict *sentinels; /* Other sentinels monitoring the same master. */
|
||||
dict *slaves; /* Slaves for this master instance. */
|
||||
unsigned int quorum;/* Number of sentinels that need to agree on failure. */
|
||||
int quorum; /* Number of sentinels that need to agree on failure. */
|
||||
int parallel_syncs; /* How many slaves to reconfigure at same time. */
|
||||
char *auth_pass; /* Password to use for AUTH against master & slaves. */
|
||||
|
||||
@@ -203,10 +203,6 @@ struct sentinelState {
|
||||
mstime_t tilt_start_time; /* When TITL started. */
|
||||
mstime_t previous_time; /* Last time we ran the time handler. */
|
||||
list *scripts_queue; /* Queue of user scripts to execute. */
|
||||
char *announce_ip; /* IP addr that is gossiped to other sentinels if
|
||||
not NULL. */
|
||||
int announce_port; /* Port that is gossiped to other sentinels if
|
||||
non zero. */
|
||||
} sentinel;
|
||||
|
||||
/* A script execution job. */
|
||||
@@ -349,7 +345,6 @@ int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2);
|
||||
void releaseSentinelRedisInstance(sentinelRedisInstance *ri);
|
||||
|
||||
void dictInstancesValDestructor (void *privdata, void *obj) {
|
||||
REDIS_NOTUSED(privdata);
|
||||
releaseSentinelRedisInstance(obj);
|
||||
}
|
||||
|
||||
@@ -397,7 +392,6 @@ struct redisCommand sentinelcmds[] = {
|
||||
{"publish",sentinelPublishCommand,3,"",0,NULL,0,0,0,0,0},
|
||||
{"info",sentinelInfoCommand,-1,"",0,NULL,0,0,0,0,0},
|
||||
{"role",sentinelRoleCommand,1,"l",0,NULL,0,0,0,0,0},
|
||||
{"client",clientCommand,-2,"rs",0,NULL,0,0,0,0,0},
|
||||
{"shutdown",shutdownCommand,-1,"",0,NULL,0,0,0,0,0}
|
||||
};
|
||||
|
||||
@@ -409,7 +403,7 @@ void initSentinelConfig(void) {
|
||||
|
||||
/* Perform the Sentinel mode initialization. */
|
||||
void initSentinel(void) {
|
||||
unsigned int j;
|
||||
int j;
|
||||
|
||||
/* Remove usual Redis commands from the command table, then just add
|
||||
* the SENTINEL command. */
|
||||
@@ -430,8 +424,6 @@ void initSentinel(void) {
|
||||
sentinel.previous_time = mstime();
|
||||
sentinel.running_scripts = 0;
|
||||
sentinel.scripts_queue = listCreate();
|
||||
sentinel.announce_ip = NULL;
|
||||
sentinel.announce_port = 0;
|
||||
}
|
||||
|
||||
/* This function gets called when the server is in Sentinel mode, started,
|
||||
@@ -463,19 +455,19 @@ void sentinelIsRunning(void) {
|
||||
* EINVAL: Invalid port number.
|
||||
*/
|
||||
sentinelAddr *createSentinelAddr(char *hostname, int port) {
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
char buf[32];
|
||||
sentinelAddr *sa;
|
||||
|
||||
if (port <= 0 || port > 65535) {
|
||||
errno = EINVAL;
|
||||
return NULL;
|
||||
}
|
||||
if (anetResolve(NULL,hostname,ip,sizeof(ip)) == ANET_ERR) {
|
||||
if (anetResolve(NULL,hostname,buf,sizeof(buf)) == ANET_ERR) {
|
||||
errno = ENOENT;
|
||||
return NULL;
|
||||
}
|
||||
sa = zmalloc(sizeof(*sa));
|
||||
sa->ip = sdsnew(ip);
|
||||
sa->ip = sdsnew(buf);
|
||||
sa->port = port;
|
||||
return sa;
|
||||
}
|
||||
@@ -923,7 +915,6 @@ sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *
|
||||
else if (flags & SRI_SENTINEL) table = master->sentinels;
|
||||
sdsname = sdsnew(name);
|
||||
if (dictFind(table,sdsname)) {
|
||||
releaseSentinelAddr(addr);
|
||||
sdsfree(sdsname);
|
||||
errno = EBUSY;
|
||||
return NULL;
|
||||
@@ -1157,9 +1148,7 @@ void sentinelDelFlagsToDictOfRedisInstances(dict *instances, int flags) {
|
||||
* 1) Remove all slaves.
|
||||
* 2) Remove all sentinels.
|
||||
* 3) Remove most of the flags resulting from runtime operations.
|
||||
* 4) Reset timers to their default value. For example after a reset it will be
|
||||
* possible to failover again the same master ASAP, without waiting the
|
||||
* failover timeout delay.
|
||||
* 4) Reset timers to their default value.
|
||||
* 5) In the process of doing this undo the failover if in progress.
|
||||
* 6) Disconnect the connections with the master (will reconnect automatically).
|
||||
*/
|
||||
@@ -1182,7 +1171,7 @@ void sentinelResetMaster(sentinelRedisInstance *ri, int flags) {
|
||||
}
|
||||
ri->failover_state = SENTINEL_FAILOVER_STATE_NONE;
|
||||
ri->failover_state_change_time = 0;
|
||||
ri->failover_start_time = 0; /* We can failover again ASAP. */
|
||||
ri->failover_start_time = 0;
|
||||
ri->promoted_slave = NULL;
|
||||
sdsfree(ri->runid);
|
||||
sdsfree(ri->slave_master_host);
|
||||
@@ -1272,7 +1261,10 @@ int sentinelResetMasterAndChangeAddress(sentinelRedisInstance *master, char *ip,
|
||||
slave = createSentinelRedisInstance(NULL,SRI_SLAVE,slaves[j]->ip,
|
||||
slaves[j]->port, master->quorum, master);
|
||||
releaseSentinelAddr(slaves[j]);
|
||||
if (slave) sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@");
|
||||
if (slave) {
|
||||
sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@");
|
||||
sentinelFlushConfig();
|
||||
}
|
||||
}
|
||||
zfree(slaves);
|
||||
|
||||
@@ -1432,13 +1424,6 @@ char *sentinelHandleConfiguration(char **argv, int argc) {
|
||||
return "Wrong hostname or port for sentinel.";
|
||||
}
|
||||
if (argc == 5) si->runid = sdsnew(argv[4]);
|
||||
} else if (!strcasecmp(argv[0],"announce-ip") && argc == 2) {
|
||||
/* announce-ip <ip-address> */
|
||||
if (strlen(argv[1]))
|
||||
sentinel.announce_ip = sdsnew(argv[1]);
|
||||
} else if (!strcasecmp(argv[0],"announce-port") && argc == 2) {
|
||||
/* announce-port <port> */
|
||||
sentinel.announce_port = atoi(argv[1]);
|
||||
} else {
|
||||
return "Unrecognized sentinel configuration statement.";
|
||||
}
|
||||
@@ -1546,7 +1531,7 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
slave_addr = master->addr;
|
||||
line = sdscatprintf(sdsempty(),
|
||||
"sentinel known-slave %s %s %d",
|
||||
master->name, slave_addr->ip, slave_addr->port);
|
||||
master->name, ri->addr->ip, ri->addr->port);
|
||||
rewriteConfigRewriteLine(state,"sentinel",line,1);
|
||||
}
|
||||
dictReleaseIterator(di2);
|
||||
@@ -1570,20 +1555,6 @@ void rewriteConfigSentinelOption(struct rewriteConfigState *state) {
|
||||
"sentinel current-epoch %llu", (unsigned long long) sentinel.current_epoch);
|
||||
rewriteConfigRewriteLine(state,"sentinel",line,1);
|
||||
|
||||
/* sentinel announce-ip. */
|
||||
if (sentinel.announce_ip) {
|
||||
line = sdsnew("sentinel announce-ip ");
|
||||
line = sdscatrepr(line, sentinel.announce_ip, sdslen(sentinel.announce_ip));
|
||||
rewriteConfigRewriteLine(state,"sentinel",line,1);
|
||||
}
|
||||
|
||||
/* sentinel announce-port. */
|
||||
if (sentinel.announce_port) {
|
||||
line = sdscatprintf(sdsempty(),"sentinel announce-port %d",
|
||||
sentinel.announce_port);
|
||||
rewriteConfigRewriteLine(state,"sentinel",line,1);
|
||||
}
|
||||
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
|
||||
@@ -1663,7 +1634,6 @@ void sentinelLinkEstablishedCallback(const redisAsyncContext *c, int status) {
|
||||
}
|
||||
|
||||
void sentinelDisconnectCallback(const redisAsyncContext *c, int status) {
|
||||
REDIS_NOTUSED(status);
|
||||
sentinelDisconnectInstanceFromContext(c);
|
||||
}
|
||||
|
||||
@@ -1844,7 +1814,6 @@ void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) {
|
||||
atoi(port), ri->quorum, ri)) != NULL)
|
||||
{
|
||||
sentinelEvent(REDIS_NOTICE,"+slave",slave,"%@");
|
||||
sentinelFlushConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2029,7 +1998,6 @@ void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) {
|
||||
void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = c->data;
|
||||
redisReply *r;
|
||||
REDIS_NOTUSED(privdata);
|
||||
|
||||
if (ri) ri->pending_commands--;
|
||||
if (!reply || !ri) return;
|
||||
@@ -2044,8 +2012,6 @@ void sentinelInfoReplyCallback(redisAsyncContext *c, void *reply, void *privdata
|
||||
* value of the command but its effects directly. */
|
||||
void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = c->data;
|
||||
REDIS_NOTUSED(reply);
|
||||
REDIS_NOTUSED(privdata);
|
||||
|
||||
if (ri) ri->pending_commands--;
|
||||
}
|
||||
@@ -2053,7 +2019,6 @@ void sentinelDiscardReplyCallback(redisAsyncContext *c, void *reply, void *privd
|
||||
void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = c->data;
|
||||
redisReply *r;
|
||||
REDIS_NOTUSED(privdata);
|
||||
|
||||
if (ri) ri->pending_commands--;
|
||||
if (!reply || !ri) return;
|
||||
@@ -2092,7 +2057,6 @@ void sentinelPingReplyCallback(redisAsyncContext *c, void *reply, void *privdata
|
||||
void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = c->data;
|
||||
redisReply *r;
|
||||
REDIS_NOTUSED(privdata);
|
||||
|
||||
if (ri) ri->pending_commands--;
|
||||
if (!reply || !ri) return;
|
||||
@@ -2108,7 +2072,7 @@ void sentinelPublishReplyCallback(redisAsyncContext *c, void *reply, void *privd
|
||||
* or sent directly to this sentinel via the (fake) PUBLISH command of Sentinel.
|
||||
*
|
||||
* If the master name specified in the message is not known, the message is
|
||||
* discarded. */
|
||||
* discareded. */
|
||||
void sentinelProcessHelloMessage(char *hello, int hello_len) {
|
||||
/* Format is composed of 8 tokens:
|
||||
* 0=ip,1=port,2=runid,3=current_epoch,4=master_name,
|
||||
@@ -2202,7 +2166,6 @@ cleanup:
|
||||
void sentinelReceiveHelloMessages(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = c->data;
|
||||
redisReply *r;
|
||||
REDIS_NOTUSED(privdata);
|
||||
|
||||
if (!reply || !ri) return;
|
||||
r = reply;
|
||||
@@ -2242,30 +2205,18 @@ int sentinelSendHello(sentinelRedisInstance *ri) {
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
char payload[REDIS_IP_STR_LEN+1024];
|
||||
int retval;
|
||||
char *announce_ip;
|
||||
int announce_port;
|
||||
sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ? ri : ri->master;
|
||||
sentinelAddr *master_addr = sentinelGetCurrentMasterAddress(master);
|
||||
|
||||
/* Try to obtain our own IP address. */
|
||||
if (anetSockName(ri->cc->c.fd,ip,sizeof(ip),NULL) == -1) return REDIS_ERR;
|
||||
if (ri->flags & SRI_DISCONNECTED) return REDIS_ERR;
|
||||
|
||||
/* Use the specified announce address if specified, otherwise try to
|
||||
* obtain our own IP address. */
|
||||
if (sentinel.announce_ip) {
|
||||
announce_ip = sentinel.announce_ip;
|
||||
} else {
|
||||
if (anetSockName(ri->cc->c.fd,ip,sizeof(ip),NULL) == -1)
|
||||
return REDIS_ERR;
|
||||
announce_ip = ip;
|
||||
}
|
||||
announce_port = sentinel.announce_port ?
|
||||
sentinel.announce_port : server.port;
|
||||
|
||||
/* Format and send the Hello message. */
|
||||
snprintf(payload,sizeof(payload),
|
||||
"%s,%d,%s,%llu," /* Info about this sentinel. */
|
||||
"%s,%s,%d,%llu", /* Info about current master. */
|
||||
announce_ip, announce_port, server.runid,
|
||||
ip, server.port, server.runid,
|
||||
(unsigned long long) sentinel.current_epoch,
|
||||
/* --- */
|
||||
master->name,master_addr->ip,master_addr->port,
|
||||
@@ -2608,7 +2559,7 @@ sentinelRedisInstance *sentinelGetMasterByNameOrReplyError(redisClient *c,
|
||||
{
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
ri = dictFetchValue(sentinel.masters,name->ptr);
|
||||
ri = dictFetchValue(sentinel.masters,c->argv[2]->ptr);
|
||||
if (!ri) {
|
||||
addReplyError(c,"No such master with that name");
|
||||
return NULL;
|
||||
@@ -2616,31 +2567,6 @@ sentinelRedisInstance *sentinelGetMasterByNameOrReplyError(redisClient *c,
|
||||
return ri;
|
||||
}
|
||||
|
||||
#define SENTINEL_ISQR_OK 0
|
||||
#define SENTINEL_ISQR_NOQUORUM (1<<0)
|
||||
#define SENTINEL_ISQR_NOAUTH (1<<1)
|
||||
int sentinelIsQuorumReachable(sentinelRedisInstance *master, int *usableptr) {
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
int usable = 1; /* Number of usable Sentinels. Init to 1 to count myself. */
|
||||
int result = SENTINEL_ISQR_OK;
|
||||
int voters = dictSize(master->sentinels)+1; /* Known Sentinels + myself. */
|
||||
|
||||
di = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
|
||||
if (ri->flags & (SRI_S_DOWN|SRI_O_DOWN)) continue;
|
||||
usable++;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
if (usable < (int)master->quorum) result |= SENTINEL_ISQR_NOQUORUM;
|
||||
if (usable < voters/2+1) result |= SENTINEL_ISQR_NOAUTH;
|
||||
if (usableptr) *usableptr = usable;
|
||||
return result;
|
||||
}
|
||||
|
||||
void sentinelCommand(redisClient *c) {
|
||||
if (!strcasecmp(c->argv[1]->ptr,"masters")) {
|
||||
/* SENTINEL MASTERS */
|
||||
@@ -2756,7 +2682,7 @@ void sentinelCommand(redisClient *c) {
|
||||
/* SENTINEL MONITOR <name> <ip> <port> <quorum> */
|
||||
sentinelRedisInstance *ri;
|
||||
long quorum, port;
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
char buf[32];
|
||||
|
||||
if (c->argc != 6) goto numargserr;
|
||||
if (getLongFromObjectOrReply(c,c->argv[5],&quorum,"Invalid quorum")
|
||||
@@ -2766,7 +2692,7 @@ void sentinelCommand(redisClient *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,c->argv[3]->ptr,ip,sizeof(ip)) == ANET_ERR) {
|
||||
if (anetResolveIP(NULL,c->argv[3]->ptr,buf,sizeof(buf)) == ANET_ERR) {
|
||||
addReplyError(c,"Invalid IP address specified");
|
||||
return;
|
||||
}
|
||||
@@ -2791,49 +2717,16 @@ void sentinelCommand(redisClient *c) {
|
||||
sentinelEvent(REDIS_WARNING,"+monitor",ri,"%@ quorum %d",ri->quorum);
|
||||
addReply(c,shared.ok);
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"flushconfig")) {
|
||||
if (c->argc != 2) goto numargserr;
|
||||
sentinelFlushConfig();
|
||||
addReply(c,shared.ok);
|
||||
return;
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"remove")) {
|
||||
/* SENTINEL REMOVE <name> */
|
||||
sentinelRedisInstance *ri;
|
||||
|
||||
if (c->argc != 3) goto numargserr;
|
||||
if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2]))
|
||||
== NULL) return;
|
||||
sentinelEvent(REDIS_WARNING,"-monitor",ri,"%@");
|
||||
dictDelete(sentinel.masters,c->argv[2]->ptr);
|
||||
sentinelFlushConfig();
|
||||
addReply(c,shared.ok);
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"ckquorum")) {
|
||||
/* SENTINEL CKQUORUM <name> */
|
||||
sentinelRedisInstance *ri;
|
||||
int usable;
|
||||
|
||||
if (c->argc != 3) goto numargserr;
|
||||
if ((ri = sentinelGetMasterByNameOrReplyError(c,c->argv[2]))
|
||||
== NULL) return;
|
||||
int result = sentinelIsQuorumReachable(ri,&usable);
|
||||
if (result == SENTINEL_ISQR_OK) {
|
||||
addReplySds(c, sdscatfmt(sdsempty(),
|
||||
"+OK %i usable Sentinels. Quorum and failover authorization "
|
||||
"can be reached\r\n",usable));
|
||||
} else {
|
||||
sds e = sdscatfmt(sdsempty(),
|
||||
"-NOQUORUM %i usable Sentinels. ",usable);
|
||||
if (result & SENTINEL_ISQR_NOQUORUM)
|
||||
e = sdscat(e,"Not enough available Sentinels to reach the"
|
||||
" specified quorum for this master");
|
||||
if (result & SENTINEL_ISQR_NOAUTH) {
|
||||
if (result & SENTINEL_ISQR_NOQUORUM) e = sdscat(e,". ");
|
||||
e = sdscat(e, "Not enough available Sentinels to reach the"
|
||||
" majority and authorize a failover");
|
||||
}
|
||||
e = sdscat(e,"\r\n");
|
||||
addReplySds(c,e);
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"set")) {
|
||||
if (c->argc < 3 || c->argc % 2 == 0) goto numargserr;
|
||||
sentinelSetCommand(c);
|
||||
@@ -3104,7 +2997,7 @@ void sentinelCheckSubjectivelyDown(sentinelRedisInstance *ri) {
|
||||
void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) {
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
unsigned int quorum = 0, odown = 0;
|
||||
int quorum = 0, odown = 0;
|
||||
|
||||
if (master->flags & SRI_S_DOWN) {
|
||||
/* Is down for enough sentinels? */
|
||||
@@ -3141,7 +3034,6 @@ void sentinelCheckObjectivelyDown(sentinelRedisInstance *master) {
|
||||
void sentinelReceiveIsMasterDownReply(redisAsyncContext *c, void *reply, void *privdata) {
|
||||
sentinelRedisInstance *ri = c->data;
|
||||
redisReply *r;
|
||||
REDIS_NOTUSED(privdata);
|
||||
|
||||
if (ri) ri->pending_commands--;
|
||||
if (!reply || !ri) return;
|
||||
@@ -3165,7 +3057,7 @@ void sentinelReceiveIsMasterDownReply(redisAsyncContext *c, void *reply, void *p
|
||||
/* If the runid in the reply is not "*" the Sentinel actually
|
||||
* replied with a vote. */
|
||||
sdsfree(ri->leader);
|
||||
if ((long long)ri->leader_epoch != r->element[2]->integer)
|
||||
if (ri->leader_epoch != r->element[2]->integer)
|
||||
redisLog(REDIS_WARNING,
|
||||
"%s voted for %s %llu", ri->name,
|
||||
r->element[1]->str,
|
||||
@@ -3284,9 +3176,9 @@ int sentinelLeaderIncr(dict *counters, char *runid) {
|
||||
/* Scan all the Sentinels attached to this master to check if there
|
||||
* is a leader for the specified epoch.
|
||||
*
|
||||
* To be a leader for a given epoch, we should have the majority of
|
||||
* the Sentinels we know (ever seen since the last SENTINEL RESET) that
|
||||
* reported the same instance as leader for the same epoch. */
|
||||
* To be a leader for a given epoch, we should have the majorify of
|
||||
* the Sentinels we know that reported the same instance as
|
||||
* leader for the same epoch. */
|
||||
char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
|
||||
dict *counters;
|
||||
dictIterator *di;
|
||||
@@ -3300,14 +3192,13 @@ char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
|
||||
redisAssert(master->flags & (SRI_O_DOWN|SRI_FAILOVER_IN_PROGRESS));
|
||||
counters = dictCreate(&leaderVotesDictType,NULL);
|
||||
|
||||
voters = dictSize(master->sentinels)+1; /* All the other sentinels and me. */
|
||||
|
||||
/* Count other sentinels votes */
|
||||
di = dictGetIterator(master->sentinels);
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
if (ri->leader != NULL && ri->leader_epoch == sentinel.current_epoch)
|
||||
sentinelLeaderIncr(counters,ri->leader);
|
||||
voters++;
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
@@ -3341,6 +3232,7 @@ char *sentinelGetLeader(sentinelRedisInstance *master, uint64_t epoch) {
|
||||
winner = myvote;
|
||||
}
|
||||
}
|
||||
voters++; /* Anyway, count me as one of the voters. */
|
||||
|
||||
voters_quorum = voters/2+1;
|
||||
if (winner && (max_votes < voters_quorum || max_votes < master->quorum))
|
||||
|
||||
+9
-7
@@ -23,8 +23,10 @@ A million repetitions of "a"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h> /* for u_int*_t */
|
||||
#if defined(__sun)
|
||||
#include "solarisfixes.h"
|
||||
#endif
|
||||
#include "sha1.h"
|
||||
#include "config.h"
|
||||
|
||||
@@ -53,12 +55,12 @@ A million repetitions of "a"
|
||||
|
||||
/* Hash a single 512-bit block. This is the core of the algorithm. */
|
||||
|
||||
void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
|
||||
void SHA1Transform(u_int32_t state[5], const unsigned char buffer[64])
|
||||
{
|
||||
uint32_t a, b, c, d, e;
|
||||
u_int32_t a, b, c, d, e;
|
||||
typedef union {
|
||||
unsigned char c[64];
|
||||
uint32_t l[16];
|
||||
u_int32_t l[16];
|
||||
} CHAR64LONG16;
|
||||
#ifdef SHA1HANDSOFF
|
||||
CHAR64LONG16 block[1]; /* use array to appear as a pointer */
|
||||
@@ -128,9 +130,9 @@ void SHA1Init(SHA1_CTX* context)
|
||||
|
||||
/* Run your data through this. */
|
||||
|
||||
void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len)
|
||||
void SHA1Update(SHA1_CTX* context, const unsigned char* data, u_int32_t len)
|
||||
{
|
||||
uint32_t i, j;
|
||||
u_int32_t i, j;
|
||||
|
||||
j = context->count[0];
|
||||
if ((context->count[0] += len << 3) < j)
|
||||
@@ -168,7 +170,7 @@ void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
|
||||
|
||||
for (i = 0; i < 2; i++)
|
||||
{
|
||||
uint32_t t = context->count[i];
|
||||
u_int32_t t = context->count[i];
|
||||
int j;
|
||||
|
||||
for (j = 0; j < 4; t >>= 8, j++)
|
||||
|
||||
+4
-4
@@ -6,12 +6,12 @@ By Steve Reid <steve@edmweb.com>
|
||||
*/
|
||||
|
||||
typedef struct {
|
||||
uint32_t state[5];
|
||||
uint32_t count[2];
|
||||
u_int32_t state[5];
|
||||
u_int32_t count[2];
|
||||
unsigned char buffer[64];
|
||||
} SHA1_CTX;
|
||||
|
||||
void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]);
|
||||
void SHA1Transform(u_int32_t state[5], const unsigned char buffer[64]);
|
||||
void SHA1Init(SHA1_CTX* context);
|
||||
void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len);
|
||||
void SHA1Update(SHA1_CTX* context, const unsigned char* data, u_int32_t len);
|
||||
void SHA1Final(unsigned char digest[20], SHA1_CTX* context);
|
||||
|
||||
@@ -28,8 +28,6 @@
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#if defined(__sun)
|
||||
|
||||
#if defined(__GNUC__)
|
||||
#include <math.h>
|
||||
#undef isnan
|
||||
@@ -50,5 +48,3 @@
|
||||
#define u_int uint
|
||||
#define u_int32_t uint32_t
|
||||
#endif /* __GNUC__ */
|
||||
|
||||
#endif /* __sun */
|
||||
|
||||
+10
-9
@@ -209,7 +209,7 @@ void sortCommand(redisClient *c) {
|
||||
}
|
||||
|
||||
/* Create a list of operations to perform for every sorted element.
|
||||
* Operations can be GET */
|
||||
* Operations can be GET/DEL/INCR/DECR */
|
||||
operations = listCreate();
|
||||
listSetFreeMethod(operations,zfree);
|
||||
j = 2; /* options start at argv[2] */
|
||||
@@ -285,15 +285,16 @@ void sortCommand(redisClient *c) {
|
||||
return;
|
||||
}
|
||||
|
||||
/* When sorting a set with no sort specified, we must sort the output
|
||||
* so the result is consistent across scripting and replication.
|
||||
/* For the STORE option, or when SORT is called from a Lua script,
|
||||
* we want to force a specific ordering even when no explicit ordering
|
||||
* was asked (SORT BY nosort). This guarantees that replication / AOF
|
||||
* is deterministic.
|
||||
*
|
||||
* The other types (list, sorted set) will retain their native order
|
||||
* even if no sort order is requested, so they remain stable across
|
||||
* scripting and replication. */
|
||||
if (dontsort &&
|
||||
sortval->type == REDIS_SET &&
|
||||
(storekey || c->flags & REDIS_LUA_CLIENT))
|
||||
* However in the case 'dontsort' is true, but the type to sort is a
|
||||
* sorted set, we don't need to do anything as ordering is guaranteed
|
||||
* in this special case. */
|
||||
if ((storekey || c->flags & REDIS_LUA_CLIENT) &&
|
||||
(dontsort && sortval->type != REDIS_ZSET))
|
||||
{
|
||||
/* Force ALPHA sorting */
|
||||
dontsort = 0;
|
||||
|
||||
+1
-2
@@ -49,7 +49,7 @@ static int label_margin_top = 1;
|
||||
* sparklineSequenceAddSample(seq, 10, NULL);
|
||||
* sparklineSequenceAddSample(seq, 20, NULL);
|
||||
* sparklineSequenceAddSample(seq, 30, "last sample label");
|
||||
* sds output = sparklineRender(sdsempty(), seq, 80, 4, SPARKLINE_FILL);
|
||||
* sds output = sparklineRender(seq, 80, 4);
|
||||
* freeSparklineSequence(seq);
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
@@ -63,7 +63,6 @@ struct sequence *createSparklineSequence(void) {
|
||||
|
||||
/* Add a new sample into a sequence. */
|
||||
void sparklineSequenceAddSample(struct sequence *seq, double value, char *label) {
|
||||
label = (label == NULL || label[0] == '\0') ? NULL : zstrdup(label);
|
||||
if (seq->length == 0) {
|
||||
seq->min = seq->max = value;
|
||||
} else {
|
||||
|
||||
@@ -139,7 +139,6 @@ ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout) {
|
||||
*ptr = '\0';
|
||||
nread++;
|
||||
}
|
||||
size--;
|
||||
}
|
||||
return nread;
|
||||
}
|
||||
|
||||
+1
-1
@@ -565,7 +565,7 @@ void hincrbyfloatCommand(redisClient *c) {
|
||||
}
|
||||
|
||||
value += incr;
|
||||
new = createStringObjectFromLongDouble(value,1);
|
||||
new = createStringObjectFromLongDouble(value);
|
||||
hashTypeTryObjectEncoding(o,&c->argv[2],NULL);
|
||||
hashTypeSet(o,c->argv[2],new);
|
||||
addReplyBulk(c,new);
|
||||
|
||||
+1
-1
@@ -321,7 +321,7 @@ void smoveCommand(redisClient *c) {
|
||||
|
||||
/* If srcset and dstset are equal, SMOVE is a no-op */
|
||||
if (srcset == dstset) {
|
||||
addReply(c,setTypeIsMember(srcset,ele) ? shared.cone : shared.czero);
|
||||
addReply(c,shared.cone);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+12
-22
@@ -69,7 +69,7 @@ void setGenericCommand(redisClient *c, int flags, robj *key, robj *val, robj *ex
|
||||
if (getLongLongFromObjectOrReply(c, expire, &milliseconds, NULL) != REDIS_OK)
|
||||
return;
|
||||
if (milliseconds <= 0) {
|
||||
addReplyErrorFormat(c,"invalid expire time in %s",c->cmd->name);
|
||||
addReplyError(c,"invalid expire time in SETEX");
|
||||
return;
|
||||
}
|
||||
if (unit == UNIT_SECONDS) milliseconds *= 1000;
|
||||
@@ -231,13 +231,13 @@ void setrangeCommand(redisClient *c) {
|
||||
|
||||
void getrangeCommand(redisClient *c) {
|
||||
robj *o;
|
||||
long long start, end;
|
||||
long start, end;
|
||||
char *str, llbuf[32];
|
||||
size_t strlen;
|
||||
|
||||
if (getLongLongFromObjectOrReply(c,c->argv[2],&start,NULL) != REDIS_OK)
|
||||
if (getLongFromObjectOrReply(c,c->argv[2],&start,NULL) != REDIS_OK)
|
||||
return;
|
||||
if (getLongLongFromObjectOrReply(c,c->argv[3],&end,NULL) != REDIS_OK)
|
||||
if (getLongFromObjectOrReply(c,c->argv[3],&end,NULL) != REDIS_OK)
|
||||
return;
|
||||
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptybulk)) == NULL ||
|
||||
checkType(c,o,REDIS_STRING)) return;
|
||||
@@ -255,11 +255,11 @@ void getrangeCommand(redisClient *c) {
|
||||
if (end < 0) end = strlen+end;
|
||||
if (start < 0) start = 0;
|
||||
if (end < 0) end = 0;
|
||||
if ((unsigned long long)end >= strlen) end = strlen-1;
|
||||
if ((unsigned)end >= strlen) end = strlen-1;
|
||||
|
||||
/* Precondition: end >= 0 && end < strlen, so the only condition where
|
||||
* nothing can be returned is: start > end. */
|
||||
if (start > end || strlen == 0) {
|
||||
if (start > end) {
|
||||
addReply(c,shared.emptybulk);
|
||||
} else {
|
||||
addReplyBulkCBuffer(c,(char*)str+start,end-start+1);
|
||||
@@ -337,21 +337,11 @@ void incrDecrCommand(redisClient *c, long long incr) {
|
||||
return;
|
||||
}
|
||||
value += incr;
|
||||
|
||||
if (o && o->refcount == 1 && o->encoding == REDIS_ENCODING_INT &&
|
||||
(value < 0 || value >= REDIS_SHARED_INTEGERS) &&
|
||||
value >= LONG_MIN && value <= LONG_MAX)
|
||||
{
|
||||
new = o;
|
||||
o->ptr = (void*)((long)value);
|
||||
} else {
|
||||
new = createStringObjectFromLongLong(value);
|
||||
if (o) {
|
||||
dbOverwrite(c->db,c->argv[1],new);
|
||||
} else {
|
||||
dbAdd(c->db,c->argv[1],new);
|
||||
}
|
||||
}
|
||||
new = createStringObjectFromLongLong(value);
|
||||
if (o)
|
||||
dbOverwrite(c->db,c->argv[1],new);
|
||||
else
|
||||
dbAdd(c->db,c->argv[1],new);
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_STRING,"incrby",c->argv[1],c->db->id);
|
||||
server.dirty++;
|
||||
@@ -397,7 +387,7 @@ void incrbyfloatCommand(redisClient *c) {
|
||||
addReplyError(c,"increment would produce NaN or Infinity");
|
||||
return;
|
||||
}
|
||||
new = createStringObjectFromLongDouble(value,1);
|
||||
new = createStringObjectFromLongDouble(value);
|
||||
if (o)
|
||||
dbOverwrite(c->db,c->argv[1],new);
|
||||
else
|
||||
|
||||
+51
-137
@@ -205,6 +205,8 @@ int zslDelete(zskiplist *zsl, double score, robj *obj) {
|
||||
zslDeleteNode(zsl, x, update);
|
||||
zslFreeNode(x);
|
||||
return 1;
|
||||
} else {
|
||||
return 0; /* not found */
|
||||
}
|
||||
return 0; /* not found */
|
||||
}
|
||||
@@ -1171,84 +1173,35 @@ void zsetConvert(robj *zobj, int encoding) {
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
/* This generic command implements both ZADD and ZINCRBY. */
|
||||
#define ZADD_NONE 0
|
||||
#define ZADD_INCR (1<<0) /* Increment the score instead of setting it. */
|
||||
#define ZADD_NX (1<<1) /* Don't touch elements not already existing. */
|
||||
#define ZADD_XX (1<<2) /* Only touch elements already exisitng. */
|
||||
#define ZADD_CH (1<<3) /* Return num of elements added or updated. */
|
||||
void zaddGenericCommand(redisClient *c, int flags) {
|
||||
void zaddGenericCommand(redisClient *c, int incr) {
|
||||
static char *nanerr = "resulting score is not a number (NaN)";
|
||||
robj *key = c->argv[1];
|
||||
robj *ele;
|
||||
robj *zobj;
|
||||
robj *curobj;
|
||||
double score = 0, *scores = NULL, curscore = 0.0;
|
||||
int j, elements;
|
||||
int scoreidx = 0;
|
||||
/* The following vars are used in order to track what the command actually
|
||||
* did during the execution, to reply to the client and to trigger the
|
||||
* notification of keyspace change. */
|
||||
int added = 0; /* Number of new elements added. */
|
||||
int updated = 0; /* Number of elements with updated score. */
|
||||
int processed = 0; /* Number of elements processed, may remain zero with
|
||||
options like XX. */
|
||||
int j, elements = (c->argc-2)/2;
|
||||
int added = 0, updated = 0;
|
||||
|
||||
/* Parse options. At the end 'scoreidx' is set to the argument position
|
||||
* of the score of the first score-element pair. */
|
||||
scoreidx = 2;
|
||||
while(scoreidx < c->argc) {
|
||||
char *opt = c->argv[scoreidx]->ptr;
|
||||
if (!strcasecmp(opt,"nx")) flags |= ZADD_NX;
|
||||
else if (!strcasecmp(opt,"xx")) flags |= ZADD_XX;
|
||||
else if (!strcasecmp(opt,"ch")) flags |= ZADD_CH;
|
||||
else if (!strcasecmp(opt,"incr")) flags |= ZADD_INCR;
|
||||
else break;
|
||||
scoreidx++;
|
||||
}
|
||||
|
||||
/* Turn options into simple to check vars. */
|
||||
int incr = (flags & ZADD_INCR) != 0;
|
||||
int nx = (flags & ZADD_NX) != 0;
|
||||
int xx = (flags & ZADD_XX) != 0;
|
||||
int ch = (flags & ZADD_CH) != 0;
|
||||
|
||||
/* After the options, we expect to have an even number of args, since
|
||||
* we expect any number of score-element pairs. */
|
||||
elements = c->argc-scoreidx;
|
||||
if (elements % 2) {
|
||||
if (c->argc % 2) {
|
||||
addReply(c,shared.syntaxerr);
|
||||
return;
|
||||
}
|
||||
elements /= 2; /* Now this holds the number of score-element pairs. */
|
||||
|
||||
/* Check for incompatible options. */
|
||||
if (nx && xx) {
|
||||
addReplyError(c,
|
||||
"XX and NX options at the same time are not compatible");
|
||||
return;
|
||||
}
|
||||
|
||||
if (incr && elements > 1) {
|
||||
addReplyError(c,
|
||||
"INCR option supports a single increment-element pair");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Start parsing all the scores, we need to emit any syntax error
|
||||
* before executing additions to the sorted set, as the command should
|
||||
* either execute fully or nothing at all. */
|
||||
scores = zmalloc(sizeof(double)*elements);
|
||||
for (j = 0; j < elements; j++) {
|
||||
if (getDoubleFromObjectOrReply(c,c->argv[scoreidx+j*2],&scores[j],NULL)
|
||||
if (getDoubleFromObjectOrReply(c,c->argv[2+j*2],&scores[j],NULL)
|
||||
!= REDIS_OK) goto cleanup;
|
||||
}
|
||||
|
||||
/* Lookup the key and create the sorted set if does not exist. */
|
||||
zobj = lookupKeyWrite(c->db,key);
|
||||
if (zobj == NULL) {
|
||||
if (xx) goto reply_to_client; /* No key + XX option: nothing to do. */
|
||||
if (server.zset_max_ziplist_entries == 0 ||
|
||||
server.zset_max_ziplist_value < sdslen(c->argv[scoreidx+1]->ptr))
|
||||
server.zset_max_ziplist_value < sdslen(c->argv[3]->ptr))
|
||||
{
|
||||
zobj = createZsetObject();
|
||||
} else {
|
||||
@@ -1269,9 +1222,8 @@ void zaddGenericCommand(redisClient *c, int flags) {
|
||||
unsigned char *eptr;
|
||||
|
||||
/* Prefer non-encoded element when dealing with ziplists. */
|
||||
ele = c->argv[scoreidx+1+j*2];
|
||||
ele = c->argv[3+j*2];
|
||||
if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {
|
||||
if (nx) continue;
|
||||
if (incr) {
|
||||
score += curscore;
|
||||
if (isnan(score)) {
|
||||
@@ -1287,8 +1239,7 @@ void zaddGenericCommand(redisClient *c, int flags) {
|
||||
server.dirty++;
|
||||
updated++;
|
||||
}
|
||||
processed++;
|
||||
} else if (!xx) {
|
||||
} else {
|
||||
/* Optimize: check if the element is too large or the list
|
||||
* becomes too long *before* executing zzlInsert. */
|
||||
zobj->ptr = zzlInsert(zobj->ptr,ele,score);
|
||||
@@ -1298,18 +1249,15 @@ void zaddGenericCommand(redisClient *c, int flags) {
|
||||
zsetConvert(zobj,REDIS_ENCODING_SKIPLIST);
|
||||
server.dirty++;
|
||||
added++;
|
||||
processed++;
|
||||
}
|
||||
} else if (zobj->encoding == REDIS_ENCODING_SKIPLIST) {
|
||||
zset *zs = zobj->ptr;
|
||||
zskiplistNode *znode;
|
||||
dictEntry *de;
|
||||
|
||||
ele = c->argv[scoreidx+1+j*2] =
|
||||
tryObjectEncoding(c->argv[scoreidx+1+j*2]);
|
||||
ele = c->argv[3+j*2] = tryObjectEncoding(c->argv[3+j*2]);
|
||||
de = dictFind(zs->dict,ele);
|
||||
if (de != NULL) {
|
||||
if (nx) continue;
|
||||
curobj = dictGetKey(de);
|
||||
curscore = *(double*)dictGetVal(de);
|
||||
|
||||
@@ -1334,30 +1282,22 @@ void zaddGenericCommand(redisClient *c, int flags) {
|
||||
server.dirty++;
|
||||
updated++;
|
||||
}
|
||||
processed++;
|
||||
} else if (!xx) {
|
||||
} else {
|
||||
znode = zslInsert(zs->zsl,score,ele);
|
||||
incrRefCount(ele); /* Inserted in skiplist. */
|
||||
redisAssertWithInfo(c,NULL,dictAdd(zs->dict,ele,&znode->score) == DICT_OK);
|
||||
incrRefCount(ele); /* Added to dictionary. */
|
||||
server.dirty++;
|
||||
added++;
|
||||
processed++;
|
||||
}
|
||||
} else {
|
||||
redisPanic("Unknown sorted set encoding");
|
||||
}
|
||||
}
|
||||
|
||||
reply_to_client:
|
||||
if (incr) { /* ZINCRBY or INCR option. */
|
||||
if (processed)
|
||||
addReplyDouble(c,score);
|
||||
else
|
||||
addReply(c,shared.nullbulk);
|
||||
} else { /* ZADD. */
|
||||
addReplyLongLong(c,ch ? added+updated : added);
|
||||
}
|
||||
if (incr) /* ZINCRBY */
|
||||
addReplyDouble(c,score);
|
||||
else /* ZADD */
|
||||
addReplyLongLong(c,added);
|
||||
|
||||
cleanup:
|
||||
zfree(scores);
|
||||
@@ -1369,11 +1309,11 @@ cleanup:
|
||||
}
|
||||
|
||||
void zaddCommand(redisClient *c) {
|
||||
zaddGenericCommand(c,ZADD_NONE);
|
||||
zaddGenericCommand(c,0);
|
||||
}
|
||||
|
||||
void zincrbyCommand(redisClient *c) {
|
||||
zaddGenericCommand(c,ZADD_INCR);
|
||||
zaddGenericCommand(c,1);
|
||||
}
|
||||
|
||||
void zremCommand(redisClient *c) {
|
||||
@@ -2041,77 +1981,51 @@ void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
|
||||
zuiClearIterator(&src[0]);
|
||||
}
|
||||
} else if (op == REDIS_OP_UNION) {
|
||||
dict *accumulator = dictCreate(&setDictType,NULL);
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
double score;
|
||||
|
||||
if (setnum) {
|
||||
/* Our union is at least as large as the largest set.
|
||||
* Resize the dictionary ASAP to avoid useless rehashing. */
|
||||
dictExpand(accumulator,zuiLength(&src[setnum-1]));
|
||||
}
|
||||
|
||||
/* Step 1: Create a dictionary of elements -> aggregated-scores
|
||||
* by iterating one sorted set after the other. */
|
||||
for (i = 0; i < setnum; i++) {
|
||||
if (zuiLength(&src[i]) == 0) continue;
|
||||
if (zuiLength(&src[i]) == 0)
|
||||
continue;
|
||||
|
||||
zuiInitIterator(&src[i]);
|
||||
while (zuiNext(&src[i],&zval)) {
|
||||
/* Initialize value */
|
||||
double score, value;
|
||||
|
||||
/* Skip an element that when already processed */
|
||||
if (dictFind(dstzset->dict,zuiObjectFromValue(&zval)) != NULL)
|
||||
continue;
|
||||
|
||||
/* Initialize score */
|
||||
score = src[i].weight * zval.score;
|
||||
if (isnan(score)) score = 0;
|
||||
|
||||
/* Search for this element in the accumulating dictionary. */
|
||||
de = dictFind(accumulator,zuiObjectFromValue(&zval));
|
||||
/* If we don't have it, we need to create a new entry. */
|
||||
if (de == NULL) {
|
||||
tmp = zuiObjectFromValue(&zval);
|
||||
/* Remember the longest single element encountered,
|
||||
* to understand if it's possible to convert to ziplist
|
||||
* at the end. */
|
||||
if (sdsEncodedObject(tmp)) {
|
||||
if (sdslen(tmp->ptr) > maxelelen)
|
||||
maxelelen = sdslen(tmp->ptr);
|
||||
/* We need to check only next sets to see if this element
|
||||
* exists, since we process every element just one time so
|
||||
* it can't exist in a previous set (otherwise it would be
|
||||
* already processed). */
|
||||
for (j = (i+1); j < setnum; j++) {
|
||||
/* It is not safe to access the zset we are
|
||||
* iterating, so explicitly check for equal object. */
|
||||
if(src[j].subject == src[i].subject) {
|
||||
value = zval.score*src[j].weight;
|
||||
zunionInterAggregate(&score,value,aggregate);
|
||||
} else if (zuiFind(&src[j],&zval,&value)) {
|
||||
value *= src[j].weight;
|
||||
zunionInterAggregate(&score,value,aggregate);
|
||||
}
|
||||
/* Add the element with its initial score. */
|
||||
de = dictAddRaw(accumulator,tmp);
|
||||
incrRefCount(tmp);
|
||||
dictSetDoubleVal(de,score);
|
||||
} else {
|
||||
/* Update the score with the score of the new instance
|
||||
* of the element found in the current sorted set.
|
||||
*
|
||||
* Here we access directly the dictEntry double
|
||||
* value inside the union as it is a big speedup
|
||||
* compared to using the getDouble/setDouble API. */
|
||||
zunionInterAggregate(&de->v.d,score,aggregate);
|
||||
}
|
||||
|
||||
tmp = zuiObjectFromValue(&zval);
|
||||
znode = zslInsert(dstzset->zsl,score,tmp);
|
||||
incrRefCount(zval.ele); /* added to skiplist */
|
||||
dictAdd(dstzset->dict,tmp,&znode->score);
|
||||
incrRefCount(zval.ele); /* added to dictionary */
|
||||
|
||||
if (sdsEncodedObject(tmp)) {
|
||||
if (sdslen(tmp->ptr) > maxelelen)
|
||||
maxelelen = sdslen(tmp->ptr);
|
||||
}
|
||||
}
|
||||
zuiClearIterator(&src[i]);
|
||||
}
|
||||
|
||||
/* Step 2: convert the dictionary into the final sorted set. */
|
||||
di = dictGetIterator(accumulator);
|
||||
|
||||
/* We now are aware of the final size of the resulting sorted set,
|
||||
* let's resize the dictionary embedded inside the sorted set to the
|
||||
* right size, in order to save rehashing time. */
|
||||
dictExpand(dstzset->dict,dictSize(accumulator));
|
||||
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
robj *ele = dictGetKey(de);
|
||||
score = dictGetDoubleVal(de);
|
||||
znode = zslInsert(dstzset->zsl,score,ele);
|
||||
incrRefCount(ele); /* added to skiplist */
|
||||
dictAdd(dstzset->dict,ele,&znode->score);
|
||||
incrRefCount(ele); /* added to dictionary */
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
/* We can free the accumulator dictionary now. */
|
||||
dictRelease(accumulator);
|
||||
} else {
|
||||
redisPanic("Unknown operator");
|
||||
}
|
||||
|
||||
+34
-143
@@ -37,11 +37,8 @@
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <float.h>
|
||||
#include <stdint.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include "util.h"
|
||||
#include "sha1.h"
|
||||
|
||||
/* Glob-style pattern matching. */
|
||||
int stringmatchlen(const char *pattern, int patternLen,
|
||||
@@ -171,12 +168,11 @@ int stringmatch(const char *pattern, const char *string, int nocase) {
|
||||
}
|
||||
|
||||
/* Convert a string representing an amount of memory into the number of
|
||||
* bytes, so for instance memtoll("1Gb") will return 1073741824 that is
|
||||
* bytes, so for instance memtoll("1Gi") will return 1073741824 that is
|
||||
* (1024*1024*1024).
|
||||
*
|
||||
* On parsing error, if *err is not NULL, it's set to 1, otherwise it's
|
||||
* set to 0. On error the function return value is 0, regardless of the
|
||||
* fact 'err' is NULL or not. */
|
||||
* set to 0 */
|
||||
long long memtoll(const char *p, int *err) {
|
||||
const char *u;
|
||||
char buf[128];
|
||||
@@ -185,7 +181,6 @@ long long memtoll(const char *p, int *err) {
|
||||
unsigned int digits;
|
||||
|
||||
if (err) *err = 0;
|
||||
|
||||
/* Search the first non digit character. */
|
||||
u = p;
|
||||
if (*u == '-') u++;
|
||||
@@ -206,114 +201,41 @@ long long memtoll(const char *p, int *err) {
|
||||
mul = 1024L*1024*1024;
|
||||
} else {
|
||||
if (err) *err = 1;
|
||||
return 0;
|
||||
mul = 1;
|
||||
}
|
||||
|
||||
/* Copy the digits into a buffer, we'll use strtoll() to convert
|
||||
* the digit (without the unit) into a number. */
|
||||
digits = u-p;
|
||||
if (digits >= sizeof(buf)) {
|
||||
if (err) *err = 1;
|
||||
return 0;
|
||||
return LLONG_MAX;
|
||||
}
|
||||
memcpy(buf,p,digits);
|
||||
buf[digits] = '\0';
|
||||
|
||||
char *endptr;
|
||||
errno = 0;
|
||||
val = strtoll(buf,&endptr,10);
|
||||
if ((val == 0 && errno == EINVAL) || *endptr != '\0') {
|
||||
if (err) *err = 1;
|
||||
return 0;
|
||||
}
|
||||
val = strtoll(buf,NULL,10);
|
||||
return val*mul;
|
||||
}
|
||||
|
||||
/* Return the number of digits of 'v' when converted to string in radix 10.
|
||||
* See ll2string() for more information. */
|
||||
uint32_t digits10(uint64_t v) {
|
||||
if (v < 10) return 1;
|
||||
if (v < 100) return 2;
|
||||
if (v < 1000) return 3;
|
||||
if (v < 1000000000000UL) {
|
||||
if (v < 100000000UL) {
|
||||
if (v < 1000000) {
|
||||
if (v < 10000) return 4;
|
||||
return 5 + (v >= 100000);
|
||||
}
|
||||
return 7 + (v >= 10000000UL);
|
||||
}
|
||||
if (v < 10000000000UL) {
|
||||
return 9 + (v >= 1000000000UL);
|
||||
}
|
||||
return 11 + (v >= 100000000000UL);
|
||||
}
|
||||
return 12 + digits10(v / 1000000000000UL);
|
||||
}
|
||||
|
||||
/* Convert a long long into a string. Returns the number of
|
||||
* characters needed to represent the number.
|
||||
* If the buffer is not big enough to store the string, 0 is returned.
|
||||
*
|
||||
* Based on the following article (that apparently does not provide a
|
||||
* novel approach but only publicizes an already used technique):
|
||||
*
|
||||
* https://www.facebook.com/notes/facebook-engineering/three-optimization-tips-for-c/10151361643253920
|
||||
*
|
||||
* Modified in order to handle signed integers since the original code was
|
||||
* designed for unsigned integers. */
|
||||
int ll2string(char* dst, size_t dstlen, long long svalue) {
|
||||
static const char digits[201] =
|
||||
"0001020304050607080910111213141516171819"
|
||||
"2021222324252627282930313233343536373839"
|
||||
"4041424344454647484950515253545556575859"
|
||||
"6061626364656667686970717273747576777879"
|
||||
"8081828384858687888990919293949596979899";
|
||||
int negative;
|
||||
unsigned long long value;
|
||||
* characters needed to represent the number, that can be shorter if passed
|
||||
* buffer length is not enough to store the whole number. */
|
||||
int ll2string(char *s, size_t len, long long value) {
|
||||
char buf[32], *p;
|
||||
unsigned long long v;
|
||||
size_t l;
|
||||
|
||||
/* The main loop works with 64bit unsigned integers for simplicity, so
|
||||
* we convert the number here and remember if it is negative. */
|
||||
if (svalue < 0) {
|
||||
if (svalue != LLONG_MIN) {
|
||||
value = -svalue;
|
||||
} else {
|
||||
value = ((unsigned long long) LLONG_MAX)+1;
|
||||
}
|
||||
negative = 1;
|
||||
} else {
|
||||
value = svalue;
|
||||
negative = 0;
|
||||
}
|
||||
|
||||
/* Check length. */
|
||||
uint32_t const length = digits10(value)+negative;
|
||||
if (length >= dstlen) return 0;
|
||||
|
||||
/* Null term. */
|
||||
uint32_t next = length;
|
||||
dst[next] = '\0';
|
||||
next--;
|
||||
while (value >= 100) {
|
||||
int const i = (value % 100) * 2;
|
||||
value /= 100;
|
||||
dst[next] = digits[i + 1];
|
||||
dst[next - 1] = digits[i];
|
||||
next -= 2;
|
||||
}
|
||||
|
||||
/* Handle last 1-2 digits. */
|
||||
if (value < 10) {
|
||||
dst[next] = '0' + (uint32_t) value;
|
||||
} else {
|
||||
int i = (uint32_t) value * 2;
|
||||
dst[next] = digits[i + 1];
|
||||
dst[next - 1] = digits[i];
|
||||
}
|
||||
|
||||
/* Add sign. */
|
||||
if (negative) dst[0] = '-';
|
||||
return length;
|
||||
if (len == 0) return 0;
|
||||
v = (value < 0) ? -value : value;
|
||||
p = buf+31; /* point to the last character */
|
||||
do {
|
||||
*p-- = '0'+(v%10);
|
||||
v /= 10;
|
||||
} while(v);
|
||||
if (value < 0) *p-- = '-';
|
||||
p++;
|
||||
l = 32-(p-buf);
|
||||
if (l+1 > len) l = len-1; /* Make sure it fits, including the nul term */
|
||||
memcpy(s,p,l);
|
||||
s[l] = '\0';
|
||||
return l;
|
||||
}
|
||||
|
||||
/* Convert a string into a long long. Returns 1 if the string could be parsed
|
||||
@@ -399,7 +321,7 @@ int string2l(const char *s, size_t slen, long *lval) {
|
||||
}
|
||||
|
||||
/* Convert a double to a string representation. Returns the number of bytes
|
||||
* required. The representation should always be parsable by strtod(3). */
|
||||
* required. The representation should always be parsable by stdtod(3). */
|
||||
int d2string(char *buf, size_t len, double value) {
|
||||
if (isnan(value)) {
|
||||
len = snprintf(buf,len,"nan");
|
||||
@@ -442,44 +364,11 @@ int d2string(char *buf, size_t len, double value) {
|
||||
* having run_id == A, and you reconnect and it has run_id == B, you can be
|
||||
* sure that it is either a different instance or it was restarted. */
|
||||
void getRandomHexChars(char *p, unsigned int len) {
|
||||
FILE *fp = fopen("/dev/urandom","r");
|
||||
char *charset = "0123456789abcdef";
|
||||
unsigned int j;
|
||||
|
||||
/* Global state. */
|
||||
static int seed_initialized = 0;
|
||||
static unsigned char seed[20]; /* The SHA1 seed, from /dev/urandom. */
|
||||
static uint64_t counter = 0; /* The counter we hash with the seed. */
|
||||
|
||||
if (!seed_initialized) {
|
||||
/* Initialize a seed and use SHA1 in counter mode, where we hash
|
||||
* the same seed with a progressive counter. For the goals of this
|
||||
* function we just need non-colliding strings, there are no
|
||||
* cryptographic security needs. */
|
||||
FILE *fp = fopen("/dev/urandom","r");
|
||||
if (fp && fread(seed,sizeof(seed),1,fp) == 1)
|
||||
seed_initialized = 1;
|
||||
if (fp) fclose(fp);
|
||||
}
|
||||
|
||||
if (seed_initialized) {
|
||||
while(len) {
|
||||
unsigned char digest[20];
|
||||
SHA1_CTX ctx;
|
||||
unsigned int copylen = len > 20 ? 20 : len;
|
||||
|
||||
SHA1Init(&ctx);
|
||||
SHA1Update(&ctx, seed, sizeof(seed));
|
||||
SHA1Update(&ctx, (unsigned char*)&counter,sizeof(counter));
|
||||
SHA1Final(digest, &ctx);
|
||||
counter++;
|
||||
|
||||
memcpy(p,digest,copylen);
|
||||
/* Convert to hex digits. */
|
||||
for (j = 0; j < copylen; j++) p[j] = charset[p[j] & 0x0F];
|
||||
len -= copylen;
|
||||
p += copylen;
|
||||
}
|
||||
} else {
|
||||
if (fp == NULL || fread(p,len,1,fp) == 0) {
|
||||
/* If we can't read from /dev/urandom, do some reasonable effort
|
||||
* in order to create some entropy, since this function is used to
|
||||
* generate run_id and cluster instance IDs */
|
||||
@@ -506,12 +395,14 @@ void getRandomHexChars(char *p, unsigned int len) {
|
||||
x += sizeof(pid);
|
||||
}
|
||||
/* Finally xor it with rand() output, that was already seeded with
|
||||
* time() at startup, and convert to hex digits. */
|
||||
for (j = 0; j < len; j++) {
|
||||
* time() at startup. */
|
||||
for (j = 0; j < len; j++)
|
||||
p[j] ^= rand();
|
||||
p[j] = charset[p[j] & 0x0F];
|
||||
}
|
||||
}
|
||||
/* Turn it into hex digits taking just 4 bits out of 8 for every byte. */
|
||||
for (j = 0; j < len; j++)
|
||||
p[j] = charset[p[j] & 0x0F];
|
||||
if (fp) fclose(fp);
|
||||
}
|
||||
|
||||
/* Given the filename, return the absolute path as an SDS string, or NULL
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
#define REDIS_VERSION "3.0.5"
|
||||
#define REDIS_VERSION "2.9.999"
|
||||
|
||||
+17
-18
@@ -183,7 +183,7 @@ static unsigned int zipIntSize(unsigned char encoding) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Encode the length 'rawlen' writing it in 'p'. If p is NULL it just returns
|
||||
/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
|
||||
* the amount of bytes required to encode such a length. */
|
||||
static unsigned int zipEncodeLength(unsigned char *p, unsigned char encoding, unsigned int rawlen) {
|
||||
unsigned char len = 1, buf[5];
|
||||
@@ -576,19 +576,19 @@ static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsig
|
||||
|
||||
/* Insert item at "p". */
|
||||
static unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
|
||||
size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), reqlen;
|
||||
unsigned int prevlensize, prevlen = 0;
|
||||
size_t curlen = intrev32ifbe(ZIPLIST_BYTES(zl)), reqlen, prevlen = 0;
|
||||
size_t offset;
|
||||
int nextdiff = 0;
|
||||
unsigned char encoding = 0;
|
||||
long long value = 123456789; /* initialized to avoid warning. Using a value
|
||||
that is easy to see if for some reason
|
||||
we use it uninitialized. */
|
||||
zlentry tail;
|
||||
zlentry entry, tail;
|
||||
|
||||
/* Find out prevlen for the entry that is inserted. */
|
||||
if (p[0] != ZIP_END) {
|
||||
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
|
||||
entry = zipEntry(p);
|
||||
prevlen = entry.prevrawlen;
|
||||
} else {
|
||||
unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl);
|
||||
if (ptail[0] != ZIP_END) {
|
||||
@@ -676,15 +676,15 @@ unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int sle
|
||||
* doesn't contain an element at the provided index, NULL is returned. */
|
||||
unsigned char *ziplistIndex(unsigned char *zl, int index) {
|
||||
unsigned char *p;
|
||||
unsigned int prevlensize, prevlen = 0;
|
||||
zlentry entry;
|
||||
if (index < 0) {
|
||||
index = (-index)-1;
|
||||
p = ZIPLIST_ENTRY_TAIL(zl);
|
||||
if (p[0] != ZIP_END) {
|
||||
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
|
||||
while (prevlen > 0 && index--) {
|
||||
p -= prevlen;
|
||||
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
|
||||
entry = zipEntry(p);
|
||||
while (entry.prevrawlen > 0 && index--) {
|
||||
p -= entry.prevrawlen;
|
||||
entry = zipEntry(p);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -722,7 +722,7 @@ unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
|
||||
|
||||
/* Return pointer to previous entry in ziplist. */
|
||||
unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
|
||||
unsigned int prevlensize, prevlen = 0;
|
||||
zlentry entry;
|
||||
|
||||
/* Iterating backwards from ZIP_END should return the tail. When "p" is
|
||||
* equal to the first element of the list, we're already at the head,
|
||||
@@ -733,14 +733,14 @@ unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
|
||||
} else if (p == ZIPLIST_ENTRY_HEAD(zl)) {
|
||||
return NULL;
|
||||
} else {
|
||||
ZIP_DECODE_PREVLEN(p, prevlensize, prevlen);
|
||||
assert(prevlen > 0);
|
||||
return p-prevlen;
|
||||
entry = zipEntry(p);
|
||||
assert(entry.prevrawlen > 0);
|
||||
return p-entry.prevrawlen;
|
||||
}
|
||||
}
|
||||
|
||||
/* Get entry pointed to by 'p' and store in either '*sstr' or 'sval' depending
|
||||
* on the encoding of the entry. '*sstr' is always set to NULL to be able
|
||||
/* Get entry pointed to by 'p' and store in either 'e' or 'v' depending
|
||||
* on the encoding of the entry. 'e' is always set to NULL to be able
|
||||
* to find out whether the string pointer or the integer value was set.
|
||||
* Return 0 if 'p' points to the end of the ziplist, 1 otherwise. */
|
||||
unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
|
||||
@@ -788,8 +788,7 @@ unsigned char *ziplistDeleteRange(unsigned char *zl, unsigned int index, unsigne
|
||||
return (p == NULL) ? zl : __ziplistDelete(zl,p,num);
|
||||
}
|
||||
|
||||
/* Compare entry pointer to by 'p' with 'sstr' of length 'slen'. */
|
||||
/* Return 1 if equal. */
|
||||
/* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
|
||||
unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
|
||||
zlentry entry;
|
||||
unsigned char sencoding;
|
||||
|
||||
+3
-2
@@ -51,9 +51,10 @@
|
||||
* <len> is the length of the following string (key or value).
|
||||
* <len> lengths are encoded in a single value or in a 5 bytes value.
|
||||
* If the first byte value (as an unsigned 8 bit value) is between 0 and
|
||||
* 253, it's a single-byte length. If it is 254 then a four bytes unsigned
|
||||
* 252, it's a single-byte length. If it is 253 then a four bytes unsigned
|
||||
* integer follows (in the host byte ordering). A value of 255 is used to
|
||||
* signal the end of the hash.
|
||||
* signal the end of the hash. The special value 254 is used to mark
|
||||
* empty space that can be used to add new key/value pairs.
|
||||
*
|
||||
* <free> is the number of free unused bytes after the string, resulting
|
||||
* from modification of values associated to a key. For instance if "foo"
|
||||
|
||||
+6
-18
@@ -328,39 +328,27 @@ float zmalloc_get_fragmentation_ratio(size_t rss) {
|
||||
return (float)rss/zmalloc_used_memory();
|
||||
}
|
||||
|
||||
/* Get the sum of the specified field (converted form kb to bytes) in
|
||||
* /proc/self/smaps. The field must be specified with trailing ":" as it
|
||||
* apperas in the smaps output.
|
||||
*
|
||||
* Example: zmalloc_get_smap_bytes_by_field("Rss:");
|
||||
*/
|
||||
#if defined(HAVE_PROC_SMAPS)
|
||||
size_t zmalloc_get_smap_bytes_by_field(char *field) {
|
||||
size_t zmalloc_get_private_dirty(void) {
|
||||
char line[1024];
|
||||
size_t bytes = 0;
|
||||
size_t pd = 0;
|
||||
FILE *fp = fopen("/proc/self/smaps","r");
|
||||
int flen = strlen(field);
|
||||
|
||||
if (!fp) return 0;
|
||||
while(fgets(line,sizeof(line),fp) != NULL) {
|
||||
if (strncmp(line,field,flen) == 0) {
|
||||
if (strncmp(line,"Private_Dirty:",14) == 0) {
|
||||
char *p = strchr(line,'k');
|
||||
if (p) {
|
||||
*p = '\0';
|
||||
bytes += strtol(line+flen,NULL,10) * 1024;
|
||||
pd += strtol(line+14,NULL,10) * 1024;
|
||||
}
|
||||
}
|
||||
}
|
||||
fclose(fp);
|
||||
return bytes;
|
||||
return pd;
|
||||
}
|
||||
#else
|
||||
size_t zmalloc_get_smap_bytes_by_field(char *field) {
|
||||
((void) field);
|
||||
size_t zmalloc_get_private_dirty(void) {
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
size_t zmalloc_get_private_dirty(void) {
|
||||
return zmalloc_get_smap_bytes_by_field("Private_Dirty:");
|
||||
}
|
||||
|
||||
@@ -76,7 +76,6 @@ void zmalloc_set_oom_handler(void (*oom_handler)(size_t));
|
||||
float zmalloc_get_fragmentation_ratio(size_t rss);
|
||||
size_t zmalloc_get_rss(void);
|
||||
size_t zmalloc_get_private_dirty(void);
|
||||
size_t zmalloc_get_smap_bytes_by_field(char *field);
|
||||
void zlibc_free(void *ptr);
|
||||
|
||||
#ifndef HAVE_MALLOC_SIZE
|
||||
|
||||
@@ -9,7 +9,6 @@ bind 127.0.0.1
|
||||
loglevel verbose
|
||||
logfile ''
|
||||
databases 16
|
||||
latency-monitor-threshold 1
|
||||
|
||||
save 900 1
|
||||
save 300 10
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Cluster-specific test functions.
|
||||
#
|
||||
# Copyright (C) 2014 Salvatore Sanfilippo antirez@gmail.com
|
||||
# This software is released under the BSD License. See the COPYING file for
|
||||
# This softare is released under the BSD License. See the COPYING file for
|
||||
# more information.
|
||||
|
||||
# Returns a parsed CLUSTER NODES output as a list of dictionaries.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Cluster test suite. Copyright (C) 2014 Salvatore Sanfilippo antirez@gmail.com
|
||||
# This software is released under the BSD License. See the COPYING file for
|
||||
# This softare is released under the BSD License. See the COPYING file for
|
||||
# more information.
|
||||
|
||||
cd tests/cluster
|
||||
@@ -17,12 +17,10 @@ proc main {} {
|
||||
}
|
||||
run_tests
|
||||
cleanup
|
||||
end_tests
|
||||
}
|
||||
|
||||
if {[catch main e]} {
|
||||
puts $::errorInfo
|
||||
if {$::pause_on_error} pause_on_error
|
||||
cleanup
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -49,18 +49,6 @@ while {[incr iterations -1]} {
|
||||
set slave_config_epoch [CI $slave cluster_my_epoch]
|
||||
}
|
||||
|
||||
test "Cluster is writable before failover" {
|
||||
for {set i 0} {$i < 100} {incr i} {
|
||||
catch {$cluster set $key:$i $val:$i} err
|
||||
assert {$err eq {OK}}
|
||||
}
|
||||
# Wait for the write to propagate to the slave if we
|
||||
# are going to kill a master.
|
||||
if {$role eq {master}} {
|
||||
R $tokill wait 1 20000
|
||||
}
|
||||
}
|
||||
|
||||
test "Killing node #$tokill" {
|
||||
kill_instance redis $tokill
|
||||
}
|
||||
@@ -79,9 +67,9 @@ while {[incr iterations -1]} {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "Cluster is writable again" {
|
||||
test "Cluster is writable" {
|
||||
for {set i 0} {$i < 100} {incr i} {
|
||||
catch {$cluster set $key:$i:2 $val:$i:2} err
|
||||
catch {$cluster set $key:$i $val:$i} err
|
||||
assert {$err eq {OK}}
|
||||
}
|
||||
}
|
||||
@@ -89,7 +77,7 @@ while {[incr iterations -1]} {
|
||||
test "Restarting node #$tokill" {
|
||||
restart_instance redis $tokill
|
||||
}
|
||||
|
||||
|
||||
test "Instance #$tokill is now a slave" {
|
||||
wait_for_condition 1000 50 {
|
||||
[RI $tokill role] eq {slave}
|
||||
@@ -102,8 +90,6 @@ while {[incr iterations -1]} {
|
||||
for {set i 0} {$i < 100} {incr i} {
|
||||
catch {$cluster get $key:$i} err
|
||||
assert {$err eq "$val:$i"}
|
||||
catch {$cluster get $key:$i:2} err
|
||||
assert {$err eq "$val:$i:2"}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
# Failover stress test.
|
||||
# In this test a different node is killed in a loop for N
|
||||
# iterations. The test checks that certain properties
|
||||
# are preseved across iterations.
|
||||
|
||||
source "../tests/includes/init-tests.tcl"
|
||||
|
||||
test "Create a 5 nodes cluster" {
|
||||
create_cluster 5 5
|
||||
}
|
||||
|
||||
test "Cluster is up" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
# Return nno-zero if the specified PID is about a process still in execution,
|
||||
# otherwise 0 is returned.
|
||||
proc process_is_running {pid} {
|
||||
# PS should return with an error if PID is non existing,
|
||||
# and catch will return non-zero. We want to return non-zero if
|
||||
# the PID exists, so we invert the return value with expr not operator.
|
||||
expr {![catch {exec ps -p $pid}]}
|
||||
}
|
||||
|
||||
# Our resharding test performs the following actions:
|
||||
#
|
||||
# - N commands are sent to the cluster in the course of the test.
|
||||
# - Every command selects a random key from key:0 to key:MAX-1.
|
||||
# - The operation RPUSH key <randomvalue> is perforemd.
|
||||
# - Tcl remembers into an array all the values pushed to each list.
|
||||
# - After N/2 commands, the resharding process is started in background.
|
||||
# - The test continues while the resharding is in progress.
|
||||
# - At the end of the test, we wait for the resharding process to stop.
|
||||
# - Finally the keys are checked to see if they contain the value they should.
|
||||
|
||||
set numkeys 50000
|
||||
set numops 200000
|
||||
set cluster [redis_cluster 127.0.0.1:[get_instance_attrib redis 0 port]]
|
||||
catch {unset content}
|
||||
array set content {}
|
||||
set tribpid {}
|
||||
|
||||
test "Cluster consistency during live resharding" {
|
||||
for {set j 0} {$j < $numops} {incr j} {
|
||||
# Trigger the resharding once we execute half the ops.
|
||||
if {$tribpid ne {} &&
|
||||
($j % 10000) == 0 &&
|
||||
![process_is_running $tribpid]} {
|
||||
set tribpid {}
|
||||
}
|
||||
|
||||
if {$j >= $numops/2 && $tribpid eq {}} {
|
||||
puts -nonewline "...Starting resharding..."
|
||||
flush stdout
|
||||
set target [dict get [get_myself [randomInt 5]] id]
|
||||
set tribpid [lindex [exec \
|
||||
../../../src/redis-trib.rb reshard \
|
||||
--from all \
|
||||
--to $target \
|
||||
--slots 100 \
|
||||
--yes \
|
||||
127.0.0.1:[get_instance_attrib redis 0 port] \
|
||||
| [info nameofexecutable] \
|
||||
../tests/helpers/onlydots.tcl \
|
||||
&] 0]
|
||||
}
|
||||
|
||||
# Write random data to random list.
|
||||
set listid [randomInt $numkeys]
|
||||
set key "key:$listid"
|
||||
set ele [randomValue]
|
||||
# We write both with Lua scripts and with plain commands.
|
||||
# This way we are able to stress Lua -> Redis command invocation
|
||||
# as well, that has tests to prevent Lua to write into wrong
|
||||
# hash slots.
|
||||
if {$listid % 2} {
|
||||
$cluster rpush $key $ele
|
||||
} else {
|
||||
$cluster eval {redis.call("rpush",KEYS[1],ARGV[1])} 1 $key $ele
|
||||
}
|
||||
lappend content($key) $ele
|
||||
|
||||
if {($j % 1000) == 0} {
|
||||
puts -nonewline W; flush stdout
|
||||
}
|
||||
}
|
||||
|
||||
# Wait for the resharding process to end
|
||||
wait_for_condition 1000 500 {
|
||||
[process_is_running $tribpid] == 0
|
||||
} else {
|
||||
fail "Resharding is not terminating after some time."
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
test "Verify $numkeys keys for consistency with logical content" {
|
||||
# Check that the Redis Cluster content matches our logical content.
|
||||
foreach {key value} [array get content] {
|
||||
assert {[$cluster lrange $key 0 -1] eq $value}
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
# Slave selection test
|
||||
# Check the algorithm trying to pick the slave with the most complete history.
|
||||
|
||||
source "../tests/includes/init-tests.tcl"
|
||||
|
||||
# Create a cluster with 5 master and 10 slaves, so that we have 2
|
||||
# slaves for each master.
|
||||
test "Create a 5 nodes cluster" {
|
||||
create_cluster 5 10
|
||||
}
|
||||
|
||||
test "Cluster is up" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "The first master has actually two slaves" {
|
||||
assert {[llength [lindex [R 0 role] 2]] == 2}
|
||||
}
|
||||
|
||||
test {Slaves of #0 are instance #5 and #10 as expected} {
|
||||
set port0 [get_instance_attrib redis 0 port]
|
||||
assert {[lindex [R 5 role] 2] == $port0}
|
||||
assert {[lindex [R 10 role] 2] == $port0}
|
||||
}
|
||||
|
||||
test "Instance #5 and #10 synced with the master" {
|
||||
wait_for_condition 1000 50 {
|
||||
[RI 5 master_link_status] eq {up} &&
|
||||
[RI 10 master_link_status] eq {up}
|
||||
} else {
|
||||
fail "Instance #5 or #10 master link status is not up"
|
||||
}
|
||||
}
|
||||
|
||||
set cluster [redis_cluster 127.0.0.1:[get_instance_attrib redis 0 port]]
|
||||
|
||||
test "Slaves are both able to receive and acknowledge writes" {
|
||||
for {set j 0} {$j < 100} {incr j} {
|
||||
$cluster set $j $j
|
||||
}
|
||||
assert {[R 0 wait 2 60000] == 2}
|
||||
}
|
||||
|
||||
test "Write data while slave #10 is paused and can't receive it" {
|
||||
# Stop the slave with a multi/exec transaction so that the master will
|
||||
# be killed as soon as it can accept writes again.
|
||||
R 10 multi
|
||||
R 10 debug sleep 10
|
||||
R 10 client kill 127.0.0.1:$port0
|
||||
R 10 deferred 1
|
||||
R 10 exec
|
||||
|
||||
# Write some data the slave can't receive.
|
||||
for {set j 0} {$j < 100} {incr j} {
|
||||
$cluster set $j $j
|
||||
}
|
||||
|
||||
# Prevent the master from accepting new slaves.
|
||||
# Use a large pause value since we'll kill it anyway.
|
||||
R 0 CLIENT PAUSE 60000
|
||||
|
||||
# Wait for the slave to return available again
|
||||
R 10 deferred 0
|
||||
assert {[R 10 read] eq {OK OK}}
|
||||
|
||||
# Kill the master so that a reconnection will not be possible.
|
||||
kill_instance redis 0
|
||||
}
|
||||
|
||||
test "Wait for instance #5 (and not #10) to turn into a master" {
|
||||
wait_for_condition 1000 50 {
|
||||
[RI 5 role] eq {master}
|
||||
} else {
|
||||
fail "No failover detected"
|
||||
}
|
||||
}
|
||||
|
||||
test "Wait for the node #10 to return alive before ending the test" {
|
||||
R 10 ping
|
||||
}
|
||||
|
||||
test "Cluster should eventually be up again" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "Node #10 should eventually replicate node #5" {
|
||||
set port5 [get_instance_attrib redis 5 port]
|
||||
wait_for_condition 1000 50 {
|
||||
([lindex [R 10 role] 2] == $port5) &&
|
||||
([lindex [R 10 role] 3] eq {connected})
|
||||
} else {
|
||||
fail "#10 didn't became slave of #5"
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
# Slave stop condition test
|
||||
# Check that if there is a disconnection time limit, the slave will not try
|
||||
# to failover its master.
|
||||
|
||||
source "../tests/includes/init-tests.tcl"
|
||||
|
||||
# Create a cluster with 5 master and 5 slaves.
|
||||
test "Create a 5 nodes cluster" {
|
||||
create_cluster 5 5
|
||||
}
|
||||
|
||||
test "Cluster is up" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "The first master has actually one slave" {
|
||||
assert {[llength [lindex [R 0 role] 2]] == 1}
|
||||
}
|
||||
|
||||
test {Slaves of #0 is instance #5 as expected} {
|
||||
set port0 [get_instance_attrib redis 0 port]
|
||||
assert {[lindex [R 5 role] 2] == $port0}
|
||||
}
|
||||
|
||||
test "Instance #5 synced with the master" {
|
||||
wait_for_condition 1000 50 {
|
||||
[RI 5 master_link_status] eq {up}
|
||||
} else {
|
||||
fail "Instance #5 master link status is not up"
|
||||
}
|
||||
}
|
||||
|
||||
test "Lower the slave validity factor of #5 to the value of 2" {
|
||||
assert {[R 5 config set cluster-slave-validity-factor 2] eq {OK}}
|
||||
}
|
||||
|
||||
test "Break master-slave link and prevent further reconnections" {
|
||||
# Stop the slave with a multi/exec transaction so that the master will
|
||||
# be killed as soon as it can accept writes again.
|
||||
R 5 multi
|
||||
R 5 client kill 127.0.0.1:$port0
|
||||
# here we should sleep 6 or more seconds (node_timeout * slave_validity)
|
||||
# but the actual validity time is actually incremented by the
|
||||
# repl-ping-slave-period value which is 10 seconds by default. So we
|
||||
# need to wait more than 16 seconds.
|
||||
R 5 debug sleep 20
|
||||
R 5 deferred 1
|
||||
R 5 exec
|
||||
|
||||
# Prevent the master from accepting new slaves.
|
||||
# Use a large pause value since we'll kill it anyway.
|
||||
R 0 CLIENT PAUSE 60000
|
||||
|
||||
# Wait for the slave to return available again
|
||||
R 5 deferred 0
|
||||
assert {[R 5 read] eq {OK OK}}
|
||||
|
||||
# Kill the master so that a reconnection will not be possible.
|
||||
kill_instance redis 0
|
||||
}
|
||||
|
||||
test "Slave #5 is reachable and alive" {
|
||||
assert {[R 5 ping] eq {PONG}}
|
||||
}
|
||||
|
||||
test "Slave #5 should not be able to failover" {
|
||||
after 10000
|
||||
assert {[RI 5 role] eq {slave}}
|
||||
}
|
||||
|
||||
test "Cluster should be down" {
|
||||
assert_cluster_state fail
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
# Replica migration test.
|
||||
# Check that orphaned masters are joined by replicas of masters having
|
||||
# multiple replicas attached, according to the migration barrier settings.
|
||||
|
||||
source "../tests/includes/init-tests.tcl"
|
||||
|
||||
# Create a cluster with 5 master and 10 slaves, so that we have 2
|
||||
# slaves for each master.
|
||||
test "Create a 5 nodes cluster" {
|
||||
create_cluster 5 10
|
||||
}
|
||||
|
||||
test "Cluster is up" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "Each master should have two replicas attached" {
|
||||
foreach_redis_id id {
|
||||
if {$id < 5} {
|
||||
wait_for_condition 1000 50 {
|
||||
[llength [lindex [R 0 role] 2]] == 2
|
||||
} else {
|
||||
fail "Master #$id does not have 2 slaves as expected"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test "Killing all the slaves of master #0 and #1" {
|
||||
kill_instance redis 5
|
||||
kill_instance redis 10
|
||||
kill_instance redis 6
|
||||
kill_instance redis 11
|
||||
after 4000
|
||||
}
|
||||
|
||||
foreach_redis_id id {
|
||||
if {$id < 5} {
|
||||
test "Master #$id should have at least one replica" {
|
||||
wait_for_condition 1000 50 {
|
||||
[llength [lindex [R $id role] 2]] >= 1
|
||||
} else {
|
||||
fail "Master #$id has no replicas"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
# Test UPDATE messages sent by other nodes when the currently authorirative
|
||||
# master is unavaialble. The test is performed in the following steps:
|
||||
#
|
||||
# 1) Master goes down.
|
||||
# 2) Slave failover and becomes new master.
|
||||
# 3) New master is partitoned away.
|
||||
# 4) Old master returns.
|
||||
# 5) At this point we expect the old master to turn into a slave ASAP because
|
||||
# of the UPDATE messages it will receive from the other nodes when its
|
||||
# configuration will be found to be outdated.
|
||||
|
||||
source "../tests/includes/init-tests.tcl"
|
||||
|
||||
test "Create a 5 nodes cluster" {
|
||||
create_cluster 5 5
|
||||
}
|
||||
|
||||
test "Cluster is up" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "Cluster is writable" {
|
||||
cluster_write_test 0
|
||||
}
|
||||
|
||||
test "Instance #5 is a slave" {
|
||||
assert {[RI 5 role] eq {slave}}
|
||||
}
|
||||
|
||||
test "Instance #5 synced with the master" {
|
||||
wait_for_condition 1000 50 {
|
||||
[RI 5 master_link_status] eq {up}
|
||||
} else {
|
||||
fail "Instance #5 master link status is not up"
|
||||
}
|
||||
}
|
||||
|
||||
set current_epoch [CI 1 cluster_current_epoch]
|
||||
|
||||
test "Killing one master node" {
|
||||
kill_instance redis 0
|
||||
}
|
||||
|
||||
test "Wait for failover" {
|
||||
wait_for_condition 1000 50 {
|
||||
[CI 1 cluster_current_epoch] > $current_epoch
|
||||
} else {
|
||||
fail "No failover detected"
|
||||
}
|
||||
}
|
||||
|
||||
test "Cluster should eventually be up again" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
|
||||
test "Cluster is writable" {
|
||||
cluster_write_test 1
|
||||
}
|
||||
|
||||
test "Instance #5 is now a master" {
|
||||
assert {[RI 5 role] eq {master}}
|
||||
}
|
||||
|
||||
test "Killing the new master #5" {
|
||||
kill_instance redis 5
|
||||
}
|
||||
|
||||
test "Cluster should be down now" {
|
||||
assert_cluster_state fail
|
||||
}
|
||||
|
||||
test "Restarting the old master node" {
|
||||
restart_instance redis 0
|
||||
}
|
||||
|
||||
test "Instance #0 gets converted into a slave" {
|
||||
wait_for_condition 1000 50 {
|
||||
[RI 0 role] eq {slave}
|
||||
} else {
|
||||
fail "Old master was not converted into slave"
|
||||
}
|
||||
}
|
||||
|
||||
test "Restarting the new master node" {
|
||||
restart_instance redis 5
|
||||
}
|
||||
|
||||
test "Cluster is up again" {
|
||||
assert_cluster_state ok
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
# Test PUBLISH propagation across the cluster.
|
||||
|
||||
source "../tests/includes/init-tests.tcl"
|
||||
|
||||
test "Create a 5 nodes cluster" {
|
||||
create_cluster 5 5
|
||||
}
|
||||
|
||||
proc test_cluster_publish {instance instances} {
|
||||
# Subscribe all the instances but the one we use to send.
|
||||
for {set j 0} {$j < $instances} {incr j} {
|
||||
if {$j != $instance} {
|
||||
R $j deferred 1
|
||||
R $j subscribe testchannel
|
||||
R $j read; # Read the subscribe reply
|
||||
}
|
||||
}
|
||||
|
||||
set data [randomValue]
|
||||
R $instance PUBLISH testchannel $data
|
||||
|
||||
# Read the message back from all the nodes.
|
||||
for {set j 0} {$j < $instances} {incr j} {
|
||||
if {$j != $instance} {
|
||||
set msg [R $j read]
|
||||
assert {$data eq [lindex $msg 2]}
|
||||
R $j unsubscribe testchannel
|
||||
R $j read; # Read the unsubscribe reply
|
||||
R $j deferred 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test "Test publishing to master" {
|
||||
test_cluster_publish 0 10
|
||||
}
|
||||
|
||||
test "Test publishing to slave" {
|
||||
test_cluster_publish 5 10
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user