Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01671edcca | ||
|
|
5f185413df | ||
|
|
2a11e94fdd |
@@ -4,7 +4,6 @@
|
||||
dump.rdb
|
||||
redis-benchmark
|
||||
redis-check-aof
|
||||
redis-check-rdb
|
||||
redis-check-dump
|
||||
redis-cli
|
||||
redis-sentinel
|
||||
|
||||
+1
-3
@@ -20,7 +20,7 @@ each source file that you contribute.
|
||||
|
||||
# How to provide a patch for a new feature
|
||||
|
||||
1. If it is a major feature or a semantical change, write an RCP (Redis Change Proposal). Check the documentation here: https://github.com/redis/redis-rcp
|
||||
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:
|
||||
@@ -31,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!
|
||||
|
||||
+19
-56
@@ -1,35 +1,18 @@
|
||||
This README is just a fast *quick start* document. You can find more detailed documentation at http://redis.io.
|
||||
Where to find complete Redis documentation?
|
||||
-------------------------------------------
|
||||
|
||||
What is Redis?
|
||||
--------------
|
||||
|
||||
Redis is often referred as a *data structures* server. What this means is that Redis provides access to mutable data structures via a set of commands, which are send using a *server-client* model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.
|
||||
|
||||
Data structures implemented into Redis have a few special properties:
|
||||
|
||||
* Redis cares to store them on disk, even if they are always served and modified into the server memory. This means that Redis is fast, but that is also non-volatile.
|
||||
* Implementation of data structures stress on memory efficiency, so data structures inside Redis will likely use less memory compared to the same data structure modeled using an high level programming language.
|
||||
* Redis offers a number of features that are natural to find into a database, like replication, tunable levels of durability, cluster, high availability.
|
||||
|
||||
Another good example is to think at Redis as a more complex version of memcached, where the opeations are not just SETs and GETs, but operations to work with complex data types like Lists, Sets, ordered data structures, and so forth.
|
||||
|
||||
If you want to know more, this is a list of selected starting points:
|
||||
|
||||
* Introduction to Redis data types. http://redis.io/topics/data-types-intro
|
||||
* Try Redis directly inside your browser. http://try.redis.io
|
||||
* The full list of Redis commands. http://redis.io/commands
|
||||
* There is much more inside the Redis official documentation. http://redis.io/documentation
|
||||
This README is just a fast "quick start" document. You can find more detailed
|
||||
documentation at http://redis.io
|
||||
|
||||
Building Redis
|
||||
--------------
|
||||
|
||||
Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD.
|
||||
We support big endian and little endian architectures, and both 32 bit
|
||||
and 64 bit systems.
|
||||
We support big endian and little endian architectures.
|
||||
|
||||
It may compile on Solaris derived systems (for instance SmartOS) but our
|
||||
support for this platform is *best effort* and Redis is not guaranteed to
|
||||
work as well as in Linux, OSX, and \*BSD there.
|
||||
support for this platform is "best effort" and Redis is not guaranteed to
|
||||
work as well as in Linux, OSX, and *BSD there.
|
||||
|
||||
It is as simple as:
|
||||
|
||||
@@ -43,39 +26,20 @@ 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
|
||||
---------
|
||||
|
||||
If after building Redis with a 32 bit target you need to rebuild it
|
||||
with a 64 bit target, or the other way around, you need to perform a
|
||||
`make distclean` in the root directory of the Redis distribution.
|
||||
"make distclean" in the root directory of the Redis distribution.
|
||||
|
||||
In case of build errors when trying to build a 32 bit binary of Redis, try
|
||||
the following steps:
|
||||
|
||||
* Install the packages libc6-dev-i386 (also try g++-multilib).
|
||||
* Try using the following command line instead of `make 32bit`:
|
||||
`make CFLAGS="-m32 -march=native" LDFLAGS="-m32"`
|
||||
* Try using the following command line instead of "make 32bit":
|
||||
|
||||
make CFLAGS="-m32 -march=native" LDFLAGS="-m32"
|
||||
|
||||
Allocator
|
||||
---------
|
||||
@@ -143,9 +107,11 @@ then in another terminal try the following:
|
||||
(integer) 1
|
||||
redis> incr mycounter
|
||||
(integer) 2
|
||||
redis>
|
||||
redis>
|
||||
|
||||
You can find the list of all the available commands at http://redis.io/commands.
|
||||
You can find the list of all the available commands here:
|
||||
|
||||
http://redis.io/commands
|
||||
|
||||
Installing Redis
|
||||
-----------------
|
||||
@@ -154,7 +120,7 @@ In order to install Redis binaries into /usr/local/bin just use:
|
||||
|
||||
% make install
|
||||
|
||||
You can use `make PREFIX=/some/other/directory install` if you wish to use a
|
||||
You can use "make PREFIX=/some/other/directory install" if you wish to use a
|
||||
different destination.
|
||||
|
||||
Make install will just install binaries in your system, but will not configure
|
||||
@@ -171,7 +137,7 @@ to run Redis properly as a background daemon that will start again on
|
||||
system reboots.
|
||||
|
||||
You'll be able to stop and start Redis using the script named
|
||||
`/etc/init.d/redis_<portnumber>`, for instance `/etc/init.d/redis_6379`.
|
||||
/etc/init.d/redis_<portnumber>, for instance /etc/init.d/redis_6379.
|
||||
|
||||
Code contributions
|
||||
---
|
||||
@@ -179,13 +145,10 @@ Code contributions
|
||||
Note: by contributing code to the Redis project in any form, including sending
|
||||
a pull request via Github, a code fragment or patch via private email or
|
||||
public discussion groups, you agree to release your code under the terms
|
||||
of the BSD license that you can find in the [COPYING][1] file included in the Redis
|
||||
of the BSD license that you can find in the COPYING file included in the Redis
|
||||
source distribution.
|
||||
|
||||
Please see the [CONTRIBUTING][2] file in this source distribution for more
|
||||
Please see the CONTRIBUTING file in this source distribution for more
|
||||
information.
|
||||
|
||||
Enjoy!
|
||||
|
||||
[1]: https://github.com/antirez/redis/blob/unstable/COPYING
|
||||
[2]: https://github.com/antirez/redis/blob/unstable/CONTRIBUTING
|
||||
Vendored
+1
-1
@@ -58,7 +58,7 @@ ifeq ($(uname_S),SunOS)
|
||||
LUA_CFLAGS= -D__C99FEATURES__=1
|
||||
endif
|
||||
|
||||
LUA_CFLAGS+= -O2 -Wall -DLUA_ANSI -DENABLE_CJSON_GLOBAL -DREDIS_STATIC='' $(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
|
||||
|
||||
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
-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
+114
-342
@@ -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. */
|
||||
static void memrevifle(void *ptr, size_t len) {
|
||||
unsigned char *p = (unsigned char *)ptr,
|
||||
*e = (unsigned char *)p+len-1,
|
||||
aux;
|
||||
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,44 +56,30 @@ static 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;
|
||||
|
||||
static 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);
|
||||
}
|
||||
|
||||
static 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;
|
||||
}
|
||||
|
||||
static void mp_buf_append(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
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 @@ static 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;
|
||||
|
||||
static 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,7 +136,7 @@ static void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
|
||||
} \
|
||||
} while(0)
|
||||
|
||||
/* ------------------------- Low level MP encoding -------------------------- */
|
||||
/* --------------------------- Low level MP encoding -------------------------- */
|
||||
|
||||
static void mp_encode_bytes(mp_buf *buf, const unsigned char *s, size_t len) {
|
||||
unsigned char hdr[5];
|
||||
@@ -254,7 +219,7 @@ static 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 */
|
||||
@@ -334,7 +299,7 @@ static void mp_encode_map(mp_buf *buf, int64_t n) {
|
||||
mp_buf_append(buf,b,enclen);
|
||||
}
|
||||
|
||||
/* --------------------------- Lua types encoding --------------------------- */
|
||||
/* ----------------------------- Lua types encoding --------------------------- */
|
||||
|
||||
static void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
|
||||
size_t len;
|
||||
@@ -349,26 +314,13 @@ static void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
|
||||
mp_buf_append(buf,&b,1);
|
||||
}
|
||||
|
||||
/* Lua 5.3 has a built in 64-bit integer type */
|
||||
static 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 */
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,11 +328,7 @@ static void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
|
||||
|
||||
/* Convert a lua table into a message pack list. */
|
||||
static void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
|
||||
#if LUA_VERSION_NUM < 502
|
||||
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++) {
|
||||
@@ -397,7 +345,7 @@ static void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
|
||||
/* 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. */
|
||||
@@ -419,43 +367,30 @@ static void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
|
||||
* of keys from numerical keys from 1 up to N, with N being the total number
|
||||
* of elements, without any hole in the middle. */
|
||||
static int table_is_an_array(lua_State *L) {
|
||||
int count = 0, max = 0;
|
||||
#if LUA_VERSION_NUM < 503
|
||||
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
|
||||
@@ -470,7 +405,6 @@ static void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
|
||||
|
||||
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);
|
||||
@@ -479,70 +413,33 @@ static void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
|
||||
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.
|
||||
*/
|
||||
static int mp_pack(lua_State *L) {
|
||||
int nargs = lua_gettop(L);
|
||||
int i;
|
||||
mp_buf *buf;
|
||||
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);
|
||||
@@ -555,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 */
|
||||
@@ -570,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) |
|
||||
@@ -616,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) |
|
||||
@@ -625,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) |
|
||||
@@ -638,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) |
|
||||
@@ -699,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 */
|
||||
@@ -720,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);
|
||||
}
|
||||
@@ -739,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;
|
||||
@@ -773,163 +654,54 @@ void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
|
||||
}
|
||||
}
|
||||
|
||||
static int mp_unpack_full(lua_State *L, int limit, int offset) {
|
||||
size_t len;
|
||||
const char *s;
|
||||
mp_cur c;
|
||||
int cnt; /* Number of objects unpacked */
|
||||
int decode_all = (!limit && !offset);
|
||||
|
||||
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 (!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 */
|
||||
}
|
||||
|
||||
return cnt;
|
||||
}
|
||||
|
||||
static int mp_unpack(lua_State *L) {
|
||||
return mp_unpack_full(L, 0, 0);
|
||||
}
|
||||
size_t len;
|
||||
const unsigned char *s;
|
||||
mp_cur *c;
|
||||
|
||||
static 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);
|
||||
}
|
||||
|
||||
static 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);
|
||||
}
|
||||
|
||||
static 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;
|
||||
if (!lua_isstring(L,-1)) {
|
||||
lua_pushstring(L,"MessagePack decoding needs a string as input.");
|
||||
lua_error(L);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
mp_cur_free(c);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
static 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}
|
||||
};
|
||||
|
||||
static 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;
|
||||
|
||||
+25
-88
@@ -30,30 +30,15 @@
|
||||
# include /path/to/local.conf
|
||||
# include /path/to/other.conf
|
||||
|
||||
################################## NETWORK #####################################
|
||||
################################ GENERAL #####################################
|
||||
|
||||
# By default, if no "bind" configuration directive is specified, Redis listens
|
||||
# for connections from all the network interfaces available on the server.
|
||||
# It is possible to listen to just one or multiple selected interfaces using
|
||||
# the "bind" configuration directive, followed by one or more IP addresses.
|
||||
#
|
||||
# Examples:
|
||||
#
|
||||
# bind 192.168.1.100 10.0.0.1
|
||||
# bind 127.0.0.1 ::1
|
||||
#
|
||||
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
|
||||
# internet, binding to all the interfaces is dangerous and will expose the
|
||||
# instance to everybody on the internet. So by default we uncomment the
|
||||
# following bind directive, that will force Redis to listen only into
|
||||
# the IPv4 lookback interface address (this means Redis will be able to
|
||||
# accept connections only from clients running into the same computer it
|
||||
# is running).
|
||||
#
|
||||
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
|
||||
# JUST UNCOMMENT THE FOLLOWING LINE.
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
bind 127.0.0.1
|
||||
# By default Redis does not run as a daemon. Use 'yes' if you need it.
|
||||
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
|
||||
daemonize no
|
||||
|
||||
# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
|
||||
# default. You can specify a custom pid file location here.
|
||||
pidfile /var/run/redis.pid
|
||||
|
||||
# Accept connections on the specified port, default is 6379.
|
||||
# If port 0 is specified Redis will not listen on a TCP socket.
|
||||
@@ -68,8 +53,16 @@ port 6379
|
||||
# in order to get the desired effect.
|
||||
tcp-backlog 511
|
||||
|
||||
# Unix socket.
|
||||
# By default Redis listens for connections from all the network interfaces
|
||||
# available on the server. It is possible to listen to just one or multiple
|
||||
# interfaces using the "bind" configuration directive, followed by one or
|
||||
# more IP addresses.
|
||||
#
|
||||
# Examples:
|
||||
#
|
||||
# bind 192.168.1.100 10.0.0.1
|
||||
# bind 127.0.0.1
|
||||
|
||||
# Specify the path for the Unix socket that will be used to listen for
|
||||
# incoming connections. There is no default, so Redis will not listen
|
||||
# on a unix socket when not specified.
|
||||
@@ -96,27 +89,6 @@ timeout 0
|
||||
# A reasonable value for this option is 60 seconds.
|
||||
tcp-keepalive 0
|
||||
|
||||
################################# GENERAL #####################################
|
||||
|
||||
# By default Redis does not run as a daemon. Use 'yes' if you need it.
|
||||
# Note that Redis will write a pid file in /var/run/redis.pid when daemonized.
|
||||
daemonize no
|
||||
|
||||
# If you run Redis from upstart or systemd, Redis can interact with your
|
||||
# supervision tree. Options:
|
||||
# supervised no - no supervision interaction
|
||||
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
|
||||
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
|
||||
# supervised auto - detect upstart or systemd method based on
|
||||
# UPSTART_JOB or NOTIFY_SOCKET environment variables
|
||||
# Note: these supervision methods only signal "process is ready."
|
||||
# They do not enable continuous liveness pings back to your supervisor.
|
||||
supervised no
|
||||
|
||||
# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
|
||||
# default. You can specify a custom pid file location here.
|
||||
pidfile /var/run/redis.pid
|
||||
|
||||
# Specify the server verbosity level.
|
||||
# This can be one of:
|
||||
# debug (a lot of information, useful for development/testing)
|
||||
@@ -270,10 +242,6 @@ 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.
|
||||
@@ -300,7 +268,7 @@ slave-read-only yes
|
||||
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
|
||||
# the server waits in order to spawn the child that trnasfers the RDB via socket
|
||||
# to the slaves.
|
||||
#
|
||||
# This is important since once the transfer starts, it is not possible to serve
|
||||
@@ -647,12 +615,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:
|
||||
@@ -794,11 +756,11 @@ 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
|
||||
@@ -852,36 +814,11 @@ notify-keyspace-events ""
|
||||
hash-max-ziplist-entries 512
|
||||
hash-max-ziplist-value 64
|
||||
|
||||
# Lists are also encoded in a special way to save a lot of space.
|
||||
# The number of entries allowed per internal list node can be specified
|
||||
# as a fixed maximum size or a maximum number of elements.
|
||||
# For a fixed maximum size, use -5 through -1, meaning:
|
||||
# -5: max size: 64 Kb <-- not recommended for normal workloads
|
||||
# -4: max size: 32 Kb <-- not recommended
|
||||
# -3: max size: 16 Kb <-- probably not recommended
|
||||
# -2: max size: 8 Kb <-- good
|
||||
# -1: max size: 4 Kb <-- good
|
||||
# Positive numbers mean store up to _exactly_ that number of elements
|
||||
# per list node.
|
||||
# The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size),
|
||||
# but if your use case is unique, adjust the settings as necessary.
|
||||
list-max-ziplist-size -2
|
||||
|
||||
# Lists may also be compressed.
|
||||
# Compress depth is the number of quicklist ziplist nodes from *each* side of
|
||||
# the list to *exclude* from compression. The head and tail of the list
|
||||
# are always uncompressed for fast push/pop operations. Settings are:
|
||||
# 0: disable all list compression
|
||||
# 1: depth 1 means "don't start compressing until after 1 node into the list,
|
||||
# going from either the head or tail"
|
||||
# So: [head]->node->node->...->node->[tail]
|
||||
# [head], [tail] will always be uncompressed; inner nodes will compress.
|
||||
# 2: [head]->[next]->node->node->...->node->[prev]->[tail]
|
||||
# 2 here means: don't compress head or head->next or tail->prev or tail,
|
||||
# but compress all nodes between them.
|
||||
# 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail]
|
||||
# etc.
|
||||
list-compress-depth 0
|
||||
# Similarly to hashes, small lists are also encoded in a special way in order
|
||||
# to save a lot of space. The special representation is only used when
|
||||
# you are under the following limits:
|
||||
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
|
||||
|
||||
+12
-20
@@ -18,7 +18,7 @@ OPTIMIZATION?=-O2
|
||||
DEPENDENCY_TARGETS=hiredis linenoise lua
|
||||
|
||||
# Default settings
|
||||
STD=-std=c99 -pedantic -DREDIS_STATIC=''
|
||||
STD=-std=c99 -pedantic
|
||||
WARN=-Wall -W
|
||||
OPT=$(OPTIMIZATION)
|
||||
|
||||
@@ -46,10 +46,6 @@ ifeq ($(USE_JEMALLOC),yes)
|
||||
MALLOC=jemalloc
|
||||
endif
|
||||
|
||||
ifeq ($(USE_JEMALLOC),no)
|
||||
MALLOC=libc
|
||||
endif
|
||||
|
||||
# Override default settings if possible
|
||||
-include .make-settings
|
||||
|
||||
@@ -62,7 +58,7 @@ 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 -lresolv -lpthread
|
||||
else
|
||||
ifeq ($(uname_S),Darwin)
|
||||
# Darwin (nothing to do)
|
||||
@@ -117,16 +113,17 @@ endif
|
||||
|
||||
REDIS_SERVER_NAME=redis-server
|
||||
REDIS_SENTINEL_NAME=redis-sentinel
|
||||
REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o redis.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o
|
||||
REDIS_SERVER_OBJ=adlist.o ae.o anet.o dict.o redis.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o
|
||||
REDIS_CLI_NAME=redis-cli
|
||||
REDIS_CLI_OBJ=anet.o sds.o adlist.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o
|
||||
REDIS_BENCHMARK_NAME=redis-benchmark
|
||||
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o sds.o adlist.o zmalloc.o redis-benchmark.o
|
||||
REDIS_CHECK_RDB_NAME=redis-check-rdb
|
||||
REDIS_CHECK_DUMP_NAME=redis-check-dump
|
||||
REDIS_CHECK_DUMP_OBJ=redis-check-dump.o lzf_c.o lzf_d.o crc64.o
|
||||
REDIS_CHECK_AOF_NAME=redis-check-aof
|
||||
REDIS_CHECK_AOF_OBJ=redis-check-aof.o
|
||||
|
||||
all: $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME)
|
||||
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 ""
|
||||
@@ -177,10 +174,6 @@ $(REDIS_SERVER_NAME): $(REDIS_SERVER_OBJ)
|
||||
$(REDIS_SENTINEL_NAME): $(REDIS_SERVER_NAME)
|
||||
$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME)
|
||||
|
||||
# redis-check-rdb
|
||||
$(REDIS_CHECK_RDB_NAME): $(REDIS_SERVER_NAME)
|
||||
$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(REDIS_CHECK_RDB_NAME)
|
||||
|
||||
# redis-cli
|
||||
$(REDIS_CLI_NAME): $(REDIS_CLI_OBJ)
|
||||
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a ../deps/linenoise/linenoise.o $(FINAL_LIBS)
|
||||
@@ -189,6 +182,10 @@ $(REDIS_CLI_NAME): $(REDIS_CLI_OBJ)
|
||||
$(REDIS_BENCHMARK_NAME): $(REDIS_BENCHMARK_OBJ)
|
||||
$(REDIS_LD) -o $@ $^ ../deps/hiredis/libhiredis.a $(FINAL_LIBS)
|
||||
|
||||
# redis-check-dump
|
||||
$(REDIS_CHECK_DUMP_NAME): $(REDIS_CHECK_DUMP_OBJ)
|
||||
$(REDIS_LD) -o $@ $^ $(FINAL_LIBS)
|
||||
|
||||
# redis-check-aof
|
||||
$(REDIS_CHECK_AOF_NAME): $(REDIS_CHECK_AOF_OBJ)
|
||||
$(REDIS_LD) -o $@ $^ $(FINAL_LIBS)
|
||||
@@ -200,7 +197,7 @@ $(REDIS_CHECK_AOF_NAME): $(REDIS_CHECK_AOF_OBJ)
|
||||
$(REDIS_CC) -c $<
|
||||
|
||||
clean:
|
||||
rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html
|
||||
rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_DUMP_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html
|
||||
|
||||
.PHONY: clean
|
||||
|
||||
@@ -224,10 +221,6 @@ lcov:
|
||||
@geninfo -o redis.info .
|
||||
@genhtml --legend -o lcov-html redis.info
|
||||
|
||||
test-sds: sds.c sds.h
|
||||
$(REDIS_CC) sds.c zmalloc.c -DSDS_TEST_MAIN -o /tmp/sds_test
|
||||
/tmp/sds_test
|
||||
|
||||
.PHONY: lcov
|
||||
|
||||
bench: $(REDIS_BENCHMARK_NAME)
|
||||
@@ -256,6 +249,5 @@ install: all
|
||||
$(REDIS_INSTALL) $(REDIS_SERVER_NAME) $(INSTALL_BIN)
|
||||
$(REDIS_INSTALL) $(REDIS_BENCHMARK_NAME) $(INSTALL_BIN)
|
||||
$(REDIS_INSTALL) $(REDIS_CLI_NAME) $(INSTALL_BIN)
|
||||
$(REDIS_INSTALL) $(REDIS_CHECK_RDB_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)
|
||||
|
||||
+2
-27
@@ -391,7 +391,7 @@ int anetUnixNonBlockConnect(char *err, char *path)
|
||||
* (unless error or EOF condition is encountered) */
|
||||
int anetRead(int fd, char *buf, int count)
|
||||
{
|
||||
ssize_t nread, totlen = 0;
|
||||
int nread, totlen = 0;
|
||||
while(totlen != count) {
|
||||
nread = read(fd,buf,count-totlen);
|
||||
if (nread == 0) return totlen;
|
||||
@@ -406,7 +406,7 @@ int anetRead(int fd, char *buf, int count)
|
||||
* (unless error is encountered) */
|
||||
int anetWrite(int fd, char *buf, int count)
|
||||
{
|
||||
ssize_t nwritten, totlen = 0;
|
||||
int nwritten, totlen = 0;
|
||||
while(totlen != count) {
|
||||
nwritten = write(fd,buf,count-totlen);
|
||||
if (nwritten == 0) return totlen;
|
||||
@@ -589,23 +589,6 @@ error:
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Format an IP,port pair into something easy to parse. If IP is IPv6
|
||||
* (matches for ":"), the ip is surrounded by []. IP and port are just
|
||||
* separated by colons. This the standard to display addresses within Redis. */
|
||||
int anetFormatAddr(char *buf, size_t buf_len, char *ip, int port) {
|
||||
return snprintf(buf,buf_len, strchr(ip,':') ?
|
||||
"[%s]:%d" : "%s:%d", ip, port);
|
||||
}
|
||||
|
||||
/* Like anetFormatAddr() but extract ip and port from the socket's peer. */
|
||||
int anetFormatPeer(int fd, char *buf, size_t buf_len) {
|
||||
char ip[INET6_ADDRSTRLEN];
|
||||
int port;
|
||||
|
||||
anetPeerToString(fd,ip,sizeof(ip),&port);
|
||||
return anetFormatAddr(buf, buf_len, ip, port);
|
||||
}
|
||||
|
||||
int anetSockName(int fd, char *ip, size_t ip_len, int *port) {
|
||||
struct sockaddr_storage sa;
|
||||
socklen_t salen = sizeof(sa);
|
||||
@@ -627,11 +610,3 @@ int anetSockName(int fd, char *ip, size_t ip_len, int *port) {
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int anetFormatSock(int fd, char *fmt, size_t fmt_len) {
|
||||
char ip[INET6_ADDRSTRLEN];
|
||||
int port;
|
||||
|
||||
anetSockName(fd,ip,sizeof(ip),&port);
|
||||
return anetFormatAddr(fmt, fmt_len, ip, port);
|
||||
}
|
||||
|
||||
@@ -70,8 +70,5 @@ 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);
|
||||
int anetFormatAddr(char *fmt, size_t fmt_len, char *ip, int port);
|
||||
int anetFormatPeer(int fd, char *fmt, size_t fmt_len);
|
||||
int anetFormatSock(int fd, char *fmt, size_t fmt_len);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -770,29 +770,52 @@ int rioWriteBulkObject(rio *r, robj *obj) {
|
||||
int rewriteListObject(rio *r, robj *key, robj *o) {
|
||||
long long count = 0, items = listTypeLength(o);
|
||||
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
quicklist *list = o->ptr;
|
||||
quicklistIter *li = quicklistGetIterator(list, AL_START_HEAD);
|
||||
quicklistEntry entry;
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *zl = o->ptr;
|
||||
unsigned char *p = ziplistIndex(zl,0);
|
||||
unsigned char *vstr;
|
||||
unsigned int vlen;
|
||||
long long vlong;
|
||||
|
||||
while (quicklistNext(li,&entry)) {
|
||||
while(ziplistGet(p,&vstr,&vlen,&vlong)) {
|
||||
if (count == 0) {
|
||||
int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
|
||||
REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
|
||||
|
||||
if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
|
||||
if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
|
||||
if (rioWriteBulkObject(r,key) == 0) return 0;
|
||||
}
|
||||
|
||||
if (entry.value) {
|
||||
if (rioWriteBulkString(r,(char*)entry.value,entry.sz) == 0) return 0;
|
||||
if (vstr) {
|
||||
if (rioWriteBulkString(r,(char*)vstr,vlen) == 0) return 0;
|
||||
} else {
|
||||
if (rioWriteBulkLongLong(r,entry.longval) == 0) return 0;
|
||||
if (rioWriteBulkLongLong(r,vlong) == 0) return 0;
|
||||
}
|
||||
p = ziplistNext(zl,p);
|
||||
if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
|
||||
items--;
|
||||
}
|
||||
} else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
list *list = o->ptr;
|
||||
listNode *ln;
|
||||
listIter li;
|
||||
|
||||
listRewind(list,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
robj *eleobj = listNodeValue(ln);
|
||||
|
||||
if (count == 0) {
|
||||
int cmd_items = (items > REDIS_AOF_REWRITE_ITEMS_PER_CMD) ?
|
||||
REDIS_AOF_REWRITE_ITEMS_PER_CMD : items;
|
||||
|
||||
if (rioWriteBulkCount(r,'*',2+cmd_items) == 0) return 0;
|
||||
if (rioWriteBulkString(r,"RPUSH",5) == 0) return 0;
|
||||
if (rioWriteBulkObject(r,key) == 0) return 0;
|
||||
}
|
||||
if (rioWriteBulkObject(r,eleobj) == 0) return 0;
|
||||
if (++count == REDIS_AOF_REWRITE_ITEMS_PER_CMD) count = 0;
|
||||
items--;
|
||||
}
|
||||
quicklistReleaseIterator(li);
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -1082,7 +1105,6 @@ int rewriteAppendOnlyFile(char *filename) {
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
di = NULL;
|
||||
}
|
||||
|
||||
/* Do an initial slow fsync here while the parent is still sending
|
||||
|
||||
+14
-24
@@ -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;
|
||||
@@ -229,17 +217,19 @@ void setbitCommand(redisClient *c) {
|
||||
return;
|
||||
}
|
||||
|
||||
byte = bitoffset >> 3;
|
||||
o = lookupKeyWrite(c->db,c->argv[1]);
|
||||
if (o == NULL) {
|
||||
o = createObject(REDIS_STRING,sdsnewlen(NULL, byte+1));
|
||||
o = createObject(REDIS_STRING,sdsempty());
|
||||
dbAdd(c->db,c->argv[1],o);
|
||||
} else {
|
||||
if (checkType(c,o,REDIS_STRING)) return;
|
||||
o = dbUnshareStringValue(c->db,c->argv[1],o);
|
||||
o->ptr = sdsgrowzero(o->ptr,byte+1);
|
||||
}
|
||||
|
||||
/* Grow sds value to the right length if necessary */
|
||||
byte = bitoffset >> 3;
|
||||
o->ptr = sdsgrowzero(o->ptr,byte+1);
|
||||
|
||||
/* Get current values */
|
||||
byteval = ((uint8_t*)o->ptr)[byte];
|
||||
bit = 7 - (bitoffset & 0x7);
|
||||
@@ -358,7 +348,7 @@ void bitopCommand(redisClient *c) {
|
||||
* 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;
|
||||
|
||||
|
||||
@@ -118,7 +118,9 @@ void processUnblockedClients(void) {
|
||||
|
||||
/* Process remaining data in the input buffer. */
|
||||
if (c->querybuf && sdslen(c->querybuf) > 0) {
|
||||
server.current_client = c;
|
||||
processInputBuffer(c);
|
||||
server.current_client = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+73
-182
@@ -40,7 +40,6 @@
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/file.h>
|
||||
#include <math.h>
|
||||
|
||||
/* A global reference to myself is handy to make code more clear.
|
||||
* Myself always points to server.cluster->myself, that is, the clusterNode
|
||||
@@ -480,7 +479,6 @@ void clusterInit(void) {
|
||||
* the IP address via MEET messages. */
|
||||
myself->port = server.port;
|
||||
|
||||
server.cluster->mf_end = 0;
|
||||
resetManualFailover();
|
||||
}
|
||||
|
||||
@@ -595,7 +593,7 @@ void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
if (cfd == ANET_ERR) {
|
||||
if (errno != EWOULDBLOCK)
|
||||
redisLog(REDIS_VERBOSE,
|
||||
"Error accepting cluster node: %s", server.neterr);
|
||||
"Accepting cluster node: %s", server.neterr);
|
||||
return;
|
||||
}
|
||||
anetNonBlock(NULL,cfd);
|
||||
@@ -784,11 +782,8 @@ int clusterNodeRemoveSlave(clusterNode *master, clusterNode *slave) {
|
||||
|
||||
for (j = 0; j < master->numslaves; j++) {
|
||||
if (master->slaves[j] == slave) {
|
||||
if ((j+1) < master->numslaves) {
|
||||
int remaining_slaves = (master->numslaves - j) - 1;
|
||||
memmove(master->slaves+j,master->slaves+(j+1),
|
||||
(sizeof(*master->slaves) * remaining_slaves));
|
||||
}
|
||||
memmove(master->slaves+j,master->slaves+(j+1),
|
||||
(master->numslaves-1)-j);
|
||||
master->numslaves--;
|
||||
return REDIS_OK;
|
||||
}
|
||||
@@ -823,30 +818,15 @@ int clusterCountNonFailingSlaves(clusterNode *n) {
|
||||
return okslaves;
|
||||
}
|
||||
|
||||
/* Low level cleanup of the node structure. Only called by clusterDelNode(). */
|
||||
void freeClusterNode(clusterNode *n) {
|
||||
sds nodename;
|
||||
int j;
|
||||
|
||||
/* If the node is a master with associated slaves, we have to set
|
||||
* all the slaves->slaveof fields to NULL (unknown). */
|
||||
if (nodeIsMaster(n)) {
|
||||
for (j = 0; j < n->numslaves; j++)
|
||||
n->slaves[j]->slaveof = NULL;
|
||||
}
|
||||
|
||||
/* Remove this node from the list of slaves of its master. */
|
||||
if (nodeIsSlave(n) && n->slaveof) clusterNodeRemoveSlave(n->slaveof,n);
|
||||
|
||||
/* Unlink from the set of nodes. */
|
||||
nodename = sdsnewlen(n->name, REDIS_CLUSTER_NAMELEN);
|
||||
redisAssert(dictDelete(server.cluster->nodes,nodename) == DICT_OK);
|
||||
sdsfree(nodename);
|
||||
|
||||
/* Release link and associated data structures. */
|
||||
if (n->slaveof) clusterNodeRemoveSlave(n->slaveof, n);
|
||||
if (n->link) freeClusterLink(n->link);
|
||||
listRelease(n->fail_reports);
|
||||
zfree(n->slaves);
|
||||
zfree(n);
|
||||
}
|
||||
|
||||
@@ -859,16 +839,11 @@ int clusterAddNode(clusterNode *node) {
|
||||
return (retval == DICT_OK) ? REDIS_OK : REDIS_ERR;
|
||||
}
|
||||
|
||||
/* Remove a node from the cluster. The functio performs the high level
|
||||
* cleanup, calling freeClusterNode() for the low level cleanup.
|
||||
* Here we do the following:
|
||||
*
|
||||
* 1) Mark all the slots handled by it as unassigned.
|
||||
* 2) Remove all the failure reports sent by this node and referenced by
|
||||
* other nodes.
|
||||
* 3) Free the node with freeClusterNode() that will in turn remove it
|
||||
* from the hash table and from the list of slaves of its master, if
|
||||
* it is a slave node.
|
||||
/* Remove a node from the cluster:
|
||||
* 1) Mark all the nodes handled by it as unassigned.
|
||||
* 2) Remove all the failure reports sent by this node.
|
||||
* 3) Free the node, that will in turn remove it from the hash table
|
||||
* and from the list of slaves of its master, if it is a slave node.
|
||||
*/
|
||||
void clusterDelNode(clusterNode *delnode) {
|
||||
int j;
|
||||
@@ -895,7 +870,11 @@ void clusterDelNode(clusterNode *delnode) {
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
/* 3) Free the node, unlinking it from the cluster. */
|
||||
/* 3) Remove this node from its master's slaves if needed. */
|
||||
if (nodeIsSlave(delnode) && delnode->slaveof)
|
||||
clusterNodeRemoveSlave(delnode->slaveof,delnode);
|
||||
|
||||
/* 4) Free the node, unlinking it from the cluster. */
|
||||
freeClusterNode(delnode);
|
||||
}
|
||||
|
||||
@@ -1139,7 +1118,6 @@ int clusterStartHandshake(char *ip, int port) {
|
||||
|
||||
/* Set norm_ip as the normalized string representation of the node
|
||||
* IP address. */
|
||||
memset(norm_ip,0,REDIS_IP_STR_LEN);
|
||||
if (sa.ss_family == AF_INET)
|
||||
inet_ntop(AF_INET,
|
||||
(void*)&(((struct sockaddr_in *)&sa)->sin_addr),
|
||||
@@ -1254,7 +1232,7 @@ void nodeIp2String(char *buf, clusterLink *link) {
|
||||
* The function returns 0 if the node address is still the same,
|
||||
* otherwise 1 is returned. */
|
||||
int nodeUpdateAddressIfNeeded(clusterNode *node, clusterLink *link, int port) {
|
||||
char ip[REDIS_IP_STR_LEN] = {0};
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
|
||||
/* We don't proceed if the link is the same as the sender link, as this
|
||||
* function is designed to see if the node link is consistent with the
|
||||
@@ -1485,8 +1463,7 @@ int clusterProcessPacket(clusterLink *link) {
|
||||
|
||||
/* Perform sanity checks */
|
||||
if (totlen < 16) return 1; /* At least signature, version, totlen, count. */
|
||||
if (ntohs(hdr->ver) != CLUSTER_PROTO_VER)
|
||||
return 1; /* Can't handle versions other than the current one.*/
|
||||
if (ntohs(hdr->ver) != 0) return 1; /* Can't handle versions other than 0.*/
|
||||
if (totlen > sdslen(link->rcvbuf)) return 1;
|
||||
if (type == CLUSTERMSG_TYPE_PING || type == CLUSTERMSG_TYPE_PONG ||
|
||||
type == CLUSTERMSG_TYPE_MEET)
|
||||
@@ -1505,8 +1482,7 @@ int clusterProcessPacket(clusterLink *link) {
|
||||
} else if (type == CLUSTERMSG_TYPE_PUBLISH) {
|
||||
uint32_t explen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
|
||||
|
||||
explen += sizeof(clusterMsgDataPublish) -
|
||||
8 +
|
||||
explen += sizeof(clusterMsgDataPublish) +
|
||||
ntohl(hdr->data.publish.msg.channel_len) +
|
||||
ntohl(hdr->data.publish.msg.message_len);
|
||||
if (totlen != explen) return 1;
|
||||
@@ -1567,12 +1543,8 @@ int clusterProcessPacket(clusterLink *link) {
|
||||
* later if we changed address, and those nodes will use our
|
||||
* official address to connect to us. So by obtaining this address
|
||||
* from the socket is a simple way to discover / update our own
|
||||
* address in the cluster without it being hardcoded in the config.
|
||||
*
|
||||
* However if we don't have an address at all, we update the address
|
||||
* even with a normal PING packet. If it's wrong it will be fixed
|
||||
* by MEET later. */
|
||||
if (type == CLUSTERMSG_TYPE_MEET || myself->ip[0] == '\0') {
|
||||
* address in the cluster without it being hardcoded in the config. */
|
||||
if (type == CLUSTERMSG_TYPE_MEET) {
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
|
||||
if (anetSockName(link->fd,ip,sizeof(ip),NULL) != -1 &&
|
||||
@@ -1631,7 +1603,7 @@ int clusterProcessPacket(clusterLink *link) {
|
||||
}
|
||||
/* Free this node as we already have it. This will
|
||||
* cause the link to be freed as well. */
|
||||
clusterDelNode(link->node);
|
||||
freeClusterNode(link->node);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -2038,8 +2010,7 @@ void clusterBroadcastMessage(void *buf, size_t len) {
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
|
||||
/* Build the message header. hdr must point to a buffer at least
|
||||
* sizeof(clusterMsg) in bytes. */
|
||||
/* Build the message header */
|
||||
void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
|
||||
int totlen = 0;
|
||||
uint64_t offset;
|
||||
@@ -2053,7 +2024,6 @@ void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
|
||||
myself->slaveof : myself;
|
||||
|
||||
memset(hdr,0,sizeof(*hdr));
|
||||
hdr->ver = htons(CLUSTER_PROTO_VER);
|
||||
hdr->sig[0] = 'R';
|
||||
hdr->sig[1] = 'C';
|
||||
hdr->sig[2] = 'm';
|
||||
@@ -2100,90 +2070,40 @@ void clusterBuildMessageHdr(clusterMsg *hdr, int type) {
|
||||
/* Send a PING or PONG packet to the specified node, making sure to add enough
|
||||
* gossip informations. */
|
||||
void clusterSendPing(clusterLink *link, int type) {
|
||||
unsigned char *buf;
|
||||
clusterMsg *hdr;
|
||||
int gossipcount = 0; /* Number of gossip sections added so far. */
|
||||
int wanted; /* Number of gossip sections we want to append if possible. */
|
||||
int totlen; /* Total packet length. */
|
||||
/* freshnodes is the max number of nodes we can hope to append at all:
|
||||
* nodes available minus two (ourself and the node we are sending the
|
||||
* message to). However practically there may be less valid nodes since
|
||||
* nodes in handshake state, disconnected, are not considered. */
|
||||
unsigned char buf[sizeof(clusterMsg)];
|
||||
clusterMsg *hdr = (clusterMsg*) buf;
|
||||
int gossipcount = 0, totlen;
|
||||
/* freshnodes is the number of nodes we can still use to populate the
|
||||
* gossip section of the ping packet. Basically we start with the nodes
|
||||
* we have in memory minus two (ourself and the node we are sending the
|
||||
* message to). Every time we add a node we decrement the counter, so when
|
||||
* it will drop to <= zero we know there is no more gossip info we can
|
||||
* send. */
|
||||
int freshnodes = dictSize(server.cluster->nodes)-2;
|
||||
|
||||
/* How many gossip sections we want to add? 1/10 of the number of nodes
|
||||
* and anyway at least 3. Why 1/10?
|
||||
*
|
||||
* If we have N masters, with N/10 entries, and we consider that in
|
||||
* node_timeout we exchange with each other node at least 4 packets
|
||||
* (we ping in the worst case in node_timeout/2 time, and we also
|
||||
* receive two pings from the host), we have a total of 8 packets
|
||||
* in the node_timeout*2 falure reports validity time. So we have
|
||||
* that, for a single PFAIL node, we can expect to receive the following
|
||||
* number of failure reports (in the specified window of time):
|
||||
*
|
||||
* PROB * GOSSIP_ENTRIES_PER_PACKET * TOTAL_PACKETS:
|
||||
*
|
||||
* PROB = probability of being featured in a single gossip entry,
|
||||
* which is 1 / NUM_OF_NODES.
|
||||
* ENTRIES = 10.
|
||||
* TOTAL_PACKETS = 2 * 4 * NUM_OF_MASTERS.
|
||||
*
|
||||
* If we assume we have just masters (so num of nodes and num of masters
|
||||
* is the same), with 1/10 we always get over the majority, and specifically
|
||||
* 80% of the number of nodes, to account for many masters failing at the
|
||||
* same time.
|
||||
*
|
||||
* Since we have non-voting slaves that lower the probability of an entry
|
||||
* to feature our node, we set the number of entires per packet as
|
||||
* 10% of the total nodes we have. */
|
||||
wanted = floor(dictSize(server.cluster->nodes)/10);
|
||||
if (wanted < 3) wanted = 3;
|
||||
if (wanted > freshnodes) wanted = freshnodes;
|
||||
|
||||
/* Compute the maxium totlen to allocate our buffer. We'll fix the totlen
|
||||
* later according to the number of gossip sections we really were able
|
||||
* to put inside the packet. */
|
||||
totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
|
||||
totlen += (sizeof(clusterMsgDataGossip)*wanted);
|
||||
/* Note: clusterBuildMessageHdr() expects the buffer to be always at least
|
||||
* sizeof(clusterMsg) or more. */
|
||||
if (totlen < (int)sizeof(clusterMsg)) totlen = sizeof(clusterMsg);
|
||||
buf = zcalloc(totlen);
|
||||
hdr = (clusterMsg*) buf;
|
||||
|
||||
/* Populate the header. */
|
||||
if (link->node && type == CLUSTERMSG_TYPE_PING)
|
||||
link->node->ping_sent = mstime();
|
||||
clusterBuildMessageHdr(hdr,type);
|
||||
|
||||
/* Populate the gossip fields */
|
||||
int maxiterations = wanted*3;
|
||||
while(freshnodes > 0 && gossipcount < wanted && maxiterations--) {
|
||||
while(freshnodes > 0 && gossipcount < 3) {
|
||||
dictEntry *de = dictGetRandomKey(server.cluster->nodes);
|
||||
clusterNode *this = dictGetVal(de);
|
||||
clusterMsgDataGossip *gossip;
|
||||
int j;
|
||||
|
||||
/* Don't include this node: the whole packet header is about us
|
||||
* already, so we just gossip about other nodes. */
|
||||
if (this == myself) continue;
|
||||
|
||||
/* Give a bias to FAIL/PFAIL nodes. */
|
||||
if (maxiterations > wanted*2 &&
|
||||
!(this->flags & (REDIS_NODE_PFAIL|REDIS_NODE_FAIL)))
|
||||
continue;
|
||||
|
||||
/* In the gossip section don't include:
|
||||
* 1) Nodes in HANDSHAKE state.
|
||||
* 1) Myself.
|
||||
* 2) Nodes in HANDSHAKE state.
|
||||
* 3) Nodes with the NOADDR flag set.
|
||||
* 4) Disconnected nodes if they don't have configured slots.
|
||||
*/
|
||||
if (this->flags & (REDIS_NODE_HANDSHAKE|REDIS_NODE_NOADDR) ||
|
||||
if (this == myself ||
|
||||
this->flags & (REDIS_NODE_HANDSHAKE|REDIS_NODE_NOADDR) ||
|
||||
(this->link == NULL && this->numslots == 0))
|
||||
{
|
||||
freshnodes--; /* Tecnically not correct, but saves CPU. */
|
||||
continue;
|
||||
freshnodes--; /* otherwise we may loop forever. */
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Check if we already added this node */
|
||||
@@ -2202,19 +2122,13 @@ void clusterSendPing(clusterLink *link, int type) {
|
||||
memcpy(gossip->ip,this->ip,sizeof(this->ip));
|
||||
gossip->port = htons(this->port);
|
||||
gossip->flags = htons(this->flags);
|
||||
gossip->notused1 = 0;
|
||||
gossip->notused2 = 0;
|
||||
gossipcount++;
|
||||
}
|
||||
|
||||
/* Ready to send... fix the totlen fiend and queue the message in the
|
||||
* output buffer. */
|
||||
totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
|
||||
totlen += (sizeof(clusterMsgDataGossip)*gossipcount);
|
||||
hdr->count = htons(gossipcount);
|
||||
hdr->totlen = htonl(totlen);
|
||||
clusterSendMessage(link,buf,totlen);
|
||||
zfree(buf);
|
||||
}
|
||||
|
||||
/* Send a PONG packet to every connected node that's not in handshake state
|
||||
@@ -2270,7 +2184,7 @@ void clusterSendPublish(clusterLink *link, robj *channel, robj *message) {
|
||||
|
||||
clusterBuildMessageHdr(hdr,CLUSTERMSG_TYPE_PUBLISH);
|
||||
totlen = sizeof(clusterMsg)-sizeof(union clusterMsgData);
|
||||
totlen += sizeof(clusterMsgDataPublish) - 8 + channel_len + message_len;
|
||||
totlen += sizeof(clusterMsgDataPublish) + channel_len + message_len;
|
||||
|
||||
hdr->data.publish.msg.channel_len = htonl(channel_len);
|
||||
hdr->data.publish.msg.message_len = htonl(message_len);
|
||||
@@ -2603,7 +2517,7 @@ void clusterHandleSlaveFailover(void) {
|
||||
|
||||
/* Compute the failover timeout (the max time we have to send votes
|
||||
* and wait for replies), and the failover retry time (the time to wait
|
||||
* before trying to get voted again).
|
||||
* before waiting again.
|
||||
*
|
||||
* Timeout is MIN(NODE_TIMEOUT*2,2000) milliseconds.
|
||||
* Retry is two times the Timeout.
|
||||
@@ -2861,7 +2775,6 @@ void clusterHandleSlaveMigration(int max_slaves) {
|
||||
}
|
||||
}
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
|
||||
/* Step 4: perform the migration if there is a target, and if I'm the
|
||||
* candidate. */
|
||||
@@ -2983,7 +2896,7 @@ void clusterCron(void) {
|
||||
/* A Node in HANDSHAKE state has a limited lifespan equal to the
|
||||
* configured node timeout. */
|
||||
if (nodeInHandshake(node) && now - node->ctime > handshake_timeout) {
|
||||
clusterDelNode(node);
|
||||
freeClusterNode(node);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -3970,7 +3883,10 @@ void clusterCommand(redisClient *c) {
|
||||
server.cluster->stats_bus_messages_sent,
|
||||
server.cluster->stats_bus_messages_received
|
||||
);
|
||||
addReplyBulkSds(c, info);
|
||||
addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
|
||||
(unsigned long)sdslen(info)));
|
||||
addReplySds(c,info);
|
||||
addReply(c,shared.crlf);
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"saveconfig") && c->argc == 2) {
|
||||
int retval = clusterSaveConfig(1);
|
||||
|
||||
@@ -4094,18 +4010,6 @@ void clusterCommand(redisClient *c) {
|
||||
addReplyBulkCString(c,ni);
|
||||
sdsfree(ni);
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"count-failure-reports") &&
|
||||
c->argc == 3)
|
||||
{
|
||||
/* CLUSTER COUNT-FAILURE-REPORTS <NODE ID> */
|
||||
clusterNode *n = clusterLookupNode(c->argv[2]->ptr);
|
||||
|
||||
if (!n) {
|
||||
addReplyErrorFormat(c,"Unknown node %s", (char*)c->argv[2]->ptr);
|
||||
return;
|
||||
} else {
|
||||
addReplyLongLong(c,clusterNodeFailureReportsCount(n));
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"failover") &&
|
||||
(c->argc == 2 || c->argc == 3))
|
||||
{
|
||||
@@ -4362,12 +4266,11 @@ void restoreCommand(redisClient *c) {
|
||||
|
||||
typedef struct migrateCachedSocket {
|
||||
int fd;
|
||||
long last_dbid;
|
||||
time_t last_use_time;
|
||||
} migrateCachedSocket;
|
||||
|
||||
/* Return a migrateCachedSocket containing a TCP socket connected with the
|
||||
* target instance, possibly returning a cached one.
|
||||
/* Return a TCP socket connected with the target instance, possibly returning
|
||||
* a cached one.
|
||||
*
|
||||
* This function is responsible of sending errors to the client if a
|
||||
* connection can't be established. In this case -1 is returned.
|
||||
@@ -4377,7 +4280,7 @@ typedef struct migrateCachedSocket {
|
||||
* If the caller detects an error while using the socket, migrateCloseSocket()
|
||||
* should be called so that the connection will be created from scratch
|
||||
* the next time. */
|
||||
migrateCachedSocket* migrateGetSocket(redisClient *c, robj *host, robj *port, long timeout) {
|
||||
int migrateGetSocket(redisClient *c, robj *host, robj *port, long timeout) {
|
||||
int fd;
|
||||
sds name = sdsempty();
|
||||
migrateCachedSocket *cs;
|
||||
@@ -4390,7 +4293,7 @@ migrateCachedSocket* migrateGetSocket(redisClient *c, robj *host, robj *port, lo
|
||||
if (cs) {
|
||||
sdsfree(name);
|
||||
cs->last_use_time = server.unixtime;
|
||||
return cs;
|
||||
return cs->fd;
|
||||
}
|
||||
|
||||
/* No cached socket, create one. */
|
||||
@@ -4410,7 +4313,7 @@ migrateCachedSocket* migrateGetSocket(redisClient *c, robj *host, robj *port, lo
|
||||
sdsfree(name);
|
||||
addReplyErrorFormat(c,"Can't connect to target node: %s",
|
||||
server.neterr);
|
||||
return NULL;
|
||||
return -1;
|
||||
}
|
||||
anetEnableTcpNoDelay(server.neterr,fd);
|
||||
|
||||
@@ -4420,16 +4323,15 @@ migrateCachedSocket* migrateGetSocket(redisClient *c, robj *host, robj *port, lo
|
||||
addReplySds(c,
|
||||
sdsnew("-IOERR error or timeout connecting to the client\r\n"));
|
||||
close(fd);
|
||||
return NULL;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Add to the cache and return it to the caller. */
|
||||
cs = zmalloc(sizeof(*cs));
|
||||
cs->fd = fd;
|
||||
cs->last_dbid = -1;
|
||||
cs->last_use_time = server.unixtime;
|
||||
dictAdd(server.migrate_cached_sockets,name,cs);
|
||||
return cs;
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* Free a migrate cached connection. */
|
||||
@@ -4470,8 +4372,7 @@ void migrateCloseTimedoutSockets(void) {
|
||||
|
||||
/* MIGRATE host port key dbid timeout [COPY | REPLACE] */
|
||||
void migrateCommand(redisClient *c) {
|
||||
migrateCachedSocket *cs;
|
||||
int copy, replace, j;
|
||||
int fd, copy, replace, j;
|
||||
long timeout;
|
||||
long dbid;
|
||||
long long ttl, expireat;
|
||||
@@ -4507,26 +4408,21 @@ try_again:
|
||||
/* Check if the key is here. If not we reply with success as there is
|
||||
* nothing to migrate (for instance the key expired in the meantime), but
|
||||
* we include such information in the reply string. */
|
||||
if ((o = lookupKeyWrite(c->db,c->argv[3])) == NULL) {
|
||||
if ((o = lookupKeyRead(c->db,c->argv[3])) == NULL) {
|
||||
addReplySds(c,sdsnew("+NOKEY\r\n"));
|
||||
return;
|
||||
}
|
||||
|
||||
/* Connect */
|
||||
cs = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
|
||||
if (cs == NULL) return; /* error sent to the client by migrateGetSocket() */
|
||||
|
||||
rioInitWithBuffer(&cmd,sdsempty());
|
||||
|
||||
/* Send the SELECT command if the current DB is not already selected. */
|
||||
int select = cs->last_dbid != dbid; /* Should we emit SELECT? */
|
||||
if (select) {
|
||||
redisAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
|
||||
redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
|
||||
redisAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
|
||||
}
|
||||
fd = migrateGetSocket(c,c->argv[1],c->argv[2],timeout);
|
||||
if (fd == -1) return; /* error sent to the client by migrateGetSocket() */
|
||||
|
||||
/* Create RESTORE payload and generate the protocol to call the command. */
|
||||
rioInitWithBuffer(&cmd,sdsempty());
|
||||
redisAssertWithInfo(c,NULL,rioWriteBulkCount(&cmd,'*',2));
|
||||
redisAssertWithInfo(c,NULL,rioWriteBulkString(&cmd,"SELECT",6));
|
||||
redisAssertWithInfo(c,NULL,rioWriteBulkLongLong(&cmd,dbid));
|
||||
|
||||
expireat = getExpire(c->db,c->argv[3]);
|
||||
if (expireat != -1) {
|
||||
ttl = expireat-mstime();
|
||||
@@ -4560,11 +4456,11 @@ try_again:
|
||||
{
|
||||
sds buf = cmd.io.buffer.ptr;
|
||||
size_t pos = 0, towrite;
|
||||
ssize_t nwritten = 0;
|
||||
int nwritten = 0;
|
||||
|
||||
while ((towrite = sdslen(buf)-pos) > 0) {
|
||||
towrite = (towrite > (64*1024) ? (64*1024) : towrite);
|
||||
nwritten = syncWrite(cs->fd,buf+pos,towrite,timeout);
|
||||
nwritten = syncWrite(fd,buf+pos,towrite,timeout);
|
||||
if (nwritten != (signed)towrite) goto socket_wr_err;
|
||||
pos += nwritten;
|
||||
}
|
||||
@@ -4576,33 +4472,28 @@ try_again:
|
||||
char buf2[1024];
|
||||
|
||||
/* Read the two replies */
|
||||
if (select && syncReadLine(cs->fd, buf1, sizeof(buf1), timeout) <= 0)
|
||||
if (syncReadLine(fd, buf1, sizeof(buf1), timeout) <= 0)
|
||||
goto socket_rd_err;
|
||||
if (syncReadLine(cs->fd, buf2, sizeof(buf2), timeout) <= 0)
|
||||
if (syncReadLine(fd, buf2, sizeof(buf2), timeout) <= 0)
|
||||
goto socket_rd_err;
|
||||
if ((select && buf1[0] == '-') || buf2[0] == '-') {
|
||||
/* On error assume that last_dbid is no longer valid. */
|
||||
cs->last_dbid = -1;
|
||||
if (buf1[0] == '-' || buf2[0] == '-') {
|
||||
addReplyErrorFormat(c,"Target instance replied with error: %s",
|
||||
(cs->last_dbid != dbid && buf1[0] == '-') ? buf1+1 : buf2+1);
|
||||
(buf1[0] == '-') ? buf1+1 : buf2+1);
|
||||
} else {
|
||||
/* Update the last_dbid in migrateCachedSocket */
|
||||
cs->last_dbid = dbid;
|
||||
robj *aux;
|
||||
|
||||
addReply(c,shared.ok);
|
||||
|
||||
if (!copy) {
|
||||
/* No COPY option: remove the local key, signal the change. */
|
||||
dbDelete(c->db,c->argv[3]);
|
||||
signalModifiedKey(c->db,c->argv[3]);
|
||||
server.dirty++;
|
||||
|
||||
/* Translate MIGRATE as DEL for replication/AOF. */
|
||||
aux = createStringObject("DEL",3);
|
||||
rewriteClientCommandVector(c,2,aux,c->argv[3]);
|
||||
decrRefCount(aux);
|
||||
}
|
||||
addReply(c,shared.ok);
|
||||
server.dirty++;
|
||||
|
||||
/* Translate MIGRATE as DEL for replication/AOF. */
|
||||
aux = createStringObject("DEL",3);
|
||||
rewriteClientCommandVector(c,2,aux,c->argv[3]);
|
||||
decrRefCount(aux);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-10
@@ -163,11 +163,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 {
|
||||
@@ -177,10 +176,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 {
|
||||
@@ -212,7 +208,6 @@ union clusterMsgData {
|
||||
} update;
|
||||
};
|
||||
|
||||
#define CLUSTER_PROTO_VER 0 /* Cluster bus protocol version. */
|
||||
|
||||
typedef struct {
|
||||
char sig[4]; /* Siganture "RCmb" (Redis Cluster message bus). */
|
||||
|
||||
+43
-87
@@ -60,8 +60,6 @@ clientBufferLimitsConfig clientBufferLimitsDefaults[REDIS_CLIENT_TYPE_COUNT] = {
|
||||
* Config file parsing
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
int supervisedToMode(const char *str);
|
||||
|
||||
int yesnotoi(char *s) {
|
||||
if (!strcasecmp(s,"yes")) return 1;
|
||||
else if (!strcasecmp(s,"no")) return 0;
|
||||
@@ -228,6 +226,11 @@ void loadServerConfigFromString(char *config) {
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) {
|
||||
server.maxmemory = memtoll(argv[1],NULL);
|
||||
server.maxmemory_enforced = (double) server.maxmemory / server.maxmemory_frag_guess;
|
||||
} else if (!strcasecmp(argv[0],"rss-aware-maxmemory") && argc==2) {
|
||||
if ((server.rss_aware_maxmemory = yesnotoi(argv[1])) == -1) {
|
||||
err = "argument must be 'yes' or 'no'"; goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) {
|
||||
if (!strcasecmp(argv[1],"volatile-lru")) {
|
||||
server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
|
||||
@@ -399,13 +402,9 @@ void loadServerConfigFromString(char *config) {
|
||||
} else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) {
|
||||
server.hash_max_ziplist_value = memtoll(argv[1], NULL);
|
||||
} else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){
|
||||
/* DEAD OPTION */
|
||||
server.list_max_ziplist_entries = memtoll(argv[1], NULL);
|
||||
} else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) {
|
||||
/* DEAD OPTION */
|
||||
} else if (!strcasecmp(argv[0],"list-max-ziplist-size") && argc == 2) {
|
||||
server.list_max_ziplist_size = atoi(argv[1]);
|
||||
} else if (!strcasecmp(argv[0],"list-compress-depth") && argc == 2) {
|
||||
server.list_compress_depth = atoi(argv[1]);
|
||||
server.list_max_ziplist_value = memtoll(argv[1], NULL);
|
||||
} else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) {
|
||||
server.set_max_intset_entries = memtoll(argv[1], NULL);
|
||||
} else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) {
|
||||
@@ -535,15 +534,6 @@ void loadServerConfigFromString(char *config) {
|
||||
goto loaderr;
|
||||
}
|
||||
server.notify_keyspace_events = flags;
|
||||
} else if (!strcasecmp(argv[0],"supervised") && argc == 2) {
|
||||
int mode = supervisedToMode(argv[1]);
|
||||
|
||||
if (mode == -1) {
|
||||
err = "Invalid option for 'supervised'. "
|
||||
"Allowed values: 'upstart', 'systemd', 'auto', or 'no'";
|
||||
goto loaderr;
|
||||
}
|
||||
server.supervised_mode = mode;
|
||||
} else if (!strcasecmp(argv[0],"sentinel")) {
|
||||
/* argc == 1 is handled by main() as we need to enter the sentinel
|
||||
* mode ASAP. */
|
||||
@@ -624,7 +614,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];
|
||||
@@ -644,15 +633,21 @@ 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;
|
||||
server.maxmemory_enforced = (double) server.maxmemory / server.maxmemory_frag_guess;
|
||||
if (server.maxmemory) {
|
||||
if (server.maxmemory < zmalloc_used_memory()) {
|
||||
redisLog(REDIS_WARNING,"WARNING: the new maxmemory value set via CONFIG SET is smaller than the current memory usage. This will result in keys eviction and/or inability to accept new write commands depending on the maxmemory-policy.");
|
||||
}
|
||||
freeMemoryIfNeeded();
|
||||
}
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"rss-aware-maxmemory")) {
|
||||
int yn = yesnotoi(o->ptr);
|
||||
|
||||
if (yn == -1) goto badfmt;
|
||||
server.rss_aware_maxmemory = yn;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"maxclients")) {
|
||||
int orig_value = server.maxclients;
|
||||
|
||||
@@ -811,12 +806,12 @@ void configSetCommand(redisClient *c) {
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"hash-max-ziplist-value")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
|
||||
server.hash_max_ziplist_value = ll;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-size")) {
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-entries")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
|
||||
server.list_max_ziplist_size = ll;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"list-compress-depth")) {
|
||||
server.list_max_ziplist_entries = ll;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"list-max-ziplist-value")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
|
||||
server.list_compress_depth = ll;
|
||||
server.list_max_ziplist_value = ll;
|
||||
} else if (!strcasecmp(c->argv[2]->ptr,"set-max-intset-entries")) {
|
||||
if (getLongLongFromObject(o,&ll) == REDIS_ERR || ll < 0) goto badfmt;
|
||||
server.set_max_intset_entries = ll;
|
||||
@@ -867,6 +862,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) {
|
||||
@@ -875,8 +871,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;
|
||||
}
|
||||
@@ -910,8 +906,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;
|
||||
@@ -1020,47 +1015,6 @@ badfmt: /* Bad format errors */
|
||||
} \
|
||||
} while(0);
|
||||
|
||||
char *maxmemoryToString() {
|
||||
char *s;
|
||||
switch(server.maxmemory_policy) {
|
||||
case REDIS_MAXMEMORY_VOLATILE_LRU: s = "volatile-lru"; break;
|
||||
case REDIS_MAXMEMORY_VOLATILE_TTL: s = "volatile-ttl"; break;
|
||||
case REDIS_MAXMEMORY_VOLATILE_RANDOM: s = "volatile-random"; break;
|
||||
case REDIS_MAXMEMORY_ALLKEYS_LRU: s = "allkeys-lru"; break;
|
||||
case REDIS_MAXMEMORY_ALLKEYS_RANDOM: s = "allkeys-random"; break;
|
||||
case REDIS_MAXMEMORY_NO_EVICTION: s = "noeviction"; break;
|
||||
default: s = "unknown"; break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
int supervisedToMode(const char *str) {
|
||||
int mode;
|
||||
if (!strcasecmp(str,"upstart")) {
|
||||
mode = REDIS_SUPERVISED_UPSTART;
|
||||
} else if (!strcasecmp(str,"systemd")) {
|
||||
mode = REDIS_SUPERVISED_SYSTEMD;
|
||||
} else if (!strcasecmp(str,"auto")) {
|
||||
mode = REDIS_SUPERVISED_AUTODETECT;
|
||||
} else if (!strcasecmp(str,"no")) {
|
||||
mode = REDIS_SUPERVISED_NONE;
|
||||
} else {
|
||||
mode = -1;
|
||||
}
|
||||
return mode;
|
||||
}
|
||||
|
||||
char *supervisedToString(void) {
|
||||
char *s;
|
||||
switch(server.supervised_mode) {
|
||||
case REDIS_SUPERVISED_UPSTART: s = "upstart"; break;
|
||||
case REDIS_SUPERVISED_SYSTEMD: s = "systemd"; break;
|
||||
case REDIS_SUPERVISED_AUTODETECT: s = "auto"; break;
|
||||
case REDIS_SUPERVISED_NONE: s = "no"; break;
|
||||
default: s = "no"; break;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
void configGetCommand(redisClient *c) {
|
||||
robj *o = c->argv[2];
|
||||
void *replylen = addDeferredMultiBulkLength(c);
|
||||
@@ -1090,10 +1044,10 @@ void configGetCommand(redisClient *c) {
|
||||
server.hash_max_ziplist_entries);
|
||||
config_get_numerical_field("hash-max-ziplist-value",
|
||||
server.hash_max_ziplist_value);
|
||||
config_get_numerical_field("list-max-ziplist-size",
|
||||
server.list_max_ziplist_size);
|
||||
config_get_numerical_field("list-compress-depth",
|
||||
server.list_compress_depth);
|
||||
config_get_numerical_field("list-max-ziplist-entries",
|
||||
server.list_max_ziplist_entries);
|
||||
config_get_numerical_field("list-max-ziplist-value",
|
||||
server.list_max_ziplist_value);
|
||||
config_get_numerical_field("set-max-intset-entries",
|
||||
server.set_max_intset_entries);
|
||||
config_get_numerical_field("zset-max-ziplist-entries",
|
||||
@@ -1150,6 +1104,8 @@ void configGetCommand(redisClient *c) {
|
||||
server.aof_rewrite_incremental_fsync);
|
||||
config_get_bool_field("aof-load-truncated",
|
||||
server.aof_load_truncated);
|
||||
config_get_bool_field("rss-aware-maxmemory",
|
||||
server.rss_aware_maxmemory);
|
||||
|
||||
/* Everything we can't handle with macros follows. */
|
||||
|
||||
@@ -1169,8 +1125,19 @@ void configGetCommand(redisClient *c) {
|
||||
matches++;
|
||||
}
|
||||
if (stringmatch(pattern,"maxmemory-policy",0)) {
|
||||
char *s;
|
||||
|
||||
switch(server.maxmemory_policy) {
|
||||
case REDIS_MAXMEMORY_VOLATILE_LRU: s = "volatile-lru"; break;
|
||||
case REDIS_MAXMEMORY_VOLATILE_TTL: s = "volatile-ttl"; break;
|
||||
case REDIS_MAXMEMORY_VOLATILE_RANDOM: s = "volatile-random"; break;
|
||||
case REDIS_MAXMEMORY_ALLKEYS_LRU: s = "allkeys-lru"; break;
|
||||
case REDIS_MAXMEMORY_ALLKEYS_RANDOM: s = "allkeys-random"; break;
|
||||
case REDIS_MAXMEMORY_NO_EVICTION: s = "noeviction"; break;
|
||||
default: s = "unknown"; break; /* too harmless to panic */
|
||||
}
|
||||
addReplyBulkCString(c,"maxmemory-policy");
|
||||
addReplyBulkCString(c,maxmemoryToString());
|
||||
addReplyBulkCString(c,s);
|
||||
matches++;
|
||||
}
|
||||
if (stringmatch(pattern,"appendfsync",0)) {
|
||||
@@ -1216,11 +1183,6 @@ void configGetCommand(redisClient *c) {
|
||||
addReplyBulkCString(c,s);
|
||||
matches++;
|
||||
}
|
||||
if (stringmatch(pattern,"supervised",0)) {
|
||||
addReplyBulkCString(c,"supervised");
|
||||
addReplyBulkCString(c,supervisedToString());
|
||||
matches++;
|
||||
}
|
||||
if (stringmatch(pattern,"client-output-buffer-limit",0)) {
|
||||
sds buf = sdsempty();
|
||||
int j;
|
||||
@@ -1905,8 +1867,8 @@ int rewriteConfig(char *path) {
|
||||
rewriteConfigNotifykeyspaceeventsOption(state);
|
||||
rewriteConfigNumericalOption(state,"hash-max-ziplist-entries",server.hash_max_ziplist_entries,REDIS_HASH_MAX_ZIPLIST_ENTRIES);
|
||||
rewriteConfigNumericalOption(state,"hash-max-ziplist-value",server.hash_max_ziplist_value,REDIS_HASH_MAX_ZIPLIST_VALUE);
|
||||
rewriteConfigNumericalOption(state,"list-max-ziplist-size",server.list_max_ziplist_size,REDIS_LIST_MAX_ZIPLIST_SIZE);
|
||||
rewriteConfigNumericalOption(state,"list-compress-depth",server.list_compress_depth,REDIS_LIST_COMPRESS_DEPTH);
|
||||
rewriteConfigNumericalOption(state,"list-max-ziplist-entries",server.list_max_ziplist_entries,REDIS_LIST_MAX_ZIPLIST_ENTRIES);
|
||||
rewriteConfigNumericalOption(state,"list-max-ziplist-value",server.list_max_ziplist_value,REDIS_LIST_MAX_ZIPLIST_VALUE);
|
||||
rewriteConfigNumericalOption(state,"set-max-intset-entries",server.set_max_intset_entries,REDIS_SET_MAX_INTSET_ENTRIES);
|
||||
rewriteConfigNumericalOption(state,"zset-max-ziplist-entries",server.zset_max_ziplist_entries,REDIS_ZSET_MAX_ZIPLIST_ENTRIES);
|
||||
rewriteConfigNumericalOption(state,"zset-max-ziplist-value",server.zset_max_ziplist_value,REDIS_ZSET_MAX_ZIPLIST_VALUE);
|
||||
@@ -1916,12 +1878,6 @@ int rewriteConfig(char *path) {
|
||||
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);
|
||||
rewriteConfigEnumOption(state,"supervised",server.supervised_mode,
|
||||
"upstart", REDIS_SUPERVISED_UPSTART,
|
||||
"systemd", REDIS_SUPERVISED_SYSTEMD,
|
||||
"auto", REDIS_SUPERVISED_AUTODETECT,
|
||||
"no", REDIS_SUPERVISED_NONE,
|
||||
NULL, REDIS_SUPERVISED_NONE);
|
||||
if (server.sentinel_mode) rewriteConfigSentinelOption(state);
|
||||
|
||||
/* Step 3: remove all the orphaned lines in the old file, that is, lines
|
||||
|
||||
+6
-13
@@ -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,24 +48,20 @@
|
||||
#define HAVE_PROC_STAT 1
|
||||
#define HAVE_PROC_MAPS 1
|
||||
#define HAVE_PROC_SMAPS 1
|
||||
#define HAVE_PROC_SOMAXCONN 1
|
||||
#define HAVE_RSS_REPORTING 1
|
||||
#endif
|
||||
|
||||
/* Test for task_info() */
|
||||
#if defined(__APPLE__)
|
||||
#define HAVE_TASKINFO 1
|
||||
#define HAVE_RSS_REPORTING 1
|
||||
#endif
|
||||
|
||||
/* Test for backtrace() */
|
||||
#if defined(__APPLE__) || (defined(__linux__) && defined(__GLIBC__))
|
||||
#if defined(__APPLE__) || defined(__linux__)
|
||||
#define HAVE_BACKTRACE 1
|
||||
#endif
|
||||
|
||||
/* MSG_NOSIGNAL. */
|
||||
#ifdef __linux__
|
||||
#define HAVE_MSG_NOSIGNAL 1
|
||||
#endif
|
||||
|
||||
/* Test for polling API */
|
||||
#ifdef __linux__
|
||||
#define HAVE_EPOLL 1
|
||||
@@ -97,6 +88,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
|
||||
@@ -121,7 +114,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[]);
|
||||
|
||||
+2
-6
@@ -181,13 +181,9 @@ uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l) {
|
||||
}
|
||||
|
||||
/* Test main */
|
||||
#ifdef REDIS_TEST
|
||||
#ifdef TEST_MAIN
|
||||
#include <stdio.h>
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int crc64Test(int argc, char *argv[]) {
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
int main(void) {
|
||||
printf("e9c6d914c4b8d9ca == %016llx\n",
|
||||
(unsigned long long) crc64(0,(unsigned char*)"123456789",9));
|
||||
return 0;
|
||||
|
||||
@@ -5,8 +5,4 @@
|
||||
|
||||
uint64_t crc64(uint64_t crc, const unsigned char *s, uint64_t l);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int crc64Test(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
@@ -60,32 +60,7 @@ robj *lookupKey(redisDb *db, robj *key) {
|
||||
robj *lookupKeyRead(redisDb *db, robj *key) {
|
||||
robj *val;
|
||||
|
||||
if (expireIfNeeded(db,key) == 1) {
|
||||
/* Key expired. If we are in the context of a master, expireIfNeeded()
|
||||
* returns 0 only when the key does not exist at all, so it's save
|
||||
* to return NULL ASAP. */
|
||||
if (server.masterhost == NULL) return NULL;
|
||||
|
||||
/* However if we are in the context of a slave, expireIfNeeded() will
|
||||
* not really try to expire the key, it only returns information
|
||||
* about the "logical" status of the key: key expiring is up to the
|
||||
* master in order to have a consistent view of master's data set.
|
||||
*
|
||||
* However, if the command caller is not the master, and as additional
|
||||
* safety measure, the command invoked is a read-only command, we can
|
||||
* safely return NULL here, and provide a more consistent behavior
|
||||
* to clients accessign expired values in a read-only fashion, that
|
||||
* will say the key as non exisitng.
|
||||
*
|
||||
* Notably this covers GETs when slaves are used to scale reads. */
|
||||
if (server.current_client &&
|
||||
server.current_client != server.master &&
|
||||
server.current_client->cmd &&
|
||||
server.current_client->cmd->flags & REDIS_CMD_READONLY)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
expireIfNeeded(db,key);
|
||||
val = lookupKey(db,key);
|
||||
if (val == NULL)
|
||||
server.stat_keyspace_misses++;
|
||||
@@ -406,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.");
|
||||
}
|
||||
@@ -450,8 +425,8 @@ void scanGenericCommand(redisClient *c, robj *o, unsigned long cursor) {
|
||||
list *keys = listCreate();
|
||||
listNode *node, *nextnode;
|
||||
long count = 10;
|
||||
sds pat = NULL;
|
||||
int patlen = 0, use_pattern = 0;
|
||||
sds pat;
|
||||
int patlen, use_pattern = 0;
|
||||
dict *ht;
|
||||
|
||||
/* Object must be NULL (to iterate keys names), or the type of the object
|
||||
@@ -688,20 +663,16 @@ void shutdownCommand(redisClient *c) {
|
||||
void renameGenericCommand(redisClient *c, int nx) {
|
||||
robj *o;
|
||||
long long expire;
|
||||
int samekey = 0;
|
||||
|
||||
/* When source and dest key is the same, no operation is performed,
|
||||
* if the key exists, however we still return an error on unexisting key. */
|
||||
if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) samekey = 1;
|
||||
/* To use the same key as src and dst is probably an error */
|
||||
if (sdscmp(c->argv[1]->ptr,c->argv[2]->ptr) == 0) {
|
||||
addReply(c,shared.sameobjecterr);
|
||||
return;
|
||||
}
|
||||
|
||||
if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr)) == NULL)
|
||||
return;
|
||||
|
||||
if (samekey) {
|
||||
addReply(c,nx ? shared.czero : shared.ok);
|
||||
return;
|
||||
}
|
||||
|
||||
incrRefCount(o);
|
||||
expire = getExpire(c->db,c->argv[1]);
|
||||
if (lookupKeyWrite(c->db,c->argv[2]) != NULL) {
|
||||
@@ -906,7 +877,7 @@ void expireGenericCommand(redisClient *c, long long basetime, int unit) {
|
||||
when += basetime;
|
||||
|
||||
/* No key, return zero. */
|
||||
if (lookupKeyWrite(c->db,key) == NULL) {
|
||||
if (lookupKeyRead(c->db,key) == NULL) {
|
||||
addReply(c,shared.czero);
|
||||
return;
|
||||
}
|
||||
|
||||
+6
-64
@@ -252,12 +252,6 @@ void computeDatasetDigest(unsigned char *final) {
|
||||
}
|
||||
}
|
||||
|
||||
void inputCatSds(void *result, const char *str) {
|
||||
/* result is actually a (sds *), so re-cast it here */
|
||||
sds *info = (sds *)result;
|
||||
*info = sdscat(*info, str);
|
||||
}
|
||||
|
||||
void debugCommand(redisClient *c) {
|
||||
if (!strcasecmp(c->argv[1]->ptr,"segfault")) {
|
||||
*((char*)-1) = 'x';
|
||||
@@ -301,46 +295,13 @@ void debugCommand(redisClient *c) {
|
||||
val = dictGetVal(de);
|
||||
strenc = strEncoding(val->encoding);
|
||||
|
||||
char extra[128] = {0};
|
||||
if (val->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
char *nextra = extra;
|
||||
int remaining = sizeof(extra);
|
||||
quicklist *ql = val->ptr;
|
||||
/* Add number of quicklist nodes */
|
||||
int used = snprintf(nextra, remaining, " ql_nodes:%u", ql->len);
|
||||
nextra += used;
|
||||
remaining -= used;
|
||||
/* Add average quicklist fill factor */
|
||||
double avg = (double)ql->count/ql->len;
|
||||
used = snprintf(nextra, remaining, " ql_avg_node:%.2f", avg);
|
||||
nextra += used;
|
||||
remaining -= used;
|
||||
/* Add quicklist fill level / max ziplist size */
|
||||
used = snprintf(nextra, remaining, " ql_ziplist_max:%d", ql->fill);
|
||||
nextra += used;
|
||||
remaining -= used;
|
||||
/* Add isCompressed? */
|
||||
int compressed = ql->compress != 0;
|
||||
used = snprintf(nextra, remaining, " ql_compressed:%d", compressed);
|
||||
nextra += used;
|
||||
remaining -= used;
|
||||
/* Add total uncompressed size */
|
||||
unsigned long sz = 0;
|
||||
for (quicklistNode *node = ql->head; node; node = node->next) {
|
||||
sz += node->sz;
|
||||
}
|
||||
used = snprintf(nextra, remaining, " ql_uncompressed_size:%lu", sz);
|
||||
nextra += used;
|
||||
remaining -= used;
|
||||
}
|
||||
|
||||
addReplyStatusFormat(c,
|
||||
"Value at:%p refcount:%d "
|
||||
"encoding:%s serializedlength:%zu "
|
||||
"lru:%d lru_seconds_idle:%llu%s",
|
||||
"encoding:%s serializedlength:%lld "
|
||||
"lru:%d lru_seconds_idle:%llu",
|
||||
(void*)val, val->refcount,
|
||||
strenc, rdbSavedObjectLen(val),
|
||||
val->lru, estimateObjectIdleTime(val)/1000, extra);
|
||||
strenc, (long long) rdbSavedObjectLen(val),
|
||||
val->lru, estimateObjectIdleTime(val));
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"sdslen") && c->argc == 3) {
|
||||
dictEntry *de;
|
||||
robj *val;
|
||||
@@ -377,7 +338,7 @@ void debugCommand(redisClient *c) {
|
||||
snprintf(buf,sizeof(buf),"%s:%lu",
|
||||
(c->argc == 3) ? "key" : (char*)c->argv[3]->ptr, j);
|
||||
key = createStringObject(buf,strlen(buf));
|
||||
if (lookupKeyWrite(c->db,key) != NULL) {
|
||||
if (lookupKeyRead(c->db,key) != NULL) {
|
||||
decrRefCount(key);
|
||||
continue;
|
||||
}
|
||||
@@ -418,25 +379,6 @@ void debugCommand(redisClient *c) {
|
||||
errstr = sdsmapchars(errstr,"\n\r"," ",2); /* no newlines in errors. */
|
||||
errstr = sdscatlen(errstr,"\r\n",2);
|
||||
addReplySds(c,errstr);
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"structsize") && c->argc == 2) {
|
||||
sds sizes = sdsempty();
|
||||
sizes = sdscatprintf(sizes,"bits:%d ", (sizeof(void*) == 8)?64:32);
|
||||
sizes = sdscatprintf(sizes,"robj:%d ", (int)sizeof(robj));
|
||||
sizes = sdscatprintf(sizes,"dictentry:%d ", (int)sizeof(dictEntry));
|
||||
sizes = sdscatprintf(sizes,"sdshdr:%d", (int)sizeof(struct sdshdr));
|
||||
addReplyBulkSds(c,sizes);
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"jemalloc") && c->argc == 3) {
|
||||
#if defined(USE_JEMALLOC)
|
||||
if (!strcasecmp(c->argv[2]->ptr, "info")) {
|
||||
sds info = sdsempty();
|
||||
je_malloc_stats_print(inputCatSds, &info, NULL);
|
||||
addReplyBulkSds(c, info);
|
||||
} else {
|
||||
addReplyErrorFormat(c, "Valid jemalloc debug fields: info");
|
||||
}
|
||||
#else
|
||||
addReplyErrorFormat(c, "jemalloc support not available");
|
||||
#endif
|
||||
} else {
|
||||
addReplyErrorFormat(c, "Unknown DEBUG subcommand or wrong number of arguments for '%s'",
|
||||
(char*)c->argv[1]->ptr);
|
||||
@@ -915,7 +857,7 @@ void sigsegvHandler(int sig, siginfo_t *info, void *secret) {
|
||||
" Suspect RAM error? Use redis-server --test-memory to verify it.\n\n"
|
||||
);
|
||||
/* free(messages); Don't call free() with possibly corrupted memory. */
|
||||
if (server.daemonize && server.supervised == 0) unlink(server.pidfile);
|
||||
if (server.daemonize) unlink(server.pidfile);
|
||||
|
||||
/* Make sure we exit with the right signal at the end. So for instance
|
||||
* the core will be dumped if enabled. */
|
||||
|
||||
+36
-94
@@ -211,9 +211,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 +232,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;
|
||||
}
|
||||
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 +270,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;
|
||||
}
|
||||
|
||||
@@ -356,10 +342,7 @@ dictEntry *dictAddRaw(dict *d, void *key)
|
||||
if ((index = _dictKeyIndex(d, key)) == -1)
|
||||
return NULL;
|
||||
|
||||
/* Allocate the memory and store the new entry.
|
||||
* Insert the element in top, with the assumption that in a database
|
||||
* system it is more likely that recently added entries are accessed
|
||||
* more frequently. */
|
||||
/* Allocate the memory and store the new entry */
|
||||
ht = dictIsRehashing(d) ? &d->ht[1] : &d->ht[0];
|
||||
entry = zmalloc(sizeof(*entry));
|
||||
entry->next = ht->table[index];
|
||||
@@ -633,11 +616,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);
|
||||
@@ -664,12 +643,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
|
||||
@@ -678,65 +654,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. */
|
||||
unsigned int dictGetRandomKeys(dict *d, dictEntry **des, unsigned int count) {
|
||||
int j; /* internal hash table id, 0 or 1. */
|
||||
unsigned 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 < 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. */
|
||||
@@ -746,11 +685,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:
|
||||
|
||||
+1
-1
@@ -164,7 +164,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);
|
||||
unsigned int dictGetRandomKeys(dict *d, dictEntry **des, unsigned int count);
|
||||
void dictPrintStats(dict *d);
|
||||
unsigned int dictGenHashFunction(const void *key, int len);
|
||||
unsigned int dictGenCaseHashFunction(const unsigned char *buf, int len);
|
||||
|
||||
+2
-6
@@ -101,16 +101,12 @@ uint64_t intrev64(uint64_t v) {
|
||||
return v;
|
||||
}
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
#ifdef TESTMAIN
|
||||
#include <stdio.h>
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int endianconvTest(int argc, char *argv[]) {
|
||||
int main(void) {
|
||||
char buf[32];
|
||||
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
|
||||
sprintf(buf,"ciaoroma");
|
||||
memrev16(buf);
|
||||
printf("%s\n", buf);
|
||||
|
||||
@@ -71,8 +71,4 @@ uint64_t intrev64(uint64_t v);
|
||||
#define ntohu64(v) intrev64(v)
|
||||
#endif
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int endianconvTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
@@ -34,7 +34,6 @@
|
||||
|
||||
#if defined(__linux__)
|
||||
#define _GNU_SOURCE
|
||||
#define _DEFAULT_SOURCE
|
||||
#endif
|
||||
|
||||
#if defined(_AIX)
|
||||
|
||||
+2
-2
@@ -651,8 +651,8 @@ struct commandHelp {
|
||||
0,
|
||||
"1.0.0" },
|
||||
{ "SPOP",
|
||||
"key [count]",
|
||||
"Remove and return one or multiple random members from a set",
|
||||
"key",
|
||||
"Remove and return a random member from a set",
|
||||
3,
|
||||
"1.0.0" },
|
||||
{ "SRANDMEMBER",
|
||||
|
||||
+3
-3
@@ -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]
|
||||
@@ -1233,7 +1233,7 @@ void pfcountCommand(redisClient *c) {
|
||||
*
|
||||
* The user specified a single key. Either return the cached value
|
||||
* or compute one and update the cache. */
|
||||
o = lookupKeyWrite(c->db,c->argv[1]);
|
||||
o = lookupKeyRead(c->db,c->argv[1]);
|
||||
if (o == NULL) {
|
||||
/* No key? Cardinality is zero since no element was added, otherwise
|
||||
* we would have a key as HLLADD creates it as a side effect. */
|
||||
@@ -1458,7 +1458,7 @@ void pfdebugCommand(redisClient *c) {
|
||||
robj *o;
|
||||
int j;
|
||||
|
||||
o = lookupKeyWrite(c->db,c->argv[2]);
|
||||
o = lookupKeyRead(c->db,c->argv[2]);
|
||||
if (o == NULL) {
|
||||
addReplyError(c,"The specified key does not exist");
|
||||
return;
|
||||
|
||||
+21
-30
@@ -281,46 +281,44 @@ size_t intsetBlobLen(intset *is) {
|
||||
return sizeof(intset)+intrev32ifbe(is->length)*intrev32ifbe(is->encoding);
|
||||
}
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
#ifdef INTSET_TEST_MAIN
|
||||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
|
||||
#if 0
|
||||
static void intsetRepr(intset *is) {
|
||||
for (uint32_t i = 0; i < intrev32ifbe(is->length); i++) {
|
||||
void intsetRepr(intset *is) {
|
||||
int i;
|
||||
for (i = 0; i < intrev32ifbe(is->length); i++) {
|
||||
printf("%lld\n", (uint64_t)_intsetGet(is,i));
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
static void error(char *err) {
|
||||
void error(char *err) {
|
||||
printf("%s\n", err);
|
||||
exit(1);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void ok(void) {
|
||||
void ok(void) {
|
||||
printf("OK\n");
|
||||
}
|
||||
|
||||
static long long usec(void) {
|
||||
long long usec(void) {
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv,NULL);
|
||||
return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
|
||||
}
|
||||
|
||||
#define assert(_e) ((_e)?(void)0:(_assert(#_e,__FILE__,__LINE__),exit(1)))
|
||||
static void _assert(char *estr, char *file, int line) {
|
||||
void _assert(char *estr, char *file, int line) {
|
||||
printf("\n\n=== ASSERTION FAILED ===\n");
|
||||
printf("==> %s:%d '%s' is not true\n",file,line,estr);
|
||||
}
|
||||
|
||||
static intset *createSet(int bits, int size) {
|
||||
intset *createSet(int bits, int size) {
|
||||
uint64_t mask = (1<<bits)-1;
|
||||
uint64_t value;
|
||||
uint64_t i, value;
|
||||
intset *is = intsetNew();
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
for (i = 0; i < size; i++) {
|
||||
if (bits > 32) {
|
||||
value = (rand()*rand()) & mask;
|
||||
} else {
|
||||
@@ -331,8 +329,10 @@ static intset *createSet(int bits, int size) {
|
||||
return is;
|
||||
}
|
||||
|
||||
static void checkConsistency(intset *is) {
|
||||
for (uint32_t i = 0; i < (intrev32ifbe(is->length)-1); i++) {
|
||||
void checkConsistency(intset *is) {
|
||||
int i;
|
||||
|
||||
for (i = 0; i < (intrev32ifbe(is->length)-1); i++) {
|
||||
uint32_t encoding = intrev32ifbe(is->encoding);
|
||||
|
||||
if (encoding == INTSET_ENC_INT16) {
|
||||
@@ -348,15 +348,11 @@ static void checkConsistency(intset *is) {
|
||||
}
|
||||
}
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int intsetTest(int argc, char **argv) {
|
||||
int main(int argc, char **argv) {
|
||||
uint8_t success;
|
||||
int i;
|
||||
intset *is;
|
||||
srand(time(NULL));
|
||||
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
sranddev();
|
||||
|
||||
printf("Value encodings: "); {
|
||||
assert(_intsetValueEncoding(-32768) == INTSET_ENC_INT16);
|
||||
@@ -367,10 +363,8 @@ int intsetTest(int argc, char **argv) {
|
||||
assert(_intsetValueEncoding(+2147483647) == INTSET_ENC_INT32);
|
||||
assert(_intsetValueEncoding(-2147483649) == INTSET_ENC_INT64);
|
||||
assert(_intsetValueEncoding(+2147483648) == INTSET_ENC_INT64);
|
||||
assert(_intsetValueEncoding(-9223372036854775808ull) ==
|
||||
INTSET_ENC_INT64);
|
||||
assert(_intsetValueEncoding(+9223372036854775807ull) ==
|
||||
INTSET_ENC_INT64);
|
||||
assert(_intsetValueEncoding(-9223372036854775808ull) == INTSET_ENC_INT64);
|
||||
assert(_intsetValueEncoding(+9223372036854775807ull) == INTSET_ENC_INT64);
|
||||
ok();
|
||||
}
|
||||
|
||||
@@ -384,7 +378,7 @@ int intsetTest(int argc, char **argv) {
|
||||
}
|
||||
|
||||
printf("Large number of random adds: "); {
|
||||
uint32_t inserts = 0;
|
||||
int inserts = 0;
|
||||
is = intsetNew();
|
||||
for (i = 0; i < 1024; i++) {
|
||||
is = intsetAdd(is,rand()%0x800,&success);
|
||||
@@ -467,8 +461,7 @@ int intsetTest(int argc, char **argv) {
|
||||
|
||||
start = usec();
|
||||
for (i = 0; i < num; i++) intsetSearch(is,rand() % ((1<<bits)-1),NULL);
|
||||
printf("%ld lookups, %ld element set, %lldusec\n",
|
||||
num,size,usec()-start);
|
||||
printf("%ld lookups, %ld element set, %lldusec\n",num,size,usec()-start);
|
||||
}
|
||||
|
||||
printf("Stress add+delete: "); {
|
||||
@@ -486,7 +479,5 @@ int intsetTest(int argc, char **argv) {
|
||||
checkConsistency(is);
|
||||
ok();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -47,8 +47,4 @@ uint8_t intsetGet(intset *is, uint32_t pos, int64_t *value);
|
||||
uint32_t intsetLen(intset *is);
|
||||
size_t intsetBlobLen(intset *is);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int intsetTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
#endif // __INTSET_H
|
||||
|
||||
+5
-13
@@ -73,7 +73,6 @@ int THPIsEnabled(void) {
|
||||
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
|
||||
@@ -81,6 +80,7 @@ int THPIsEnabled(void) {
|
||||
int THPGetAnonHugePagesSize(void) {
|
||||
return zmalloc_get_smap_bytes_by_field("AnonHugePages:");
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ---------------------------- Latency API --------------------------------- */
|
||||
|
||||
@@ -228,7 +228,6 @@ 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;
|
||||
@@ -365,13 +364,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++;
|
||||
}
|
||||
|
||||
@@ -458,10 +452,6 @@ sds createLatencyReport(void) {
|
||||
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");
|
||||
}
|
||||
@@ -522,6 +512,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 +534,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,
|
||||
|
||||
@@ -86,8 +86,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 */
|
||||
|
||||
+15
-41
@@ -49,7 +49,7 @@
|
||||
* the difference between 15 and 14 is very small
|
||||
* for small blocks (and 14 is usually a bit faster).
|
||||
* For a low-memory/faster configuration, use HLOG == 13;
|
||||
* For best compression, use 15 or 16 (or more, up to 22).
|
||||
* For best compression, use 15 or 16 (or more, up to 23).
|
||||
*/
|
||||
#ifndef HLOG
|
||||
# define HLOG 16
|
||||
@@ -94,7 +94,7 @@
|
||||
/*
|
||||
* Avoid assigning values to errno variable? for some embedding purposes
|
||||
* (linux kernel for example), this is necessary. NOTE: this breaks
|
||||
* the documentation in lzf.h. Avoiding errno has no speed impact.
|
||||
* the documentation in lzf.h.
|
||||
*/
|
||||
#ifndef AVOID_ERRNO
|
||||
# define AVOID_ERRNO 0
|
||||
@@ -121,52 +121,16 @@
|
||||
# define CHECK_INPUT 1
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Whether to store pointers or offsets inside the hash table. On
|
||||
* 64 bit architetcures, pointers take up twice as much space,
|
||||
* and might also be slower. Default is to autodetect.
|
||||
*/
|
||||
/*#define LZF_USER_OFFSETS autodetect */
|
||||
|
||||
/*****************************************************************************/
|
||||
/* nothing should be changed below */
|
||||
|
||||
#ifdef __cplusplus
|
||||
# include <cstring>
|
||||
# include <climits>
|
||||
using namespace std;
|
||||
#else
|
||||
# include <string.h>
|
||||
# include <limits.h>
|
||||
#endif
|
||||
|
||||
#ifndef LZF_USE_OFFSETS
|
||||
# if defined (WIN32)
|
||||
# define LZF_USE_OFFSETS defined(_M_X64)
|
||||
# else
|
||||
# if __cplusplus > 199711L
|
||||
# include <cstdint>
|
||||
# else
|
||||
# include <stdint.h>
|
||||
# endif
|
||||
# define LZF_USE_OFFSETS (UINTPTR_MAX > 0xffffffffU)
|
||||
# endif
|
||||
#endif
|
||||
|
||||
typedef unsigned char u8;
|
||||
|
||||
#if LZF_USE_OFFSETS
|
||||
# define LZF_HSLOT_BIAS ((const u8 *)in_data)
|
||||
typedef unsigned int LZF_HSLOT;
|
||||
#else
|
||||
# define LZF_HSLOT_BIAS 0
|
||||
typedef const u8 *LZF_HSLOT;
|
||||
#endif
|
||||
|
||||
typedef LZF_HSLOT LZF_STATE[1 << (HLOG)];
|
||||
typedef const u8 *LZF_STATE[1 << (HLOG)];
|
||||
|
||||
#if !STRICT_ALIGN
|
||||
/* for unaligned accesses we need a 16 bit datatype. */
|
||||
# include <limits.h>
|
||||
# if USHRT_MAX == 65535
|
||||
typedef unsigned short u16;
|
||||
# elif UINT_MAX == 65535
|
||||
@@ -178,7 +142,17 @@ typedef LZF_HSLOT LZF_STATE[1 << (HLOG)];
|
||||
#endif
|
||||
|
||||
#if ULTRA_FAST
|
||||
# undef VERY_FAST
|
||||
# if defined(VERY_FAST)
|
||||
# undef VERY_FAST
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if INIT_HTAB
|
||||
# ifdef __cplusplus
|
||||
# include <cstring>
|
||||
# else
|
||||
# include <string.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+23
-19
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2000-2010 Marc Alexander Lehmann <schmorp@schmorp.de>
|
||||
* Copyright (c) 2000-2008 Marc Alexander Lehmann <schmorp@schmorp.de>
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without modifica-
|
||||
* tion, are permitted provided that the following conditions are met:
|
||||
@@ -40,8 +40,8 @@
|
||||
|
||||
/*
|
||||
* don't play with this unless you benchmark!
|
||||
* the data format is not dependent on the hash function.
|
||||
* the hash function might seem strange, just believe me,
|
||||
* decompression is not dependent on the hash function
|
||||
* the hashing function might seem strange, just believe me
|
||||
* it works ;)
|
||||
*/
|
||||
#ifndef FRST
|
||||
@@ -89,9 +89,9 @@
|
||||
/*
|
||||
* compressed format
|
||||
*
|
||||
* 000LLLLL <L+1> ; literal, L+1=1..33 octets
|
||||
* LLLooooo oooooooo ; backref L+1=1..7 octets, o+1=1..4096 offset
|
||||
* 111ooooo LLLLLLLL oooooooo ; backref L+8 octets, o+1=1..4096 offset
|
||||
* 000LLLLL <L+1> ; literal
|
||||
* LLLooooo oooooooo ; backref L
|
||||
* 111ooooo LLLLLLLL oooooooo ; backref L+7
|
||||
*
|
||||
*/
|
||||
|
||||
@@ -106,6 +106,7 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
#if !LZF_STATE_ARG
|
||||
LZF_STATE htab;
|
||||
#endif
|
||||
const u8 **hslot;
|
||||
const u8 *ip = (const u8 *)in_data;
|
||||
u8 *op = (u8 *)out_data;
|
||||
const u8 *in_end = ip + in_len;
|
||||
@@ -132,6 +133,10 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
|
||||
#if INIT_HTAB
|
||||
memset (htab, 0, sizeof (htab));
|
||||
# if 0
|
||||
for (hslot = htab; hslot < htab + HSIZE; hslot++)
|
||||
*hslot++ = ip;
|
||||
# endif
|
||||
#endif
|
||||
|
||||
lit = 0; op++; /* start run */
|
||||
@@ -139,23 +144,24 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
hval = FRST (ip);
|
||||
while (ip < in_end - 2)
|
||||
{
|
||||
LZF_HSLOT *hslot;
|
||||
|
||||
hval = NEXT (hval, ip);
|
||||
hslot = htab + IDX (hval);
|
||||
ref = *hslot + LZF_HSLOT_BIAS; *hslot = ip - LZF_HSLOT_BIAS;
|
||||
ref = *hslot; *hslot = ip;
|
||||
|
||||
if (1
|
||||
#if INIT_HTAB
|
||||
&& ref < ip /* the next test will actually take care of this, but this is faster */
|
||||
#endif
|
||||
&& (off = ip - ref - 1) < MAX_OFF
|
||||
&& ip + 4 < in_end
|
||||
&& ref > (u8 *)in_data
|
||||
&& ref[2] == ip[2]
|
||||
#if STRICT_ALIGN
|
||||
&& ((ref[1] << 8) | ref[0]) == ((ip[1] << 8) | ip[0])
|
||||
&& ref[0] == ip[0]
|
||||
&& ref[1] == ip[1]
|
||||
&& ref[2] == ip[2]
|
||||
#else
|
||||
&& *(u16 *)ref == *(u16 *)ip
|
||||
&& ref[2] == ip[2]
|
||||
#endif
|
||||
)
|
||||
{
|
||||
@@ -164,13 +170,12 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
unsigned int maxlen = in_end - ip - len;
|
||||
maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;
|
||||
|
||||
if (expect_false (op + 3 + 1 >= out_end)) /* first a faster conservative test */
|
||||
if (op - !lit + 3 + 1 >= out_end) /* second the exact but rare test */
|
||||
return 0;
|
||||
|
||||
op [- lit - 1] = lit - 1; /* stop run */
|
||||
op -= !lit; /* undo run if length is zero */
|
||||
|
||||
if (expect_false (op + 3 + 1 >= out_end))
|
||||
return 0;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
if (expect_true (maxlen > 16))
|
||||
@@ -217,7 +222,6 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
}
|
||||
|
||||
*op++ = off;
|
||||
|
||||
lit = 0; op++; /* start run */
|
||||
|
||||
ip += len + 1;
|
||||
@@ -233,12 +237,12 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
hval = FRST (ip);
|
||||
|
||||
hval = NEXT (hval, ip);
|
||||
htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;
|
||||
htab[IDX (hval)] = ip;
|
||||
ip++;
|
||||
|
||||
# if VERY_FAST && !ULTRA_FAST
|
||||
hval = NEXT (hval, ip);
|
||||
htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;
|
||||
htab[IDX (hval)] = ip;
|
||||
ip++;
|
||||
# endif
|
||||
#else
|
||||
@@ -247,7 +251,7 @@ lzf_compress (const void *const in_data, unsigned int in_len,
|
||||
do
|
||||
{
|
||||
hval = NEXT (hval, ip);
|
||||
htab[IDX (hval)] = ip - LZF_HSLOT_BIAS;
|
||||
htab[IDX (hval)] = ip;
|
||||
ip++;
|
||||
}
|
||||
while (len--);
|
||||
|
||||
+11
-46
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2000-2010 Marc Alexander Lehmann <schmorp@schmorp.de>
|
||||
* Copyright (c) 2000-2007 Marc Alexander Lehmann <schmorp@schmorp.de>
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without modifica-
|
||||
* tion, are permitted provided that the following conditions are met:
|
||||
@@ -43,14 +43,14 @@
|
||||
# define SET_ERRNO(n) errno = (n)
|
||||
#endif
|
||||
|
||||
#if USE_REP_MOVSB /* small win on amd, big loss on intel */
|
||||
/*
|
||||
#if (__i386 || __amd64) && __GNUC__ >= 3
|
||||
# define lzf_movsb(dst, src, len) \
|
||||
asm ("rep movsb" \
|
||||
: "=D" (dst), "=S" (src), "=c" (len) \
|
||||
: "0" (dst), "1" (src), "2" (len));
|
||||
#endif
|
||||
#endif
|
||||
*/
|
||||
|
||||
unsigned int
|
||||
lzf_decompress (const void *const in_data, unsigned int in_len,
|
||||
@@ -86,17 +86,9 @@ lzf_decompress (const void *const in_data, unsigned int in_len,
|
||||
#ifdef lzf_movsb
|
||||
lzf_movsb (op, ip, ctrl);
|
||||
#else
|
||||
switch (ctrl)
|
||||
{
|
||||
case 32: *op++ = *ip++; case 31: *op++ = *ip++; case 30: *op++ = *ip++; case 29: *op++ = *ip++;
|
||||
case 28: *op++ = *ip++; case 27: *op++ = *ip++; case 26: *op++ = *ip++; case 25: *op++ = *ip++;
|
||||
case 24: *op++ = *ip++; case 23: *op++ = *ip++; case 22: *op++ = *ip++; case 21: *op++ = *ip++;
|
||||
case 20: *op++ = *ip++; case 19: *op++ = *ip++; case 18: *op++ = *ip++; case 17: *op++ = *ip++;
|
||||
case 16: *op++ = *ip++; case 15: *op++ = *ip++; case 14: *op++ = *ip++; case 13: *op++ = *ip++;
|
||||
case 12: *op++ = *ip++; case 11: *op++ = *ip++; case 10: *op++ = *ip++; case 9: *op++ = *ip++;
|
||||
case 8: *op++ = *ip++; case 7: *op++ = *ip++; case 6: *op++ = *ip++; case 5: *op++ = *ip++;
|
||||
case 4: *op++ = *ip++; case 3: *op++ = *ip++; case 2: *op++ = *ip++; case 1: *op++ = *ip++;
|
||||
}
|
||||
do
|
||||
*op++ = *ip++;
|
||||
while (--ctrl);
|
||||
#endif
|
||||
}
|
||||
else /* back reference */
|
||||
@@ -142,39 +134,12 @@ lzf_decompress (const void *const in_data, unsigned int in_len,
|
||||
len += 2;
|
||||
lzf_movsb (op, ref, len);
|
||||
#else
|
||||
switch (len)
|
||||
{
|
||||
default:
|
||||
len += 2;
|
||||
*op++ = *ref++;
|
||||
*op++ = *ref++;
|
||||
|
||||
if (op >= ref + len)
|
||||
{
|
||||
/* disjunct areas */
|
||||
memcpy (op, ref, len);
|
||||
op += len;
|
||||
}
|
||||
else
|
||||
{
|
||||
/* overlapping, use octte by octte copying */
|
||||
do
|
||||
*op++ = *ref++;
|
||||
while (--len);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 9: *op++ = *ref++;
|
||||
case 8: *op++ = *ref++;
|
||||
case 7: *op++ = *ref++;
|
||||
case 6: *op++ = *ref++;
|
||||
case 5: *op++ = *ref++;
|
||||
case 4: *op++ = *ref++;
|
||||
case 3: *op++ = *ref++;
|
||||
case 2: *op++ = *ref++;
|
||||
case 1: *op++ = *ref++;
|
||||
case 0: *op++ = *ref++; /* two octets more */
|
||||
*op++ = *ref++;
|
||||
}
|
||||
do
|
||||
*op++ = *ref++;
|
||||
while (--len);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
+40
-31
@@ -525,14 +525,6 @@ void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) {
|
||||
addReply(c,shared.crlf);
|
||||
}
|
||||
|
||||
/* Add sds to reply (takes ownership of sds and frees it) */
|
||||
void addReplyBulkSds(redisClient *c, sds s) {
|
||||
addReplySds(c,sdscatfmt(sdsempty(),"$%u\r\n",
|
||||
(unsigned long)sdslen(s)));
|
||||
addReplySds(c,s);
|
||||
addReply(c,shared.crlf);
|
||||
}
|
||||
|
||||
/* Add a C nul term string as bulk reply */
|
||||
void addReplyBulkCString(redisClient *c, char *s) {
|
||||
if (s == NULL) {
|
||||
@@ -797,8 +789,7 @@ void freeClientsInAsyncFreeQueue(void) {
|
||||
|
||||
void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
redisClient *c = privdata;
|
||||
ssize_t nwritten = 0, totwritten = 0;
|
||||
size_t objlen;
|
||||
int nwritten = 0, totwritten = 0, objlen;
|
||||
size_t objmem;
|
||||
robj *o;
|
||||
REDIS_NOTUSED(el);
|
||||
@@ -813,7 +804,7 @@ void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
|
||||
/* If the buffer was sent, set bufpos to zero to continue with
|
||||
* the remainder of the reply. */
|
||||
if ((int)c->sentlen == c->bufpos) {
|
||||
if (c->sentlen == c->bufpos) {
|
||||
c->bufpos = 0;
|
||||
c->sentlen = 0;
|
||||
}
|
||||
@@ -848,7 +839,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;
|
||||
@@ -936,10 +926,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++) {
|
||||
@@ -1106,19 +1094,18 @@ int processMultibulkBuffer(redisClient *c) {
|
||||
}
|
||||
|
||||
void processInputBuffer(redisClient *c) {
|
||||
server.current_client = c;
|
||||
/* Keep processing while there is something in the input buffer */
|
||||
while(sdslen(c->querybuf)) {
|
||||
/* Return if clients are paused. */
|
||||
if (!(c->flags & REDIS_SLAVE) && clientsArePaused()) break;
|
||||
if (!(c->flags & REDIS_SLAVE) && clientsArePaused()) return;
|
||||
|
||||
/* Immediately abort if the client is in the middle of something. */
|
||||
if (c->flags & REDIS_BLOCKED) break;
|
||||
if (c->flags & REDIS_BLOCKED) return;
|
||||
|
||||
/* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
|
||||
* written to the client. Make sure to not let the reply grow after
|
||||
* this flag has been set (i.e. don't process more commands). */
|
||||
if (c->flags & REDIS_CLOSE_AFTER_REPLY) break;
|
||||
if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
|
||||
|
||||
/* Determine request type when unknown. */
|
||||
if (!c->reqtype) {
|
||||
@@ -1146,7 +1133,6 @@ void processInputBuffer(redisClient *c) {
|
||||
resetClient(c);
|
||||
}
|
||||
}
|
||||
server.current_client = NULL;
|
||||
}
|
||||
|
||||
void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
@@ -1156,6 +1142,7 @@ void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
REDIS_NOTUSED(el);
|
||||
REDIS_NOTUSED(mask);
|
||||
|
||||
server.current_client = c;
|
||||
readlen = REDIS_IOBUF_LEN;
|
||||
/* If this is a multi bulk request, and we are processing a bulk reply
|
||||
* that is large enough, try to maximize the probability that the query
|
||||
@@ -1177,7 +1164,7 @@ void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
nread = read(fd, c->querybuf+qblen, readlen);
|
||||
if (nread == -1) {
|
||||
if (errno == EAGAIN) {
|
||||
return;
|
||||
nread = 0;
|
||||
} else {
|
||||
redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
|
||||
freeClient(c);
|
||||
@@ -1188,11 +1175,14 @@ void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
freeClient(c);
|
||||
return;
|
||||
}
|
||||
|
||||
sdsIncrLen(c->querybuf,nread);
|
||||
c->lastinteraction = server.unixtime;
|
||||
if (c->flags & REDIS_MASTER) c->reploff += nread;
|
||||
server.stat_net_input_bytes += nread;
|
||||
if (nread) {
|
||||
sdsIncrLen(c->querybuf,nread);
|
||||
c->lastinteraction = server.unixtime;
|
||||
if (c->flags & REDIS_MASTER) c->reploff += nread;
|
||||
} else {
|
||||
server.current_client = NULL;
|
||||
return;
|
||||
}
|
||||
if (sdslen(c->querybuf) > server.client_max_querybuf_len) {
|
||||
sds ci = catClientInfoString(sdsempty(),c), bytes = sdsempty();
|
||||
|
||||
@@ -1204,6 +1194,7 @@ void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
return;
|
||||
}
|
||||
processInputBuffer(c);
|
||||
server.current_client = NULL;
|
||||
}
|
||||
|
||||
void getClientsMaxBuffers(unsigned long *longest_output_list,
|
||||
@@ -1224,6 +1215,17 @@ void getClientsMaxBuffers(unsigned long *longest_output_list,
|
||||
*biggest_input_buffer = bib;
|
||||
}
|
||||
|
||||
/* This is a helper function for genClientPeerId().
|
||||
* It writes the specified ip/port to "peerid" as a null termiated string
|
||||
* in the form ip:port if ip does not contain ":" itself, otherwise
|
||||
* [ip]:port format is used (for IPv6 addresses basically). */
|
||||
void formatPeerId(char *peerid, size_t peerid_len, char *ip, int port) {
|
||||
if (strchr(ip,':'))
|
||||
snprintf(peerid,peerid_len,"[%s]:%d",ip,port);
|
||||
else
|
||||
snprintf(peerid,peerid_len,"%s:%d",ip,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 IPv6 addresses we use [] around the IP part, like in "[::1]:1234".
|
||||
@@ -1232,17 +1234,24 @@ void getClientsMaxBuffers(unsigned long *longest_output_list,
|
||||
* A Peer ID always fits inside a buffer of REDIS_PEER_ID_LEN bytes, including
|
||||
* the null term.
|
||||
*
|
||||
* The function returns REDIS_OK on succcess, and REDIS_ERR on failure.
|
||||
*
|
||||
* On failure the function still populates 'peerid' with the "?:0" string
|
||||
* in case you want to relax error checking or need to display something
|
||||
* anyway (see anetPeerToString implementation for more info). */
|
||||
void genClientPeerId(redisClient *client, char *peerid,
|
||||
size_t peerid_len) {
|
||||
int genClientPeerId(redisClient *client, char *peerid, size_t peerid_len) {
|
||||
char ip[REDIS_IP_STR_LEN];
|
||||
int port;
|
||||
|
||||
if (client->flags & REDIS_UNIX_SOCKET) {
|
||||
/* Unix socket client. */
|
||||
snprintf(peerid,peerid_len,"%s:0",server.unixsocket);
|
||||
return REDIS_OK;
|
||||
} else {
|
||||
/* TCP client. */
|
||||
anetFormatPeer(client->fd,peerid,peerid_len);
|
||||
int retval = anetPeerToString(client->fd,ip,sizeof(ip),&port);
|
||||
formatPeerId(peerid,peerid_len,ip,port);
|
||||
return (retval == -1) ? REDIS_ERR : REDIS_OK;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1618,7 +1627,7 @@ int checkClientOutputBufferLimits(redisClient *c) {
|
||||
* called from contexts where the client can't be freed safely, i.e. from the
|
||||
* lower level functions pushing data inside the client output buffers. */
|
||||
void asyncCloseClientOnOutputBufferLimitReached(redisClient *c) {
|
||||
redisAssert(c->reply_bytes < SIZE_MAX-(1024*64));
|
||||
redisAssert(c->reply_bytes < ULONG_MAX-(1024*64));
|
||||
if (c->reply_bytes == 0 || c->flags & REDIS_CLOSE_ASAP) return;
|
||||
if (checkClientOutputBufferLimits(c)) {
|
||||
sds client = catClientInfoString(sdsempty(),c);
|
||||
|
||||
+26
-40
@@ -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);
|
||||
}
|
||||
@@ -180,10 +162,11 @@ robj *dupStringObject(robj *o) {
|
||||
}
|
||||
}
|
||||
|
||||
robj *createQuicklistObject(void) {
|
||||
quicklist *l = quicklistCreate();
|
||||
robj *createListObject(void) {
|
||||
list *l = listCreate();
|
||||
robj *o = createObject(REDIS_LIST,l);
|
||||
o->encoding = REDIS_ENCODING_QUICKLIST;
|
||||
listSetFreeMethod(l,decrRefCountVoid);
|
||||
o->encoding = REDIS_ENCODING_LINKEDLIST;
|
||||
return o;
|
||||
}
|
||||
|
||||
@@ -241,8 +224,11 @@ void freeStringObject(robj *o) {
|
||||
|
||||
void freeListObject(robj *o) {
|
||||
switch (o->encoding) {
|
||||
case REDIS_ENCODING_QUICKLIST:
|
||||
quicklistRelease(o->ptr);
|
||||
case REDIS_ENCODING_LINKEDLIST:
|
||||
listRelease((list*) o->ptr);
|
||||
break;
|
||||
case REDIS_ENCODING_ZIPLIST:
|
||||
zfree(o->ptr);
|
||||
break;
|
||||
default:
|
||||
redisPanic("Unknown list encoding type");
|
||||
@@ -674,7 +660,7 @@ char *strEncoding(int encoding) {
|
||||
case REDIS_ENCODING_RAW: return "raw";
|
||||
case REDIS_ENCODING_INT: return "int";
|
||||
case REDIS_ENCODING_HT: return "hashtable";
|
||||
case REDIS_ENCODING_QUICKLIST: return "quicklist";
|
||||
case REDIS_ENCODING_LINKEDLIST: return "linkedlist";
|
||||
case REDIS_ENCODING_ZIPLIST: return "ziplist";
|
||||
case REDIS_ENCODING_INTSET: return "intset";
|
||||
case REDIS_ENCODING_SKIPLIST: return "skiplist";
|
||||
|
||||
-2650
File diff suppressed because it is too large
Load Diff
-169
@@ -1,169 +0,0 @@
|
||||
/* quicklist.h - A generic doubly linked quicklist implementation
|
||||
*
|
||||
* Copyright (c) 2014, Matt Stancliff <matt@genges.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 quicklist of conditions and the following disclaimer.
|
||||
* * Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this quicklist of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* * Neither the name of Redis nor the names of its contributors may be used
|
||||
* to endorse or promote products derived from this software without
|
||||
* specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
* POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef __QUICKLIST_H__
|
||||
#define __QUICKLIST_H__
|
||||
|
||||
/* Node, quicklist, and Iterator are the only data structures used currently. */
|
||||
|
||||
/* quicklistNode is a 32 byte struct describing a ziplist for a quicklist.
|
||||
* We use bit fields keep the quicklistNode at 32 bytes.
|
||||
* count: 16 bits, max 65536 (max zl bytes is 65k, so max count actually < 32k).
|
||||
* encoding: 2 bits, RAW=1, LZF=2.
|
||||
* container: 2 bits, NONE=1, ZIPLIST=2.
|
||||
* recompress: 1 bit, bool, true if node is temporarry decompressed for usage.
|
||||
* attempted_compress: 1 bit, boolean, used for verifying during testing.
|
||||
* extra: 12 bits, free for future use; pads out the remainder of 32 bits */
|
||||
typedef struct quicklistNode {
|
||||
struct quicklistNode *prev;
|
||||
struct quicklistNode *next;
|
||||
unsigned char *zl;
|
||||
unsigned int sz; /* ziplist size in bytes */
|
||||
unsigned int count : 16; /* count of items in ziplist */
|
||||
unsigned int encoding : 2; /* RAW==1 or LZF==2 */
|
||||
unsigned int container : 2; /* NONE==1 or ZIPLIST==2 */
|
||||
unsigned int recompress : 1; /* was this node previous compressed? */
|
||||
unsigned int attempted_compress : 1; /* node can't compress; too small */
|
||||
unsigned int extra : 10; /* more bits to steal for future usage */
|
||||
} quicklistNode;
|
||||
|
||||
/* quicklistLZF is a 4+N byte struct holding 'sz' followed by 'compressed'.
|
||||
* 'sz' is byte length of 'compressed' field.
|
||||
* 'compressed' is LZF data with total (compressed) length 'sz'
|
||||
* NOTE: uncompressed length is stored in quicklistNode->sz.
|
||||
* When quicklistNode->zl is compressed, node->zl points to a quicklistLZF */
|
||||
typedef struct quicklistLZF {
|
||||
unsigned int sz; /* LZF size in bytes*/
|
||||
char compressed[];
|
||||
} quicklistLZF;
|
||||
|
||||
/* quicklist is a 32 byte struct (on 64-bit systems) describing a quicklist.
|
||||
* 'count' is the number of total entries.
|
||||
* 'len' is the number of quicklist nodes.
|
||||
* 'compress' is: -1 if compression disabled, otherwise it's the number
|
||||
* of quicklistNodes to leave uncompressed at ends of quicklist.
|
||||
* 'fill' is the user-requested (or default) fill factor. */
|
||||
typedef struct quicklist {
|
||||
quicklistNode *head;
|
||||
quicklistNode *tail;
|
||||
unsigned long count; /* total count of all entries in all ziplists */
|
||||
unsigned int len; /* number of quicklistNodes */
|
||||
int fill : 16; /* fill factor for individual nodes */
|
||||
unsigned int compress : 16; /* depth of end nodes not to compress;0=off */
|
||||
} quicklist;
|
||||
|
||||
typedef struct quicklistIter {
|
||||
const quicklist *quicklist;
|
||||
quicklistNode *current;
|
||||
unsigned char *zi;
|
||||
long offset; /* offset in current ziplist */
|
||||
int direction;
|
||||
} quicklistIter;
|
||||
|
||||
typedef struct quicklistEntry {
|
||||
const quicklist *quicklist;
|
||||
quicklistNode *node;
|
||||
unsigned char *zi;
|
||||
unsigned char *value;
|
||||
unsigned int sz;
|
||||
long long longval;
|
||||
int offset;
|
||||
} quicklistEntry;
|
||||
|
||||
#define QUICKLIST_HEAD 0
|
||||
#define QUICKLIST_TAIL -1
|
||||
|
||||
/* quicklist node encodings */
|
||||
#define QUICKLIST_NODE_ENCODING_RAW 1
|
||||
#define QUICKLIST_NODE_ENCODING_LZF 2
|
||||
|
||||
/* quicklist compression disable */
|
||||
#define QUICKLIST_NOCOMPRESS 0
|
||||
|
||||
/* quicklist container formats */
|
||||
#define QUICKLIST_NODE_CONTAINER_NONE 1
|
||||
#define QUICKLIST_NODE_CONTAINER_ZIPLIST 2
|
||||
|
||||
#define quicklistNodeIsCompressed(node) \
|
||||
((node)->encoding == QUICKLIST_NODE_ENCODING_LZF)
|
||||
|
||||
/* Prototypes */
|
||||
quicklist *quicklistCreate(void);
|
||||
quicklist *quicklistNew(int fill, int compress);
|
||||
void quicklistSetCompressDepth(quicklist *quicklist, int depth);
|
||||
void quicklistSetFill(quicklist *quicklist, int fill);
|
||||
void quicklistSetOptions(quicklist *quicklist, int fill, int depth);
|
||||
void quicklistRelease(quicklist *quicklist);
|
||||
int quicklistPushHead(quicklist *quicklist, void *value, const size_t sz);
|
||||
int quicklistPushTail(quicklist *quicklist, void *value, const size_t sz);
|
||||
void quicklistPush(quicklist *quicklist, void *value, const size_t sz,
|
||||
int where);
|
||||
void quicklistAppendZiplist(quicklist *quicklist, unsigned char *zl);
|
||||
quicklist *quicklistAppendValuesFromZiplist(quicklist *quicklist,
|
||||
unsigned char *zl);
|
||||
quicklist *quicklistCreateFromZiplist(int fill, int compress,
|
||||
unsigned char *zl);
|
||||
void quicklistInsertAfter(quicklist *quicklist, quicklistEntry *node,
|
||||
void *value, const size_t sz);
|
||||
void quicklistInsertBefore(quicklist *quicklist, quicklistEntry *node,
|
||||
void *value, const size_t sz);
|
||||
void quicklistDelEntry(quicklistIter *iter, quicklistEntry *entry);
|
||||
int quicklistReplaceAtIndex(quicklist *quicklist, long index, void *data,
|
||||
int sz);
|
||||
int quicklistDelRange(quicklist *quicklist, const long start, const long stop);
|
||||
quicklistIter *quicklistGetIterator(const quicklist *quicklist, int direction);
|
||||
quicklistIter *quicklistGetIteratorAtIdx(const quicklist *quicklist,
|
||||
int direction, const long long idx);
|
||||
int quicklistNext(quicklistIter *iter, quicklistEntry *node);
|
||||
void quicklistReleaseIterator(quicklistIter *iter);
|
||||
quicklist *quicklistDup(quicklist *orig);
|
||||
int quicklistIndex(const quicklist *quicklist, const long long index,
|
||||
quicklistEntry *entry);
|
||||
void quicklistRewind(quicklist *quicklist, quicklistIter *li);
|
||||
void quicklistRewindTail(quicklist *quicklist, quicklistIter *li);
|
||||
void quicklistRotate(quicklist *quicklist);
|
||||
int quicklistPopCustom(quicklist *quicklist, int where, unsigned char **data,
|
||||
unsigned int *sz, long long *sval,
|
||||
void *(*saver)(unsigned char *data, unsigned int sz));
|
||||
int quicklistPop(quicklist *quicklist, int where, unsigned char **data,
|
||||
unsigned int *sz, long long *slong);
|
||||
unsigned int quicklistCount(quicklist *ql);
|
||||
int quicklistCompare(unsigned char *p1, unsigned char *p2, int p2_len);
|
||||
size_t quicklistGetLzf(const quicklistNode *node, void **data);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int quicklistTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
/* Directions for iterators */
|
||||
#define AL_START_HEAD 0
|
||||
#define AL_START_TAIL 1
|
||||
|
||||
#endif /* __QUICKLIST_H__ */
|
||||
@@ -40,20 +40,6 @@
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#define RDB_LOAD_NONE 0
|
||||
#define RDB_LOAD_ENC (1<<0)
|
||||
#define RDB_LOAD_PLAIN (1<<1)
|
||||
|
||||
#define rdbExitReportCorruptRDB(reason) rdbCheckThenExit(reason, __LINE__);
|
||||
|
||||
void rdbCheckThenExit(char *reason, int where) {
|
||||
redisLog(REDIS_WARNING, "Corrupt RDB detected at rdb.c:%d (%s). "
|
||||
"Running 'redis-check-rdb %s'",
|
||||
where, reason, server.rdb_filename);
|
||||
redis_check_rdb(server.rdb_filename);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
static int rdbWriteRaw(rio *rdb, void *p, size_t len) {
|
||||
if (rdb && rioWrite(rdb,p,len) == 0)
|
||||
return -1;
|
||||
@@ -175,11 +161,9 @@ int rdbEncodeInteger(long long value, unsigned char *enc) {
|
||||
}
|
||||
|
||||
/* Loads an integer-encoded object with the specified encoding type "enctype".
|
||||
* The returned value changes according to the flags, see
|
||||
* rdbGenerincLoadStringObject() for more info. */
|
||||
void *rdbLoadIntegerObject(rio *rdb, int enctype, int flags) {
|
||||
int plain = flags & RDB_LOAD_PLAIN;
|
||||
int encode = flags & RDB_LOAD_ENC;
|
||||
* If the "encode" argument is set the function may return an integer-encoded
|
||||
* string object, otherwise it always returns a raw string object. */
|
||||
robj *rdbLoadIntegerObject(rio *rdb, int enctype, int encode) {
|
||||
unsigned char enc[4];
|
||||
long long val;
|
||||
|
||||
@@ -198,19 +182,12 @@ void *rdbLoadIntegerObject(rio *rdb, int enctype, int flags) {
|
||||
val = (int32_t)v;
|
||||
} else {
|
||||
val = 0; /* anti-warning */
|
||||
rdbExitReportCorruptRDB("Unknown RDB integer encoding type");
|
||||
redisPanic("Unknown RDB integer encoding type");
|
||||
}
|
||||
if (plain) {
|
||||
char buf[REDIS_LONGSTR_SIZE], *p;
|
||||
int len = ll2string(buf,sizeof(buf),val);
|
||||
p = zmalloc(len);
|
||||
memcpy(p,buf,len);
|
||||
return p;
|
||||
} else if (encode) {
|
||||
if (encode)
|
||||
return createStringObjectFromLongLong(val);
|
||||
} else {
|
||||
else
|
||||
return createObject(REDIS_STRING,sdsfromlonglong(val));
|
||||
}
|
||||
}
|
||||
|
||||
/* String objects in the form "2391" "-100" without any space and with a
|
||||
@@ -232,33 +209,10 @@ int rdbTryIntegerEncoding(char *s, size_t len, unsigned char *enc) {
|
||||
return rdbEncodeInteger(value,enc);
|
||||
}
|
||||
|
||||
ssize_t rdbSaveLzfBlob(rio *rdb, void *data, size_t compress_len,
|
||||
size_t original_len) {
|
||||
unsigned char byte;
|
||||
ssize_t n, nwritten = 0;
|
||||
|
||||
/* Data compressed! Let's save it on disk */
|
||||
byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
|
||||
if ((n = rdbWriteRaw(rdb,&byte,1)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
if ((n = rdbSaveLen(rdb,compress_len)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
if ((n = rdbSaveLen(rdb,original_len)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
if ((n = rdbWriteRaw(rdb,data,compress_len)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
return nwritten;
|
||||
|
||||
writeerr:
|
||||
return -1;
|
||||
}
|
||||
|
||||
ssize_t rdbSaveLzfStringObject(rio *rdb, unsigned char *s, size_t len) {
|
||||
int rdbSaveLzfStringObject(rio *rdb, unsigned char *s, size_t len) {
|
||||
size_t comprlen, outlen;
|
||||
unsigned char byte;
|
||||
int n, nwritten = 0;
|
||||
void *out;
|
||||
|
||||
/* We require at least four bytes compression for this to be worth it */
|
||||
@@ -270,16 +224,29 @@ ssize_t rdbSaveLzfStringObject(rio *rdb, unsigned char *s, size_t len) {
|
||||
zfree(out);
|
||||
return 0;
|
||||
}
|
||||
ssize_t nwritten = rdbSaveLzfBlob(rdb, out, comprlen, len);
|
||||
/* Data compressed! Let's save it on disk */
|
||||
byte = (REDIS_RDB_ENCVAL<<6)|REDIS_RDB_ENC_LZF;
|
||||
if ((n = rdbWriteRaw(rdb,&byte,1)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
if ((n = rdbSaveLen(rdb,comprlen)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
if ((n = rdbSaveLen(rdb,len)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
if ((n = rdbWriteRaw(rdb,out,comprlen)) == -1) goto writeerr;
|
||||
nwritten += n;
|
||||
|
||||
zfree(out);
|
||||
return nwritten;
|
||||
|
||||
writeerr:
|
||||
zfree(out);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Load an LZF compressed string in RDB format. The returned value
|
||||
* changes according to 'flags'. For more info check the
|
||||
* rdbGenericLoadStringObject() function. */
|
||||
void *rdbLoadLzfStringObject(rio *rdb, int flags) {
|
||||
int plain = flags & RDB_LOAD_PLAIN;
|
||||
robj *rdbLoadLzfStringObject(rio *rdb) {
|
||||
unsigned int len, clen;
|
||||
unsigned char *c = NULL;
|
||||
sds val = NULL;
|
||||
@@ -287,37 +254,22 @@ void *rdbLoadLzfStringObject(rio *rdb, int flags) {
|
||||
if ((clen = rdbLoadLen(rdb,NULL)) == REDIS_RDB_LENERR) return NULL;
|
||||
if ((len = rdbLoadLen(rdb,NULL)) == REDIS_RDB_LENERR) return NULL;
|
||||
if ((c = zmalloc(clen)) == NULL) goto err;
|
||||
|
||||
/* Allocate our target according to the uncompressed size. */
|
||||
if (plain) {
|
||||
val = zmalloc(len);
|
||||
} else {
|
||||
if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
|
||||
}
|
||||
|
||||
/* Load the compressed representation and uncompress it to target. */
|
||||
if ((val = sdsnewlen(NULL,len)) == NULL) goto err;
|
||||
if (rioRead(rdb,c,clen) == 0) goto err;
|
||||
if (lzf_decompress(c,clen,val,len) == 0) goto err;
|
||||
zfree(c);
|
||||
|
||||
if (plain)
|
||||
return val;
|
||||
else
|
||||
return createObject(REDIS_STRING,val);
|
||||
return createObject(REDIS_STRING,val);
|
||||
err:
|
||||
zfree(c);
|
||||
if (plain)
|
||||
zfree(val);
|
||||
else
|
||||
sdsfree(val);
|
||||
sdsfree(val);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Save a string object as [len][data] on disk. If the object is a string
|
||||
* representation of an integer value we try to save it in a special form */
|
||||
ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) {
|
||||
int rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) {
|
||||
int enclen;
|
||||
ssize_t n, nwritten = 0;
|
||||
int n, nwritten = 0;
|
||||
|
||||
/* Try integer encoding */
|
||||
if (len <= 11) {
|
||||
@@ -348,9 +300,9 @@ ssize_t rdbSaveRawString(rio *rdb, unsigned char *s, size_t len) {
|
||||
}
|
||||
|
||||
/* Save a long long value as either an encoded string or a string. */
|
||||
ssize_t rdbSaveLongLongAsStringObject(rio *rdb, long long value) {
|
||||
int rdbSaveLongLongAsStringObject(rio *rdb, long long value) {
|
||||
unsigned char buf[32];
|
||||
ssize_t n, nwritten = 0;
|
||||
int n, nwritten = 0;
|
||||
int enclen = rdbEncodeInteger(value,buf);
|
||||
if (enclen > 0) {
|
||||
return rdbWriteRaw(rdb,buf,enclen);
|
||||
@@ -378,21 +330,10 @@ int rdbSaveStringObject(rio *rdb, robj *obj) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Load a string object from an RDB file according to flags:
|
||||
*
|
||||
* RDB_LOAD_NONE (no flags): load an RDB object, unencoded.
|
||||
* RDB_LOAD_ENC: If the returned type is a Redis object, try to
|
||||
* encode it in a special way to be more memory
|
||||
* efficient. When this flag is passed the function
|
||||
* no longer guarantees that obj->ptr is an SDS string.
|
||||
* RDB_LOAD_PLAIN: Return a plain string allocated with zmalloc()
|
||||
* instead of a Redis object.
|
||||
*/
|
||||
void *rdbGenericLoadStringObject(rio *rdb, int flags) {
|
||||
int encode = flags & RDB_LOAD_ENC;
|
||||
int plain = flags & RDB_LOAD_PLAIN;
|
||||
robj *rdbGenericLoadStringObject(rio *rdb, int encode) {
|
||||
int isencoded;
|
||||
uint32_t len;
|
||||
robj *o;
|
||||
|
||||
len = rdbLoadLen(rdb,&isencoded);
|
||||
if (isencoded) {
|
||||
@@ -400,39 +341,30 @@ void *rdbGenericLoadStringObject(rio *rdb, int flags) {
|
||||
case REDIS_RDB_ENC_INT8:
|
||||
case REDIS_RDB_ENC_INT16:
|
||||
case REDIS_RDB_ENC_INT32:
|
||||
return rdbLoadIntegerObject(rdb,len,flags);
|
||||
return rdbLoadIntegerObject(rdb,len,encode);
|
||||
case REDIS_RDB_ENC_LZF:
|
||||
return rdbLoadLzfStringObject(rdb,flags);
|
||||
return rdbLoadLzfStringObject(rdb);
|
||||
default:
|
||||
rdbExitReportCorruptRDB("Unknown RDB encoding type");
|
||||
redisPanic("Unknown RDB encoding type");
|
||||
}
|
||||
}
|
||||
|
||||
if (len == REDIS_RDB_LENERR) return NULL;
|
||||
if (!plain) {
|
||||
robj *o = encode ? createStringObject(NULL,len) :
|
||||
createRawStringObject(NULL,len);
|
||||
if (len && rioRead(rdb,o->ptr,len) == 0) {
|
||||
decrRefCount(o);
|
||||
return NULL;
|
||||
}
|
||||
return o;
|
||||
} else {
|
||||
void *buf = zmalloc(len);
|
||||
if (len && rioRead(rdb,buf,len) == 0) {
|
||||
zfree(buf);
|
||||
return NULL;
|
||||
}
|
||||
return buf;
|
||||
o = encode ? createStringObject(NULL,len) :
|
||||
createRawStringObject(NULL,len);
|
||||
if (len && rioRead(rdb,o->ptr,len) == 0) {
|
||||
decrRefCount(o);
|
||||
return NULL;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
robj *rdbLoadStringObject(rio *rdb) {
|
||||
return rdbGenericLoadStringObject(rdb,RDB_LOAD_NONE);
|
||||
return rdbGenericLoadStringObject(rdb,0);
|
||||
}
|
||||
|
||||
robj *rdbLoadEncodedStringObject(rio *rdb) {
|
||||
return rdbGenericLoadStringObject(rdb,RDB_LOAD_ENC);
|
||||
return rdbGenericLoadStringObject(rdb,1);
|
||||
}
|
||||
|
||||
/* Save a double value. Doubles are saved as strings prefixed by an unsigned
|
||||
@@ -501,8 +433,10 @@ int rdbSaveObjectType(rio *rdb, robj *o) {
|
||||
case REDIS_STRING:
|
||||
return rdbSaveType(rdb,REDIS_RDB_TYPE_STRING);
|
||||
case REDIS_LIST:
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST)
|
||||
return rdbSaveType(rdb,REDIS_RDB_TYPE_LIST_QUICKLIST);
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST)
|
||||
return rdbSaveType(rdb,REDIS_RDB_TYPE_LIST_ZIPLIST);
|
||||
else if (o->encoding == REDIS_ENCODING_LINKEDLIST)
|
||||
return rdbSaveType(rdb,REDIS_RDB_TYPE_LIST);
|
||||
else
|
||||
redisPanic("Unknown list encoding");
|
||||
case REDIS_SET:
|
||||
@@ -542,8 +476,8 @@ int rdbLoadObjectType(rio *rdb) {
|
||||
}
|
||||
|
||||
/* Save a Redis object. Returns -1 on error, number of bytes written on success. */
|
||||
ssize_t rdbSaveObject(rio *rdb, robj *o) {
|
||||
ssize_t n = 0, nwritten = 0;
|
||||
int rdbSaveObject(rio *rdb, robj *o) {
|
||||
int n, nwritten = 0;
|
||||
|
||||
if (o->type == REDIS_STRING) {
|
||||
/* Save a string value */
|
||||
@@ -551,24 +485,25 @@ ssize_t rdbSaveObject(rio *rdb, robj *o) {
|
||||
nwritten += n;
|
||||
} else if (o->type == REDIS_LIST) {
|
||||
/* Save a list value */
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
quicklist *ql = o->ptr;
|
||||
quicklistNode *node = ql->head;
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
size_t l = ziplistBlobLen((unsigned char*)o->ptr);
|
||||
|
||||
if ((n = rdbSaveLen(rdb,ql->len)) == -1) return -1;
|
||||
if ((n = rdbSaveRawString(rdb,o->ptr,l)) == -1) return -1;
|
||||
nwritten += n;
|
||||
} else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
list *list = o->ptr;
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
|
||||
if ((n = rdbSaveLen(rdb,listLength(list))) == -1) return -1;
|
||||
nwritten += n;
|
||||
|
||||
do {
|
||||
if (quicklistNodeIsCompressed(node)) {
|
||||
void *data;
|
||||
size_t compress_len = quicklistGetLzf(node, &data);
|
||||
if ((n = rdbSaveLzfBlob(rdb,data,compress_len,node->sz)) == -1) return -1;
|
||||
nwritten += n;
|
||||
} else {
|
||||
if ((n = rdbSaveRawString(rdb,node->zl,node->sz)) == -1) return -1;
|
||||
nwritten += n;
|
||||
}
|
||||
} while ((node = node->next));
|
||||
listRewind(list,&li);
|
||||
while((ln = listNext(&li))) {
|
||||
robj *eleobj = listNodeValue(ln);
|
||||
if ((n = rdbSaveStringObject(rdb,eleobj)) == -1) return -1;
|
||||
nwritten += n;
|
||||
}
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -664,8 +599,8 @@ ssize_t rdbSaveObject(rio *rdb, robj *o) {
|
||||
* the rdbSaveObject() function. Currently we use a trick to get
|
||||
* this length with very little changes to the code. In the future
|
||||
* we could switch to a faster solution. */
|
||||
size_t rdbSavedObjectLen(robj *o) {
|
||||
ssize_t len = rdbSaveObject(NULL,o);
|
||||
off_t rdbSavedObjectLen(robj *o) {
|
||||
int len = rdbSaveObject(NULL,o);
|
||||
redisAssertWithInfo(NULL,o,len != -1);
|
||||
return len;
|
||||
}
|
||||
@@ -692,39 +627,6 @@ int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val,
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Save an AUX field. */
|
||||
int rdbSaveAuxField(rio *rdb, void *key, size_t keylen, void *val, size_t vallen) {
|
||||
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_AUX) == -1) return -1;
|
||||
if (rdbSaveRawString(rdb,key,keylen) == -1) return -1;
|
||||
if (rdbSaveRawString(rdb,val,vallen) == -1) return -1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Wrapper for rdbSaveAuxField() used when key/val length can be obtained
|
||||
* with strlen(). */
|
||||
int rdbSaveAuxFieldStrStr(rio *rdb, char *key, char *val) {
|
||||
return rdbSaveAuxField(rdb,key,strlen(key),val,strlen(val));
|
||||
}
|
||||
|
||||
/* Wrapper for strlen(key) + integer type (up to long long range). */
|
||||
int rdbSaveAuxFieldStrInt(rio *rdb, char *key, long long val) {
|
||||
char buf[REDIS_LONGSTR_SIZE];
|
||||
int vlen = ll2string(buf,sizeof(buf),val);
|
||||
return rdbSaveAuxField(rdb,key,strlen(key),buf,vlen);
|
||||
}
|
||||
|
||||
/* Save a few default AUX fields with information about the RDB generated. */
|
||||
int rdbSaveInfoAuxFields(rio *rdb) {
|
||||
int redis_bits = (sizeof(void*) == 8) ? 64 : 32;
|
||||
|
||||
/* Add a few fields about the state when the RDB was created. */
|
||||
if (rdbSaveAuxFieldStrStr(rdb,"redis-ver",REDIS_VERSION) == -1) return -1;
|
||||
if (rdbSaveAuxFieldStrInt(rdb,"redis-bits",redis_bits) == -1) return -1;
|
||||
if (rdbSaveAuxFieldStrInt(rdb,"ctime",time(NULL)) == -1) return -1;
|
||||
if (rdbSaveAuxFieldStrInt(rdb,"used-mem",zmalloc_used_memory()) == -1) return -1;
|
||||
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
|
||||
@@ -745,7 +647,6 @@ int rdbSaveRio(rio *rdb, int *error) {
|
||||
rdb->update_cksum = rioGenericUpdateChecksum;
|
||||
snprintf(magic,sizeof(magic),"REDIS%04d",REDIS_RDB_VERSION);
|
||||
if (rdbWriteRaw(rdb,magic,9) == -1) goto werr;
|
||||
if (rdbSaveInfoAuxFields(rdb) == -1) goto werr;
|
||||
|
||||
for (j = 0; j < server.dbnum; j++) {
|
||||
redisDb *db = server.db+j;
|
||||
@@ -758,21 +659,6 @@ int rdbSaveRio(rio *rdb, int *error) {
|
||||
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_SELECTDB) == -1) goto werr;
|
||||
if (rdbSaveLen(rdb,j) == -1) goto werr;
|
||||
|
||||
/* Write the RESIZE DB opcode. We trim the size to UINT32_MAX, which
|
||||
* is currently the largest type we are able to represent in RDB sizes.
|
||||
* However this does not limit the actual size of the DB to load since
|
||||
* these sizes are just hints to resize the hash tables. */
|
||||
uint32_t db_size, expires_size;
|
||||
db_size = (dictSize(db->dict) <= UINT32_MAX) ?
|
||||
dictSize(db->dict) :
|
||||
UINT32_MAX;
|
||||
expires_size = (dictSize(db->dict) <= UINT32_MAX) ?
|
||||
dictSize(db->expires) :
|
||||
UINT32_MAX;
|
||||
if (rdbSaveType(rdb,REDIS_RDB_OPCODE_RESIZEDB) == -1) goto werr;
|
||||
if (rdbSaveLen(rdb,db_size) == -1) goto werr;
|
||||
if (rdbSaveLen(rdb,expires_size) == -1) goto werr;
|
||||
|
||||
/* Iterate this DB writing every entry */
|
||||
while((de = dictNext(di)) != NULL) {
|
||||
sds keystr = dictGetKey(de);
|
||||
@@ -834,7 +720,7 @@ int rdbSave(char *filename) {
|
||||
char tmpfile[256];
|
||||
FILE *fp;
|
||||
rio rdb;
|
||||
int error = 0;
|
||||
int error;
|
||||
|
||||
snprintf(tmpfile,256,"temp-%d.rdb", (int) getpid());
|
||||
fp = fopen(tmpfile,"w");
|
||||
@@ -933,7 +819,7 @@ void rdbRemoveTempFile(pid_t childpid) {
|
||||
/* Load a Redis object of the specified type from the specified file.
|
||||
* On success a newly allocated object is returned, otherwise NULL. */
|
||||
robj *rdbLoadObject(int rdbtype, rio *rdb) {
|
||||
robj *o = NULL, *ele, *dec;
|
||||
robj *o, *ele, *dec;
|
||||
size_t len;
|
||||
unsigned int i;
|
||||
|
||||
@@ -945,18 +831,33 @@ robj *rdbLoadObject(int rdbtype, rio *rdb) {
|
||||
/* Read list value */
|
||||
if ((len = rdbLoadLen(rdb,NULL)) == REDIS_RDB_LENERR) return NULL;
|
||||
|
||||
o = createQuicklistObject();
|
||||
quicklistSetOptions(o->ptr, server.list_max_ziplist_size,
|
||||
server.list_compress_depth);
|
||||
/* Use a real list when there are too many entries */
|
||||
if (len > server.list_max_ziplist_entries) {
|
||||
o = createListObject();
|
||||
} else {
|
||||
o = createZiplistObject();
|
||||
}
|
||||
|
||||
/* Load every single element of the list */
|
||||
while(len--) {
|
||||
if ((ele = rdbLoadEncodedStringObject(rdb)) == NULL) return NULL;
|
||||
dec = getDecodedObject(ele);
|
||||
size_t len = sdslen(dec->ptr);
|
||||
quicklistPushTail(o->ptr, dec->ptr, len);
|
||||
decrRefCount(dec);
|
||||
decrRefCount(ele);
|
||||
|
||||
/* If we are using a ziplist and the value is too big, convert
|
||||
* the object to a real list. */
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST &&
|
||||
sdsEncodedObject(ele) &&
|
||||
sdslen(ele->ptr) > server.list_max_ziplist_value)
|
||||
listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
|
||||
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
dec = getDecodedObject(ele);
|
||||
o->ptr = ziplistPush(o->ptr,dec->ptr,sdslen(dec->ptr),REDIS_TAIL);
|
||||
decrRefCount(dec);
|
||||
decrRefCount(ele);
|
||||
} else {
|
||||
ele = tryObjectEncoding(ele);
|
||||
listAddNodeTail(o->ptr,ele);
|
||||
}
|
||||
}
|
||||
} else if (rdbtype == REDIS_RDB_TYPE_SET) {
|
||||
/* Read list/set value */
|
||||
@@ -1088,33 +989,25 @@ robj *rdbLoadObject(int rdbtype, rio *rdb) {
|
||||
|
||||
/* Add pair to hash table */
|
||||
ret = dictAdd((dict*)o->ptr, field, value);
|
||||
if (ret == DICT_ERR) {
|
||||
rdbExitReportCorruptRDB("Duplicate keys detected");
|
||||
}
|
||||
redisAssert(ret == DICT_OK);
|
||||
}
|
||||
|
||||
/* All pairs should be read by now */
|
||||
redisAssert(len == 0);
|
||||
} else if (rdbtype == REDIS_RDB_TYPE_LIST_QUICKLIST) {
|
||||
if ((len = rdbLoadLen(rdb,NULL)) == REDIS_RDB_LENERR) return NULL;
|
||||
o = createQuicklistObject();
|
||||
quicklistSetOptions(o->ptr, server.list_max_ziplist_size,
|
||||
server.list_compress_depth);
|
||||
|
||||
while (len--) {
|
||||
unsigned char *zl = rdbGenericLoadStringObject(rdb,RDB_LOAD_PLAIN);
|
||||
if (zl == NULL) return NULL;
|
||||
quicklistAppendZiplist(o->ptr, zl);
|
||||
}
|
||||
} else if (rdbtype == REDIS_RDB_TYPE_HASH_ZIPMAP ||
|
||||
rdbtype == REDIS_RDB_TYPE_LIST_ZIPLIST ||
|
||||
rdbtype == REDIS_RDB_TYPE_SET_INTSET ||
|
||||
rdbtype == REDIS_RDB_TYPE_ZSET_ZIPLIST ||
|
||||
rdbtype == REDIS_RDB_TYPE_HASH_ZIPLIST)
|
||||
{
|
||||
unsigned char *encoded = rdbGenericLoadStringObject(rdb,RDB_LOAD_PLAIN);
|
||||
if (encoded == NULL) return NULL;
|
||||
o = createObject(REDIS_STRING,encoded); /* Obj type fixed below. */
|
||||
robj *aux = rdbLoadStringObject(rdb);
|
||||
|
||||
if (aux == NULL) return NULL;
|
||||
o = createObject(REDIS_STRING,NULL); /* string is just placeholder */
|
||||
o->ptr = zmalloc(sdslen(aux->ptr));
|
||||
memcpy(o->ptr,aux->ptr,sdslen(aux->ptr));
|
||||
decrRefCount(aux);
|
||||
|
||||
/* Fix the object encoding, and make sure to convert the encoded
|
||||
* data type into the base type if accordingly to the current
|
||||
@@ -1155,7 +1048,8 @@ robj *rdbLoadObject(int rdbtype, rio *rdb) {
|
||||
case REDIS_RDB_TYPE_LIST_ZIPLIST:
|
||||
o->type = REDIS_LIST;
|
||||
o->encoding = REDIS_ENCODING_ZIPLIST;
|
||||
listTypeConvert(o,REDIS_ENCODING_QUICKLIST);
|
||||
if (ziplistLen(o->ptr) > server.list_max_ziplist_entries)
|
||||
listTypeConvert(o,REDIS_ENCODING_LINKEDLIST);
|
||||
break;
|
||||
case REDIS_RDB_TYPE_SET_INTSET:
|
||||
o->type = REDIS_SET;
|
||||
@@ -1176,11 +1070,11 @@ robj *rdbLoadObject(int rdbtype, rio *rdb) {
|
||||
hashTypeConvert(o, REDIS_ENCODING_HT);
|
||||
break;
|
||||
default:
|
||||
rdbExitReportCorruptRDB("Unknown encoding");
|
||||
redisPanic("Unknown encoding");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
rdbExitReportCorruptRDB("Unknown object type");
|
||||
redisPanic("Unknown object type");
|
||||
}
|
||||
return o;
|
||||
}
|
||||
@@ -1193,9 +1087,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;
|
||||
}
|
||||
@@ -1269,12 +1162,7 @@ int rdbLoad(char *filename) {
|
||||
|
||||
/* Read type. */
|
||||
if ((type = rdbLoadType(&rdb)) == -1) goto eoferr;
|
||||
|
||||
/* Handle special types. */
|
||||
if (type == REDIS_RDB_OPCODE_EXPIRETIME) {
|
||||
/* EXPIRETIME: load an expire associated with the next key
|
||||
* to load. Note that after loading an expire we need to
|
||||
* load the actual type, and continue. */
|
||||
if ((expiretime = rdbLoadTime(&rdb)) == -1) goto eoferr;
|
||||
/* We read the time so we need to read the object type again. */
|
||||
if ((type = rdbLoadType(&rdb)) == -1) goto eoferr;
|
||||
@@ -1282,67 +1170,27 @@ int rdbLoad(char *filename) {
|
||||
* into milliseconds. */
|
||||
expiretime *= 1000;
|
||||
} else if (type == REDIS_RDB_OPCODE_EXPIRETIME_MS) {
|
||||
/* EXPIRETIME_MS: milliseconds precision expire times introduced
|
||||
* with RDB v3. Like EXPIRETIME but no with more precision. */
|
||||
/* Milliseconds precision expire times introduced with RDB
|
||||
* version 3. */
|
||||
if ((expiretime = rdbLoadMillisecondTime(&rdb)) == -1) goto eoferr;
|
||||
/* We read the time so we need to read the object type again. */
|
||||
if ((type = rdbLoadType(&rdb)) == -1) goto eoferr;
|
||||
} else if (type == REDIS_RDB_OPCODE_EOF) {
|
||||
/* EOF: End of file, exit the main loop. */
|
||||
}
|
||||
|
||||
if (type == REDIS_RDB_OPCODE_EOF)
|
||||
break;
|
||||
} else if (type == REDIS_RDB_OPCODE_SELECTDB) {
|
||||
/* SELECTDB: Select the specified database. */
|
||||
|
||||
/* Handle SELECT DB opcode as a special case */
|
||||
if (type == REDIS_RDB_OPCODE_SELECTDB) {
|
||||
if ((dbid = rdbLoadLen(&rdb,NULL)) == REDIS_RDB_LENERR)
|
||||
goto eoferr;
|
||||
if (dbid >= (unsigned)server.dbnum) {
|
||||
redisLog(REDIS_WARNING,
|
||||
"FATAL: Data file was created with a Redis "
|
||||
"server configured to handle more than %d "
|
||||
"databases. Exiting\n", server.dbnum);
|
||||
redisLog(REDIS_WARNING,"FATAL: Data file was created with a Redis server configured to handle more than %d databases. Exiting\n", server.dbnum);
|
||||
exit(1);
|
||||
}
|
||||
db = server.db+dbid;
|
||||
continue; /* Read type again. */
|
||||
} else if (type == REDIS_RDB_OPCODE_RESIZEDB) {
|
||||
/* RESIZEDB: Hint about the size of the keys in the currently
|
||||
* selected data base, in order to avoid useless rehashing. */
|
||||
uint32_t db_size, expires_size;
|
||||
if ((db_size = rdbLoadLen(&rdb,NULL)) == REDIS_RDB_LENERR)
|
||||
goto eoferr;
|
||||
if ((expires_size = rdbLoadLen(&rdb,NULL)) == REDIS_RDB_LENERR)
|
||||
goto eoferr;
|
||||
dictExpand(db->dict,db_size);
|
||||
dictExpand(db->expires,expires_size);
|
||||
continue; /* Read type again. */
|
||||
} else if (type == REDIS_RDB_OPCODE_AUX) {
|
||||
/* AUX: generic string-string fields. Use to add state to RDB
|
||||
* which is backward compatible. Implementations of RDB loading
|
||||
* are requierd to skip AUX fields they don't understand.
|
||||
*
|
||||
* An AUX field is composed of two strings: key and value. */
|
||||
robj *auxkey, *auxval;
|
||||
if ((auxkey = rdbLoadStringObject(&rdb)) == NULL) goto eoferr;
|
||||
if ((auxval = rdbLoadStringObject(&rdb)) == NULL) goto eoferr;
|
||||
|
||||
if (((char*)auxkey->ptr)[0] == '%') {
|
||||
/* All the fields with a name staring with '%' are considered
|
||||
* information fields and are logged at startup with a log
|
||||
* level of NOTICE. */
|
||||
redisLog(REDIS_NOTICE,"RDB '%s': %s",
|
||||
(char*)auxkey->ptr,
|
||||
(char*)auxval->ptr);
|
||||
} else {
|
||||
/* We ignore fields we don't understand, as by AUX field
|
||||
* contract. */
|
||||
redisLog(REDIS_DEBUG,"Unrecognized RDB AUX field: '%s'",
|
||||
(char*)auxkey->ptr);
|
||||
}
|
||||
|
||||
decrRefCount(auxkey);
|
||||
decrRefCount(auxval);
|
||||
continue; /* Read type again. */
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Read key */
|
||||
if ((key = rdbLoadStringObject(&rdb)) == NULL) goto eoferr;
|
||||
/* Read value */
|
||||
@@ -1375,7 +1223,7 @@ int rdbLoad(char *filename) {
|
||||
redisLog(REDIS_WARNING,"RDB file was saved with checksum disabled: no check performed.");
|
||||
} else if (cksum != expected) {
|
||||
redisLog(REDIS_WARNING,"Wrong RDB checksum. Aborting now.");
|
||||
rdbExitReportCorruptRDB("RDB CRC error");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1385,7 +1233,7 @@ int rdbLoad(char *filename) {
|
||||
|
||||
eoferr: /* unexpected end of file is handled here with a fatal exit */
|
||||
redisLog(REDIS_WARNING,"Short read or OOM loading DB. Unrecoverable error, aborting now.");
|
||||
rdbExitReportCorruptRDB("Unexpected EOF reading RDB file");
|
||||
exit(1);
|
||||
return REDIS_ERR; /* Just to avoid warning */
|
||||
}
|
||||
|
||||
@@ -1643,9 +1491,7 @@ int rdbSaveToSlavesSockets(void) {
|
||||
{
|
||||
retval = REDIS_ERR;
|
||||
}
|
||||
zfree(msg);
|
||||
}
|
||||
zfree(clientids);
|
||||
exitFromChild((retval == REDIS_OK) ? 0 : 1);
|
||||
} else {
|
||||
/* Parent */
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
/* The current RDB version. When the format changes in a way that is no longer
|
||||
* backward compatible this number gets incremented. */
|
||||
#define REDIS_RDB_VERSION 7
|
||||
#define REDIS_RDB_VERSION 6
|
||||
|
||||
/* Defines related to the dump file format. To store 32 bits lengths for short
|
||||
* keys requires a lot of space, so we check the most significant 2 bits of
|
||||
@@ -74,7 +74,6 @@
|
||||
#define REDIS_RDB_TYPE_SET 2
|
||||
#define REDIS_RDB_TYPE_ZSET 3
|
||||
#define REDIS_RDB_TYPE_HASH 4
|
||||
/* NOTE: WHEN ADDING NEW RDB TYPE, UPDATE rdbIsObjectType() BELOW */
|
||||
|
||||
/* Object types for encoded objects. */
|
||||
#define REDIS_RDB_TYPE_HASH_ZIPMAP 9
|
||||
@@ -82,15 +81,11 @@
|
||||
#define REDIS_RDB_TYPE_SET_INTSET 11
|
||||
#define REDIS_RDB_TYPE_ZSET_ZIPLIST 12
|
||||
#define REDIS_RDB_TYPE_HASH_ZIPLIST 13
|
||||
#define REDIS_RDB_TYPE_LIST_QUICKLIST 14
|
||||
/* NOTE: WHEN ADDING NEW RDB TYPE, UPDATE rdbIsObjectType() BELOW */
|
||||
|
||||
/* Test if a type is an object type. */
|
||||
#define rdbIsObjectType(t) ((t >= 0 && t <= 4) || (t >= 9 && t <= 14))
|
||||
#define rdbIsObjectType(t) ((t >= 0 && t <= 4) || (t >= 9 && t <= 13))
|
||||
|
||||
/* Special RDB opcodes (saved/loaded with rdbSaveType/rdbLoadType). */
|
||||
#define REDIS_RDB_OPCODE_AUX 250
|
||||
#define REDIS_RDB_OPCODE_RESIZEDB 251
|
||||
#define REDIS_RDB_OPCODE_EXPIRETIME_MS 252
|
||||
#define REDIS_RDB_OPCODE_EXPIRETIME 253
|
||||
#define REDIS_RDB_OPCODE_SELECTDB 254
|
||||
@@ -109,8 +104,9 @@ int rdbSaveBackground(char *filename);
|
||||
int rdbSaveToSlavesSockets(void);
|
||||
void rdbRemoveTempFile(pid_t childpid);
|
||||
int rdbSave(char *filename);
|
||||
ssize_t rdbSaveObject(rio *rdb, robj *o);
|
||||
size_t rdbSavedObjectLen(robj *o);
|
||||
int rdbSaveObject(rio *rdb, robj *o);
|
||||
off_t rdbSavedObjectLen(robj *o);
|
||||
off_t rdbSavedObjectPages(robj *o);
|
||||
robj *rdbLoadObject(int type, rio *rdb);
|
||||
void backgroundSaveDoneHandler(int exitcode, int bysignal);
|
||||
int rdbSaveKeyValuePair(rio *rdb, robj *key, robj *val, long long expiretime, long long now);
|
||||
|
||||
+35
-54
@@ -86,14 +86,13 @@ typedef struct _client {
|
||||
char **randptr; /* Pointers to :rand: strings inside the command buf */
|
||||
size_t randlen; /* Number of pointers in client->randptr */
|
||||
size_t randfree; /* Number of unused pointers in client->randptr */
|
||||
size_t written; /* Bytes of 'obuf' already written */
|
||||
unsigned int written; /* Bytes of 'obuf' already written */
|
||||
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 +212,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) {
|
||||
size_t 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)
|
||||
@@ -266,7 +264,7 @@ static void writeHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
|
||||
if (sdslen(c->obuf) > c->written) {
|
||||
void *ptr = c->obuf+c->written;
|
||||
ssize_t nwritten = write(c->context->fd,ptr,sdslen(c->obuf)-c->written);
|
||||
int nwritten = write(c->context->fd,ptr,sdslen(c->obuf)-c->written);
|
||||
if (nwritten == -1) {
|
||||
if (errno != EPIPE)
|
||||
fprintf(stderr, "Writing to socket: %s\n", strerror(errno));
|
||||
@@ -301,7 +299,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,16 +325,12 @@ 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
|
||||
@@ -345,23 +340,26 @@ 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) {
|
||||
@@ -373,7 +371,7 @@ static client createClient(char *cmd, size_t len, client from) {
|
||||
for (j = 0; j < (int)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 +390,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;
|
||||
@@ -558,7 +555,7 @@ usage:
|
||||
" -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"
|
||||
@@ -603,12 +600,8 @@ int showThroughput(struct aeEventLoop *eventLoop, long long id, void *clientData
|
||||
fprintf(stderr,"All clients disconnected... aborting.\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (config.csv) return 250;
|
||||
if (config.idlemode == 1) {
|
||||
printf("clients: %d\r", config.liveclients);
|
||||
fflush(stdout);
|
||||
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 +635,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);
|
||||
@@ -700,8 +693,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';
|
||||
|
||||
@@ -738,24 +731,12 @@ int main(int argc, const char **argv) {
|
||||
free(cmd);
|
||||
}
|
||||
|
||||
if (test_is_selected("rpush")) {
|
||||
len = redisFormatCommand(&cmd,"RPUSH mylist %s",data);
|
||||
benchmark("RPUSH",cmd,len);
|
||||
free(cmd);
|
||||
}
|
||||
|
||||
if (test_is_selected("lpop")) {
|
||||
len = redisFormatCommand(&cmd,"LPOP mylist");
|
||||
benchmark("LPOP",cmd,len);
|
||||
free(cmd);
|
||||
}
|
||||
|
||||
if (test_is_selected("rpop")) {
|
||||
len = redisFormatCommand(&cmd,"RPOP mylist");
|
||||
benchmark("RPOP",cmd,len);
|
||||
free(cmd);
|
||||
}
|
||||
|
||||
if (test_is_selected("sadd")) {
|
||||
len = redisFormatCommand(&cmd,
|
||||
"SADD myset element:__rand_int__");
|
||||
|
||||
@@ -29,19 +29,74 @@
|
||||
*/
|
||||
|
||||
|
||||
#include "redis.h"
|
||||
#include "rdb.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/mman.h>
|
||||
#include <string.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <stdint.h>
|
||||
#include <limits.h>
|
||||
#include "lzf.h"
|
||||
#include "crc64.h"
|
||||
|
||||
/* Object types */
|
||||
#define REDIS_STRING 0
|
||||
#define REDIS_LIST 1
|
||||
#define REDIS_SET 2
|
||||
#define REDIS_ZSET 3
|
||||
#define REDIS_HASH 4
|
||||
#define REDIS_HASH_ZIPMAP 9
|
||||
#define REDIS_LIST_ZIPLIST 10
|
||||
#define REDIS_SET_INTSET 11
|
||||
#define REDIS_ZSET_ZIPLIST 12
|
||||
#define REDIS_HASH_ZIPLIST 13
|
||||
|
||||
/* Objects encoding. Some kind of objects like Strings and Hashes can be
|
||||
* internally represented in multiple ways. The 'encoding' field of the object
|
||||
* is set to one of this fields for this object. */
|
||||
#define REDIS_ENCODING_RAW 0 /* Raw representation */
|
||||
#define REDIS_ENCODING_INT 1 /* Encoded as integer */
|
||||
#define REDIS_ENCODING_ZIPMAP 2 /* Encoded as zipmap */
|
||||
#define REDIS_ENCODING_HT 3 /* Encoded as a hash table */
|
||||
|
||||
/* Object types only used for dumping to disk */
|
||||
#define REDIS_EXPIRETIME_MS 252
|
||||
#define REDIS_EXPIRETIME 253
|
||||
#define REDIS_SELECTDB 254
|
||||
#define REDIS_EOF 255
|
||||
|
||||
/* Defines related to the dump file format. To store 32 bits lengths for short
|
||||
* keys requires a lot of space, so we check the most significant 2 bits of
|
||||
* the first byte to interpreter the length:
|
||||
*
|
||||
* 00|000000 => if the two MSB are 00 the len is the 6 bits of this byte
|
||||
* 01|000000 00000000 => 01, the len is 14 byes, 6 bits + 8 bits of next byte
|
||||
* 10|000000 [32 bit integer] => if it's 01, a full 32 bit len will follow
|
||||
* 11|000000 this means: specially encoded object will follow. The six bits
|
||||
* number specify the kind of object that follows.
|
||||
* See the REDIS_RDB_ENC_* defines.
|
||||
*
|
||||
* Lengths up to 63 are stored using a single byte, most DB keys, and may
|
||||
* values, will fit inside. */
|
||||
#define REDIS_RDB_6BITLEN 0
|
||||
#define REDIS_RDB_14BITLEN 1
|
||||
#define REDIS_RDB_32BITLEN 2
|
||||
#define REDIS_RDB_ENCVAL 3
|
||||
#define REDIS_RDB_LENERR UINT_MAX
|
||||
|
||||
/* When a length of a string object stored on disk has the first two bits
|
||||
* set, the remaining two bits specify a special encoding for the object
|
||||
* accordingly to the following defines: */
|
||||
#define REDIS_RDB_ENC_INT8 0 /* 8 bit signed integer */
|
||||
#define REDIS_RDB_ENC_INT16 1 /* 16 bit signed integer */
|
||||
#define REDIS_RDB_ENC_INT32 2 /* 32 bit signed integer */
|
||||
#define REDIS_RDB_ENC_LZF 3 /* string compressed with FASTLZ */
|
||||
|
||||
#define ERROR(...) { \
|
||||
redisLog(REDIS_WARNING, __VA_ARGS__); \
|
||||
printf(__VA_ARGS__); \
|
||||
exit(1); \
|
||||
}
|
||||
|
||||
@@ -78,23 +133,28 @@ typedef struct {
|
||||
char success;
|
||||
} entry;
|
||||
|
||||
/* Global vars that are actually used as constants. The following double
|
||||
* values are used for double on-disk serialization, and are initialized
|
||||
* 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];
|
||||
|
||||
/* Return true if 't' is a valid object type. */
|
||||
static int rdbCheckType(unsigned char t) {
|
||||
int checkType(unsigned char t) {
|
||||
/* In case a new object type is added, update the following
|
||||
* condition as necessary. */
|
||||
return
|
||||
(t >= REDIS_RDB_TYPE_HASH_ZIPMAP && t <= REDIS_RDB_TYPE_HASH_ZIPLIST) ||
|
||||
t <= REDIS_RDB_TYPE_HASH ||
|
||||
t >= REDIS_RDB_OPCODE_EXPIRETIME_MS;
|
||||
(t >= REDIS_HASH_ZIPMAP && t <= REDIS_HASH_ZIPLIST) ||
|
||||
t <= REDIS_HASH ||
|
||||
t >= REDIS_EXPIRETIME_MS;
|
||||
}
|
||||
|
||||
/* when number of bytes to read is negative, do a peek */
|
||||
static int readBytes(void *target, long num) {
|
||||
int readBytes(void *target, long num) {
|
||||
char peek = (num < 0) ? 1 : 0;
|
||||
num = (num < 0) ? -num : num;
|
||||
|
||||
@@ -113,28 +173,28 @@ int processHeader(void) {
|
||||
int dump_version;
|
||||
|
||||
if (!readBytes(buf, 9)) {
|
||||
ERROR("Cannot read header");
|
||||
ERROR("Cannot read header\n");
|
||||
}
|
||||
|
||||
/* expect the first 5 bytes to equal REDIS */
|
||||
if (memcmp(buf,"REDIS",5) != 0) {
|
||||
ERROR("Wrong signature in header");
|
||||
ERROR("Wrong signature in header\n");
|
||||
}
|
||||
|
||||
dump_version = (int)strtol(buf + 5, NULL, 10);
|
||||
if (dump_version < 1 || dump_version > 6) {
|
||||
ERROR("Unknown RDB format version: %d", dump_version);
|
||||
ERROR("Unknown RDB format version: %d\n", dump_version);
|
||||
}
|
||||
return dump_version;
|
||||
}
|
||||
|
||||
static int loadType(entry *e) {
|
||||
int loadType(entry *e) {
|
||||
uint32_t offset = CURR_OFFSET;
|
||||
|
||||
/* this byte needs to qualify as type */
|
||||
unsigned char t;
|
||||
if (readBytes(&t, 1)) {
|
||||
if (rdbCheckType(t)) {
|
||||
if (checkType(t)) {
|
||||
e->type = t;
|
||||
return 1;
|
||||
} else {
|
||||
@@ -148,18 +208,18 @@ static int loadType(entry *e) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int peekType() {
|
||||
int peekType() {
|
||||
unsigned char t;
|
||||
if (readBytes(&t, -1) && (rdbCheckType(t)))
|
||||
if (readBytes(&t, -1) && (checkType(t)))
|
||||
return t;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* discard time, just consume the bytes */
|
||||
static int processTime(int type) {
|
||||
int processTime(int type) {
|
||||
uint32_t offset = CURR_OFFSET;
|
||||
unsigned char t[8];
|
||||
int timelen = (type == REDIS_RDB_OPCODE_EXPIRETIME_MS) ? 8 : 4;
|
||||
int timelen = (type == REDIS_EXPIRETIME_MS) ? 8 : 4;
|
||||
|
||||
if (readBytes(t,timelen)) {
|
||||
return 1;
|
||||
@@ -171,7 +231,7 @@ static int processTime(int type) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint32_t loadLength(int *isencoded) {
|
||||
uint32_t loadLength(int *isencoded) {
|
||||
unsigned char buf[2];
|
||||
uint32_t len;
|
||||
int type;
|
||||
@@ -197,7 +257,7 @@ static uint32_t loadLength(int *isencoded) {
|
||||
}
|
||||
}
|
||||
|
||||
static char *loadIntegerObject(int enctype) {
|
||||
char *loadIntegerObject(int enctype) {
|
||||
uint32_t offset = CURR_OFFSET;
|
||||
unsigned char enc[4];
|
||||
long long val;
|
||||
@@ -224,36 +284,36 @@ static char *loadIntegerObject(int enctype) {
|
||||
|
||||
/* convert val into string */
|
||||
char *buf;
|
||||
buf = zmalloc(sizeof(char) * 128);
|
||||
buf = malloc(sizeof(char) * 128);
|
||||
sprintf(buf, "%lld", val);
|
||||
return buf;
|
||||
}
|
||||
|
||||
static char* loadLzfStringObject() {
|
||||
char* loadLzfStringObject() {
|
||||
unsigned int slen, clen;
|
||||
char *c, *s;
|
||||
|
||||
if ((clen = loadLength(NULL)) == REDIS_RDB_LENERR) return NULL;
|
||||
if ((slen = loadLength(NULL)) == REDIS_RDB_LENERR) return NULL;
|
||||
|
||||
c = zmalloc(clen);
|
||||
c = malloc(clen);
|
||||
if (!readBytes(c, clen)) {
|
||||
zfree(c);
|
||||
free(c);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
s = zmalloc(slen+1);
|
||||
s = malloc(slen+1);
|
||||
if (lzf_decompress(c,clen,s,slen) == 0) {
|
||||
zfree(c); zfree(s);
|
||||
free(c); free(s);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
zfree(c);
|
||||
free(c);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* returns NULL when not processable, char* when valid */
|
||||
static char* loadStringObject() {
|
||||
char* loadStringObject() {
|
||||
uint32_t offset = CURR_OFFSET;
|
||||
int isencoded;
|
||||
uint32_t len;
|
||||
@@ -276,48 +336,48 @@ static char* loadStringObject() {
|
||||
|
||||
if (len == REDIS_RDB_LENERR) return NULL;
|
||||
|
||||
char *buf = zmalloc(sizeof(char) * (len+1));
|
||||
char *buf = malloc(sizeof(char) * (len+1));
|
||||
if (buf == NULL) return NULL;
|
||||
buf[len] = '\0';
|
||||
if (!readBytes(buf, len)) {
|
||||
zfree(buf);
|
||||
free(buf);
|
||||
return NULL;
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
static int processStringObject(char** store) {
|
||||
int processStringObject(char** store) {
|
||||
unsigned long offset = CURR_OFFSET;
|
||||
char *key = loadStringObject();
|
||||
if (key == NULL) {
|
||||
SHIFT_ERROR(offset, "Error reading string object");
|
||||
zfree(key);
|
||||
free(key);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (store != NULL) {
|
||||
*store = key;
|
||||
} else {
|
||||
zfree(key);
|
||||
free(key);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static double* loadDoubleValue() {
|
||||
double* loadDoubleValue() {
|
||||
char buf[256];
|
||||
unsigned char len;
|
||||
double* val;
|
||||
|
||||
if (!readBytes(&len,1)) return NULL;
|
||||
|
||||
val = zmalloc(sizeof(double));
|
||||
val = malloc(sizeof(double));
|
||||
switch(len) {
|
||||
case 255: *val = R_NegInf; return val;
|
||||
case 254: *val = R_PosInf; return val;
|
||||
case 253: *val = R_Nan; return val;
|
||||
default:
|
||||
if (!readBytes(buf, len)) {
|
||||
zfree(val);
|
||||
free(val);
|
||||
return NULL;
|
||||
}
|
||||
buf[len] = '\0';
|
||||
@@ -326,24 +386,24 @@ static double* loadDoubleValue() {
|
||||
}
|
||||
}
|
||||
|
||||
static int processDoubleValue(double** store) {
|
||||
int processDoubleValue(double** store) {
|
||||
unsigned long offset = CURR_OFFSET;
|
||||
double *val = loadDoubleValue();
|
||||
if (val == NULL) {
|
||||
SHIFT_ERROR(offset, "Error reading double value");
|
||||
zfree(val);
|
||||
free(val);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (store != NULL) {
|
||||
*store = val;
|
||||
} else {
|
||||
zfree(val);
|
||||
free(val);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int loadPair(entry *e) {
|
||||
int loadPair(entry *e) {
|
||||
uint32_t offset = CURR_OFFSET;
|
||||
uint32_t i;
|
||||
|
||||
@@ -357,10 +417,10 @@ static int loadPair(entry *e) {
|
||||
}
|
||||
|
||||
uint32_t length = 0;
|
||||
if (e->type == REDIS_RDB_TYPE_LIST ||
|
||||
e->type == REDIS_RDB_TYPE_SET ||
|
||||
e->type == REDIS_RDB_TYPE_ZSET ||
|
||||
e->type == REDIS_RDB_TYPE_HASH) {
|
||||
if (e->type == REDIS_LIST ||
|
||||
e->type == REDIS_SET ||
|
||||
e->type == REDIS_ZSET ||
|
||||
e->type == REDIS_HASH) {
|
||||
if ((length = loadLength(NULL)) == REDIS_RDB_LENERR) {
|
||||
SHIFT_ERROR(offset, "Error reading %s length", types[e->type]);
|
||||
return 0;
|
||||
@@ -368,19 +428,19 @@ static int loadPair(entry *e) {
|
||||
}
|
||||
|
||||
switch(e->type) {
|
||||
case REDIS_RDB_TYPE_STRING:
|
||||
case REDIS_RDB_TYPE_HASH_ZIPMAP:
|
||||
case REDIS_RDB_TYPE_LIST_ZIPLIST:
|
||||
case REDIS_RDB_TYPE_SET_INTSET:
|
||||
case REDIS_RDB_TYPE_ZSET_ZIPLIST:
|
||||
case REDIS_RDB_TYPE_HASH_ZIPLIST:
|
||||
case REDIS_STRING:
|
||||
case REDIS_HASH_ZIPMAP:
|
||||
case REDIS_LIST_ZIPLIST:
|
||||
case REDIS_SET_INTSET:
|
||||
case REDIS_ZSET_ZIPLIST:
|
||||
case REDIS_HASH_ZIPLIST:
|
||||
if (!processStringObject(NULL)) {
|
||||
SHIFT_ERROR(offset, "Error reading entry value");
|
||||
return 0;
|
||||
}
|
||||
break;
|
||||
case REDIS_RDB_TYPE_LIST:
|
||||
case REDIS_RDB_TYPE_SET:
|
||||
case REDIS_LIST:
|
||||
case REDIS_SET:
|
||||
for (i = 0; i < length; i++) {
|
||||
offset = CURR_OFFSET;
|
||||
if (!processStringObject(NULL)) {
|
||||
@@ -389,7 +449,7 @@ static int loadPair(entry *e) {
|
||||
}
|
||||
}
|
||||
break;
|
||||
case REDIS_RDB_TYPE_ZSET:
|
||||
case REDIS_ZSET:
|
||||
for (i = 0; i < length; i++) {
|
||||
offset = CURR_OFFSET;
|
||||
if (!processStringObject(NULL)) {
|
||||
@@ -403,7 +463,7 @@ static int loadPair(entry *e) {
|
||||
}
|
||||
}
|
||||
break;
|
||||
case REDIS_RDB_TYPE_HASH:
|
||||
case REDIS_HASH:
|
||||
for (i = 0; i < length; i++) {
|
||||
offset = CURR_OFFSET;
|
||||
if (!processStringObject(NULL)) {
|
||||
@@ -426,7 +486,7 @@ static int loadPair(entry *e) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
static entry loadEntry() {
|
||||
entry loadEntry() {
|
||||
entry e = { NULL, -1, 0 };
|
||||
uint32_t length, offset[4];
|
||||
|
||||
@@ -439,7 +499,7 @@ static entry loadEntry() {
|
||||
}
|
||||
|
||||
offset[1] = CURR_OFFSET;
|
||||
if (e.type == REDIS_RDB_OPCODE_SELECTDB) {
|
||||
if (e.type == REDIS_SELECTDB) {
|
||||
if ((length = loadLength(NULL)) == REDIS_RDB_LENERR) {
|
||||
SHIFT_ERROR(offset[1], "Error reading database number");
|
||||
return e;
|
||||
@@ -448,7 +508,7 @@ static entry loadEntry() {
|
||||
SHIFT_ERROR(offset[1], "Database number out of range (%d)", length);
|
||||
return e;
|
||||
}
|
||||
} else if (e.type == REDIS_RDB_OPCODE_EOF) {
|
||||
} else if (e.type == REDIS_EOF) {
|
||||
if (positions[level].offset < positions[level].size) {
|
||||
SHIFT_ERROR(offset[0], "Unexpected EOF");
|
||||
} else {
|
||||
@@ -457,8 +517,8 @@ static entry loadEntry() {
|
||||
return e;
|
||||
} else {
|
||||
/* optionally consume expire */
|
||||
if (e.type == REDIS_RDB_OPCODE_EXPIRETIME ||
|
||||
e.type == REDIS_RDB_OPCODE_EXPIRETIME_MS) {
|
||||
if (e.type == REDIS_EXPIRETIME ||
|
||||
e.type == REDIS_EXPIRETIME_MS) {
|
||||
if (!processTime(e.type)) return e;
|
||||
if (!loadType(&e)) return e;
|
||||
}
|
||||
@@ -484,31 +544,31 @@ static entry loadEntry() {
|
||||
return e;
|
||||
}
|
||||
|
||||
static void printCentered(int indent, int width, char* body) {
|
||||
void printCentered(int indent, int width, char* body) {
|
||||
char head[256], tail[256];
|
||||
memset(head, '\0', 256);
|
||||
memset(tail, '\0', 256);
|
||||
|
||||
memset(head, '=', indent);
|
||||
memset(tail, '=', width - 2 - indent - strlen(body));
|
||||
redisLog(REDIS_WARNING, "%s %s %s", head, body, tail);
|
||||
printf("%s %s %s\n", head, body, tail);
|
||||
}
|
||||
|
||||
static void printValid(uint64_t ops, uint64_t bytes) {
|
||||
void printValid(uint64_t ops, uint64_t bytes) {
|
||||
char body[80];
|
||||
sprintf(body, "Processed %llu valid opcodes (in %llu bytes)",
|
||||
(unsigned long long) ops, (unsigned long long) bytes);
|
||||
printCentered(4, 80, body);
|
||||
}
|
||||
|
||||
static void printSkipped(uint64_t bytes, uint64_t offset) {
|
||||
void printSkipped(uint64_t bytes, uint64_t offset) {
|
||||
char body[80];
|
||||
sprintf(body, "Skipped %llu bytes (resuming at 0x%08llx)",
|
||||
(unsigned long long) bytes, (unsigned long long) offset);
|
||||
printCentered(4, 80, body);
|
||||
}
|
||||
|
||||
static void printErrorStack(entry *e) {
|
||||
void printErrorStack(entry *e) {
|
||||
unsigned int i;
|
||||
char body[64];
|
||||
|
||||
@@ -538,20 +598,20 @@ static void printErrorStack(entry *e) {
|
||||
|
||||
/* display error stack */
|
||||
for (i = 0; i < errors.level; i++) {
|
||||
redisLog(REDIS_WARNING, "0x%08lx - %s",
|
||||
printf("0x%08lx - %s\n",
|
||||
(unsigned long) errors.offset[i], errors.error[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void process(void) {
|
||||
uint64_t num_errors = 0, num_valid_ops = 0, num_valid_bytes = 0;
|
||||
entry entry = { NULL, -1, 0 };
|
||||
entry entry;
|
||||
int dump_version = processHeader();
|
||||
|
||||
/* Exclude the final checksum for RDB >= 5. Will be checked at the end. */
|
||||
if (dump_version >= 5) {
|
||||
if (positions[0].size < 8) {
|
||||
redisLog(REDIS_WARNING, "RDB version >= 5 but no room for checksum.");
|
||||
printf("RDB version >= 5 but no room for checksum.\n");
|
||||
exit(1);
|
||||
}
|
||||
positions[0].size -= 8;
|
||||
@@ -600,7 +660,7 @@ void process(void) {
|
||||
/* advance position */
|
||||
positions[0] = positions[1];
|
||||
}
|
||||
zfree(entry.key);
|
||||
free(entry.key);
|
||||
}
|
||||
|
||||
/* because there is another potential error,
|
||||
@@ -608,7 +668,7 @@ void process(void) {
|
||||
printValid(num_valid_ops, num_valid_bytes);
|
||||
|
||||
/* expect an eof */
|
||||
if (entry.type != REDIS_RDB_OPCODE_EOF) {
|
||||
if (entry.type != REDIS_EOF) {
|
||||
/* last byte should be EOF, add error */
|
||||
errors.level = 0;
|
||||
SHIFT_ERROR(positions[0].offset, "Expected EOF, got %s", types[entry.type]);
|
||||
@@ -636,40 +696,47 @@ void process(void) {
|
||||
if (crc != crc2) {
|
||||
SHIFT_ERROR(positions[0].offset, "RDB CRC64 does not match.");
|
||||
} else {
|
||||
redisLog(REDIS_WARNING, "CRC64 checksum is OK");
|
||||
printf("CRC64 checksum is OK\n");
|
||||
}
|
||||
}
|
||||
|
||||
/* print summary on errors */
|
||||
if (num_errors) {
|
||||
redisLog(REDIS_WARNING, "Total unprocessable opcodes: %llu",
|
||||
printf("\n");
|
||||
printf("Total unprocessable opcodes: %llu\n",
|
||||
(unsigned long long) num_errors);
|
||||
}
|
||||
}
|
||||
|
||||
int redis_check_rdb(char *rdbfilename) {
|
||||
int main(int argc, char **argv) {
|
||||
/* expect the first argument to be the dump file */
|
||||
if (argc <= 1) {
|
||||
printf("Usage: %s <dump.rdb>\n", argv[0]);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
int fd;
|
||||
off_t size;
|
||||
struct stat stat;
|
||||
void *data;
|
||||
|
||||
fd = open(rdbfilename, O_RDONLY);
|
||||
fd = open(argv[1], O_RDONLY);
|
||||
if (fd < 1) {
|
||||
ERROR("Cannot open file: %s", rdbfilename);
|
||||
ERROR("Cannot open file: %s\n", argv[1]);
|
||||
}
|
||||
if (fstat(fd, &stat) == -1) {
|
||||
ERROR("Cannot stat: %s", rdbfilename);
|
||||
ERROR("Cannot stat: %s\n", argv[1]);
|
||||
} else {
|
||||
size = stat.st_size;
|
||||
}
|
||||
|
||||
if (sizeof(size_t) == sizeof(int32_t) && size >= INT_MAX) {
|
||||
ERROR("Cannot check dump files >2GB on a 32-bit platform");
|
||||
ERROR("Cannot check dump files >2GB on a 32-bit platform\n");
|
||||
}
|
||||
|
||||
data = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
|
||||
if (data == MAP_FAILED) {
|
||||
ERROR("Cannot mmap: %s", rdbfilename);
|
||||
ERROR("Cannot mmap: %s\n", argv[1]);
|
||||
}
|
||||
|
||||
/* Initialize static vars */
|
||||
@@ -679,16 +746,22 @@ int redis_check_rdb(char *rdbfilename) {
|
||||
errors.level = 0;
|
||||
|
||||
/* Object types */
|
||||
sprintf(types[REDIS_RDB_TYPE_STRING], "STRING");
|
||||
sprintf(types[REDIS_RDB_TYPE_LIST], "LIST");
|
||||
sprintf(types[REDIS_RDB_TYPE_SET], "SET");
|
||||
sprintf(types[REDIS_RDB_TYPE_ZSET], "ZSET");
|
||||
sprintf(types[REDIS_RDB_TYPE_HASH], "HASH");
|
||||
sprintf(types[REDIS_STRING], "STRING");
|
||||
sprintf(types[REDIS_LIST], "LIST");
|
||||
sprintf(types[REDIS_SET], "SET");
|
||||
sprintf(types[REDIS_ZSET], "ZSET");
|
||||
sprintf(types[REDIS_HASH], "HASH");
|
||||
|
||||
/* Object types only used for dumping to disk */
|
||||
sprintf(types[REDIS_RDB_OPCODE_EXPIRETIME], "EXPIRETIME");
|
||||
sprintf(types[REDIS_RDB_OPCODE_SELECTDB], "SELECTDB");
|
||||
sprintf(types[REDIS_RDB_OPCODE_EOF], "EOF");
|
||||
sprintf(types[REDIS_EXPIRETIME], "EXPIRETIME");
|
||||
sprintf(types[REDIS_SELECTDB], "SELECTDB");
|
||||
sprintf(types[REDIS_EOF], "EOF");
|
||||
|
||||
/* Double constants initialization */
|
||||
R_Zero = 0.0;
|
||||
R_PosInf = 1.0/R_Zero;
|
||||
R_NegInf = -1.0/R_Zero;
|
||||
R_Nan = R_Zero/R_Zero;
|
||||
|
||||
process();
|
||||
|
||||
@@ -696,15 +769,3 @@ int redis_check_rdb(char *rdbfilename) {
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* RDB check main: called form redis.c when Redis is executed with the
|
||||
* redis-check-rdb alias. */
|
||||
int redis_check_rdb_main(char **argv, int argc) {
|
||||
if (argc != 2) {
|
||||
fprintf(stderr, "Usage: %s <rdb-file-name>\n", argv[0]);
|
||||
exit(1);
|
||||
}
|
||||
redisLog(REDIS_WARNING, "Checking RDB file %s", argv[1]);
|
||||
exit(redis_check_rdb(argv[1]));
|
||||
return 0;
|
||||
}
|
||||
+43
-362
@@ -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;
|
||||
@@ -145,8 +128,9 @@ static void cliRefreshPrompt(void) {
|
||||
len = snprintf(config.prompt,sizeof(config.prompt),"redis %s",
|
||||
config.hostsocket);
|
||||
else
|
||||
len = anetFormatAddr(config.prompt, sizeof(config.prompt),
|
||||
config.hostip, config.hostport);
|
||||
len = snprintf(config.prompt,sizeof(config.prompt),
|
||||
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)
|
||||
len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]",
|
||||
@@ -154,30 +138,6 @@ static void cliRefreshPrompt(void) {
|
||||
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
|
||||
*--------------------------------------------------------------------------- */
|
||||
@@ -342,7 +302,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;
|
||||
|
||||
@@ -355,7 +315,7 @@ 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;
|
||||
|
||||
@@ -533,7 +493,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++) {
|
||||
@@ -644,9 +604,6 @@ static int cliSendCommand(int argc, char **argv, int repeat) {
|
||||
|
||||
output_raw = 0;
|
||||
if (!strcasecmp(command,"info") ||
|
||||
(argc == 3 && !strcasecmp(command,"debug") &&
|
||||
(!strcasecmp(argv[1],"jemalloc") &&
|
||||
!strcasecmp(argv[2],"info"))) ||
|
||||
(argc == 2 && !strcasecmp(command,"cluster") &&
|
||||
(!strcasecmp(argv[1],"nodes") ||
|
||||
!strcasecmp(argv[1],"info"))) ||
|
||||
@@ -715,17 +672,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);
|
||||
@@ -733,15 +689,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");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -789,17 +742,9 @@ static int parseOptions(int argc, char **argv) {
|
||||
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")) {
|
||||
@@ -885,13 +830,9 @@ static void usage(void) {
|
||||
" 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"
|
||||
@@ -936,33 +877,6 @@ 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) {
|
||||
sds historyfile = NULL;
|
||||
int history = 0;
|
||||
@@ -976,9 +890,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);
|
||||
}
|
||||
}
|
||||
@@ -1018,8 +933,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);
|
||||
@@ -1040,9 +973,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;
|
||||
}
|
||||
@@ -1086,7 +1020,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);
|
||||
}
|
||||
|
||||
/*------------------------------------------------------------------------------
|
||||
@@ -1107,7 +1041,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);
|
||||
@@ -1137,148 +1071,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
|
||||
*--------------------------------------------------------------------------- */
|
||||
@@ -1898,7 +1690,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);
|
||||
@@ -1952,7 +1744,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:
|
||||
@@ -1964,9 +1755,6 @@ static void statMode(void) {
|
||||
case 3:
|
||||
printf("SAVE+AOF");
|
||||
break;
|
||||
case 4:
|
||||
printf("LOAD");
|
||||
break;
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
@@ -2008,94 +1796,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.
|
||||
*
|
||||
@@ -2187,10 +1887,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;
|
||||
@@ -2207,9 +1904,6 @@ int main(int argc, char **argv) {
|
||||
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
|
||||
@@ -2221,18 +1915,14 @@ int main(int argc, char **argv) {
|
||||
argc -= firstarg;
|
||||
argv += firstarg;
|
||||
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
|
||||
/* Latency mode */
|
||||
if (config.latency_mode) {
|
||||
if (cliConnect(0) == REDIS_ERR) exit(1);
|
||||
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);
|
||||
@@ -2270,20 +1960,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);
|
||||
|
||||
+32
-58
@@ -72,7 +72,7 @@ class ClusterNode
|
||||
@friends
|
||||
end
|
||||
|
||||
def slots
|
||||
def slots
|
||||
@info[:slots]
|
||||
end
|
||||
|
||||
@@ -154,7 +154,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 +213,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 +273,7 @@ class ClusterNode
|
||||
def info
|
||||
@info
|
||||
end
|
||||
|
||||
|
||||
def is_dirty?
|
||||
@dirty
|
||||
end
|
||||
@@ -540,6 +540,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
|
||||
@@ -557,31 +558,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
|
||||
@@ -608,8 +594,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
|
||||
@@ -623,33 +609,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
|
||||
@@ -789,7 +763,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.
|
||||
@@ -1165,7 +1139,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.
|
||||
@@ -1232,7 +1206,7 @@ end
|
||||
|
||||
#################################################################################
|
||||
# Libraries
|
||||
#
|
||||
#
|
||||
# We try to don't depend on external libs since this is a critical part
|
||||
# of Redis Cluster.
|
||||
#################################################################################
|
||||
|
||||
+146
-339
@@ -46,14 +46,12 @@
|
||||
#include <sys/time.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/uio.h>
|
||||
#include <sys/un.h>
|
||||
#include <limits.h>
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/utsname.h>
|
||||
#include <locale.h>
|
||||
#include <sys/sysctl.h>
|
||||
|
||||
/* Our shared "common" objects */
|
||||
|
||||
@@ -162,7 +160,7 @@ struct redisCommand redisCommandTable[] = {
|
||||
{"smove",smoveCommand,4,"wF",0,NULL,1,2,1,0,0},
|
||||
{"sismember",sismemberCommand,3,"rF",0,NULL,1,1,1,0,0},
|
||||
{"scard",scardCommand,2,"rF",0,NULL,1,1,1,0,0},
|
||||
{"spop",spopCommand,-2,"wRsF",0,NULL,1,1,1,0,0},
|
||||
{"spop",spopCommand,2,"wRsF",0,NULL,1,1,1,0,0},
|
||||
{"srandmember",srandmemberCommand,-2,"rR",0,NULL,1,1,1,0,0},
|
||||
{"sinter",sinterCommand,-2,"rS",0,NULL,1,-1,1,0,0},
|
||||
{"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0},
|
||||
@@ -249,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},
|
||||
@@ -261,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,0,0,0,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},
|
||||
{"dump",dumpCommand,2,"ar",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},
|
||||
{"client",clientCommand,-2,"ars",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},
|
||||
@@ -282,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}
|
||||
@@ -878,30 +876,27 @@ 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 */
|
||||
@@ -1073,13 +1068,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.
|
||||
@@ -1415,8 +1404,6 @@ void initServerConfig(void) {
|
||||
server.syslog_ident = zstrdup(REDIS_DEFAULT_SYSLOG_IDENT);
|
||||
server.syslog_facility = LOG_LOCAL0;
|
||||
server.daemonize = REDIS_DEFAULT_DAEMONIZE;
|
||||
server.supervised = 0;
|
||||
server.supervised_mode = REDIS_SUPERVISED_NONE;
|
||||
server.aof_state = REDIS_AOF_OFF;
|
||||
server.aof_fsync = REDIS_DEFAULT_AOF_FSYNC;
|
||||
server.aof_no_fsync_on_rewrite = REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE;
|
||||
@@ -1434,7 +1421,7 @@ void initServerConfig(void) {
|
||||
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 = NULL;
|
||||
server.pidfile = zstrdup(REDIS_DEFAULT_PID_FILE);
|
||||
server.rdb_filename = zstrdup(REDIS_DEFAULT_RDB_FILENAME);
|
||||
server.aof_filename = zstrdup(REDIS_DEFAULT_AOF_FILENAME);
|
||||
server.requirepass = NULL;
|
||||
@@ -1446,12 +1433,15 @@ void initServerConfig(void) {
|
||||
server.maxclients = REDIS_MAX_CLIENTS;
|
||||
server.bpop_blocked_clients = 0;
|
||||
server.maxmemory = REDIS_DEFAULT_MAXMEMORY;
|
||||
server.maxmemory_frag_guess = REDIS_DEFAULT_MAXMEMORY_FRAG_GUESS;
|
||||
server.maxmemory_enforced = (double) REDIS_DEFAULT_MAXMEMORY / server.maxmemory_frag_guess;
|
||||
server.maxmemory_policy = REDIS_DEFAULT_MAXMEMORY_POLICY;
|
||||
server.maxmemory_samples = REDIS_DEFAULT_MAXMEMORY_SAMPLES;
|
||||
server.rss_aware_maxmemory = REDIS_DEFAULT_RSS_AWARE_MAXMEMORY;
|
||||
server.hash_max_ziplist_entries = REDIS_HASH_MAX_ZIPLIST_ENTRIES;
|
||||
server.hash_max_ziplist_value = REDIS_HASH_MAX_ZIPLIST_VALUE;
|
||||
server.list_max_ziplist_size = REDIS_LIST_MAX_ZIPLIST_SIZE;
|
||||
server.list_compress_depth = REDIS_LIST_COMPRESS_DEPTH;
|
||||
server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
|
||||
server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
|
||||
server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
|
||||
server.zset_max_ziplist_entries = REDIS_ZSET_MAX_ZIPLIST_ENTRIES;
|
||||
server.zset_max_ziplist_value = REDIS_ZSET_MAX_ZIPLIST_VALUE;
|
||||
@@ -1529,7 +1519,6 @@ void initServerConfig(void) {
|
||||
server.lpushCommand = lookupCommandByCString("lpush");
|
||||
server.lpopCommand = lookupCommandByCString("lpop");
|
||||
server.rpopCommand = lookupCommandByCString("rpop");
|
||||
server.sremCommand = lookupCommandByCString("srem");
|
||||
|
||||
/* Slow log */
|
||||
server.slowlog_log_slower_than = REDIS_SLOWLOG_LOG_SLOWER_THAN;
|
||||
@@ -1568,33 +1557,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) {
|
||||
f = maxfiles;
|
||||
while(f > oldlimit) {
|
||||
rlim_t 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. "
|
||||
@@ -1615,7 +1604,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).",
|
||||
@@ -1626,23 +1615,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.
|
||||
*
|
||||
@@ -1713,8 +1685,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;
|
||||
@@ -1727,15 +1697,10 @@ 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;
|
||||
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) {
|
||||
@@ -1762,7 +1727,6 @@ void initServer(void) {
|
||||
server.clients_waiting_acks = listCreate();
|
||||
server.get_ack_from_slaves = 0;
|
||||
server.clients_paused = 0;
|
||||
server.system_memory_size = zmalloc_get_memory_size();
|
||||
|
||||
createSharedObjects();
|
||||
adjustOpenFilesLimit();
|
||||
@@ -2002,9 +1966,6 @@ struct redisCommand *lookupCommandOrOriginal(sds name) {
|
||||
* + REDIS_PROPAGATE_NONE (no propagation of command at all)
|
||||
* + REDIS_PROPAGATE_AOF (propagate into the AOF file if is enabled)
|
||||
* + REDIS_PROPAGATE_REPL (propagate into the replication link)
|
||||
*
|
||||
* This should not be used inside commands implementation. Use instead
|
||||
* alsoPropagate(), preventCommandPropagation(), forceCommandPropagation().
|
||||
*/
|
||||
void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
|
||||
int flags)
|
||||
@@ -2016,31 +1977,11 @@ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
|
||||
}
|
||||
|
||||
/* Used inside commands to schedule the propagation of additional commands
|
||||
* after the current command is propagated to AOF / Replication.
|
||||
*
|
||||
* 'cmd' must be a pointer to the Redis command to replicate, dbid is the
|
||||
* database ID the command should be propagated into.
|
||||
* Arguments of the command to propagte are passed as an array of redis
|
||||
* objects pointers of len 'argc', using the 'argv' vector.
|
||||
*
|
||||
* The function does not take a reference to the passed 'argv' vector,
|
||||
* so it is up to the caller to release the passed argv (but it is usually
|
||||
* stack allocated). The function autoamtically increments ref count of
|
||||
* passed objects, so the caller does not need to. */
|
||||
* after the current command is propagated to AOF / Replication. */
|
||||
void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc,
|
||||
int target)
|
||||
{
|
||||
robj **argvcopy;
|
||||
int j;
|
||||
|
||||
if (server.loading) return; /* No propagation during loading. */
|
||||
|
||||
argvcopy = zmalloc(sizeof(robj*)*argc);
|
||||
for (j = 0; j < argc; j++) {
|
||||
argvcopy[j] = argv[j];
|
||||
incrRefCount(argv[j]);
|
||||
}
|
||||
redisOpArrayAppend(&server.also_propagate,cmd,dbid,argvcopy,argc,target);
|
||||
redisOpArrayAppend(&server.also_propagate,cmd,dbid,argv,argc,target);
|
||||
}
|
||||
|
||||
/* It is possible to call the function forceCommandPropagation() inside a
|
||||
@@ -2051,13 +1992,6 @@ void forceCommandPropagation(redisClient *c, int flags) {
|
||||
if (flags & REDIS_PROPAGATE_AOF) c->flags |= REDIS_FORCE_AOF;
|
||||
}
|
||||
|
||||
/* Avoid that the executed command is propagated at all. This way we
|
||||
* are free to just propagate what we want using the alsoPropagate()
|
||||
* API. */
|
||||
void preventCommandPropagation(redisClient *c) {
|
||||
c->flags |= REDIS_PREVENT_PROP;
|
||||
}
|
||||
|
||||
/* Call() is the core of Redis execution of a command */
|
||||
void call(redisClient *c, int flags) {
|
||||
long long dirty, start, duration;
|
||||
@@ -2067,7 +2001,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);
|
||||
}
|
||||
@@ -2111,7 +2045,7 @@ void call(redisClient *c, int flags) {
|
||||
}
|
||||
|
||||
/* Propagate the command into the AOF and replication link */
|
||||
if (flags & REDIS_CALL_PROPAGATE && (c->flags & REDIS_PREVENT_PROP) == 0) {
|
||||
if (flags & REDIS_CALL_PROPAGATE) {
|
||||
int flags = REDIS_PROPAGATE_NONE;
|
||||
|
||||
if (c->flags & REDIS_FORCE_REPL) flags |= REDIS_PROPAGATE_REPL;
|
||||
@@ -2122,24 +2056,20 @@ void call(redisClient *c, int flags) {
|
||||
propagate(c->cmd,c->db->id,c->argv,c->argc,flags);
|
||||
}
|
||||
|
||||
/* Restore the old replication flags, since call can be executed
|
||||
/* Restore the old FORCE_AOF/REPL flags, since call can be executed
|
||||
* recursively. */
|
||||
c->flags &= ~(REDIS_FORCE_AOF|REDIS_FORCE_REPL|REDIS_PREVENT_PROP);
|
||||
c->flags |= client_old_flags &
|
||||
(REDIS_FORCE_AOF|REDIS_FORCE_REPL|REDIS_PREVENT_PROP);
|
||||
c->flags &= ~(REDIS_FORCE_AOF|REDIS_FORCE_REPL);
|
||||
c->flags |= client_old_flags & (REDIS_FORCE_AOF|REDIS_FORCE_REPL);
|
||||
|
||||
/* Handle the alsoPropagate() API to handle commands that want to propagate
|
||||
* multiple separated commands. Note that alsoPropagate() is not affected
|
||||
* by REDIS_PREVENT_PROP flag. */
|
||||
* multiple separated commands. */
|
||||
if (server.also_propagate.numops) {
|
||||
int j;
|
||||
redisOp *rop;
|
||||
|
||||
if (flags & REDIS_CALL_PROPAGATE) {
|
||||
for (j = 0; j < server.also_propagate.numops; j++) {
|
||||
rop = &server.also_propagate.ops[j];
|
||||
propagate(rop->cmd,rop->dbid,rop->argv,rop->argc,rop->target);
|
||||
}
|
||||
for (j = 0; j < server.also_propagate.numops; j++) {
|
||||
rop = &server.also_propagate.ops[j];
|
||||
propagate(rop->cmd, rop->dbid, rop->argv, rop->argc, rop->target);
|
||||
}
|
||||
redisOpArrayFree(&server.also_propagate);
|
||||
}
|
||||
@@ -2410,7 +2340,7 @@ int prepareForShutdown(int flags) {
|
||||
return REDIS_ERR;
|
||||
}
|
||||
}
|
||||
if (server.daemonize || server.pidfile) {
|
||||
if (server.daemonize) {
|
||||
redisLog(REDIS_NOTICE,"Removing the pid file.");
|
||||
unlink(server.pidfile);
|
||||
}
|
||||
@@ -2517,6 +2447,7 @@ void timeCommand(redisClient *c) {
|
||||
addReplyBulkLongLong(c,tv.tv_usec);
|
||||
}
|
||||
|
||||
|
||||
/* Helper function for addReplyCommand() to output flags. */
|
||||
int addReplyCommandFlag(redisClient *c, struct redisCommand *cmd, int f, char *reply) {
|
||||
if (cmd->flags & f) {
|
||||
@@ -2735,14 +2666,7 @@ sds genRedisInfoString(char *section) {
|
||||
if (allsections || defsections || !strcasecmp(section,"memory")) {
|
||||
char hmem[64];
|
||||
char peak_hmem[64];
|
||||
char total_system_hmem[64];
|
||||
char used_memory_lua_hmem[64];
|
||||
char used_memory_rss_hmem[64];
|
||||
char maxmemory_hmem[64];
|
||||
size_t zmalloc_used = zmalloc_used_memory();
|
||||
size_t total_system_mem = server.system_memory_size;
|
||||
char *evict_policy = maxmemoryToString();
|
||||
long long memory_lua = (long long)lua_gc(server.lua,LUA_GCCOUNT,0)*1024;
|
||||
|
||||
/* Peak memory is updated from time to time by serverCron() so it
|
||||
* may happen that the instantaneous value is slightly bigger than
|
||||
@@ -2753,42 +2677,23 @@ sds genRedisInfoString(char *section) {
|
||||
|
||||
bytesToHuman(hmem,zmalloc_used);
|
||||
bytesToHuman(peak_hmem,server.stat_peak_memory);
|
||||
bytesToHuman(total_system_hmem,total_system_mem);
|
||||
bytesToHuman(used_memory_lua_hmem,memory_lua);
|
||||
bytesToHuman(used_memory_rss_hmem,server.resident_set_size);
|
||||
bytesToHuman(maxmemory_hmem,server.maxmemory);
|
||||
|
||||
if (sections++) info = sdscat(info,"\r\n");
|
||||
info = sdscatprintf(info,
|
||||
"# Memory\r\n"
|
||||
"used_memory:%zu\r\n"
|
||||
"used_memory_human:%s\r\n"
|
||||
"used_memory_rss:%zu\r\n"
|
||||
"used_memory_rss_human:%s\r\n"
|
||||
"used_memory_peak:%zu\r\n"
|
||||
"used_memory_peak_human:%s\r\n"
|
||||
"total_system_memory:%lu\r\n"
|
||||
"total_system_memory_human:%s\r\n"
|
||||
"used_memory_lua:%lld\r\n"
|
||||
"used_memory_lua_human:%s\r\n"
|
||||
"maxmemory:%lld\r\n"
|
||||
"maxmemory_human:%s\r\n"
|
||||
"maxmemory_policy:%s\r\n"
|
||||
"mem_fragmentation_ratio:%.2f\r\n"
|
||||
"mem_allocator:%s\r\n",
|
||||
zmalloc_used,
|
||||
hmem,
|
||||
server.resident_set_size,
|
||||
used_memory_rss_hmem,
|
||||
server.stat_peak_memory,
|
||||
peak_hmem,
|
||||
(unsigned long)total_system_mem,
|
||||
total_system_hmem,
|
||||
memory_lua,
|
||||
used_memory_lua_hmem,
|
||||
server.maxmemory,
|
||||
maxmemory_hmem,
|
||||
evict_policy,
|
||||
((long long)lua_gc(server.lua,LUA_GCCOUNT,0))*1024LL,
|
||||
zmalloc_get_fragmentation_ratio(server.resident_set_size),
|
||||
ZMALLOC_LIB
|
||||
);
|
||||
@@ -2855,14 +2760,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,
|
||||
@@ -2888,10 +2793,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"
|
||||
@@ -2906,11 +2807,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,
|
||||
@@ -3109,7 +3006,11 @@ void infoCommand(redisClient *c) {
|
||||
addReply(c,shared.syntaxerr);
|
||||
return;
|
||||
}
|
||||
addReplyBulkSds(c, genRedisInfoString(section));
|
||||
sds info = genRedisInfoString(section);
|
||||
addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
|
||||
(unsigned long)sdslen(info)));
|
||||
addReplySds(c,info);
|
||||
addReply(c,shared.crlf);
|
||||
}
|
||||
|
||||
void monitorCommand(redisClient *c) {
|
||||
@@ -3197,7 +3098,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;
|
||||
@@ -3250,9 +3157,9 @@ void evictionPoolPopulate(dict *sampledict, dict *keydict, struct evictionPoolEn
|
||||
}
|
||||
|
||||
int freeMemoryIfNeeded(void) {
|
||||
size_t mem_used, mem_tofree, mem_freed;
|
||||
size_t mem_used, mem_tofree, mem_freed, mem_target = server.maxmemory;
|
||||
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. */
|
||||
@@ -3276,14 +3183,72 @@ int freeMemoryIfNeeded(void) {
|
||||
mem_used -= aofRewriteBufferSize();
|
||||
}
|
||||
|
||||
/* If we use RSS aware maxmemory, update the target memory using
|
||||
* the current fragmentation figure. */
|
||||
#ifdef HAVE_RSS_REPORTING
|
||||
if (server.rss_aware_maxmemory &&
|
||||
server.maxmemory_policy != REDIS_MAXMEMORY_NO_EVICTION)
|
||||
{
|
||||
static unsigned long iterations = 0;
|
||||
static unsigned long sampling_stage = 1;
|
||||
static float last_observed_frag = 0;
|
||||
|
||||
/* For some time, we analyze what happens during memory pressure, when
|
||||
* objects are evicted and reallocated. */
|
||||
if (mem_used > server.maxmemory_enforced) {
|
||||
unsigned long sample_cycles = 1000000;
|
||||
|
||||
/* Every sample_cycle cycles we sample the fragmentation, and
|
||||
* compare it with the previos one. If it is no longer raising,
|
||||
* we take it as a guess of the fragmentation with this workload. */
|
||||
if (sampling_stage && iterations < sample_cycles) {
|
||||
iterations++;
|
||||
if (iterations == sample_cycles) {
|
||||
float current_frag = zmalloc_get_fragmentation_ratio(server.resident_set_size);
|
||||
if (last_observed_frag == 0) {
|
||||
/* First sample we get. */
|
||||
last_observed_frag = current_frag;
|
||||
} else {
|
||||
if (current_frag <= last_observed_frag) {
|
||||
size_t enforced_new;
|
||||
|
||||
sampling_stage = 0;
|
||||
server.maxmemory_frag_guess = current_frag;
|
||||
/* Update the global fragmentation guess and use
|
||||
* it (also used it for successive
|
||||
* "CONFIG SET maxmemory" commands). */
|
||||
if (server.maxmemory_frag_guess < 1)
|
||||
server.maxmemory_frag_guess = 1;
|
||||
else if (server.maxmemory_frag_guess > 2)
|
||||
server.maxmemory_frag_guess = 2;
|
||||
|
||||
/* Only set the new limit if it is higher than our
|
||||
* initial guess, otherwise it is futile: RSS will
|
||||
* not go backward anyway. */
|
||||
enforced_new = (double) server.maxmemory /
|
||||
server.maxmemory_frag_guess;
|
||||
if (enforced_new > server.maxmemory_enforced)
|
||||
server.maxmemory_enforced = enforced_new;
|
||||
redisLog(REDIS_NOTICE,"RSS aware maxmemory, fragmentation looks stable at: %f", server.maxmemory_frag_guess);
|
||||
}
|
||||
last_observed_frag = current_frag;
|
||||
}
|
||||
iterations = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
mem_target = server.maxmemory_enforced;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Check if we are over the memory limit. */
|
||||
if (mem_used <= server.maxmemory) return REDIS_OK;
|
||||
if (mem_used <= mem_target) return REDIS_OK;
|
||||
|
||||
if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION)
|
||||
return REDIS_ERR; /* We need to free memory, but policy forbids. */
|
||||
|
||||
/* Compute how much memory we need to free. */
|
||||
mem_tofree = mem_used - server.maxmemory;
|
||||
mem_tofree = mem_used - mem_target;
|
||||
mem_freed = 0;
|
||||
latencyStartMonitor(latency);
|
||||
while (mem_freed < mem_tofree) {
|
||||
@@ -3383,11 +3348,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++;
|
||||
@@ -3442,10 +3403,6 @@ void linuxMemoryWarnings(void) {
|
||||
#endif /* __linux__ */
|
||||
|
||||
void createPidFile(void) {
|
||||
/* If pidfile requested, but no pidfile defined, use
|
||||
* default pidfile path */
|
||||
if (!server.pidfile) server.pidfile = zstrdup(REDIS_DEFAULT_PID_FILE);
|
||||
|
||||
/* Try to write the pid file in a best-effort way. */
|
||||
FILE *fp = fopen(server.pidfile,"w");
|
||||
if (fp) {
|
||||
@@ -3508,27 +3465,15 @@ void redisAsciiArt(void) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -3637,131 +3582,9 @@ void redisSetProcTitle(char *title) {
|
||||
#endif
|
||||
}
|
||||
|
||||
/*
|
||||
* Check whether systemd or upstart have been used to start redis.
|
||||
*/
|
||||
|
||||
int redisSupervisedUpstart(void) {
|
||||
const char *upstart_job = getenv("UPSTART_JOB");
|
||||
|
||||
if (!upstart_job) {
|
||||
redisLog(REDIS_WARNING,
|
||||
"upstart supervision requested, but UPSTART_JOB not found");
|
||||
return 0;
|
||||
}
|
||||
|
||||
redisLog(REDIS_NOTICE, "supervised by upstart, will stop to signal readyness");
|
||||
raise(SIGSTOP);
|
||||
unsetenv("UPSTART_JOB");
|
||||
return 1;
|
||||
}
|
||||
|
||||
int redisSupervisedSystemd(void) {
|
||||
const char *notify_socket = getenv("NOTIFY_SOCKET");
|
||||
int fd = 1;
|
||||
struct sockaddr_un su;
|
||||
struct iovec iov;
|
||||
struct msghdr hdr;
|
||||
int sendto_flags = 0;
|
||||
|
||||
if (!notify_socket) {
|
||||
redisLog(REDIS_WARNING,
|
||||
"systemd supervision requested, but NOTIFY_SOCKET not found");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ((strchr("@/", notify_socket[0])) == NULL || strlen(notify_socket) < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
redisLog(REDIS_NOTICE, "supervised by systemd, will signal readyness");
|
||||
if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) {
|
||||
redisLog(REDIS_WARNING,
|
||||
"Can't connect to systemd socket %s", notify_socket);
|
||||
return 0;
|
||||
}
|
||||
|
||||
memset(&su, 0, sizeof(su));
|
||||
su.sun_family = AF_UNIX;
|
||||
strncpy (su.sun_path, notify_socket, sizeof(su.sun_path) -1);
|
||||
su.sun_path[sizeof(su.sun_path) - 1] = '\0';
|
||||
|
||||
if (notify_socket[0] == '@')
|
||||
su.sun_path[0] = '\0';
|
||||
|
||||
memset(&iov, 0, sizeof(iov));
|
||||
iov.iov_base = "READY=1";
|
||||
iov.iov_len = strlen("READY=1");
|
||||
|
||||
memset(&hdr, 0, sizeof(hdr));
|
||||
hdr.msg_name = &su;
|
||||
hdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) +
|
||||
strlen(notify_socket);
|
||||
hdr.msg_iov = &iov;
|
||||
hdr.msg_iovlen = 1;
|
||||
|
||||
unsetenv("NOTIFY_SOCKET");
|
||||
#ifdef HAVE_MSG_NOSIGNAL
|
||||
sendto_flags |= MSG_NOSIGNAL;
|
||||
#endif
|
||||
if (sendmsg(fd, &hdr, sendto_flags) < 0) {
|
||||
redisLog(REDIS_WARNING, "Can't send notification to systemd");
|
||||
close(fd);
|
||||
return 0;
|
||||
}
|
||||
close(fd);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int redisIsSupervised(int mode) {
|
||||
if (mode == REDIS_SUPERVISED_AUTODETECT) {
|
||||
const char *upstart_job = getenv("UPSTART_JOB");
|
||||
const char *notify_socket = getenv("NOTIFY_SOCKET");
|
||||
|
||||
if (upstart_job) {
|
||||
redisSupervisedUpstart();
|
||||
} else if (notify_socket) {
|
||||
redisSupervisedSystemd();
|
||||
}
|
||||
} else if (mode == REDIS_SUPERVISED_UPSTART) {
|
||||
return redisSupervisedUpstart();
|
||||
} else if (mode == REDIS_SUPERVISED_SYSTEMD) {
|
||||
return redisSupervisedSystemd();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
struct timeval tv;
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
if (argc == 3 && !strcasecmp(argv[1], "test")) {
|
||||
if (!strcasecmp(argv[2], "ziplist")) {
|
||||
return ziplistTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "quicklist")) {
|
||||
quicklistTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "intset")) {
|
||||
return intsetTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "zipmap")) {
|
||||
return zipmapTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "sha1test")) {
|
||||
return sha1Test(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "util")) {
|
||||
return utilTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "sds")) {
|
||||
return sdsTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "endianconv")) {
|
||||
return endianconvTest(argc, argv);
|
||||
} else if (!strcasecmp(argv[2], "crc64")) {
|
||||
return crc64Test(argc, argv);
|
||||
}
|
||||
|
||||
return -1; /* test not found */
|
||||
}
|
||||
#endif
|
||||
|
||||
/* We need to initialize our libraries, and the server configuration. */
|
||||
#ifdef INIT_SETPROCTITLE_REPLACEMENT
|
||||
spt_init(argc, argv);
|
||||
@@ -3783,12 +3606,6 @@ int main(int argc, char **argv) {
|
||||
initSentinel();
|
||||
}
|
||||
|
||||
/* Check if we need to start in redis-check-rdb mode. We just execute
|
||||
* the program main. However the program is part of the Redis executable
|
||||
* so that we can easily execute an RDB check on loading errors. */
|
||||
if (strstr(argv[0],"redis-check-rdb") != NULL)
|
||||
exit(redis_check_rdb_main(argv,argc));
|
||||
|
||||
if (argc >= 2) {
|
||||
int j = 1; /* First option to parse in argv[] */
|
||||
sds options = sdsempty();
|
||||
@@ -3820,11 +3637,6 @@ int main(int argc, char **argv) {
|
||||
while(j != argc) {
|
||||
if (argv[j][0] == '-' && argv[j][1] == '-') {
|
||||
/* Option name */
|
||||
if (!strcmp(argv[j], "--check-rdb")) {
|
||||
/* Argument has no options, need to skip for parsing. */
|
||||
j++;
|
||||
continue;
|
||||
}
|
||||
if (sdslen(options)) options = sdscat(options,"\n");
|
||||
options = sdscat(options,argv[j]+2);
|
||||
options = sdscat(options," ");
|
||||
@@ -3849,13 +3661,9 @@ int main(int argc, char **argv) {
|
||||
} else {
|
||||
redisLog(REDIS_WARNING, "Warning: no config file specified, using the default config. In order to specify a config file use %s /path/to/%s.conf", argv[0], server.sentinel_mode ? "sentinel" : "redis");
|
||||
}
|
||||
|
||||
server.supervised = redisIsSupervised(server.supervised_mode);
|
||||
int background = server.daemonize && !server.supervised;
|
||||
if (background) daemonize();
|
||||
|
||||
if (server.daemonize) daemonize();
|
||||
initServer();
|
||||
if (background || server.pidfile) createPidFile();
|
||||
if (server.daemonize) createPidFile();
|
||||
redisSetProcTitle(argv[0]);
|
||||
redisAsciiArt();
|
||||
|
||||
@@ -3865,7 +3673,6 @@ int main(int argc, char **argv) {
|
||||
#ifdef __linux__
|
||||
linuxMemoryWarnings();
|
||||
#endif
|
||||
checkTcpBacklogSettings();
|
||||
loadDataFromDisk();
|
||||
if (server.cluster_enabled) {
|
||||
if (verifyClusterConfigWithData() == REDIS_ERR) {
|
||||
|
||||
+33
-63
@@ -32,7 +32,10 @@
|
||||
|
||||
#include "fmacros.h"
|
||||
#include "config.h"
|
||||
|
||||
#if defined(__sun)
|
||||
#include "solarisfixes.h"
|
||||
#endif
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -62,13 +65,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#include "util.h" /* Misc functions useful in many places */
|
||||
#include "latency.h" /* Latency monitor API */
|
||||
#include "sparkline.h" /* ASII graphs API */
|
||||
#include "quicklist.h"
|
||||
|
||||
/* Following includes allow test functions to be called from Redis main() */
|
||||
#include "zipmap.h"
|
||||
#include "sha1.h"
|
||||
#include "endianconv.h"
|
||||
#include "crc64.h"
|
||||
|
||||
/* Error codes */
|
||||
#define REDIS_OK 0
|
||||
@@ -101,6 +97,7 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#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 */
|
||||
@@ -124,6 +121,8 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_DEFAULT_REPL_DISABLE_TCP_NODELAY 0
|
||||
#define REDIS_DEFAULT_MAXMEMORY 0
|
||||
#define REDIS_DEFAULT_MAXMEMORY_SAMPLES 5
|
||||
#define REDIS_DEFAULT_MAXMEMORY_FRAG_GUESS 1.4
|
||||
#define REDIS_DEFAULT_RSS_AWARE_MAXMEMORY 0
|
||||
#define REDIS_DEFAULT_AOF_FILENAME "appendonly.aof"
|
||||
#define REDIS_DEFAULT_AOF_NO_FSYNC_ON_REWRITE 0
|
||||
#define REDIS_DEFAULT_AOF_LOAD_TRUNCATED 1
|
||||
@@ -131,7 +130,7 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#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
|
||||
@@ -143,13 +142,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 */
|
||||
@@ -202,7 +194,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_ENCODING_INTSET 6 /* Encoded as intset */
|
||||
#define REDIS_ENCODING_SKIPLIST 7 /* Encoded as skiplist */
|
||||
#define REDIS_ENCODING_EMBSTR 8 /* Embedded sds string encoding */
|
||||
#define REDIS_ENCODING_QUICKLIST 9 /* Encoded as linked list of ziplists */
|
||||
|
||||
/* Defines related to the dump file format. To store 32 bits lengths for short
|
||||
* keys requires a lot of space, so we check the most significant 2 bits of
|
||||
@@ -257,7 +248,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#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. */
|
||||
#define REDIS_PREVENT_PROP (1<<19) /* Don't propagate to AOF / Slaves. */
|
||||
|
||||
/* Client block type (btype field in client structure)
|
||||
* if REDIS_BLOCKED flag is set. */
|
||||
@@ -314,12 +304,6 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
#define REDIS_LOG_RAW (1<<10) /* Modifier to log without timestamp */
|
||||
#define REDIS_DEFAULT_VERBOSITY REDIS_NOTICE
|
||||
|
||||
/* Supervision options */
|
||||
#define REDIS_SUPERVISED_NONE 0
|
||||
#define REDIS_SUPERVISED_AUTODETECT 1
|
||||
#define REDIS_SUPERVISED_SYSTEMD 2
|
||||
#define REDIS_SUPERVISED_UPSTART 3
|
||||
|
||||
/* Anti-warning macro... */
|
||||
#define REDIS_NOTUSED(V) ((void) V)
|
||||
|
||||
@@ -335,14 +319,12 @@ typedef long long mstime_t; /* millisecond time type. */
|
||||
/* Zip structure related defaults */
|
||||
#define REDIS_HASH_MAX_ZIPLIST_ENTRIES 512
|
||||
#define REDIS_HASH_MAX_ZIPLIST_VALUE 64
|
||||
#define REDIS_LIST_MAX_ZIPLIST_ENTRIES 512
|
||||
#define REDIS_LIST_MAX_ZIPLIST_VALUE 64
|
||||
#define REDIS_SET_MAX_INTSET_ENTRIES 512
|
||||
#define REDIS_ZSET_MAX_ZIPLIST_ENTRIES 128
|
||||
#define REDIS_ZSET_MAX_ZIPLIST_VALUE 64
|
||||
|
||||
/* List defaults */
|
||||
#define REDIS_LIST_MAX_ZIPLIST_SIZE -2
|
||||
#define REDIS_LIST_COMPRESS_DEPTH 0
|
||||
|
||||
/* HyperLogLog defines */
|
||||
#define REDIS_DEFAULT_HLL_SPARSE_MAX_BYTES 3000
|
||||
|
||||
@@ -543,8 +525,8 @@ typedef struct redisClient {
|
||||
int multibulklen; /* number of multi bulk arguments left to read */
|
||||
long bulklen; /* length of bulk argument in multi bulk request */
|
||||
list *reply;
|
||||
unsigned long long reply_bytes; /* Tot bytes of objects in reply list */
|
||||
size_t sentlen; /* Amount of bytes already sent in the current
|
||||
unsigned long reply_bytes; /* Tot bytes of objects in reply list */
|
||||
int sentlen; /* Amount of bytes already sent in the current
|
||||
buffer or object being sent. */
|
||||
time_t ctime; /* Client creation time */
|
||||
time_t lastinteraction; /* time of the last interaction, used for timeout */
|
||||
@@ -554,8 +536,8 @@ typedef struct redisClient {
|
||||
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 */
|
||||
off_t repldboff; /* replication DB file offset */
|
||||
off_t repldbsize; /* replication DB file size */
|
||||
sds replpreamble; /* replication DB preamble. */
|
||||
long long reploff; /* replication offset if this is our master */
|
||||
long long repl_ack_off; /* replication ack offset, if this is a slave */
|
||||
@@ -709,7 +691,7 @@ struct redisServer {
|
||||
off_t loading_process_events_interval_bytes;
|
||||
/* Fast pointers to often looked up command */
|
||||
struct redisCommand *delCommand, *multiCommand, *lpushCommand, *lpopCommand,
|
||||
*rpopCommand, *sremCommand;
|
||||
*rpopCommand;
|
||||
/* Fields used only for stats */
|
||||
time_t stat_starttime; /* Server start time */
|
||||
long long stat_numcommands; /* Number of processed commands */
|
||||
@@ -730,16 +712,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 */
|
||||
@@ -747,8 +725,6 @@ struct redisServer {
|
||||
int active_expire_enabled; /* Can be disabled for testing purposes. */
|
||||
size_t client_max_querybuf_len; /* Limit for client query buffer length */
|
||||
int dbnum; /* Total number of configured DBs */
|
||||
int supervised; /* 1 if supervised, 0 otherwise. */
|
||||
int supervised_mode; /* See REDIS_SUPERVISED_* */
|
||||
int daemonize; /* True if running as a daemon */
|
||||
clientBufferLimitsConfig client_obuf_limits[REDIS_CLIENT_TYPE_COUNT];
|
||||
/* AOF persistence */
|
||||
@@ -865,6 +841,10 @@ struct redisServer {
|
||||
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 */
|
||||
/* RSS aware maxmemory additional state. */
|
||||
int rss_aware_maxmemory; /* Non zero if enabled. */
|
||||
unsigned long long maxmemory_enforced; /* Currently enforced maxmemory. */
|
||||
float maxmemory_frag_guess; /* Guessed fragmentation. */
|
||||
/* Blocked clients */
|
||||
unsigned int bpop_blocked_clients; /* Number of clients blocked by lists */
|
||||
list *unblocked_clients; /* list of clients to unblock before next loop */
|
||||
@@ -878,14 +858,12 @@ struct redisServer {
|
||||
/* Zip structure config, see redis.conf for more information */
|
||||
size_t hash_max_ziplist_entries;
|
||||
size_t hash_max_ziplist_value;
|
||||
size_t list_max_ziplist_entries;
|
||||
size_t list_max_ziplist_value;
|
||||
size_t set_max_intset_entries;
|
||||
size_t zset_max_ziplist_entries;
|
||||
size_t zset_max_ziplist_value;
|
||||
size_t hll_sparse_max_bytes;
|
||||
/* List parameters */
|
||||
int list_max_ziplist_size;
|
||||
int list_compress_depth;
|
||||
/* time cache */
|
||||
time_t unixtime; /* Unix time sampled every cron cycle. */
|
||||
long long mstime; /* Like 'unixtime' but with milliseconds resolution. */
|
||||
/* Pubsub */
|
||||
@@ -925,8 +903,6 @@ struct redisServer {
|
||||
int assert_line;
|
||||
int bug_report_start; /* True if bug report header was already logged. */
|
||||
int watchdog_period; /* Software watchdog period in ms. 0 = off */
|
||||
/* System hardware info */
|
||||
size_t system_memory_size; /* Total memory in system as reported by OS */
|
||||
};
|
||||
|
||||
typedef struct pubsubPattern {
|
||||
@@ -975,13 +951,15 @@ typedef struct {
|
||||
robj *subject;
|
||||
unsigned char encoding;
|
||||
unsigned char direction; /* Iteration direction */
|
||||
quicklistIter *iter;
|
||||
unsigned char *zi;
|
||||
listNode *ln;
|
||||
} listTypeIterator;
|
||||
|
||||
/* Structure for an entry while iterating over a list. */
|
||||
typedef struct {
|
||||
listTypeIterator *li;
|
||||
quicklistEntry entry; /* Entry in quicklist */
|
||||
unsigned char *zi; /* Entry in ziplist */
|
||||
listNode *ln; /* Entry in linked list */
|
||||
} listTypeEntry;
|
||||
|
||||
/* Structure to hold set iteration abstraction. */
|
||||
@@ -1058,7 +1036,6 @@ void addReplyBulkCBuffer(redisClient *c, void *p, size_t len);
|
||||
void addReplyBulkLongLong(redisClient *c, long long ll);
|
||||
void addReply(redisClient *c, robj *obj);
|
||||
void addReplySds(redisClient *c, sds s);
|
||||
void addReplyBulkSds(redisClient *c, sds s);
|
||||
void addReplyError(redisClient *c, char *err);
|
||||
void addReplyStatus(redisClient *c, char *status);
|
||||
void addReplyDouble(redisClient *c, double d);
|
||||
@@ -1108,7 +1085,7 @@ int listTypeNext(listTypeIterator *li, listTypeEntry *entry);
|
||||
robj *listTypeGet(listTypeEntry *entry);
|
||||
void listTypeInsert(listTypeEntry *entry, robj *value, int where);
|
||||
int listTypeEqual(listTypeEntry *entry, robj *o);
|
||||
void listTypeDelete(listTypeIterator *iter, listTypeEntry *entry);
|
||||
void listTypeDelete(listTypeEntry *entry);
|
||||
void listTypeConvert(robj *subject, int enc);
|
||||
void unblockClientWaitingData(redisClient *c);
|
||||
void handleClientsBlockedOnLists(void);
|
||||
@@ -1145,8 +1122,8 @@ 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 *createQuicklistObject(void);
|
||||
robj *createStringObjectFromLongDouble(long double value);
|
||||
robj *createListObject(void);
|
||||
robj *createZiplistObject(void);
|
||||
robj *createSetObject(void);
|
||||
robj *createIntsetObject(void);
|
||||
@@ -1253,7 +1230,6 @@ void call(redisClient *c, int flags);
|
||||
void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags);
|
||||
void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target);
|
||||
void forceCommandPropagation(redisClient *c, int flags);
|
||||
void preventCommandPropagation(redisClient *c);
|
||||
int prepareForShutdown();
|
||||
#ifdef __GNUC__
|
||||
void redisLog(int level, const char *fmt, ...)
|
||||
@@ -1274,7 +1250,6 @@ void closeListeningSockets(int unlink_unix_socket);
|
||||
void updateCachedTime(void);
|
||||
void resetServerStats(void);
|
||||
unsigned int getLRUClock(void);
|
||||
char *maxmemoryToString(void);
|
||||
|
||||
/* Set data type */
|
||||
robj *setTypeCreate(robj *value);
|
||||
@@ -1286,7 +1261,6 @@ void setTypeReleaseIterator(setTypeIterator *si);
|
||||
int setTypeNext(setTypeIterator *si, robj **objele, int64_t *llele);
|
||||
robj *setTypeNextObject(setTypeIterator *si);
|
||||
int setTypeRandomElement(robj *setobj, robj **objele, int64_t *llele);
|
||||
unsigned long setTypeRandomElements(robj *set, unsigned long count, robj *aux_set);
|
||||
unsigned long setTypeSize(robj *subject);
|
||||
void setTypeConvert(robj *subject, int enc);
|
||||
|
||||
@@ -1382,10 +1356,6 @@ void sentinelTimer(void);
|
||||
char *sentinelHandleConfiguration(char **argv, int argc);
|
||||
void sentinelIsRunning(void);
|
||||
|
||||
/* redis-check-rdb */
|
||||
int redis_check_rdb(char *rdbfilename);
|
||||
int redis_check_rdb_main(char **argv, int argc);
|
||||
|
||||
/* Scripting */
|
||||
void scriptingInit(void);
|
||||
|
||||
|
||||
+12
-22
@@ -56,7 +56,7 @@ char *replicationGetSlaveName(redisClient *c) {
|
||||
buf[0] = '\0';
|
||||
if (anetPeerToString(c->fd,ip,sizeof(ip),NULL) != -1) {
|
||||
if (c->slave_listening_port)
|
||||
anetFormatAddr(buf,sizeof(buf),ip,c->slave_listening_port);
|
||||
snprintf(buf,sizeof(buf),"%s:%d",ip,c->slave_listening_port);
|
||||
else
|
||||
snprintf(buf,sizeof(buf),"%s:<unknown-slave-port>",ip);
|
||||
} else {
|
||||
@@ -690,7 +690,6 @@ void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
freeClient(slave);
|
||||
return;
|
||||
}
|
||||
server.stat_net_output_bytes += nwritten;
|
||||
sdsrange(slave->replpreamble,nwritten,-1);
|
||||
if (sdslen(slave->replpreamble) == 0) {
|
||||
sdsfree(slave->replpreamble);
|
||||
@@ -719,7 +718,6 @@ void sendBulkToSlave(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
return;
|
||||
}
|
||||
slave->repldboff += nwritten;
|
||||
server.stat_net_output_bytes += nwritten;
|
||||
if (slave->repldboff == slave->repldbsize) {
|
||||
close(slave->repldbfd);
|
||||
slave->repldbfd = -1;
|
||||
@@ -854,23 +852,6 @@ void replicationEmptyDbCallback(void *privdata) {
|
||||
replicationSendNewlineToMaster();
|
||||
}
|
||||
|
||||
/* Once we have a link with the master and the synchroniziation was
|
||||
* performed, this function materializes the master client we store
|
||||
* at server.master, starting from the specified file descriptor. */
|
||||
void replicationCreateMasterClient(int fd) {
|
||||
server.master = createClient(fd);
|
||||
server.master->flags |= REDIS_MASTER;
|
||||
server.master->authenticated = 1;
|
||||
server.repl_state = REDIS_REPL_CONNECTED;
|
||||
server.master->reploff = server.repl_master_initial_offset;
|
||||
memcpy(server.master->replrunid, server.repl_master_runid,
|
||||
sizeof(server.repl_master_runid));
|
||||
/* If master offset is set to -1, this master is old and is not
|
||||
* PSYNC capable, so we flag it accordingly. */
|
||||
if (server.master->reploff == -1)
|
||||
server.master->flags |= REDIS_PRE_PSYNC;
|
||||
}
|
||||
|
||||
/* Asynchronously read the SYNC payload we receive from a master */
|
||||
#define REPL_MAX_WRITTEN_BEFORE_FSYNC (1024*1024*8) /* 8 MB */
|
||||
void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
@@ -957,7 +938,6 @@ void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
replicationAbortSyncTransfer();
|
||||
return;
|
||||
}
|
||||
server.stat_net_input_bytes += nread;
|
||||
|
||||
/* When a mark is used, we want to detect EOF asap in order to avoid
|
||||
* writing the EOF mark into the file... */
|
||||
@@ -1034,7 +1014,17 @@ void readSyncBulkPayload(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
/* Final setup of the connected slave <- master link */
|
||||
zfree(server.repl_transfer_tmpfile);
|
||||
close(server.repl_transfer_fd);
|
||||
replicationCreateMasterClient(server.repl_transfer_s);
|
||||
server.master = createClient(server.repl_transfer_s);
|
||||
server.master->flags |= REDIS_MASTER;
|
||||
server.master->authenticated = 1;
|
||||
server.repl_state = REDIS_REPL_CONNECTED;
|
||||
server.master->reploff = server.repl_master_initial_offset;
|
||||
memcpy(server.master->replrunid, server.repl_master_runid,
|
||||
sizeof(server.repl_master_runid));
|
||||
/* If master offset is set to -1, this master is old and is not
|
||||
* PSYNC capable, so we flag it accordingly. */
|
||||
if (server.master->reploff == -1)
|
||||
server.master->flags |= REDIS_PRE_PSYNC;
|
||||
redisLog(REDIS_NOTICE, "MASTER <-> SLAVE sync: Finished with success");
|
||||
/* Restart the AOF subsystem now that we finished the sync. This
|
||||
* will trigger an AOF rewrite, and when done will start appending
|
||||
|
||||
+1
-39
@@ -30,7 +30,6 @@
|
||||
#include "redis.h"
|
||||
#include "sha1.h"
|
||||
#include "rand.h"
|
||||
#include "cluster.h"
|
||||
|
||||
#include <lua.h>
|
||||
#include <lauxlib.h>
|
||||
@@ -214,27 +213,11 @@ int luaRedisGenericCommand(lua_State *lua, int raise_error) {
|
||||
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++;
|
||||
|
||||
/* Require at least one argument */
|
||||
if (argc == 0) {
|
||||
luaPushError(lua,
|
||||
"Please specify at least one argument for redis.call()");
|
||||
inuse--;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -289,7 +272,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 +291,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,23 +337,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. */
|
||||
if (server.cluster_enabled) {
|
||||
/* 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.
|
||||
@@ -443,10 +409,8 @@ cleanup:
|
||||
* return the plain error. */
|
||||
lua_pushstring(lua,"err");
|
||||
lua_gettable(lua,-2);
|
||||
inuse--;
|
||||
return lua_error(lua);
|
||||
}
|
||||
inuse--;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -573,7 +537,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);
|
||||
@@ -584,7 +547,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);
|
||||
|
||||
@@ -295,7 +295,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 +369,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 +390,7 @@ 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);
|
||||
va_end(ap);
|
||||
if (buf[buflen-2] != '\0') {
|
||||
if (buf != staticbuf) zfree(buf);
|
||||
buflen *= 2;
|
||||
@@ -415,7 +415,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
|
||||
@@ -570,7 +570,7 @@ sds sdstrim(sds s, const char *cset) {
|
||||
sp = start = s;
|
||||
ep = end = s+sdslen(s)-1;
|
||||
while(sp <= end && strchr(cset, *sp)) sp++;
|
||||
while(ep > sp && strchr(cset, *ep)) ep--;
|
||||
while(ep > start && strchr(cset, *ep)) ep--;
|
||||
len = (sp > ep) ? 0 : ((ep-sp)+1);
|
||||
if (sh->buf != sp) memmove(sh->buf, sp, len);
|
||||
sh->buf[len] = '\0';
|
||||
@@ -643,8 +643,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
|
||||
@@ -962,15 +962,12 @@ sds sdsjoin(char **argv, int argc, char *sep) {
|
||||
return join;
|
||||
}
|
||||
|
||||
#if defined(REDIS_TEST) || defined(SDS_TEST_MAIN)
|
||||
#ifdef SDS_TEST_MAIN
|
||||
#include <stdio.h>
|
||||
#include "testhelp.h"
|
||||
#include "limits.h"
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int sdsTest(int argc, char *argv[]) {
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
int main(void) {
|
||||
{
|
||||
struct sdshdr *sh;
|
||||
sds x = sdsnew("foo"), y;
|
||||
@@ -1016,18 +1013,6 @@ int sdsTest(int argc, char *argv[]) {
|
||||
sdslen(x) == 35 &&
|
||||
memcmp(x,"--4294967295,18446744073709551615--",35) == 0)
|
||||
|
||||
sdsfree(x);
|
||||
x = sdsnew(" x ");
|
||||
sdstrim(x," x");
|
||||
test_cond("sdstrim() works when all chars match",
|
||||
sdslen(x) == 0)
|
||||
|
||||
sdsfree(x);
|
||||
x = sdsnew(" x ");
|
||||
sdstrim(x," ");
|
||||
test_cond("sdstrim() works when a single char remains",
|
||||
sdslen(x) == 1 && x[0] == 'x')
|
||||
|
||||
sdsfree(x);
|
||||
x = sdsnew("xxciaoyyy");
|
||||
sdstrim(x,"xy");
|
||||
@@ -1095,7 +1080,7 @@ int sdsTest(int argc, char *argv[]) {
|
||||
memcmp(y,"\"\\a\\n\\x00foo\\r\"",15) == 0)
|
||||
|
||||
{
|
||||
unsigned int oldfree;
|
||||
int oldfree;
|
||||
|
||||
sdsfree(x);
|
||||
x = sdsnew("0");
|
||||
@@ -1116,9 +1101,3 @@ int sdsTest(int argc, char *argv[]) {
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef SDS_TEST_MAIN
|
||||
int main(void) {
|
||||
return sdsTest();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -98,8 +98,4 @@ void sdsIncrLen(sds s, int incr);
|
||||
sds sdsRemoveFreeSpace(sds s);
|
||||
size_t sdsAllocSize(sds s);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int sdsTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+19
-94
@@ -190,7 +190,6 @@ typedef struct sentinelRedisInstance {
|
||||
* are set to NULL no script is executed. */
|
||||
char *notification_script;
|
||||
char *client_reconfig_script;
|
||||
sds info; /* cached INFO output */
|
||||
} sentinelRedisInstance;
|
||||
|
||||
/* Main state. */
|
||||
@@ -577,7 +576,7 @@ void sentinelEvent(int level, char *type, sentinelRedisInstance *ri,
|
||||
if (level == REDIS_WARNING && ri != NULL) {
|
||||
sentinelRedisInstance *master = (ri->flags & SRI_MASTER) ?
|
||||
ri : ri->master;
|
||||
if (master && master->notification_script) {
|
||||
if (master->notification_script) {
|
||||
sentinelScheduleScriptExecution(master->notification_script,
|
||||
type,msg,NULL);
|
||||
}
|
||||
@@ -897,7 +896,7 @@ sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *
|
||||
sentinelRedisInstance *ri;
|
||||
sentinelAddr *addr;
|
||||
dict *table = NULL;
|
||||
char slavename[REDIS_PEER_ID_LEN], *sdsname;
|
||||
char slavename[128], *sdsname;
|
||||
|
||||
redisAssert(flags & (SRI_MASTER|SRI_SLAVE|SRI_SENTINEL));
|
||||
redisAssert((flags & SRI_MASTER) || master != NULL);
|
||||
@@ -908,7 +907,9 @@ sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *
|
||||
|
||||
/* For slaves and sentinel we use ip:port as name. */
|
||||
if (flags & (SRI_SLAVE|SRI_SENTINEL)) {
|
||||
anetFormatAddr(slavename, sizeof(slavename), hostname, port);
|
||||
snprintf(slavename,sizeof(slavename),
|
||||
strchr(hostname,':') ? "[%s]:%d" : "%s:%d",
|
||||
hostname,port);
|
||||
name = slavename;
|
||||
}
|
||||
|
||||
@@ -982,7 +983,6 @@ sentinelRedisInstance *createSentinelRedisInstance(char *name, int flags, char *
|
||||
ri->promoted_slave = NULL;
|
||||
ri->notification_script = NULL;
|
||||
ri->client_reconfig_script = NULL;
|
||||
ri->info = NULL;
|
||||
|
||||
/* Role */
|
||||
ri->role_reported = ri->flags & (SRI_MASTER|SRI_SLAVE);
|
||||
@@ -1015,7 +1015,6 @@ void releaseSentinelRedisInstance(sentinelRedisInstance *ri) {
|
||||
sdsfree(ri->slave_master_host);
|
||||
sdsfree(ri->leader);
|
||||
sdsfree(ri->auth_pass);
|
||||
sdsfree(ri->info);
|
||||
releaseSentinelAddr(ri->addr);
|
||||
|
||||
/* Clear state into the master if needed. */
|
||||
@@ -1031,11 +1030,11 @@ sentinelRedisInstance *sentinelRedisInstanceLookupSlave(
|
||||
{
|
||||
sds key;
|
||||
sentinelRedisInstance *slave;
|
||||
char buf[REDIS_PEER_ID_LEN];
|
||||
|
||||
redisAssert(ri->flags & SRI_MASTER);
|
||||
anetFormatAddr(buf,sizeof(buf),ip,port);
|
||||
key = sdsnew(buf);
|
||||
key = sdscatprintf(sdsempty(),
|
||||
strchr(ip,':') ? "[%s]:%d" : "%s:%d",
|
||||
ip,port);
|
||||
slave = dictFetchValue(ri->slaves,key);
|
||||
sdsfree(key);
|
||||
return slave;
|
||||
@@ -1786,10 +1785,6 @@ void sentinelRefreshInstanceInfo(sentinelRedisInstance *ri, const char *info) {
|
||||
int numlines, j;
|
||||
int role = 0;
|
||||
|
||||
/* cache full INFO output for instance */
|
||||
sdsfree(ri->info);
|
||||
ri->info = sdsnew(info);
|
||||
|
||||
/* The following fields must be reset to a given value in the case they
|
||||
* are not found at all in the INFO output. */
|
||||
ri->master_link_down_time = 0;
|
||||
@@ -2741,12 +2736,6 @@ void sentinelCommand(redisClient *c) {
|
||||
!= REDIS_OK) return;
|
||||
if (getLongFromObjectOrReply(c,c->argv[4],&port,"Invalid port")
|
||||
!= REDIS_OK) return;
|
||||
|
||||
if (quorum <= 0) {
|
||||
addReplyError(c, "Quorum must be 1 or greater.");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Make sure the IP field is actually a valid IP before passing it
|
||||
* to createSentinelRedisInstance(), otherwise we may trigger a
|
||||
* DNS lookup at runtime. */
|
||||
@@ -2788,67 +2777,6 @@ void sentinelCommand(redisClient *c) {
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"set")) {
|
||||
if (c->argc < 3 || c->argc % 2 == 0) goto numargserr;
|
||||
sentinelSetCommand(c);
|
||||
} else if (!strcasecmp(c->argv[1]->ptr,"info-cache")) {
|
||||
if (c->argc < 2) goto numargserr;
|
||||
mstime_t now = mstime();
|
||||
|
||||
/* Create an ad-hoc dictionary type so that we can iterate
|
||||
* a dictionary composed of just the master groups the user
|
||||
* requested. */
|
||||
dictType copy_keeper = instancesDictType;
|
||||
copy_keeper.valDestructor = NULL;
|
||||
dict *masters_local = sentinel.masters;
|
||||
if (c->argc > 2) {
|
||||
masters_local = dictCreate(©_keeper, NULL);
|
||||
|
||||
for (int i = 2; i < c->argc; i++) {
|
||||
sentinelRedisInstance *ri;
|
||||
ri = sentinelGetMasterByName(c->argv[i]->ptr);
|
||||
if (!ri) continue; /* ignore non-existing names */
|
||||
dictAdd(masters_local, ri->name, ri);
|
||||
}
|
||||
}
|
||||
|
||||
/* Reply format:
|
||||
* 1.) master name
|
||||
* 2.) 1.) info from master
|
||||
* 2.) info from replica
|
||||
* ...
|
||||
* 3.) other master name
|
||||
* ...
|
||||
*/
|
||||
addReplyMultiBulkLen(c,dictSize(masters_local) * 2);
|
||||
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
di = dictGetIterator(masters_local);
|
||||
while ((de = dictNext(di)) != NULL) {
|
||||
sentinelRedisInstance *ri = dictGetVal(de);
|
||||
addReplyBulkCBuffer(c,ri->name,strlen(ri->name));
|
||||
addReplyMultiBulkLen(c,dictSize(ri->slaves) + 1); /* +1 for self */
|
||||
addReplyMultiBulkLen(c,2);
|
||||
addReplyLongLong(c, now - ri->info_refresh);
|
||||
if (ri->info)
|
||||
addReplyBulkCBuffer(c,ri->info,sdslen(ri->info));
|
||||
else
|
||||
addReply(c,shared.nullbulk);
|
||||
|
||||
dictIterator *sdi;
|
||||
dictEntry *sde;
|
||||
sdi = dictGetIterator(ri->slaves);
|
||||
while ((sde = dictNext(sdi)) != NULL) {
|
||||
sentinelRedisInstance *sri = dictGetVal(sde);
|
||||
addReplyMultiBulkLen(c,2);
|
||||
addReplyLongLong(c, now - sri->info_refresh);
|
||||
if (sri->info)
|
||||
addReplyBulkCBuffer(c,sri->info,sdslen(sri->info));
|
||||
else
|
||||
addReply(c,shared.nullbulk);
|
||||
}
|
||||
dictReleaseIterator(sdi);
|
||||
}
|
||||
dictReleaseIterator(di);
|
||||
if (masters_local != sentinel.masters) dictRelease(masters_local);
|
||||
} else {
|
||||
addReplyErrorFormat(c,"Unknown sentinel subcommand '%s'",
|
||||
(char*)c->argv[1]->ptr);
|
||||
@@ -2862,30 +2790,24 @@ numargserr:
|
||||
|
||||
/* SENTINEL INFO [section] */
|
||||
void sentinelInfoCommand(redisClient *c) {
|
||||
char *section = c->argc == 2 ? c->argv[1]->ptr : "default";
|
||||
sds info = sdsempty();
|
||||
int defsections = !strcasecmp(section,"default");
|
||||
int sections = 0;
|
||||
|
||||
if (c->argc > 2) {
|
||||
addReply(c,shared.syntaxerr);
|
||||
return;
|
||||
}
|
||||
|
||||
int defsections = 0, allsections = 0;
|
||||
char *section = c->argc == 2 ? c->argv[1]->ptr : NULL;
|
||||
if (section) {
|
||||
allsections = !strcasecmp(section,"all");
|
||||
defsections = !strcasecmp(section,"default");
|
||||
} else {
|
||||
defsections = 1;
|
||||
}
|
||||
|
||||
int sections = 0;
|
||||
sds info = sdsempty();
|
||||
if (defsections || allsections || !strcasecmp(section,"server")) {
|
||||
if (!strcasecmp(section,"server") || defsections) {
|
||||
if (sections++) info = sdscat(info,"\r\n");
|
||||
sds serversection = genRedisInfoString("server");
|
||||
info = sdscatlen(info,serversection,sdslen(serversection));
|
||||
sdsfree(serversection);
|
||||
}
|
||||
|
||||
if (defsections || allsections || !strcasecmp(section,"sentinel")) {
|
||||
if (!strcasecmp(section,"sentinel") || defsections) {
|
||||
dictIterator *di;
|
||||
dictEntry *de;
|
||||
int master_id = 0;
|
||||
@@ -2920,7 +2842,10 @@ void sentinelInfoCommand(redisClient *c) {
|
||||
dictReleaseIterator(di);
|
||||
}
|
||||
|
||||
addReplyBulkSds(c, info);
|
||||
addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
|
||||
(unsigned long)sdslen(info)));
|
||||
addReplySds(c,info);
|
||||
addReply(c,shared.crlf);
|
||||
}
|
||||
|
||||
/* Implements Sentinel verison of the ROLE command. The output is
|
||||
|
||||
+7
-6
@@ -24,7 +24,9 @@ A million repetitions of "a"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h> /* for u_int*_t */
|
||||
#if defined(__sun)
|
||||
#include "solarisfixes.h"
|
||||
#endif
|
||||
#include "sha1.h"
|
||||
#include "config.h"
|
||||
|
||||
@@ -197,19 +199,16 @@ void SHA1Final(unsigned char digest[20], SHA1_CTX* context)
|
||||
}
|
||||
/* ================ end of sha1.c ================ */
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
#if 0
|
||||
#define BUFSIZE 4096
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int sha1Test(int argc, char **argv)
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
SHA1_CTX ctx;
|
||||
unsigned char hash[20], buf[BUFSIZE];
|
||||
int i;
|
||||
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
|
||||
for(i=0;i<BUFSIZE;i++)
|
||||
buf[i] = i;
|
||||
|
||||
@@ -224,4 +223,6 @@ int sha1Test(int argc, char **argv)
|
||||
printf("\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
#ifndef SHA1_H
|
||||
#define SHA1_H
|
||||
/* ================ sha1.h ================ */
|
||||
/*
|
||||
SHA-1 in C
|
||||
@@ -17,8 +15,3 @@ 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, u_int32_t len);
|
||||
void SHA1Final(unsigned char digest[20], SHA1_CTX* context);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int sha1Test(int argc, char **argv);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -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 */
|
||||
|
||||
+24
-45
@@ -220,7 +220,7 @@ void sortCommand(redisClient *c) {
|
||||
if (sortval)
|
||||
incrRefCount(sortval);
|
||||
else
|
||||
sortval = createQuicklistObject();
|
||||
sortval = createListObject();
|
||||
|
||||
/* The SORT command has an SQL-alike syntax, parse it */
|
||||
while(j < c->argc) {
|
||||
@@ -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;
|
||||
@@ -322,17 +323,17 @@ void sortCommand(redisClient *c) {
|
||||
}
|
||||
if (end >= vectorlen) end = vectorlen-1;
|
||||
|
||||
/* Whenever possible, we load elements into the output array in a more
|
||||
* direct way. This is possible if:
|
||||
/* Optimization:
|
||||
*
|
||||
* 1) The object to sort is a sorted set or a list (internally sorted).
|
||||
* 1) if the object to sort is a sorted set.
|
||||
* 2) There is nothing to sort as dontsort is true (BY <constant string>).
|
||||
* 3) We have a LIMIT option that actually reduces the number of elements
|
||||
* to fetch.
|
||||
*
|
||||
* In this special case, if we have a LIMIT option that actually reduces
|
||||
* the number of elements to fetch, we also optimize to just load the
|
||||
* range we are interested in and allocating a vector that is big enough
|
||||
* for the selected range length. */
|
||||
if ((sortval->type == REDIS_ZSET || sortval->type == REDIS_LIST) &&
|
||||
* In this case to load all the objects in the vector is a huge waste of
|
||||
* resources. We just allocate a vector that is big enough for the selected
|
||||
* range length, and make sure to load just this part in the vector. */
|
||||
if (sortval->type == REDIS_ZSET &&
|
||||
dontsort &&
|
||||
(start != 0 || end != vectorlen-1))
|
||||
{
|
||||
@@ -343,32 +344,7 @@ void sortCommand(redisClient *c) {
|
||||
vector = zmalloc(sizeof(redisSortObject)*vectorlen);
|
||||
j = 0;
|
||||
|
||||
if (sortval->type == REDIS_LIST && dontsort) {
|
||||
/* Special handling for a list, if 'dontsort' is true.
|
||||
* This makes sure we return elements in the list original
|
||||
* ordering, accordingly to DESC / ASC options.
|
||||
*
|
||||
* Note that in this case we also handle LIMIT here in a direct
|
||||
* way, just getting the required range, as an optimization. */
|
||||
if (end >= start) {
|
||||
listTypeIterator *li;
|
||||
listTypeEntry entry;
|
||||
li = listTypeInitIterator(sortval,
|
||||
desc ? (long)(listTypeLength(sortval) - start - 1) : start,
|
||||
desc ? REDIS_HEAD : REDIS_TAIL);
|
||||
|
||||
while(j < vectorlen && listTypeNext(li,&entry)) {
|
||||
vector[j].obj = listTypeGet(&entry);
|
||||
vector[j].u.score = 0;
|
||||
vector[j].u.cmpobj = NULL;
|
||||
j++;
|
||||
}
|
||||
listTypeReleaseIterator(li);
|
||||
/* Fix start/end: output code is not aware of this optimization. */
|
||||
end -= start;
|
||||
start = 0;
|
||||
}
|
||||
} else if (sortval->type == REDIS_LIST) {
|
||||
if (sortval->type == REDIS_LIST) {
|
||||
listTypeIterator *li = listTypeInitIterator(sortval,0,REDIS_TAIL);
|
||||
listTypeEntry entry;
|
||||
while(listTypeNext(li,&entry)) {
|
||||
@@ -424,7 +400,10 @@ void sortCommand(redisClient *c) {
|
||||
j++;
|
||||
ln = desc ? ln->backward : ln->level[0].forward;
|
||||
}
|
||||
/* Fix start/end: output code is not aware of this optimization. */
|
||||
/* The code producing the output does not know that in the case of
|
||||
* sorted set, 'dontsort', and LIMIT, we are able to get just the
|
||||
* range, already sorted, so we need to adjust "start" and "end"
|
||||
* to make sure start is set to 0. */
|
||||
end -= start;
|
||||
start = 0;
|
||||
} else if (sortval->type == REDIS_ZSET) {
|
||||
@@ -531,7 +510,7 @@ void sortCommand(redisClient *c) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
robj *sobj = createQuicklistObject();
|
||||
robj *sobj = createZiplistObject();
|
||||
|
||||
/* STORE option specified, set the sorting result as a List object */
|
||||
for (j = start; j <= end; j++) {
|
||||
|
||||
+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 {
|
||||
|
||||
+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);
|
||||
|
||||
+261
-99
@@ -33,37 +33,75 @@
|
||||
* List API
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
/* Check the argument length to see if it requires us to convert the ziplist
|
||||
* to a real list. Only check raw-encoded objects because integer encoded
|
||||
* objects are never too long. */
|
||||
void listTypeTryConversion(robj *subject, robj *value) {
|
||||
if (subject->encoding != REDIS_ENCODING_ZIPLIST) return;
|
||||
if (sdsEncodedObject(value) &&
|
||||
sdslen(value->ptr) > server.list_max_ziplist_value)
|
||||
listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
|
||||
}
|
||||
|
||||
/* The function pushes an element to the specified list object 'subject',
|
||||
* at head or tail position as specified by 'where'.
|
||||
*
|
||||
* There is no need for the caller to increment the refcount of 'value' as
|
||||
* the function takes care of it if needed. */
|
||||
void listTypePush(robj *subject, robj *value, int where) {
|
||||
if (subject->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
int pos = (where == REDIS_HEAD) ? QUICKLIST_HEAD : QUICKLIST_TAIL;
|
||||
/* Check if we need to convert the ziplist */
|
||||
listTypeTryConversion(subject,value);
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
|
||||
ziplistLen(subject->ptr) >= server.list_max_ziplist_entries)
|
||||
listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
|
||||
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
int pos = (where == REDIS_HEAD) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
|
||||
value = getDecodedObject(value);
|
||||
size_t len = sdslen(value->ptr);
|
||||
quicklistPush(subject->ptr, value->ptr, len, pos);
|
||||
subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),pos);
|
||||
decrRefCount(value);
|
||||
} else if (subject->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
if (where == REDIS_HEAD) {
|
||||
listAddNodeHead(subject->ptr,value);
|
||||
} else {
|
||||
listAddNodeTail(subject->ptr,value);
|
||||
}
|
||||
incrRefCount(value);
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
}
|
||||
|
||||
void *listPopSaver(unsigned char *data, unsigned int sz) {
|
||||
return createStringObject((char*)data,sz);
|
||||
}
|
||||
|
||||
robj *listTypePop(robj *subject, int where) {
|
||||
long long vlong;
|
||||
robj *value = NULL;
|
||||
|
||||
int ql_where = where == REDIS_HEAD ? QUICKLIST_HEAD : QUICKLIST_TAIL;
|
||||
if (subject->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
if (quicklistPopCustom(subject->ptr, ql_where, (unsigned char **)&value,
|
||||
NULL, &vlong, listPopSaver)) {
|
||||
if (!value)
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *p;
|
||||
unsigned char *vstr;
|
||||
unsigned int vlen;
|
||||
long long vlong;
|
||||
int pos = (where == REDIS_HEAD) ? 0 : -1;
|
||||
p = ziplistIndex(subject->ptr,pos);
|
||||
if (ziplistGet(p,&vstr,&vlen,&vlong)) {
|
||||
if (vstr) {
|
||||
value = createStringObject((char*)vstr,vlen);
|
||||
} else {
|
||||
value = createStringObjectFromLongLong(vlong);
|
||||
}
|
||||
/* We only need to delete an element when it exists */
|
||||
subject->ptr = ziplistDelete(subject->ptr,&p);
|
||||
}
|
||||
} else if (subject->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
list *list = subject->ptr;
|
||||
listNode *ln;
|
||||
if (where == REDIS_HEAD) {
|
||||
ln = listFirst(list);
|
||||
} else {
|
||||
ln = listLast(list);
|
||||
}
|
||||
if (ln != NULL) {
|
||||
value = listNodeValue(ln);
|
||||
incrRefCount(value);
|
||||
listDelNode(list,ln);
|
||||
}
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
@@ -72,28 +110,25 @@ robj *listTypePop(robj *subject, int where) {
|
||||
}
|
||||
|
||||
unsigned long listTypeLength(robj *subject) {
|
||||
if (subject->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
return quicklistCount(subject->ptr);
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
return ziplistLen(subject->ptr);
|
||||
} else if (subject->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
return listLength((list*)subject->ptr);
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
}
|
||||
|
||||
/* Initialize an iterator at the specified index. */
|
||||
listTypeIterator *listTypeInitIterator(robj *subject, long index,
|
||||
unsigned char direction) {
|
||||
listTypeIterator *listTypeInitIterator(robj *subject, long index, unsigned char direction) {
|
||||
listTypeIterator *li = zmalloc(sizeof(listTypeIterator));
|
||||
li->subject = subject;
|
||||
li->encoding = subject->encoding;
|
||||
li->direction = direction;
|
||||
li->iter = NULL;
|
||||
/* REDIS_HEAD means start at TAIL and move *towards* head.
|
||||
* REDIS_TAIL means start at HEAD and move *towards tail. */
|
||||
int iter_direction =
|
||||
direction == REDIS_HEAD ? AL_START_TAIL : AL_START_HEAD;
|
||||
if (li->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
li->iter = quicklistGetIteratorAtIdx(li->subject->ptr,
|
||||
iter_direction, index);
|
||||
if (li->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
li->zi = ziplistIndex(subject->ptr,index);
|
||||
} else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
li->ln = listIndex(subject->ptr,index);
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -102,7 +137,6 @@ listTypeIterator *listTypeInitIterator(robj *subject, long index,
|
||||
|
||||
/* Clean up the iterator. */
|
||||
void listTypeReleaseIterator(listTypeIterator *li) {
|
||||
zfree(li->iter);
|
||||
zfree(li);
|
||||
}
|
||||
|
||||
@@ -114,8 +148,24 @@ int listTypeNext(listTypeIterator *li, listTypeEntry *entry) {
|
||||
redisAssert(li->subject->encoding == li->encoding);
|
||||
|
||||
entry->li = li;
|
||||
if (li->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
return quicklistNext(li->iter, &entry->entry);
|
||||
if (li->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
entry->zi = li->zi;
|
||||
if (entry->zi != NULL) {
|
||||
if (li->direction == REDIS_TAIL)
|
||||
li->zi = ziplistNext(li->subject->ptr,li->zi);
|
||||
else
|
||||
li->zi = ziplistPrev(li->subject->ptr,li->zi);
|
||||
return 1;
|
||||
}
|
||||
} else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
entry->ln = li->ln;
|
||||
if (entry->ln != NULL) {
|
||||
if (li->direction == REDIS_TAIL)
|
||||
li->ln = li->ln->next;
|
||||
else
|
||||
li->ln = li->ln->prev;
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -124,14 +174,24 @@ int listTypeNext(listTypeIterator *li, listTypeEntry *entry) {
|
||||
|
||||
/* Return entry or NULL at the current position of the iterator. */
|
||||
robj *listTypeGet(listTypeEntry *entry) {
|
||||
listTypeIterator *li = entry->li;
|
||||
robj *value = NULL;
|
||||
if (entry->li->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
if (entry->entry.value) {
|
||||
value = createStringObject((char *)entry->entry.value,
|
||||
entry->entry.sz);
|
||||
} else {
|
||||
value = createStringObjectFromLongLong(entry->entry.longval);
|
||||
if (li->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *vstr;
|
||||
unsigned int vlen;
|
||||
long long vlong;
|
||||
redisAssert(entry->zi != NULL);
|
||||
if (ziplistGet(entry->zi,&vstr,&vlen,&vlong)) {
|
||||
if (vstr) {
|
||||
value = createStringObject((char*)vstr,vlen);
|
||||
} else {
|
||||
value = createStringObjectFromLongLong(vlong);
|
||||
}
|
||||
}
|
||||
} else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
redisAssert(entry->ln != NULL);
|
||||
value = listNodeValue(entry->ln);
|
||||
incrRefCount(value);
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -139,18 +199,30 @@ robj *listTypeGet(listTypeEntry *entry) {
|
||||
}
|
||||
|
||||
void listTypeInsert(listTypeEntry *entry, robj *value, int where) {
|
||||
if (entry->li->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
robj *subject = entry->li->subject;
|
||||
if (entry->li->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
value = getDecodedObject(value);
|
||||
sds str = value->ptr;
|
||||
size_t len = sdslen(str);
|
||||
if (where == REDIS_TAIL) {
|
||||
quicklistInsertAfter((quicklist *)entry->entry.quicklist,
|
||||
&entry->entry, str, len);
|
||||
} else if (where == REDIS_HEAD) {
|
||||
quicklistInsertBefore((quicklist *)entry->entry.quicklist,
|
||||
&entry->entry, str, len);
|
||||
unsigned char *next = ziplistNext(subject->ptr,entry->zi);
|
||||
|
||||
/* When we insert after the current element, but the current element
|
||||
* is the tail of the list, we need to do a push. */
|
||||
if (next == NULL) {
|
||||
subject->ptr = ziplistPush(subject->ptr,value->ptr,sdslen(value->ptr),REDIS_TAIL);
|
||||
} else {
|
||||
subject->ptr = ziplistInsert(subject->ptr,next,value->ptr,sdslen(value->ptr));
|
||||
}
|
||||
} else {
|
||||
subject->ptr = ziplistInsert(subject->ptr,entry->zi,value->ptr,sdslen(value->ptr));
|
||||
}
|
||||
decrRefCount(value);
|
||||
} else if (entry->li->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
if (where == REDIS_TAIL) {
|
||||
listInsertNode(subject->ptr,entry->ln,value,AL_START_TAIL);
|
||||
} else {
|
||||
listInsertNode(subject->ptr,entry->ln,value,AL_START_HEAD);
|
||||
}
|
||||
incrRefCount(value);
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -158,33 +230,59 @@ void listTypeInsert(listTypeEntry *entry, robj *value, int where) {
|
||||
|
||||
/* Compare the given object with the entry at the current position. */
|
||||
int listTypeEqual(listTypeEntry *entry, robj *o) {
|
||||
if (entry->li->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
listTypeIterator *li = entry->li;
|
||||
if (li->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
redisAssertWithInfo(NULL,o,sdsEncodedObject(o));
|
||||
return quicklistCompare(entry->entry.zi,o->ptr,sdslen(o->ptr));
|
||||
return ziplistCompare(entry->zi,o->ptr,sdslen(o->ptr));
|
||||
} else if (li->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
return equalStringObjects(o,listNodeValue(entry->ln));
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
}
|
||||
|
||||
/* Delete the element pointed to. */
|
||||
void listTypeDelete(listTypeIterator *iter, listTypeEntry *entry) {
|
||||
if (entry->li->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
quicklistDelEntry(iter->iter, &entry->entry);
|
||||
void listTypeDelete(listTypeEntry *entry) {
|
||||
listTypeIterator *li = entry->li;
|
||||
if (li->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *p = entry->zi;
|
||||
li->subject->ptr = ziplistDelete(li->subject->ptr,&p);
|
||||
|
||||
/* Update position of the iterator depending on the direction */
|
||||
if (li->direction == REDIS_TAIL)
|
||||
li->zi = p;
|
||||
else
|
||||
li->zi = ziplistPrev(li->subject->ptr,p);
|
||||
} else if (entry->li->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
listNode *next;
|
||||
if (li->direction == REDIS_TAIL)
|
||||
next = entry->ln->next;
|
||||
else
|
||||
next = entry->ln->prev;
|
||||
listDelNode(li->subject->ptr,entry->ln);
|
||||
li->ln = next;
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
}
|
||||
|
||||
/* Create a quicklist from a single ziplist */
|
||||
void listTypeConvert(robj *subject, int enc) {
|
||||
redisAssertWithInfo(NULL,subject,subject->type==REDIS_LIST);
|
||||
redisAssertWithInfo(NULL,subject,subject->encoding==REDIS_ENCODING_ZIPLIST);
|
||||
listTypeIterator *li;
|
||||
listTypeEntry entry;
|
||||
redisAssertWithInfo(NULL,subject,subject->type == REDIS_LIST);
|
||||
|
||||
if (enc == REDIS_ENCODING_QUICKLIST) {
|
||||
size_t zlen = server.list_max_ziplist_size;
|
||||
int depth = server.list_compress_depth;
|
||||
subject->ptr = quicklistCreateFromZiplist(zlen, depth, subject->ptr);
|
||||
subject->encoding = REDIS_ENCODING_QUICKLIST;
|
||||
if (enc == REDIS_ENCODING_LINKEDLIST) {
|
||||
list *l = listCreate();
|
||||
listSetFreeMethod(l,decrRefCountVoid);
|
||||
|
||||
/* listTypeGet returns a robj with incremented refcount */
|
||||
li = listTypeInitIterator(subject,0,REDIS_TAIL);
|
||||
while (listTypeNext(li,&entry)) listAddNodeTail(l,listTypeGet(&entry));
|
||||
listTypeReleaseIterator(li);
|
||||
|
||||
subject->encoding = REDIS_ENCODING_LINKEDLIST;
|
||||
zfree(subject->ptr);
|
||||
subject->ptr = l;
|
||||
} else {
|
||||
redisPanic("Unsupported list conversion");
|
||||
}
|
||||
@@ -206,9 +304,7 @@ void pushGenericCommand(redisClient *c, int where) {
|
||||
for (j = 2; j < c->argc; j++) {
|
||||
c->argv[j] = tryObjectEncoding(c->argv[j]);
|
||||
if (!lobj) {
|
||||
lobj = createQuicklistObject();
|
||||
quicklistSetOptions(lobj->ptr, server.list_max_ziplist_size,
|
||||
server.list_compress_depth);
|
||||
lobj = createZiplistObject();
|
||||
dbAdd(c->db,c->argv[1],lobj);
|
||||
}
|
||||
listTypePush(lobj,c->argv[j],where);
|
||||
@@ -238,10 +334,17 @@ void pushxGenericCommand(redisClient *c, robj *refval, robj *val, int where) {
|
||||
listTypeEntry entry;
|
||||
int inserted = 0;
|
||||
|
||||
if ((subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
|
||||
if ((subject = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
|
||||
checkType(c,subject,REDIS_LIST)) return;
|
||||
|
||||
if (refval != NULL) {
|
||||
/* We're not sure if this value can be inserted yet, but we cannot
|
||||
* convert the list inside the iterator. We don't want to loop over
|
||||
* the list twice (once to see if the value can be inserted and once
|
||||
* to do the actual insert), so we assume this value can be inserted
|
||||
* and convert the ziplist to a regular list if necessary. */
|
||||
listTypeTryConversion(subject,val);
|
||||
|
||||
/* Seek refval from head to tail */
|
||||
iter = listTypeInitIterator(subject,0,REDIS_TAIL);
|
||||
while (listTypeNext(iter,&entry)) {
|
||||
@@ -254,6 +357,10 @@ void pushxGenericCommand(redisClient *c, robj *refval, robj *val, int where) {
|
||||
listTypeReleaseIterator(iter);
|
||||
|
||||
if (inserted) {
|
||||
/* Check if the length exceeds the ziplist length threshold. */
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST &&
|
||||
ziplistLen(subject->ptr) > server.list_max_ziplist_entries)
|
||||
listTypeConvert(subject,REDIS_ENCODING_LINKEDLIST);
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_LIST,"linsert",
|
||||
c->argv[1],c->db->id);
|
||||
@@ -311,19 +418,31 @@ void lindexCommand(redisClient *c) {
|
||||
if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != REDIS_OK))
|
||||
return;
|
||||
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
quicklistEntry entry;
|
||||
if (quicklistIndex(o->ptr, index, &entry)) {
|
||||
if (entry.value) {
|
||||
value = createStringObject((char*)entry.value,entry.sz);
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *p;
|
||||
unsigned char *vstr;
|
||||
unsigned int vlen;
|
||||
long long vlong;
|
||||
p = ziplistIndex(o->ptr,index);
|
||||
if (ziplistGet(p,&vstr,&vlen,&vlong)) {
|
||||
if (vstr) {
|
||||
value = createStringObject((char*)vstr,vlen);
|
||||
} else {
|
||||
value = createStringObjectFromLongLong(entry.longval);
|
||||
value = createStringObjectFromLongLong(vlong);
|
||||
}
|
||||
addReplyBulk(c,value);
|
||||
decrRefCount(value);
|
||||
} else {
|
||||
addReply(c,shared.nullbulk);
|
||||
}
|
||||
} else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
listNode *ln = listIndex(o->ptr,index);
|
||||
if (ln != NULL) {
|
||||
value = listNodeValue(ln);
|
||||
addReplyBulk(c,value);
|
||||
} else {
|
||||
addReply(c,shared.nullbulk);
|
||||
}
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -333,18 +452,35 @@ void lsetCommand(redisClient *c) {
|
||||
robj *o = lookupKeyWriteOrReply(c,c->argv[1],shared.nokeyerr);
|
||||
if (o == NULL || checkType(c,o,REDIS_LIST)) return;
|
||||
long index;
|
||||
robj *value = c->argv[3];
|
||||
robj *value = (c->argv[3] = tryObjectEncoding(c->argv[3]));
|
||||
|
||||
if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != REDIS_OK))
|
||||
return;
|
||||
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
quicklist *ql = o->ptr;
|
||||
int replaced = quicklistReplaceAtIndex(ql, index,
|
||||
value->ptr, sdslen(value->ptr));
|
||||
if (!replaced) {
|
||||
listTypeTryConversion(o,value);
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *p, *zl = o->ptr;
|
||||
p = ziplistIndex(zl,index);
|
||||
if (p == NULL) {
|
||||
addReply(c,shared.outofrangeerr);
|
||||
} else {
|
||||
o->ptr = ziplistDelete(o->ptr,&p);
|
||||
value = getDecodedObject(value);
|
||||
o->ptr = ziplistInsert(o->ptr,p,value->ptr,sdslen(value->ptr));
|
||||
decrRefCount(value);
|
||||
addReply(c,shared.ok);
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_LIST,"lset",c->argv[1],c->db->id);
|
||||
server.dirty++;
|
||||
}
|
||||
} else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
listNode *ln = listIndex(o->ptr,index);
|
||||
if (ln == NULL) {
|
||||
addReply(c,shared.outofrangeerr);
|
||||
} else {
|
||||
decrRefCount((robj*)listNodeValue(ln));
|
||||
listNodeValue(ln) = value;
|
||||
incrRefCount(value);
|
||||
addReply(c,shared.ok);
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_LIST,"lset",c->argv[1],c->db->id);
|
||||
@@ -413,28 +549,43 @@ void lrangeCommand(redisClient *c) {
|
||||
|
||||
/* Return the result in form of a multi-bulk reply */
|
||||
addReplyMultiBulkLen(c,rangelen);
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
listTypeIterator *iter = listTypeInitIterator(o, start, REDIS_TAIL);
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
unsigned char *p = ziplistIndex(o->ptr,start);
|
||||
unsigned char *vstr;
|
||||
unsigned int vlen;
|
||||
long long vlong;
|
||||
|
||||
while(rangelen--) {
|
||||
listTypeEntry entry;
|
||||
listTypeNext(iter, &entry);
|
||||
quicklistEntry *qe = &entry.entry;
|
||||
if (qe->value) {
|
||||
addReplyBulkCBuffer(c,qe->value,qe->sz);
|
||||
ziplistGet(p,&vstr,&vlen,&vlong);
|
||||
if (vstr) {
|
||||
addReplyBulkCBuffer(c,vstr,vlen);
|
||||
} else {
|
||||
addReplyBulkLongLong(c,qe->longval);
|
||||
addReplyBulkLongLong(c,vlong);
|
||||
}
|
||||
p = ziplistNext(o->ptr,p);
|
||||
}
|
||||
} else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
listNode *ln;
|
||||
|
||||
/* If we are nearest to the end of the list, reach the element
|
||||
* starting from tail and going backward, as it is faster. */
|
||||
if (start > llen/2) start -= llen;
|
||||
ln = listIndex(o->ptr,start);
|
||||
|
||||
while(rangelen--) {
|
||||
addReplyBulk(c,ln->value);
|
||||
ln = ln->next;
|
||||
}
|
||||
listTypeReleaseIterator(iter);
|
||||
} else {
|
||||
redisPanic("List encoding is not QUICKLIST!");
|
||||
redisPanic("List encoding is not LINKEDLIST nor ZIPLIST!");
|
||||
}
|
||||
}
|
||||
|
||||
void ltrimCommand(redisClient *c) {
|
||||
robj *o;
|
||||
long start, end, llen, ltrim, rtrim;
|
||||
long start, end, llen, j, ltrim, rtrim;
|
||||
list *list;
|
||||
listNode *ln;
|
||||
|
||||
if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
|
||||
(getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;
|
||||
@@ -461,9 +612,19 @@ void ltrimCommand(redisClient *c) {
|
||||
}
|
||||
|
||||
/* Remove list elements to perform the trim */
|
||||
if (o->encoding == REDIS_ENCODING_QUICKLIST) {
|
||||
quicklistDelRange(o->ptr,0,ltrim);
|
||||
quicklistDelRange(o->ptr,-rtrim,rtrim);
|
||||
if (o->encoding == REDIS_ENCODING_ZIPLIST) {
|
||||
o->ptr = ziplistDeleteRange(o->ptr,0,ltrim);
|
||||
o->ptr = ziplistDeleteRange(o->ptr,-rtrim,rtrim);
|
||||
} else if (o->encoding == REDIS_ENCODING_LINKEDLIST) {
|
||||
list = o->ptr;
|
||||
for (j = 0; j < ltrim; j++) {
|
||||
ln = listFirst(list);
|
||||
listDelNode(list,ln);
|
||||
}
|
||||
for (j = 0; j < rtrim; j++) {
|
||||
ln = listLast(list);
|
||||
listDelNode(list,ln);
|
||||
}
|
||||
} else {
|
||||
redisPanic("Unknown list encoding");
|
||||
}
|
||||
@@ -480,9 +641,10 @@ void ltrimCommand(redisClient *c) {
|
||||
|
||||
void lremCommand(redisClient *c) {
|
||||
robj *subject, *obj;
|
||||
obj = c->argv[3];
|
||||
obj = c->argv[3] = tryObjectEncoding(c->argv[3]);
|
||||
long toremove;
|
||||
long removed = 0;
|
||||
listTypeEntry entry;
|
||||
|
||||
if ((getLongFromObjectOrReply(c, c->argv[2], &toremove, NULL) != REDIS_OK))
|
||||
return;
|
||||
@@ -490,6 +652,10 @@ void lremCommand(redisClient *c) {
|
||||
subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero);
|
||||
if (subject == NULL || checkType(c,subject,REDIS_LIST)) return;
|
||||
|
||||
/* Make sure obj is raw when we're dealing with a ziplist */
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST)
|
||||
obj = getDecodedObject(obj);
|
||||
|
||||
listTypeIterator *li;
|
||||
if (toremove < 0) {
|
||||
toremove = -toremove;
|
||||
@@ -498,10 +664,9 @@ void lremCommand(redisClient *c) {
|
||||
li = listTypeInitIterator(subject,0,REDIS_TAIL);
|
||||
}
|
||||
|
||||
listTypeEntry entry;
|
||||
while (listTypeNext(li,&entry)) {
|
||||
if (listTypeEqual(&entry,obj)) {
|
||||
listTypeDelete(li, &entry);
|
||||
listTypeDelete(&entry);
|
||||
server.dirty++;
|
||||
removed++;
|
||||
if (toremove && removed == toremove) break;
|
||||
@@ -509,10 +674,11 @@ void lremCommand(redisClient *c) {
|
||||
}
|
||||
listTypeReleaseIterator(li);
|
||||
|
||||
if (listTypeLength(subject) == 0) {
|
||||
dbDelete(c->db,c->argv[1]);
|
||||
}
|
||||
/* Clean up raw encoded object */
|
||||
if (subject->encoding == REDIS_ENCODING_ZIPLIST)
|
||||
decrRefCount(obj);
|
||||
|
||||
if (listTypeLength(subject) == 0) dbDelete(c->db,c->argv[1]);
|
||||
addReplyLongLong(c,removed);
|
||||
if (removed) signalModifiedKey(c->db,c->argv[1]);
|
||||
}
|
||||
@@ -536,9 +702,7 @@ void lremCommand(redisClient *c) {
|
||||
void rpoplpushHandlePush(redisClient *c, robj *dstkey, robj *dstobj, robj *value) {
|
||||
/* Create the list if the key does not exist */
|
||||
if (!dstobj) {
|
||||
dstobj = createQuicklistObject();
|
||||
quicklistSetOptions(dstobj->ptr, server.list_max_ziplist_size,
|
||||
server.list_compress_depth);
|
||||
dstobj = createZiplistObject();
|
||||
dbAdd(c->db,dstkey,dstobj);
|
||||
}
|
||||
signalModifiedKey(c->db,dstkey);
|
||||
@@ -846,9 +1010,7 @@ void handleClientsBlockedOnLists(void) {
|
||||
}
|
||||
}
|
||||
|
||||
if (listTypeLength(o) == 0) {
|
||||
dbDelete(rl->db,rl->key);
|
||||
}
|
||||
if (listTypeLength(o) == 0) dbDelete(rl->db,rl->key);
|
||||
/* We don't call signalModifiedKey() as it was already called
|
||||
* when an element was pushed on the list. */
|
||||
}
|
||||
|
||||
+5
-191
@@ -33,8 +33,7 @@
|
||||
* Set Commands
|
||||
*----------------------------------------------------------------------------*/
|
||||
|
||||
void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum,
|
||||
robj *dstkey, int op);
|
||||
void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op);
|
||||
|
||||
/* Factory method to return a set that *can* hold "value". When the object has
|
||||
* an integer-encodable value, an intset will be returned. Otherwise a regular
|
||||
@@ -45,11 +44,6 @@ robj *setTypeCreate(robj *value) {
|
||||
return createSetObject();
|
||||
}
|
||||
|
||||
/* Add the specified value into a set. The function takes care of incrementing
|
||||
* the reference count of the object if needed in order to retain a copy.
|
||||
*
|
||||
* If the value was already member of the set, nothing is done and 0 is
|
||||
* returned, otherwise the new element is added and 1 is returned. */
|
||||
int setTypeAdd(robj *subject, robj *value) {
|
||||
long long llval;
|
||||
if (subject->encoding == REDIS_ENCODING_HT) {
|
||||
@@ -74,8 +68,7 @@ int setTypeAdd(robj *subject, robj *value) {
|
||||
|
||||
/* The set *was* an intset and this value is not integer
|
||||
* encodable, so dictAdd should always work. */
|
||||
redisAssertWithInfo(NULL,value,
|
||||
dictAdd(subject->ptr,value,NULL) == DICT_OK);
|
||||
redisAssertWithInfo(NULL,value,dictAdd(subject->ptr,value,NULL) == DICT_OK);
|
||||
incrRefCount(value);
|
||||
return 1;
|
||||
}
|
||||
@@ -242,8 +235,7 @@ void setTypeConvert(robj *setobj, int enc) {
|
||||
si = setTypeInitIterator(setobj);
|
||||
while (setTypeNext(si,NULL,&intele) != -1) {
|
||||
element = createStringObjectFromLongLong(intele);
|
||||
redisAssertWithInfo(NULL,element,
|
||||
dictAdd(d,element,NULL) == DICT_OK);
|
||||
redisAssertWithInfo(NULL,element,dictAdd(d,element,NULL) == DICT_OK);
|
||||
}
|
||||
setTypeReleaseIterator(si);
|
||||
|
||||
@@ -385,185 +377,15 @@ void scardCommand(redisClient *c) {
|
||||
addReplyLongLong(c,setTypeSize(o));
|
||||
}
|
||||
|
||||
/* Handle the "SPOP key <count>" variant. The normal version of the
|
||||
* command is handled by the spopCommand() function itself. */
|
||||
|
||||
/* How many times bigger should be the set compared to the remaining size
|
||||
* for us to use the "create new set" strategy? Read later in the
|
||||
* implementation for more info. */
|
||||
#define SPOP_MOVE_STRATEGY_MUL 5
|
||||
|
||||
void spopWithCountCommand(redisClient *c) {
|
||||
long l;
|
||||
unsigned long count, size;
|
||||
robj *set;
|
||||
|
||||
/* Get the count argument */
|
||||
if (getLongFromObjectOrReply(c,c->argv[2],&l,NULL) != REDIS_OK) return;
|
||||
if (l >= 0) {
|
||||
count = (unsigned) l;
|
||||
} else {
|
||||
addReply(c,shared.outofrangeerr);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Make sure a key with the name inputted exists, and that it's type is
|
||||
* indeed a set. Otherwise, return nil */
|
||||
if ((set = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk))
|
||||
== NULL || checkType(c,set,REDIS_SET)) return;
|
||||
|
||||
/* If count is zero, serve an empty multibulk ASAP to avoid special
|
||||
* cases later. */
|
||||
if (count == 0) {
|
||||
addReply(c,shared.emptymultibulk);
|
||||
return;
|
||||
}
|
||||
|
||||
size = setTypeSize(set);
|
||||
|
||||
/* Generate an SPOP keyspace notification */
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_SET,"spop",c->argv[1],c->db->id);
|
||||
server.dirty += count;
|
||||
|
||||
/* CASE 1:
|
||||
* The number of requested elements is greater than or equal to
|
||||
* the number of elements inside the set: simply return the whole set. */
|
||||
if (count >= size) {
|
||||
/* We just return the entire set */
|
||||
sunionDiffGenericCommand(c,c->argv+1,1,NULL,REDIS_OP_UNION);
|
||||
|
||||
/* Delete the set as it is now empty */
|
||||
dbDelete(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",c->argv[1],c->db->id);
|
||||
|
||||
/* Propagate this command as an DEL operation */
|
||||
rewriteClientCommandVector(c,2,shared.del,c->argv[1]);
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
server.dirty++;
|
||||
return;
|
||||
}
|
||||
|
||||
/* Case 2 and 3 require to replicate SPOP as a set of SERM commands.
|
||||
* Prepare our replication argument vector. Also send the array length
|
||||
* which is common to both the code paths. */
|
||||
robj *propargv[3];
|
||||
propargv[0] = createStringObject("SREM",4);
|
||||
propargv[1] = c->argv[1];
|
||||
addReplyMultiBulkLen(c,count);
|
||||
|
||||
/* Common iteration vars. */
|
||||
robj *objele;
|
||||
int encoding;
|
||||
int64_t llele;
|
||||
unsigned long remaining = size-count; /* Elements left after SPOP. */
|
||||
|
||||
/* If we are here, the number of requested elements is less than the
|
||||
* number of elements inside the set. Also we are sure that count < size.
|
||||
* Use two different strategies.
|
||||
*
|
||||
* CASE 2: The number of elements to return is small compared to the
|
||||
* set size. We can just extract random elements and return them to
|
||||
* the set. */
|
||||
if (remaining*SPOP_MOVE_STRATEGY_MUL > count) {
|
||||
while(count--) {
|
||||
encoding = setTypeRandomElement(set,&objele,&llele);
|
||||
if (encoding == REDIS_ENCODING_INTSET) {
|
||||
objele = createStringObjectFromLongLong(llele);
|
||||
} else {
|
||||
incrRefCount(objele);
|
||||
}
|
||||
|
||||
/* Return the element to the client and remove from the set. */
|
||||
addReplyBulk(c,objele);
|
||||
setTypeRemove(set,objele);
|
||||
|
||||
/* Replicate/AOF this command as an SREM operation */
|
||||
propargv[2] = objele;
|
||||
alsoPropagate(server.sremCommand,c->db->id,propargv,3,
|
||||
REDIS_PROPAGATE_AOF|REDIS_PROPAGATE_REPL);
|
||||
decrRefCount(objele);
|
||||
}
|
||||
} else {
|
||||
/* CASE 3: The number of elements to return is very big, approaching
|
||||
* the size of the set itself. After some time extracting random elements
|
||||
* from such a set becomes computationally expensive, so we use
|
||||
* a different strategy, we extract random elements that we don't
|
||||
* want to return (the elements that will remain part of the set),
|
||||
* creating a new set as we do this (that will be stored as the original
|
||||
* set). Then we return the elements left in the original set and
|
||||
* release it. */
|
||||
robj *newset = NULL;
|
||||
|
||||
/* Create a new set with just the remaining elements. */
|
||||
while(remaining--) {
|
||||
encoding = setTypeRandomElement(set,&objele,&llele);
|
||||
if (encoding == REDIS_ENCODING_INTSET) {
|
||||
objele = createStringObjectFromLongLong(llele);
|
||||
} else {
|
||||
incrRefCount(objele);
|
||||
}
|
||||
if (!newset) newset = setTypeCreate(objele);
|
||||
setTypeAdd(newset,objele);
|
||||
setTypeRemove(set,objele);
|
||||
decrRefCount(objele);
|
||||
}
|
||||
|
||||
/* Assign the new set as the key value. */
|
||||
incrRefCount(set); /* Protect the old set value. */
|
||||
dbOverwrite(c->db,c->argv[1],newset);
|
||||
|
||||
/* Tranfer the old set to the client and release it. */
|
||||
setTypeIterator *si;
|
||||
si = setTypeInitIterator(set);
|
||||
while((encoding = setTypeNext(si,&objele,&llele)) != -1) {
|
||||
if (encoding == REDIS_ENCODING_INTSET) {
|
||||
objele = createStringObjectFromLongLong(llele);
|
||||
} else {
|
||||
incrRefCount(objele);
|
||||
}
|
||||
addReplyBulk(c,objele);
|
||||
|
||||
/* Replicate/AOF this command as an SREM operation */
|
||||
propargv[2] = objele;
|
||||
alsoPropagate(server.sremCommand,c->db->id,propargv,3,
|
||||
REDIS_PROPAGATE_AOF|REDIS_PROPAGATE_REPL);
|
||||
|
||||
decrRefCount(objele);
|
||||
}
|
||||
setTypeReleaseIterator(si);
|
||||
decrRefCount(set);
|
||||
}
|
||||
|
||||
/* Don't propagate the command itself even if we incremented the
|
||||
* dirty counter. We don't want to propagate an SPOP command since
|
||||
* we propagated the command as a set of SREMs operations using
|
||||
* the alsoPropagate() API. */
|
||||
decrRefCount(propargv[0]);
|
||||
preventCommandPropagation(c);
|
||||
}
|
||||
|
||||
void spopCommand(redisClient *c) {
|
||||
robj *set, *ele, *aux;
|
||||
int64_t llele;
|
||||
int encoding;
|
||||
|
||||
if (c->argc == 3) {
|
||||
spopWithCountCommand(c);
|
||||
return;
|
||||
} else if (c->argc > 3) {
|
||||
addReply(c,shared.syntaxerr);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Make sure a key with the name inputted exists, and that it's type is
|
||||
* indeed a set */
|
||||
if ((set = lookupKeyWriteOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
|
||||
checkType(c,set,REDIS_SET)) return;
|
||||
|
||||
/* Get a random element from the set */
|
||||
encoding = setTypeRandomElement(set,&ele,&llele);
|
||||
|
||||
/* Remove the element from the set */
|
||||
if (encoding == REDIS_ENCODING_INTSET) {
|
||||
ele = createStringObjectFromLongLong(llele);
|
||||
set->ptr = intsetRemove(set->ptr,llele,NULL);
|
||||
@@ -571,7 +393,6 @@ void spopCommand(redisClient *c) {
|
||||
incrRefCount(ele);
|
||||
setTypeRemove(set,ele);
|
||||
}
|
||||
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_SET,"spop",c->argv[1],c->db->id);
|
||||
|
||||
/* Replicate/AOF this command as an SREM operation */
|
||||
@@ -580,16 +401,11 @@ void spopCommand(redisClient *c) {
|
||||
decrRefCount(ele);
|
||||
decrRefCount(aux);
|
||||
|
||||
/* Add the element to the reply */
|
||||
addReplyBulk(c,ele);
|
||||
|
||||
/* Delete the set if it's empty */
|
||||
if (setTypeSize(set) == 0) {
|
||||
dbDelete(c->db,c->argv[1]);
|
||||
notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",c->argv[1],c->db->id);
|
||||
}
|
||||
|
||||
/* Set has been modified */
|
||||
signalModifiedKey(c->db,c->argv[1]);
|
||||
server.dirty++;
|
||||
}
|
||||
@@ -771,8 +587,7 @@ int qsortCompareSetsByRevCardinality(const void *s1, const void *s2) {
|
||||
return (o2 ? setTypeSize(o2) : 0) - (o1 ? setTypeSize(o1) : 0);
|
||||
}
|
||||
|
||||
void sinterGenericCommand(redisClient *c, robj **setkeys,
|
||||
unsigned long setnum, robj *dstkey) {
|
||||
void sinterGenericCommand(redisClient *c, robj **setkeys, unsigned long setnum, robj *dstkey) {
|
||||
robj **sets = zmalloc(sizeof(robj*)*setnum);
|
||||
setTypeIterator *si;
|
||||
robj *eleobj, *dstset = NULL;
|
||||
@@ -919,8 +734,7 @@ void sinterstoreCommand(redisClient *c) {
|
||||
#define REDIS_OP_DIFF 1
|
||||
#define REDIS_OP_INTER 2
|
||||
|
||||
void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum,
|
||||
robj *dstkey, int op) {
|
||||
void sunionDiffGenericCommand(redisClient *c, robj **setkeys, int setnum, robj *dstkey, int op) {
|
||||
robj **sets = zmalloc(sizeof(robj*)*setnum);
|
||||
setTypeIterator *si;
|
||||
robj *ele, *dstset = NULL;
|
||||
|
||||
+6
-18
@@ -61,8 +61,6 @@ static int checkStringLength(redisClient *c, long long size) {
|
||||
#define REDIS_SET_NO_FLAGS 0
|
||||
#define REDIS_SET_NX (1<<0) /* Set if key not exists. */
|
||||
#define REDIS_SET_XX (1<<1) /* Set if key exists. */
|
||||
#define REDIS_SET_EX (1<<2) /* Set if time in seconds is given */
|
||||
#define REDIS_SET_PX (1<<3) /* Set if time in ms in given */
|
||||
|
||||
void setGenericCommand(redisClient *c, int flags, robj *key, robj *val, robj *expire, int unit, robj *ok_reply, robj *abort_reply) {
|
||||
long long milliseconds = 0; /* initialized to avoid any harmness warning */
|
||||
@@ -104,28 +102,18 @@ void setCommand(redisClient *c) {
|
||||
robj *next = (j == c->argc-1) ? NULL : c->argv[j+1];
|
||||
|
||||
if ((a[0] == 'n' || a[0] == 'N') &&
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
|
||||
!(flags & REDIS_SET_XX))
|
||||
{
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0') {
|
||||
flags |= REDIS_SET_NX;
|
||||
} else if ((a[0] == 'x' || a[0] == 'X') &&
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
|
||||
!(flags & REDIS_SET_NX))
|
||||
{
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0') {
|
||||
flags |= REDIS_SET_XX;
|
||||
} else if ((a[0] == 'e' || a[0] == 'E') &&
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
|
||||
!(flags & REDIS_SET_PX) && next)
|
||||
{
|
||||
flags |= REDIS_SET_EX;
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' && next) {
|
||||
unit = UNIT_SECONDS;
|
||||
expire = next;
|
||||
j++;
|
||||
} else if ((a[0] == 'p' || a[0] == 'P') &&
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' &&
|
||||
!(flags & REDIS_SET_EX) && next)
|
||||
{
|
||||
flags |= REDIS_SET_PX;
|
||||
(a[1] == 'x' || a[1] == 'X') && a[2] == '\0' && next) {
|
||||
unit = UNIT_MILLISECONDS;
|
||||
expire = next;
|
||||
j++;
|
||||
@@ -206,7 +194,7 @@ void setrangeCommand(redisClient *c) {
|
||||
if (checkStringLength(c,offset+sdslen(value)) != REDIS_OK)
|
||||
return;
|
||||
|
||||
o = createObject(REDIS_STRING,sdsnewlen(NULL, offset+sdslen(value)));
|
||||
o = createObject(REDIS_STRING,sdsempty());
|
||||
dbAdd(c->db,c->argv[1],o);
|
||||
} else {
|
||||
size_t olen;
|
||||
@@ -409,7 +397,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
|
||||
|
||||
+1
-1
@@ -1382,7 +1382,7 @@ void zremrangeGenericCommand(redisClient *c, int rangetype) {
|
||||
robj *key = c->argv[1];
|
||||
robj *zobj;
|
||||
int keyremoved = 0;
|
||||
unsigned long deleted = 0;
|
||||
unsigned long deleted;
|
||||
zrangespec range;
|
||||
zlexrangespec lexrange;
|
||||
long start, end, llen;
|
||||
|
||||
+17
-108
@@ -38,10 +38,8 @@
|
||||
#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 +169,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 +182,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,26 +202,16 @@ 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;
|
||||
}
|
||||
|
||||
@@ -442,44 +428,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 +459,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
|
||||
@@ -574,10 +529,10 @@ int pathIsBaseName(char *path) {
|
||||
return strchr(path,'/') == NULL && strchr(path,'\\') == NULL;
|
||||
}
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
#ifdef UTIL_TEST_MAIN
|
||||
#include <assert.h>
|
||||
|
||||
static void test_string2ll(void) {
|
||||
void test_string2ll(void) {
|
||||
char buf[32];
|
||||
long long v;
|
||||
|
||||
@@ -632,7 +587,7 @@ static void test_string2ll(void) {
|
||||
assert(string2ll(buf,strlen(buf),&v) == 0);
|
||||
}
|
||||
|
||||
static void test_string2l(void) {
|
||||
void test_string2l(void) {
|
||||
char buf[32];
|
||||
long v;
|
||||
|
||||
@@ -681,55 +636,9 @@ static void test_string2l(void) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static void test_ll2string(void) {
|
||||
char buf[32];
|
||||
long long v;
|
||||
int sz;
|
||||
|
||||
v = 0;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 1);
|
||||
assert(!strcmp(buf, "0"));
|
||||
|
||||
v = -1;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 2);
|
||||
assert(!strcmp(buf, "-1"));
|
||||
|
||||
v = 99;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 2);
|
||||
assert(!strcmp(buf, "99"));
|
||||
|
||||
v = -99;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 3);
|
||||
assert(!strcmp(buf, "-99"));
|
||||
|
||||
v = -2147483648;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 11);
|
||||
assert(!strcmp(buf, "-2147483648"));
|
||||
|
||||
v = LLONG_MIN;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 20);
|
||||
assert(!strcmp(buf, "-9223372036854775808"));
|
||||
|
||||
v = LLONG_MAX;
|
||||
sz = ll2string(buf, sizeof buf, v);
|
||||
assert(sz == 19);
|
||||
assert(!strcmp(buf, "9223372036854775807"));
|
||||
}
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int utilTest(int argc, char **argv) {
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
test_string2ll();
|
||||
test_string2l();
|
||||
test_ll2string();
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -42,8 +42,4 @@ int d2string(char *buf, size_t len, double value);
|
||||
sds getAbsolutePath(char *filename);
|
||||
int pathIsBaseName(char *path);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int utilTest(int argc, char **argv);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
#define REDIS_VERSION "3.1.999"
|
||||
#define REDIS_VERSION "2.9.999"
|
||||
|
||||
+42
-268
@@ -143,7 +143,6 @@
|
||||
#define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
|
||||
#define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
|
||||
#define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
|
||||
#define ZIPLIST_END_SIZE (sizeof(uint8_t))
|
||||
#define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
|
||||
#define ZIPLIST_ENTRY_TAIL(zl) ((zl)+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)))
|
||||
#define ZIPLIST_ENTRY_END(zl) ((zl)+intrev32ifbe(ZIPLIST_BYTES(zl))-1)
|
||||
@@ -163,13 +162,6 @@ typedef struct zlentry {
|
||||
unsigned char *p;
|
||||
} zlentry;
|
||||
|
||||
#define ZIPLIST_ENTRY_ZERO(zle) { \
|
||||
(zle)->prevrawlensize = (zle)->prevrawlen = 0; \
|
||||
(zle)->lensize = (zle)->len = (zle)->headersize = 0; \
|
||||
(zle)->encoding = 0; \
|
||||
(zle)->p = NULL; \
|
||||
}
|
||||
|
||||
/* Extract the encoding from the byte pointed by 'ptr' and set it into
|
||||
* 'encoding'. */
|
||||
#define ZIP_ENTRY_ENCODING(ptr, encoding) do { \
|
||||
@@ -177,8 +169,6 @@ typedef struct zlentry {
|
||||
if ((encoding) < ZIP_STR_MASK) (encoding) &= ZIP_STR_MASK; \
|
||||
} while(0)
|
||||
|
||||
void ziplistRepr(unsigned char *zl);
|
||||
|
||||
/* Return bytes needed to store integer encoded by 'encoding' */
|
||||
static unsigned int zipIntSize(unsigned char encoding) {
|
||||
switch(encoding) {
|
||||
@@ -414,12 +404,14 @@ static int64_t zipLoadInteger(unsigned char *p, unsigned char encoding) {
|
||||
}
|
||||
|
||||
/* Return a struct with all information about an entry. */
|
||||
static void zipEntry(unsigned char *p, zlentry *e) {
|
||||
static zlentry zipEntry(unsigned char *p) {
|
||||
zlentry e;
|
||||
|
||||
ZIP_DECODE_PREVLEN(p, e->prevrawlensize, e->prevrawlen);
|
||||
ZIP_DECODE_LENGTH(p + e->prevrawlensize, e->encoding, e->lensize, e->len);
|
||||
e->headersize = e->prevrawlensize + e->lensize;
|
||||
e->p = p;
|
||||
ZIP_DECODE_PREVLEN(p, e.prevrawlensize, e.prevrawlen);
|
||||
ZIP_DECODE_LENGTH(p + e.prevrawlensize, e.encoding, e.lensize, e.len);
|
||||
e.headersize = e.prevrawlensize + e.lensize;
|
||||
e.p = p;
|
||||
return e;
|
||||
}
|
||||
|
||||
/* Create a new empty ziplist. */
|
||||
@@ -468,13 +460,13 @@ static unsigned char *__ziplistCascadeUpdate(unsigned char *zl, unsigned char *p
|
||||
zlentry cur, next;
|
||||
|
||||
while (p[0] != ZIP_END) {
|
||||
zipEntry(p, &cur);
|
||||
cur = zipEntry(p);
|
||||
rawlen = cur.headersize + cur.len;
|
||||
rawlensize = zipPrevEncodeLength(NULL,rawlen);
|
||||
|
||||
/* Abort if there is no next entry. */
|
||||
if (p[rawlen] == ZIP_END) break;
|
||||
zipEntry(p+rawlen, &next);
|
||||
next = zipEntry(p+rawlen);
|
||||
|
||||
/* Abort when "prevlen" has not changed. */
|
||||
if (next.prevrawlen == rawlen) break;
|
||||
@@ -529,7 +521,7 @@ static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsig
|
||||
int nextdiff = 0;
|
||||
zlentry first, tail;
|
||||
|
||||
zipEntry(p, &first);
|
||||
first = zipEntry(p);
|
||||
for (i = 0; p[0] != ZIP_END && i < num; i++) {
|
||||
p += zipRawEntryLength(p);
|
||||
deleted++;
|
||||
@@ -553,7 +545,7 @@ static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsig
|
||||
/* When the tail contains more than one entry, we need to take
|
||||
* "nextdiff" in account as well. Otherwise, a change in the
|
||||
* size of prevlen doesn't have an effect on the *tail* offset. */
|
||||
zipEntry(p, &tail);
|
||||
tail = zipEntry(p);
|
||||
if (p[tail.headersize+tail.len] != ZIP_END) {
|
||||
ZIPLIST_TAIL_OFFSET(zl) =
|
||||
intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
|
||||
@@ -643,7 +635,7 @@ static unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsig
|
||||
/* When the tail contains more than one entry, we need to take
|
||||
* "nextdiff" in account as well. Otherwise, a change in the
|
||||
* size of prevlen doesn't have an effect on the *tail* offset. */
|
||||
zipEntry(p+reqlen, &tail);
|
||||
tail = zipEntry(p+reqlen);
|
||||
if (p[reqlen+tail.headersize+tail.len] != ZIP_END) {
|
||||
ZIPLIST_TAIL_OFFSET(zl) =
|
||||
intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
|
||||
@@ -673,121 +665,6 @@ static unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsig
|
||||
return zl;
|
||||
}
|
||||
|
||||
/* Merge ziplists 'first' and 'second' by appending 'second' to 'first'.
|
||||
*
|
||||
* NOTE: The larger ziplist is reallocated to contain the new merged ziplist.
|
||||
* Either 'first' or 'second' can be used for the result. The parameter not
|
||||
* used will be free'd and set to NULL.
|
||||
*
|
||||
* After calling this function, the input parameters are no longer valid since
|
||||
* they are changed and free'd in-place.
|
||||
*
|
||||
* The result ziplist is the contents of 'first' followed by 'second'.
|
||||
*
|
||||
* On failure: returns NULL if the merge is impossible.
|
||||
* On success: returns the merged ziplist (which is expanded version of either
|
||||
* 'first' or 'second', also frees the other unused input ziplist, and sets the
|
||||
* input ziplist argument equal to newly reallocated ziplist return value. */
|
||||
unsigned char *ziplistMerge(unsigned char **first, unsigned char **second) {
|
||||
/* If any params are null, we can't merge, so NULL. */
|
||||
if (first == NULL || *first == NULL || second == NULL || *second == NULL)
|
||||
return NULL;
|
||||
|
||||
/* Can't merge same list into itself. */
|
||||
if (*first == *second)
|
||||
return NULL;
|
||||
|
||||
size_t first_bytes = intrev32ifbe(ZIPLIST_BYTES(*first));
|
||||
size_t first_len = intrev16ifbe(ZIPLIST_LENGTH(*first));
|
||||
|
||||
size_t second_bytes = intrev32ifbe(ZIPLIST_BYTES(*second));
|
||||
size_t second_len = intrev16ifbe(ZIPLIST_LENGTH(*second));
|
||||
|
||||
int append;
|
||||
unsigned char *source, *target;
|
||||
size_t target_bytes, source_bytes;
|
||||
/* Pick the largest ziplist so we can resize easily in-place.
|
||||
* We must also track if we are now appending or prepending to
|
||||
* the target ziplist. */
|
||||
if (first_len >= second_len) {
|
||||
/* retain first, append second to first. */
|
||||
target = *first;
|
||||
target_bytes = first_bytes;
|
||||
source = *second;
|
||||
source_bytes = second_bytes;
|
||||
append = 1;
|
||||
} else {
|
||||
/* else, retain second, prepend first to second. */
|
||||
target = *second;
|
||||
target_bytes = second_bytes;
|
||||
source = *first;
|
||||
source_bytes = first_bytes;
|
||||
append = 0;
|
||||
}
|
||||
|
||||
/* Calculate final bytes (subtract one pair of metadata) */
|
||||
size_t zlbytes = first_bytes + second_bytes -
|
||||
ZIPLIST_HEADER_SIZE - ZIPLIST_END_SIZE;
|
||||
size_t zllength = first_len + second_len;
|
||||
|
||||
/* Combined zl length should be limited within UINT16_MAX */
|
||||
zllength = zllength < UINT16_MAX ? zllength : UINT16_MAX;
|
||||
|
||||
/* Save offset positions before we start ripping memory apart. */
|
||||
size_t first_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*first));
|
||||
size_t second_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*second));
|
||||
|
||||
/* Extend target to new zlbytes then append or prepend source. */
|
||||
target = zrealloc(target, zlbytes);
|
||||
if (append) {
|
||||
/* append == appending to target */
|
||||
/* Copy source after target (copying over original [END]):
|
||||
* [TARGET - END, SOURCE - HEADER] */
|
||||
memcpy(target + target_bytes - ZIPLIST_END_SIZE,
|
||||
source + ZIPLIST_HEADER_SIZE,
|
||||
source_bytes - ZIPLIST_HEADER_SIZE);
|
||||
} else {
|
||||
/* !append == prepending to target */
|
||||
/* Move target *contents* exactly size of (source - [END]),
|
||||
* then copy source into vacataed space (source - [END]):
|
||||
* [SOURCE - END, TARGET - HEADER] */
|
||||
memmove(target + source_bytes - ZIPLIST_END_SIZE,
|
||||
target + ZIPLIST_HEADER_SIZE,
|
||||
target_bytes - ZIPLIST_HEADER_SIZE);
|
||||
memcpy(target, source, source_bytes - ZIPLIST_END_SIZE);
|
||||
}
|
||||
|
||||
/* Update header metadata. */
|
||||
ZIPLIST_BYTES(target) = intrev32ifbe(zlbytes);
|
||||
ZIPLIST_LENGTH(target) = intrev16ifbe(zllength);
|
||||
/* New tail offset is:
|
||||
* + N bytes of first ziplist
|
||||
* - 1 byte for [END] of first ziplist
|
||||
* + M bytes for the offset of the original tail of the second ziplist
|
||||
* - J bytes for HEADER because second_offset keeps no header. */
|
||||
ZIPLIST_TAIL_OFFSET(target) = intrev32ifbe(
|
||||
(first_bytes - ZIPLIST_END_SIZE) +
|
||||
(second_offset - ZIPLIST_HEADER_SIZE));
|
||||
|
||||
/* __ziplistCascadeUpdate just fixes the prev length values until it finds a
|
||||
* correct prev length value (then it assumes the rest of the list is okay).
|
||||
* We tell CascadeUpdate to start at the first ziplist's tail element to fix
|
||||
* the merge seam. */
|
||||
target = __ziplistCascadeUpdate(target, target+first_offset);
|
||||
|
||||
/* Now free and NULL out what we didn't realloc */
|
||||
if (append) {
|
||||
zfree(*second);
|
||||
*second = NULL;
|
||||
*first = target;
|
||||
} else {
|
||||
zfree(*first);
|
||||
*first = NULL;
|
||||
*second = target;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
|
||||
unsigned char *p;
|
||||
p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
|
||||
@@ -871,7 +748,7 @@ unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *sl
|
||||
if (p == NULL || p[0] == ZIP_END) return 0;
|
||||
if (sstr) *sstr = NULL;
|
||||
|
||||
zipEntry(p, &entry);
|
||||
entry = zipEntry(p);
|
||||
if (ZIP_IS_STR(entry.encoding)) {
|
||||
if (sstr) {
|
||||
*slen = entry.len;
|
||||
@@ -906,7 +783,7 @@ unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
|
||||
}
|
||||
|
||||
/* Delete a range of entries from the ziplist. */
|
||||
unsigned char *ziplistDeleteRange(unsigned char *zl, int index, unsigned int num) {
|
||||
unsigned char *ziplistDeleteRange(unsigned char *zl, unsigned int index, unsigned int num) {
|
||||
unsigned char *p = ziplistIndex(zl,index);
|
||||
return (p == NULL) ? zl : __ziplistDelete(zl,p,num);
|
||||
}
|
||||
@@ -919,7 +796,7 @@ unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int
|
||||
long long zval, sval;
|
||||
if (p[0] == ZIP_END) return 0;
|
||||
|
||||
zipEntry(p, &entry);
|
||||
entry = zipEntry(p);
|
||||
if (ZIP_IS_STR(entry.encoding)) {
|
||||
/* Raw compare */
|
||||
if (entry.len == slen) {
|
||||
@@ -1036,7 +913,7 @@ void ziplistRepr(unsigned char *zl) {
|
||||
intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)));
|
||||
p = ZIPLIST_ENTRY_HEAD(zl);
|
||||
while(*p != ZIP_END) {
|
||||
zipEntry(p, &entry);
|
||||
entry = zipEntry(p);
|
||||
printf(
|
||||
"{"
|
||||
"addr 0x%08lx, "
|
||||
@@ -1075,14 +952,14 @@ void ziplistRepr(unsigned char *zl) {
|
||||
printf("{end}\n\n");
|
||||
}
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
#ifdef ZIPLIST_TEST_MAIN
|
||||
#include <sys/time.h>
|
||||
#include "adlist.h"
|
||||
#include "sds.h"
|
||||
|
||||
#define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
|
||||
|
||||
static unsigned char *createList() {
|
||||
unsigned char *createList() {
|
||||
unsigned char *zl = ziplistNew();
|
||||
zl = ziplistPush(zl, (unsigned char*)"foo", 3, ZIPLIST_TAIL);
|
||||
zl = ziplistPush(zl, (unsigned char*)"quux", 4, ZIPLIST_TAIL);
|
||||
@@ -1091,7 +968,7 @@ static unsigned char *createList() {
|
||||
return zl;
|
||||
}
|
||||
|
||||
static unsigned char *createIntList() {
|
||||
unsigned char *createIntList() {
|
||||
unsigned char *zl = ziplistNew();
|
||||
char buf[32];
|
||||
|
||||
@@ -1110,13 +987,13 @@ static unsigned char *createIntList() {
|
||||
return zl;
|
||||
}
|
||||
|
||||
static long long usec(void) {
|
||||
long long usec(void) {
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv,NULL);
|
||||
return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
|
||||
}
|
||||
|
||||
static void stress(int pos, int num, int maxsize, int dnum) {
|
||||
void stress(int pos, int num, int maxsize, int dnum) {
|
||||
int i,j,k;
|
||||
unsigned char *zl;
|
||||
char posstr[2][5] = { "HEAD", "TAIL" };
|
||||
@@ -1139,7 +1016,7 @@ static void stress(int pos, int num, int maxsize, int dnum) {
|
||||
}
|
||||
}
|
||||
|
||||
static unsigned char *pop(unsigned char *zl, int where) {
|
||||
void pop(unsigned char *zl, int where) {
|
||||
unsigned char *p, *vstr;
|
||||
unsigned int vlen;
|
||||
long long vlong;
|
||||
@@ -1151,22 +1028,20 @@ static unsigned char *pop(unsigned char *zl, int where) {
|
||||
else
|
||||
printf("Pop tail: ");
|
||||
|
||||
if (vstr) {
|
||||
if (vstr)
|
||||
if (vlen && fwrite(vstr,vlen,1,stdout) == 0) perror("fwrite");
|
||||
}
|
||||
else {
|
||||
else
|
||||
printf("%lld", vlong);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
return ziplistDelete(zl,&p);
|
||||
ziplistDeleteRange(zl,-1,1);
|
||||
} else {
|
||||
printf("ERROR: Could not pop\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
static int randstring(char *target, unsigned int min, unsigned int max) {
|
||||
int randstring(char *target, unsigned int min, unsigned int max) {
|
||||
int p = 0;
|
||||
int len = min+rand()%(max-min+1);
|
||||
int minval, maxval;
|
||||
@@ -1192,24 +1067,23 @@ static int randstring(char *target, unsigned int min, unsigned int max) {
|
||||
return len;
|
||||
}
|
||||
|
||||
static void verify(unsigned char *zl, zlentry *e) {
|
||||
void verify(unsigned char *zl, zlentry *e) {
|
||||
int i;
|
||||
int len = ziplistLen(zl);
|
||||
zlentry _e;
|
||||
|
||||
ZIPLIST_ENTRY_ZERO(&_e);
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
for (i = 0; i < len; i++) {
|
||||
memset(&e[i], 0, sizeof(zlentry));
|
||||
zipEntry(ziplistIndex(zl, i), &e[i]);
|
||||
e[i] = zipEntry(ziplistIndex(zl, i));
|
||||
|
||||
memset(&_e, 0, sizeof(zlentry));
|
||||
zipEntry(ziplistIndex(zl, -len+i), &_e);
|
||||
_e = zipEntry(ziplistIndex(zl, -len+i));
|
||||
|
||||
assert(memcmp(&e[i], &_e, sizeof(zlentry)) == 0);
|
||||
}
|
||||
}
|
||||
|
||||
int ziplistTest(int argc, char **argv) {
|
||||
int main(int argc, char **argv) {
|
||||
unsigned char *zl, *p;
|
||||
unsigned char *entry;
|
||||
unsigned int elen;
|
||||
@@ -1222,25 +1096,21 @@ int ziplistTest(int argc, char **argv) {
|
||||
zl = createIntList();
|
||||
ziplistRepr(zl);
|
||||
|
||||
zfree(zl);
|
||||
|
||||
zl = createList();
|
||||
ziplistRepr(zl);
|
||||
|
||||
zl = pop(zl,ZIPLIST_TAIL);
|
||||
pop(zl,ZIPLIST_TAIL);
|
||||
ziplistRepr(zl);
|
||||
|
||||
zl = pop(zl,ZIPLIST_HEAD);
|
||||
pop(zl,ZIPLIST_HEAD);
|
||||
ziplistRepr(zl);
|
||||
|
||||
zl = pop(zl,ZIPLIST_TAIL);
|
||||
pop(zl,ZIPLIST_TAIL);
|
||||
ziplistRepr(zl);
|
||||
|
||||
zl = pop(zl,ZIPLIST_TAIL);
|
||||
pop(zl,ZIPLIST_TAIL);
|
||||
ziplistRepr(zl);
|
||||
|
||||
zfree(zl);
|
||||
|
||||
printf("Get element at index 3:\n");
|
||||
{
|
||||
zl = createList();
|
||||
@@ -1256,7 +1126,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("%lld\n", value);
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Get element at index 4 (out of range):\n");
|
||||
@@ -1270,7 +1139,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
return 1;
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Get element at index -1 (last element):\n");
|
||||
@@ -1288,7 +1156,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("%lld\n", value);
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Get element at index -4 (first element):\n");
|
||||
@@ -1306,7 +1173,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("%lld\n", value);
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Get element at index -5 (reverse out of range):\n");
|
||||
@@ -1320,7 +1186,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
return 1;
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Iterate list from 0 to end:\n");
|
||||
@@ -1338,7 +1203,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Iterate list from 1 to end:\n");
|
||||
@@ -1356,7 +1220,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Iterate list from 2 to end:\n");
|
||||
@@ -1374,7 +1237,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Iterate starting out of range:\n");
|
||||
@@ -1387,7 +1249,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("ERROR\n");
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Iterate from back to front:\n");
|
||||
@@ -1405,7 +1266,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Iterate from back to front, deleting all items:\n");
|
||||
@@ -1424,7 +1284,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
printf("\n");
|
||||
}
|
||||
printf("\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Delete inclusive range 0,0:\n");
|
||||
@@ -1432,7 +1291,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
zl = createList();
|
||||
zl = ziplistDeleteRange(zl, 0, 1);
|
||||
ziplistRepr(zl);
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Delete inclusive range 0,1:\n");
|
||||
@@ -1440,7 +1298,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
zl = createList();
|
||||
zl = ziplistDeleteRange(zl, 0, 2);
|
||||
ziplistRepr(zl);
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Delete inclusive range 1,2:\n");
|
||||
@@ -1448,7 +1305,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
zl = createList();
|
||||
zl = ziplistDeleteRange(zl, 1, 2);
|
||||
ziplistRepr(zl);
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Delete with start index out of range:\n");
|
||||
@@ -1456,7 +1312,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
zl = createList();
|
||||
zl = ziplistDeleteRange(zl, 5, 1);
|
||||
ziplistRepr(zl);
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Delete with num overflow:\n");
|
||||
@@ -1464,7 +1319,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
zl = createList();
|
||||
zl = ziplistDeleteRange(zl, 1, 5);
|
||||
ziplistRepr(zl);
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Delete foo while iterating:\n");
|
||||
@@ -1489,12 +1343,11 @@ int ziplistTest(int argc, char **argv) {
|
||||
}
|
||||
printf("\n");
|
||||
ziplistRepr(zl);
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Regression test for >255 byte strings:\n");
|
||||
{
|
||||
char v1[257] = {0}, v2[257] = {0};
|
||||
char v1[257],v2[257];
|
||||
memset(v1,'x',256);
|
||||
memset(v2,'y',256);
|
||||
zl = ziplistNew();
|
||||
@@ -1509,15 +1362,13 @@ int ziplistTest(int argc, char **argv) {
|
||||
assert(ziplistGet(p,&entry,&elen,&value));
|
||||
assert(strncmp(v2,(char*)entry,elen) == 0);
|
||||
printf("SUCCESS\n\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Regression test deleting next to last entries:\n");
|
||||
{
|
||||
char v[3][257] = {{0}};
|
||||
zlentry e[3] = {{.prevrawlensize = 0, .prevrawlen = 0, .lensize = 0,
|
||||
.len = 0, .headersize = 0, .encoding = 0, .p = NULL}};
|
||||
size_t i;
|
||||
char v[3][257];
|
||||
zlentry e[3];
|
||||
int i;
|
||||
|
||||
for (i = 0; i < (sizeof(v)/sizeof(v[0])); i++) {
|
||||
memset(v[i], 'a' + i, sizeof(v[0]));
|
||||
@@ -1548,7 +1399,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
assert(e[1].prevrawlensize == 5);
|
||||
|
||||
printf("SUCCESS\n\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Create long list and check indices:\n");
|
||||
@@ -1570,7 +1420,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
assert(999-i == value);
|
||||
}
|
||||
printf("SUCCESS\n\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Compare strings with ziplist entries:\n");
|
||||
@@ -1596,82 +1445,6 @@ int ziplistTest(int argc, char **argv) {
|
||||
return 1;
|
||||
}
|
||||
printf("SUCCESS\n\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Merge test:\n");
|
||||
{
|
||||
/* create list gives us: [hello, foo, quux, 1024] */
|
||||
zl = createList();
|
||||
unsigned char *zl2 = createList();
|
||||
|
||||
unsigned char *zl3 = ziplistNew();
|
||||
unsigned char *zl4 = ziplistNew();
|
||||
|
||||
if (ziplistMerge(&zl4, &zl4)) {
|
||||
printf("ERROR: Allowed merging of one ziplist into itself.\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Merge two empty ziplists, get empty result back. */
|
||||
zl4 = ziplistMerge(&zl3, &zl4);
|
||||
ziplistRepr(zl4);
|
||||
if (ziplistLen(zl4)) {
|
||||
printf("ERROR: Merging two empty ziplists created entries.\n");
|
||||
return 1;
|
||||
}
|
||||
zfree(zl4);
|
||||
|
||||
zl2 = ziplistMerge(&zl, &zl2);
|
||||
/* merge gives us: [hello, foo, quux, 1024, hello, foo, quux, 1024] */
|
||||
ziplistRepr(zl2);
|
||||
|
||||
if (ziplistLen(zl2) != 8) {
|
||||
printf("ERROR: Merged length not 8, but: %u\n", ziplistLen(zl2));
|
||||
return 1;
|
||||
}
|
||||
|
||||
p = ziplistIndex(zl2,0);
|
||||
if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
|
||||
printf("ERROR: not \"hello\"\n");
|
||||
return 1;
|
||||
}
|
||||
if (ziplistCompare(p,(unsigned char*)"hella",5)) {
|
||||
printf("ERROR: \"hella\"\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
p = ziplistIndex(zl2,3);
|
||||
if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
|
||||
printf("ERROR: not \"1024\"\n");
|
||||
return 1;
|
||||
}
|
||||
if (ziplistCompare(p,(unsigned char*)"1025",4)) {
|
||||
printf("ERROR: \"1025\"\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
p = ziplistIndex(zl2,4);
|
||||
if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
|
||||
printf("ERROR: not \"hello\"\n");
|
||||
return 1;
|
||||
}
|
||||
if (ziplistCompare(p,(unsigned char*)"hella",5)) {
|
||||
printf("ERROR: \"hella\"\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
p = ziplistIndex(zl2,7);
|
||||
if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
|
||||
printf("ERROR: not \"1024\"\n");
|
||||
return 1;
|
||||
}
|
||||
if (ziplistCompare(p,(unsigned char*)"1025",4)) {
|
||||
printf("ERROR: \"1025\"\n");
|
||||
return 1;
|
||||
}
|
||||
printf("SUCCESS\n\n");
|
||||
zfree(zl);
|
||||
}
|
||||
|
||||
printf("Stress with random payloads of different encoding:\n");
|
||||
@@ -1691,7 +1464,7 @@ int ziplistTest(int argc, char **argv) {
|
||||
for (i = 0; i < 20000; i++) {
|
||||
zl = ziplistNew();
|
||||
ref = listCreate();
|
||||
listSetFreeMethod(ref,(void (*)(void*))sdsfree);
|
||||
listSetFreeMethod(ref,sdsfree);
|
||||
len = rand() % 256;
|
||||
|
||||
/* Create lists */
|
||||
@@ -1759,4 +1532,5 @@ int ziplistTest(int argc, char **argv) {
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
+1
-6
@@ -32,7 +32,6 @@
|
||||
#define ZIPLIST_TAIL 1
|
||||
|
||||
unsigned char *ziplistNew(void);
|
||||
unsigned char *ziplistMerge(unsigned char **first, unsigned char **second);
|
||||
unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where);
|
||||
unsigned char *ziplistIndex(unsigned char *zl, int index);
|
||||
unsigned char *ziplistNext(unsigned char *zl, unsigned char *p);
|
||||
@@ -40,12 +39,8 @@ unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p);
|
||||
unsigned int ziplistGet(unsigned char *p, unsigned char **sval, unsigned int *slen, long long *lval);
|
||||
unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen);
|
||||
unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p);
|
||||
unsigned char *ziplistDeleteRange(unsigned char *zl, int index, unsigned int num);
|
||||
unsigned char *ziplistDeleteRange(unsigned char *zl, unsigned int index, unsigned int num);
|
||||
unsigned int ziplistCompare(unsigned char *p, unsigned char *s, unsigned int slen);
|
||||
unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip);
|
||||
unsigned int ziplistLen(unsigned char *zl);
|
||||
size_t ziplistBlobLen(unsigned char *zl);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int ziplistTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
+6
-9
@@ -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"
|
||||
@@ -370,8 +371,8 @@ size_t zipmapBlobLen(unsigned char *zm) {
|
||||
return totlen;
|
||||
}
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
static void zipmapRepr(unsigned char *p) {
|
||||
#ifdef ZIPMAP_TEST_MAIN
|
||||
void zipmapRepr(unsigned char *p) {
|
||||
unsigned int l;
|
||||
|
||||
printf("{status %u}",*p++);
|
||||
@@ -404,13 +405,9 @@ static void zipmapRepr(unsigned char *p) {
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
#define UNUSED(x) (void)(x)
|
||||
int zipmapTest(int argc, char *argv[]) {
|
||||
int main(void) {
|
||||
unsigned char *zm;
|
||||
|
||||
UNUSED(argc);
|
||||
UNUSED(argv);
|
||||
|
||||
zm = zipmapNew();
|
||||
|
||||
zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
|
||||
|
||||
@@ -46,8 +46,4 @@ unsigned int zipmapLen(unsigned char *zm);
|
||||
size_t zipmapBlobLen(unsigned char *zm);
|
||||
void zipmapRepr(unsigned char *p);
|
||||
|
||||
#ifdef REDIS_TEST
|
||||
int zipmapTest(int argc, char *argv[]);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+1
-58
@@ -356,7 +356,7 @@ size_t zmalloc_get_smap_bytes_by_field(char *field) {
|
||||
}
|
||||
#else
|
||||
size_t zmalloc_get_smap_bytes_by_field(char *field) {
|
||||
((void) field);
|
||||
REDIS_NOTUSED(field);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
@@ -364,60 +364,3 @@ size_t zmalloc_get_smap_bytes_by_field(char *field) {
|
||||
size_t zmalloc_get_private_dirty(void) {
|
||||
return zmalloc_get_smap_bytes_by_field("Private_Dirty:");
|
||||
}
|
||||
|
||||
/* Returns the size of physical memory (RAM) in bytes.
|
||||
* It looks ugly, but this is the cleanest way to achive cross platform results.
|
||||
* Cleaned up from:
|
||||
*
|
||||
* http://nadeausoftware.com/articles/2012/09/c_c_tip_how_get_physical_memory_size_system
|
||||
*
|
||||
* Note that this function:
|
||||
* 1) Was released under the following CC attribution license:
|
||||
* http://creativecommons.org/licenses/by/3.0/deed.en_US.
|
||||
* 2) Was originally implemented by David Robert Nadeau.
|
||||
* 3) Was modified for Redis by Matt Stancliff.
|
||||
* 4) This note exists in order to comply with the original license.
|
||||
*/
|
||||
size_t zmalloc_get_memory_size(void) {
|
||||
#if defined(__unix__) || defined(__unix) || defined(unix) || \
|
||||
(defined(__APPLE__) && defined(__MACH__))
|
||||
#if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64))
|
||||
int mib[2];
|
||||
mib[0] = CTL_HW;
|
||||
#if defined(HW_MEMSIZE)
|
||||
mib[1] = HW_MEMSIZE; /* OSX. --------------------- */
|
||||
#elif defined(HW_PHYSMEM64)
|
||||
mib[1] = HW_PHYSMEM64; /* NetBSD, OpenBSD. --------- */
|
||||
#endif
|
||||
int64_t size = 0; /* 64-bit */
|
||||
size_t len = sizeof(size);
|
||||
if (sysctl( mib, 2, &size, &len, NULL, 0) == 0)
|
||||
return (size_t)size;
|
||||
return 0L; /* Failed? */
|
||||
|
||||
#elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
|
||||
/* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */
|
||||
return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE);
|
||||
|
||||
#elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM))
|
||||
/* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */
|
||||
int mib[2];
|
||||
mib[0] = CTL_HW;
|
||||
#if defined(HW_REALMEM)
|
||||
mib[1] = HW_REALMEM; /* FreeBSD. ----------------- */
|
||||
#elif defined(HW_PYSMEM)
|
||||
mib[1] = HW_PHYSMEM; /* Others. ------------------ */
|
||||
#endif
|
||||
unsigned int size = 0; /* 32-bit */
|
||||
size_t len = sizeof(size);
|
||||
if (sysctl(mib, 2, &size, &len, NULL, 0) == 0)
|
||||
return (size_t)size;
|
||||
return 0L; /* Failed? */
|
||||
#endif /* sysctl and sysconf variants */
|
||||
|
||||
#else
|
||||
return 0L; /* Unknown OS. */
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -77,7 +77,6 @@ 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);
|
||||
size_t zmalloc_get_memory_size(void);
|
||||
void zlibc_free(void *ptr);
|
||||
|
||||
#ifndef HAVE_MALLOC_SIZE
|
||||
|
||||
@@ -21,7 +21,6 @@ proc main {} {
|
||||
|
||||
if {[catch main e]} {
|
||||
puts $::errorInfo
|
||||
if {$::pause_on_error} pause_on_error
|
||||
cleanup
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -66,18 +66,9 @@ test "Cluster consistency during live resharding" {
|
||||
}
|
||||
|
||||
# Write random data to random list.
|
||||
set listid [randomInt $numkeys]
|
||||
set key "key:$listid"
|
||||
set key "key:[randomInt $numkeys]"
|
||||
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
|
||||
}
|
||||
$cluster rpush $key $ele
|
||||
lappend content($key) $ele
|
||||
|
||||
if {($j % 1000) == 0} {
|
||||
|
||||
@@ -27,17 +27,10 @@ test "Cluster nodes are reachable" {
|
||||
|
||||
test "Cluster nodes hard reset" {
|
||||
foreach_redis_id id {
|
||||
if {$::valgrind} {
|
||||
set node_timeout 10000
|
||||
} else {
|
||||
set node_timeout 3000
|
||||
}
|
||||
catch {R $id flushall} ; # May fail for readonly slaves.
|
||||
R $id MULTI
|
||||
R $id cluster reset hard
|
||||
R $id cluster set-config-epoch [expr {$id+1}]
|
||||
R $id EXEC
|
||||
R $id config set cluster-node-timeout $node_timeout
|
||||
R $id config set cluster-node-timeout 3000
|
||||
R $id config set cluster-slave-validity-factor 10
|
||||
R $id config rewrite
|
||||
}
|
||||
|
||||
+14
-41
@@ -16,7 +16,6 @@ source ../support/server.tcl
|
||||
source ../support/test.tcl
|
||||
|
||||
set ::verbose 0
|
||||
set ::valgrind 0
|
||||
set ::pause_on_error 0
|
||||
set ::simulate_error 0
|
||||
set ::sentinel_instances {}
|
||||
@@ -33,25 +32,6 @@ if {[catch {cd tmp}]} {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Execute the specified instance of the server specified by 'type', using
|
||||
# the provided configuration file. Returns the PID of the process.
|
||||
proc exec_instance {type cfgfile} {
|
||||
if {$type eq "redis"} {
|
||||
set prgname redis-server
|
||||
} elseif {$type eq "sentinel"} {
|
||||
set prgname redis-sentinel
|
||||
} else {
|
||||
error "Unknown instance type."
|
||||
}
|
||||
|
||||
if {$::valgrind} {
|
||||
set pid [exec valgrind --track-origins=yes --suppressions=../../../src/valgrind.sup --show-reachable=no --show-possibly-lost=no --leak-check=full ../../../src/${prgname} $cfgfile &]
|
||||
} else {
|
||||
set pid [exec ../../../src/${prgname} $cfgfile &]
|
||||
}
|
||||
return $pid
|
||||
}
|
||||
|
||||
# Spawn a redis or sentinel instance, depending on 'type'.
|
||||
proc spawn_instance {type base_port count {conf {}}} {
|
||||
for {set j 0} {$j < $count} {incr j} {
|
||||
@@ -78,7 +58,14 @@ proc spawn_instance {type base_port count {conf {}}} {
|
||||
close $cfg
|
||||
|
||||
# Finally exec it and remember the pid for later cleanup.
|
||||
set pid [exec_instance $type $cfgfile]
|
||||
if {$type eq "redis"} {
|
||||
set prgname redis-server
|
||||
} elseif {$type eq "sentinel"} {
|
||||
set prgname redis-sentinel
|
||||
} else {
|
||||
error "Unknown instance type."
|
||||
}
|
||||
set pid [exec ../../../src/${prgname} $cfgfile &]
|
||||
lappend ::pids $pid
|
||||
|
||||
# Check availability
|
||||
@@ -111,7 +98,6 @@ proc cleanup {} {
|
||||
proc abort_sentinel_test msg {
|
||||
puts "WARNING: Aborting the test."
|
||||
puts ">>>>>>>> $msg"
|
||||
if {$::pause_on_error} pause_on_error
|
||||
cleanup
|
||||
exit 1
|
||||
}
|
||||
@@ -127,8 +113,6 @@ proc parse_options {} {
|
||||
set ::pause_on_error 1
|
||||
} elseif {$opt eq "--fail"} {
|
||||
set ::simulate_error 1
|
||||
} elseif {$opt eq {--valgrind}} {
|
||||
set ::valgrind 1
|
||||
} elseif {$opt eq "--help"} {
|
||||
puts "Hello, I'm sentinel.tcl and I run Sentinel unit tests."
|
||||
puts "\nOptions:"
|
||||
@@ -376,31 +360,15 @@ proc get_instance_id_by_port {type port} {
|
||||
# The instance can be restarted with restart-instance.
|
||||
proc kill_instance {type id} {
|
||||
set pid [get_instance_attrib $type $id pid]
|
||||
set port [get_instance_attrib $type $id port]
|
||||
|
||||
if {$pid == -1} {
|
||||
error "You tried to kill $type $id twice."
|
||||
}
|
||||
|
||||
exec kill -9 $pid
|
||||
set_instance_attrib $type $id pid -1
|
||||
set_instance_attrib $type $id link you_tried_to_talk_with_killed_instance
|
||||
|
||||
# Remove the PID from the list of pids to kill at exit.
|
||||
set ::pids [lsearch -all -inline -not -exact $::pids $pid]
|
||||
|
||||
# Wait for the port it was using to be available again, so that's not
|
||||
# an issue to start a new server ASAP with the same port.
|
||||
set retry 10
|
||||
while {[incr retry -1]} {
|
||||
set port_is_free [catch {set s [socket 127.0.01 $port]}]
|
||||
if {$port_is_free} break
|
||||
catch {close $s}
|
||||
after 1000
|
||||
}
|
||||
if {$retry == 0} {
|
||||
error "Port $port does not return available after killing instance."
|
||||
}
|
||||
}
|
||||
|
||||
# Return true of the instance of the specified type/id is killed.
|
||||
@@ -417,7 +385,12 @@ proc restart_instance {type id} {
|
||||
|
||||
# Execute the instance with its old setup and append the new pid
|
||||
# file for cleanup.
|
||||
set pid [exec_instance $type $cfgfile]
|
||||
if {$type eq "redis"} {
|
||||
set prgname redis-server
|
||||
} else {
|
||||
set prgname redis-sentinel
|
||||
}
|
||||
set pid [exec ../../../src/${prgname} $cfgfile &]
|
||||
set_instance_attrib $type $id pid $pid
|
||||
lappend ::pids $pid
|
||||
|
||||
|
||||
@@ -204,30 +204,6 @@ tags {"aof"} {
|
||||
}
|
||||
}
|
||||
|
||||
## Uses the alsoPropagate() API.
|
||||
create_aof {
|
||||
append_to_aof [formatCommand sadd set foo]
|
||||
append_to_aof [formatCommand sadd set bar]
|
||||
append_to_aof [formatCommand sadd set gah]
|
||||
append_to_aof [formatCommand spop set 2]
|
||||
}
|
||||
|
||||
start_server_aof [list dir $server_path] {
|
||||
test "AOF+SPOP: Server should have been started" {
|
||||
assert_equal 1 [is_alive $srv]
|
||||
}
|
||||
|
||||
test "AOF+SPOP: Set should have 1 member" {
|
||||
set client [redis [dict get $srv host] [dict get $srv port]]
|
||||
wait_for_condition 50 100 {
|
||||
[catch {$client ping} e] == 0
|
||||
} else {
|
||||
fail "Loading DB is taking too much time."
|
||||
}
|
||||
assert_equal 1 [$client scard set]
|
||||
}
|
||||
}
|
||||
|
||||
## Test that EXPIREAT is loaded correctly
|
||||
create_aof {
|
||||
append_to_aof [formatCommand rpush list foo]
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
set server_path [tmpdir server.log]
|
||||
set system_name [string tolower [exec uname -s]]
|
||||
|
||||
if {$system_name eq {linux} || $system_name eq {darwin}} {
|
||||
start_server [list overrides [list dir $server_path]] {
|
||||
test "Server is able to generate a stack trace on selected systems" {
|
||||
r config set watchdog-period 200
|
||||
r debug sleep 1
|
||||
set pattern "*debugCommand*"
|
||||
set retry 10
|
||||
while {$retry} {
|
||||
set result [exec tail -100 < [srv 0 stdout]]
|
||||
if {[string match $pattern $result]} {
|
||||
break
|
||||
}
|
||||
incr retry -1
|
||||
after 1000
|
||||
}
|
||||
if {$retry == 0} {
|
||||
error "assertion:expected stack trace not found into log file"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ start_server_and_kill_it [list "dir" $server_path] {
|
||||
test {Server should not start if RDB is corrupted} {
|
||||
wait_for_condition 50 100 {
|
||||
[string match {*RDB checksum*} \
|
||||
[exec tail -n10 < [dict get $srv stdout]]]
|
||||
[exec tail -n1 < [dict get $srv stdout]]]
|
||||
} else {
|
||||
fail "Server started even if RDB was corrupted!"
|
||||
}
|
||||
|
||||
@@ -132,24 +132,5 @@ start_server {tags {"repl"}} {
|
||||
}
|
||||
assert {[$master dbsize] > 0}
|
||||
}
|
||||
|
||||
test {Replication of SPOP command -- alsoPropagate() API} {
|
||||
$master del myset
|
||||
set size [randomInt 100]
|
||||
set content {}
|
||||
for {set j 0} {$j < $size} {incr j} {
|
||||
lappend content [randomValue]
|
||||
}
|
||||
$master sadd myset {*}$content
|
||||
|
||||
set count [randomInt 100]
|
||||
set result [$master spop myset $count]
|
||||
|
||||
wait_for_condition 50 100 {
|
||||
[$master debug digest] eq [$slave debug digest]
|
||||
} else {
|
||||
fail "SPOP replication inconsistency"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,8 +118,7 @@ foreach dl {no yes} {
|
||||
[lindex $slaves 1] slaveof $master_host $master_port
|
||||
[lindex $slaves 2] slaveof $master_host $master_port
|
||||
|
||||
# Wait for all the three slaves to reach the "online"
|
||||
# state from the POV of the master.
|
||||
# Wait for all the three slaves to reach the "online" state
|
||||
set retry 500
|
||||
while {$retry} {
|
||||
set info [r -3 info]
|
||||
@@ -134,17 +133,6 @@ foreach dl {no yes} {
|
||||
error "assertion:Slaves not correctly synchronized"
|
||||
}
|
||||
|
||||
# Wait that slaves acknowledge they are online so
|
||||
# we are sure that DBSIZE and DEBUG DIGEST will not
|
||||
# fail because of timing issues.
|
||||
wait_for_condition 500 100 {
|
||||
[lindex [[lindex $slaves 0] role] 3] eq {connected} &&
|
||||
[lindex [[lindex $slaves 1] role] 3] eq {connected} &&
|
||||
[lindex [[lindex $slaves 2] role] 3] eq {connected}
|
||||
} else {
|
||||
fail "Slaves still not connected after some time"
|
||||
}
|
||||
|
||||
# Stop the write load
|
||||
stop_write_load $load_handle0
|
||||
stop_write_load $load_handle1
|
||||
@@ -152,8 +140,16 @@ foreach dl {no yes} {
|
||||
stop_write_load $load_handle3
|
||||
stop_write_load $load_handle4
|
||||
|
||||
# Make sure that slaves and master have same
|
||||
# number of keys
|
||||
# Wait that slaves exit the "loading" state
|
||||
wait_for_condition 500 100 {
|
||||
![string match {*loading:1*} [[lindex $slaves 0] info]] &&
|
||||
![string match {*loading:1*} [[lindex $slaves 1] info]] &&
|
||||
![string match {*loading:1*} [[lindex $slaves 2] info]]
|
||||
} else {
|
||||
fail "Slaves still loading data after too much time"
|
||||
}
|
||||
|
||||
# Make sure that slaves and master have same number of keys
|
||||
wait_for_condition 500 100 {
|
||||
[$master dbsize] == [[lindex $slaves 0] dbsize] &&
|
||||
[$master dbsize] == [[lindex $slaves 1] dbsize] &&
|
||||
|
||||
@@ -226,8 +226,6 @@ proc ::redis_cluster::get_keys_from_command {cmd argv} {
|
||||
# Special handling for other commands
|
||||
switch -exact $cmd {
|
||||
mget {return $argv}
|
||||
eval {return [lrange $argv 2 1+[lindex $argv 1]]}
|
||||
evalsha {return [lrange $argv 2 1+[lindex $argv 1]]}
|
||||
}
|
||||
|
||||
# All the remaining commands are not handled.
|
||||
|
||||
@@ -70,9 +70,6 @@ proc kill_server config {
|
||||
if {$::valgrind} {
|
||||
check_valgrind_errors [dict get $config stderr]
|
||||
}
|
||||
|
||||
# Remove this pid from the set of active pids in the test server.
|
||||
send_data_packet $::test_server_fd server-killed $pid
|
||||
}
|
||||
|
||||
proc is_alive config {
|
||||
@@ -207,14 +204,11 @@ proc start_server {options {code undefined}} {
|
||||
set stderr [format "%s/%s" [dict get $config "dir"] "stderr"]
|
||||
|
||||
if {$::valgrind} {
|
||||
set pid [exec valgrind --track-origins=yes --suppressions=src/valgrind.sup --show-reachable=no --show-possibly-lost=no --leak-check=full src/redis-server $config_file > $stdout 2> $stderr &]
|
||||
exec valgrind --suppressions=src/valgrind.sup --show-reachable=no --show-possibly-lost=no --leak-check=full src/redis-server $config_file > $stdout 2> $stderr &
|
||||
} else {
|
||||
set pid [exec src/redis-server $config_file > $stdout 2> $stderr &]
|
||||
exec src/redis-server $config_file > $stdout 2> $stderr &
|
||||
}
|
||||
|
||||
# Tell the test server about this new instance.
|
||||
send_data_packet $::test_server_fd server-spawned $pid
|
||||
|
||||
# check that the server actually started
|
||||
# ugly but tries to be as fast as possible...
|
||||
if {$::valgrind} {set retrynum 1000} else {set retrynum 100}
|
||||
@@ -240,9 +234,9 @@ proc start_server {options {code undefined}} {
|
||||
return
|
||||
}
|
||||
|
||||
# Wait for actual startup
|
||||
while {![info exists _pid]} {
|
||||
regexp {PID:\s(\d+)} [exec cat $stdout] _ _pid
|
||||
# find out the pid
|
||||
while {![info exists pid]} {
|
||||
regexp {PID:\s(\d+)} [exec cat $stdout] _ pid
|
||||
after 100
|
||||
}
|
||||
|
||||
|
||||
@@ -19,12 +19,9 @@ proc assert_match {pattern value} {
|
||||
}
|
||||
}
|
||||
|
||||
proc assert_equal {expected value {detail ""}} {
|
||||
proc assert_equal {expected value} {
|
||||
if {$expected ne $value} {
|
||||
if {$detail ne ""} {
|
||||
set detail " (detail: $detail)"
|
||||
}
|
||||
error "assertion:Expected '$value' to be equal to '$expected'$detail"
|
||||
error "assertion:Expected '$value' to be equal to '$expected'"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+20
-58
@@ -16,10 +16,8 @@ set ::all_tests {
|
||||
unit/dump
|
||||
unit/auth
|
||||
unit/protocol
|
||||
unit/keyspace
|
||||
unit/basic
|
||||
unit/scan
|
||||
unit/type/string
|
||||
unit/type/incr
|
||||
unit/type/list
|
||||
unit/type/list-2
|
||||
unit/type/list-3
|
||||
@@ -40,7 +38,6 @@ set ::all_tests {
|
||||
integration/aof
|
||||
integration/rdb
|
||||
integration/convert-zipmap-hash-on-load
|
||||
integration/logging
|
||||
unit/pubsub
|
||||
unit/slowlog
|
||||
unit/scripting
|
||||
@@ -68,9 +65,6 @@ set ::file ""; # If set, runs only the tests in this comma separated list
|
||||
set ::curfile ""; # Hold the filename of the current suite
|
||||
set ::accurate 0; # If true runs fuzz tests with more iterations
|
||||
set ::force_failure 0
|
||||
set ::timeout 600; # 10 minutes without progresses will quit the test.
|
||||
set ::last_progress [clock seconds]
|
||||
set ::active_servers {} ; # Pids of active Redis instances.
|
||||
|
||||
# Set to 1 when we are running in client mode. The Redis test uses a
|
||||
# server-client model to run tests simultaneously. The server instance
|
||||
@@ -206,19 +200,11 @@ proc test_server_main {} {
|
||||
vwait forever
|
||||
}
|
||||
|
||||
# This function gets called 10 times per second.
|
||||
# This function gets called 10 times per second, for now does nothing but
|
||||
# may be used in the future in order to detect test clients taking too much
|
||||
# time to execute the task.
|
||||
proc test_server_cron {} {
|
||||
set elapsed [expr {[clock seconds]-$::last_progress}]
|
||||
|
||||
if {$elapsed > $::timeout} {
|
||||
set err "\[[colorstr red TIMEOUT]\]: clients state report follows."
|
||||
puts $err
|
||||
show_clients_state
|
||||
kill_clients
|
||||
force_kill_all_servers
|
||||
the_end
|
||||
}
|
||||
|
||||
# Do some work here.
|
||||
after 100 test_server_cron
|
||||
}
|
||||
|
||||
@@ -244,8 +230,6 @@ proc read_from_test_client fd {
|
||||
set bytes [gets $fd]
|
||||
set payload [read $fd $bytes]
|
||||
foreach {status data} $payload break
|
||||
set ::last_progress [clock seconds]
|
||||
|
||||
if {$status eq {ready}} {
|
||||
if {!$::quiet} {
|
||||
puts "\[$status\]: $data"
|
||||
@@ -272,15 +256,12 @@ proc read_from_test_client fd {
|
||||
set ::active_clients_task($fd) "(ERR) $data"
|
||||
} elseif {$status eq {exception}} {
|
||||
puts "\[[colorstr red $status]\]: $data"
|
||||
kill_clients
|
||||
force_kill_all_servers
|
||||
foreach p $::clients_pids {
|
||||
catch {exec kill -9 $p}
|
||||
}
|
||||
exit 1
|
||||
} elseif {$status eq {testing}} {
|
||||
set ::active_clients_task($fd) "(IN PROGRESS) $data"
|
||||
} elseif {$status eq {server-spawned}} {
|
||||
lappend ::active_servers $data
|
||||
} elseif {$status eq {server-killed}} {
|
||||
set ::active_servers [lsearch -all -inline -not -exact $::active_servers $data]
|
||||
} else {
|
||||
if {!$::quiet} {
|
||||
puts "\[$status\]: $data"
|
||||
@@ -288,31 +269,6 @@ proc read_from_test_client fd {
|
||||
}
|
||||
}
|
||||
|
||||
proc show_clients_state {} {
|
||||
# The following loop is only useful for debugging tests that may
|
||||
# enter an infinite loop. Commented out normally.
|
||||
foreach x $::active_clients {
|
||||
if {[info exist ::active_clients_task($x)]} {
|
||||
puts "$x => $::active_clients_task($x)"
|
||||
} else {
|
||||
puts "$x => ???"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
proc kill_clients {} {
|
||||
foreach p $::clients_pids {
|
||||
catch {exec kill $p}
|
||||
}
|
||||
}
|
||||
|
||||
proc force_kill_all_servers {} {
|
||||
foreach p $::active_servers {
|
||||
puts "Killing still running Redis server $p"
|
||||
catch {exec kill -9 $p}
|
||||
}
|
||||
}
|
||||
|
||||
# A new client is idle. Remove it from the list of active clients and
|
||||
# if there are still test units to run, launch them.
|
||||
proc signal_idle_client fd {
|
||||
@@ -320,7 +276,17 @@ proc signal_idle_client fd {
|
||||
set ::active_clients \
|
||||
[lsearch -all -inline -not -exact $::active_clients $fd]
|
||||
|
||||
if 0 {show_clients_state}
|
||||
if 0 {
|
||||
# The following loop is only useful for debugging tests that may
|
||||
# enter an infinite loop. Commented out normally.
|
||||
foreach x $::active_clients {
|
||||
if {[info exist ::active_clients_task($x)]} {
|
||||
puts "$x => $::active_clients_task($x)"
|
||||
} else {
|
||||
puts "$x => ???"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# New unit to process?
|
||||
if {$::next_test != [llength $::all_tests]} {
|
||||
@@ -395,8 +361,7 @@ proc print_help_screen {} {
|
||||
"--quiet Don't show individual tests."
|
||||
"--single <unit> Just execute the specified unit (see next option)."
|
||||
"--list-tests List all the available test units."
|
||||
"--clients <num> Number of test clients (default 16)."
|
||||
"--timeout <sec> Test timeout in seconds (default 10 min)."
|
||||
"--clients <num> Number of test clients (16)."
|
||||
"--force-failure Force the execution of a test that always fails."
|
||||
"--help Print this help screen."
|
||||
} "\n"]
|
||||
@@ -445,9 +410,6 @@ for {set j 0} {$j < [llength $argv]} {incr j} {
|
||||
} elseif {$opt eq {--clients}} {
|
||||
set ::numclients $arg
|
||||
incr j
|
||||
} elseif {$opt eq {--timeout}} {
|
||||
set ::timeout $arg
|
||||
incr j
|
||||
} elseif {$opt eq {--help}} {
|
||||
print_help_screen
|
||||
exit 0
|
||||
|
||||
@@ -77,10 +77,10 @@ start_server {tags {"aofrw"}} {
|
||||
}
|
||||
|
||||
foreach d {string int} {
|
||||
foreach e {quicklist} {
|
||||
foreach e {ziplist linkedlist} {
|
||||
test "AOF rewrite of list with $e encoding, $d data" {
|
||||
r flushall
|
||||
set len 1000
|
||||
if {$e eq {ziplist}} {set len 10} else {set len 1000}
|
||||
for {set j 0} {$j < $len} {incr j} {
|
||||
if {$d eq {string}} {
|
||||
set data [randstring 0 16 alpha]
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
start_server {tags {"string"}} {
|
||||
start_server {tags {"basic"}} {
|
||||
test {DEL all keys to start with a clean DB} {
|
||||
foreach key [r keys *] {r del $key}
|
||||
r dbsize
|
||||
} {0}
|
||||
|
||||
test {SET and GET an item} {
|
||||
r set x foobar
|
||||
r get x
|
||||
@@ -9,6 +14,38 @@ start_server {tags {"string"}} {
|
||||
r get x
|
||||
} {}
|
||||
|
||||
test {DEL against a single item} {
|
||||
r del x
|
||||
r get x
|
||||
} {}
|
||||
|
||||
test {Vararg DEL} {
|
||||
r set foo1 a
|
||||
r set foo2 b
|
||||
r set foo3 c
|
||||
list [r del foo1 foo2 foo3 foo4] [r mget foo1 foo2 foo3]
|
||||
} {3 {{} {} {}}}
|
||||
|
||||
test {KEYS with pattern} {
|
||||
foreach key {key_x key_y key_z foo_a foo_b foo_c} {
|
||||
r set $key hello
|
||||
}
|
||||
lsort [r keys foo*]
|
||||
} {foo_a foo_b foo_c}
|
||||
|
||||
test {KEYS to get all keys} {
|
||||
lsort [r keys *]
|
||||
} {foo_a foo_b foo_c key_x key_y key_z}
|
||||
|
||||
test {DBSIZE} {
|
||||
r dbsize
|
||||
} {6}
|
||||
|
||||
test {DEL all keys} {
|
||||
foreach key [r keys *] {r del $key}
|
||||
r dbsize
|
||||
} {0}
|
||||
|
||||
test {Very big payload in GET/SET} {
|
||||
set buf [string repeat "abcd" 1000000]
|
||||
r set foo $buf
|
||||
@@ -38,7 +75,6 @@ start_server {tags {"string"}} {
|
||||
} {}
|
||||
|
||||
test {SET 10000 numeric keys and access all them in reverse order} {
|
||||
r flushdb
|
||||
set err {}
|
||||
for {set x 0} {$x < 10000} {incr x} {
|
||||
r set $x $x
|
||||
@@ -54,11 +90,157 @@ start_server {tags {"string"}} {
|
||||
set _ $err
|
||||
} {}
|
||||
|
||||
test {DBSIZE should be 10000 now} {
|
||||
test {DBSIZE should be 10101 now} {
|
||||
r dbsize
|
||||
} {10000}
|
||||
} {10101}
|
||||
}
|
||||
|
||||
test {INCR against non existing key} {
|
||||
set res {}
|
||||
append res [r incr novar]
|
||||
append res [r get novar]
|
||||
} {11}
|
||||
|
||||
test {INCR against key created by incr itself} {
|
||||
r incr novar
|
||||
} {2}
|
||||
|
||||
test {INCR against key originally set with SET} {
|
||||
r set novar 100
|
||||
r incr novar
|
||||
} {101}
|
||||
|
||||
test {INCR over 32bit value} {
|
||||
r set novar 17179869184
|
||||
r incr novar
|
||||
} {17179869185}
|
||||
|
||||
test {INCRBY over 32bit value with over 32bit increment} {
|
||||
r set novar 17179869184
|
||||
r incrby novar 17179869184
|
||||
} {34359738368}
|
||||
|
||||
test {INCR fails against key with spaces (left)} {
|
||||
r set novar " 11"
|
||||
catch {r incr novar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {INCR fails against key with spaces (right)} {
|
||||
r set novar "11 "
|
||||
catch {r incr novar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {INCR fails against key with spaces (both)} {
|
||||
r set novar " 11 "
|
||||
catch {r incr novar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {INCR fails against a key holding a list} {
|
||||
r rpush mylist 1
|
||||
catch {r incr mylist} err
|
||||
r rpop mylist
|
||||
format $err
|
||||
} {WRONGTYPE*}
|
||||
|
||||
test {DECRBY over 32bit value with over 32bit increment, negative res} {
|
||||
r set novar 17179869184
|
||||
r decrby novar 17179869185
|
||||
} {-1}
|
||||
|
||||
test {INCR uses shared objects in the 0-9999 range} {
|
||||
r set foo -1
|
||||
r incr foo
|
||||
assert {[r object refcount foo] > 1}
|
||||
r set foo 9998
|
||||
r incr foo
|
||||
assert {[r object refcount foo] > 1}
|
||||
r incr foo
|
||||
assert {[r object refcount foo] == 1}
|
||||
}
|
||||
|
||||
test {INCR can modify objects in-place} {
|
||||
r set foo 20000
|
||||
r incr foo
|
||||
assert {[r object refcount foo] == 1}
|
||||
set old [lindex [split [r debug object foo]] 1]
|
||||
r incr foo
|
||||
set new [lindex [split [r debug object foo]] 1]
|
||||
assert {[string range $old 0 2] eq "at:"}
|
||||
assert {[string range $new 0 2] eq "at:"}
|
||||
assert {$old eq $new}
|
||||
}
|
||||
|
||||
test {INCRBYFLOAT against non existing key} {
|
||||
r del novar
|
||||
list [roundFloat [r incrbyfloat novar 1]] \
|
||||
[roundFloat [r get novar]] \
|
||||
[roundFloat [r incrbyfloat novar 0.25]] \
|
||||
[roundFloat [r get novar]]
|
||||
} {1 1 1.25 1.25}
|
||||
|
||||
test {INCRBYFLOAT against key originally set with SET} {
|
||||
r set novar 1.5
|
||||
roundFloat [r incrbyfloat novar 1.5]
|
||||
} {3}
|
||||
|
||||
test {INCRBYFLOAT over 32bit value} {
|
||||
r set novar 17179869184
|
||||
r incrbyfloat novar 1.5
|
||||
} {17179869185.5}
|
||||
|
||||
test {INCRBYFLOAT over 32bit value with over 32bit increment} {
|
||||
r set novar 17179869184
|
||||
r incrbyfloat novar 17179869184
|
||||
} {34359738368}
|
||||
|
||||
test {INCRBYFLOAT fails against key with spaces (left)} {
|
||||
set err {}
|
||||
r set novar " 11"
|
||||
catch {r incrbyfloat novar 1.0} err
|
||||
format $err
|
||||
} {ERR*valid*}
|
||||
|
||||
test {INCRBYFLOAT fails against key with spaces (right)} {
|
||||
set err {}
|
||||
r set novar "11 "
|
||||
catch {r incrbyfloat novar 1.0} err
|
||||
format $err
|
||||
} {ERR*valid*}
|
||||
|
||||
test {INCRBYFLOAT fails against key with spaces (both)} {
|
||||
set err {}
|
||||
r set novar " 11 "
|
||||
catch {r incrbyfloat novar 1.0} err
|
||||
format $err
|
||||
} {ERR*valid*}
|
||||
|
||||
test {INCRBYFLOAT fails against a key holding a list} {
|
||||
r del mylist
|
||||
set err {}
|
||||
r rpush mylist 1
|
||||
catch {r incrbyfloat mylist 1.0} err
|
||||
r del mylist
|
||||
format $err
|
||||
} {WRONGTYPE*}
|
||||
|
||||
test {INCRBYFLOAT does not allow NaN or Infinity} {
|
||||
r set foo 0
|
||||
set err {}
|
||||
catch {r incrbyfloat foo +inf} err
|
||||
set err
|
||||
# p.s. no way I can force NaN to test it from the API because
|
||||
# there is no way to increment / decrement by infinity nor to
|
||||
# perform divisions.
|
||||
} {ERR*would produce*}
|
||||
|
||||
test {INCRBYFLOAT decrement} {
|
||||
r set foo 1
|
||||
roundFloat [r incrbyfloat foo -1.1]
|
||||
} {-0.1}
|
||||
|
||||
test "SETNX target key missing" {
|
||||
r del novar
|
||||
assert_equal 1 [r setnx novar foobared]
|
||||
@@ -102,6 +284,172 @@ start_server {tags {"string"}} {
|
||||
assert_equal 20 [r get x]
|
||||
}
|
||||
|
||||
test "DEL against expired key" {
|
||||
r debug set-active-expire 0
|
||||
r setex keyExpire 1 valExpire
|
||||
after 1100
|
||||
assert_equal 0 [r del keyExpire]
|
||||
r debug set-active-expire 1
|
||||
}
|
||||
|
||||
test {EXISTS} {
|
||||
set res {}
|
||||
r set newkey test
|
||||
append res [r exists newkey]
|
||||
r del newkey
|
||||
append res [r exists newkey]
|
||||
} {10}
|
||||
|
||||
test {Zero length value in key. SET/GET/EXISTS} {
|
||||
r set emptykey {}
|
||||
set res [r get emptykey]
|
||||
append res [r exists emptykey]
|
||||
r del emptykey
|
||||
append res [r exists emptykey]
|
||||
} {10}
|
||||
|
||||
test {Commands pipelining} {
|
||||
set fd [r channel]
|
||||
puts -nonewline $fd "SET k1 xyzk\r\nGET k1\r\nPING\r\n"
|
||||
flush $fd
|
||||
set res {}
|
||||
append res [string match OK* [r read]]
|
||||
append res [r read]
|
||||
append res [string match PONG* [r read]]
|
||||
format $res
|
||||
} {1xyzk1}
|
||||
|
||||
test {Non existing command} {
|
||||
catch {r foobaredcommand} err
|
||||
string match ERR* $err
|
||||
} {1}
|
||||
|
||||
test {RENAME basic usage} {
|
||||
r set mykey hello
|
||||
r rename mykey mykey1
|
||||
r rename mykey1 mykey2
|
||||
r get mykey2
|
||||
} {hello}
|
||||
|
||||
test {RENAME source key should no longer exist} {
|
||||
r exists mykey
|
||||
} {0}
|
||||
|
||||
test {RENAME against already existing key} {
|
||||
r set mykey a
|
||||
r set mykey2 b
|
||||
r rename mykey2 mykey
|
||||
set res [r get mykey]
|
||||
append res [r exists mykey2]
|
||||
} {b0}
|
||||
|
||||
test {RENAMENX basic usage} {
|
||||
r del mykey
|
||||
r del mykey2
|
||||
r set mykey foobar
|
||||
r renamenx mykey mykey2
|
||||
set res [r get mykey2]
|
||||
append res [r exists mykey]
|
||||
} {foobar0}
|
||||
|
||||
test {RENAMENX against already existing key} {
|
||||
r set mykey foo
|
||||
r set mykey2 bar
|
||||
r renamenx mykey mykey2
|
||||
} {0}
|
||||
|
||||
test {RENAMENX against already existing key (2)} {
|
||||
set res [r get mykey]
|
||||
append res [r get mykey2]
|
||||
} {foobar}
|
||||
|
||||
test {RENAME against non existing source key} {
|
||||
catch {r rename nokey foobar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {RENAME where source and dest key is the same} {
|
||||
catch {r rename mykey mykey} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {RENAME with volatile key, should move the TTL as well} {
|
||||
r del mykey mykey2
|
||||
r set mykey foo
|
||||
r expire mykey 100
|
||||
assert {[r ttl mykey] > 95 && [r ttl mykey] <= 100}
|
||||
r rename mykey mykey2
|
||||
assert {[r ttl mykey2] > 95 && [r ttl mykey2] <= 100}
|
||||
}
|
||||
|
||||
test {RENAME with volatile key, should not inherit TTL of target key} {
|
||||
r del mykey mykey2
|
||||
r set mykey foo
|
||||
r set mykey2 bar
|
||||
r expire mykey2 100
|
||||
assert {[r ttl mykey] == -1 && [r ttl mykey2] > 0}
|
||||
r rename mykey mykey2
|
||||
r ttl mykey2
|
||||
} {-1}
|
||||
|
||||
test {DEL all keys again (DB 0)} {
|
||||
foreach key [r keys *] {
|
||||
r del $key
|
||||
}
|
||||
r dbsize
|
||||
} {0}
|
||||
|
||||
test {DEL all keys again (DB 1)} {
|
||||
r select 10
|
||||
foreach key [r keys *] {
|
||||
r del $key
|
||||
}
|
||||
set res [r dbsize]
|
||||
r select 9
|
||||
format $res
|
||||
} {0}
|
||||
|
||||
test {MOVE basic usage} {
|
||||
r set mykey foobar
|
||||
r move mykey 10
|
||||
set res {}
|
||||
lappend res [r exists mykey]
|
||||
lappend res [r dbsize]
|
||||
r select 10
|
||||
lappend res [r get mykey]
|
||||
lappend res [r dbsize]
|
||||
r select 9
|
||||
format $res
|
||||
} [list 0 0 foobar 1]
|
||||
|
||||
test {MOVE against key existing in the target DB} {
|
||||
r set mykey hello
|
||||
r move mykey 10
|
||||
} {0}
|
||||
|
||||
test {MOVE against non-integer DB (#1428)} {
|
||||
r set mykey hello
|
||||
catch {r move mykey notanumber} e
|
||||
set e
|
||||
} {*ERR*index out of range}
|
||||
|
||||
test {SET/GET keys in different DBs} {
|
||||
r set a hello
|
||||
r set b world
|
||||
r select 10
|
||||
r set a foo
|
||||
r set b bared
|
||||
r select 9
|
||||
set res {}
|
||||
lappend res [r get a]
|
||||
lappend res [r get b]
|
||||
r select 10
|
||||
lappend res [r get a]
|
||||
lappend res [r get b]
|
||||
r select 9
|
||||
format $res
|
||||
} {hello world foo bared}
|
||||
|
||||
test {MGET} {
|
||||
r flushdb
|
||||
r set foo BAR
|
||||
@@ -119,8 +467,37 @@ start_server {tags {"string"}} {
|
||||
r mget foo baazz bar myset
|
||||
} {BAR {} FOO {}}
|
||||
|
||||
test {RANDOMKEY} {
|
||||
r flushdb
|
||||
r set foo x
|
||||
r set bar y
|
||||
set foo_seen 0
|
||||
set bar_seen 0
|
||||
for {set i 0} {$i < 100} {incr i} {
|
||||
set rkey [r randomkey]
|
||||
if {$rkey eq {foo}} {
|
||||
set foo_seen 1
|
||||
}
|
||||
if {$rkey eq {bar}} {
|
||||
set bar_seen 1
|
||||
}
|
||||
}
|
||||
list $foo_seen $bar_seen
|
||||
} {1 1}
|
||||
|
||||
test {RANDOMKEY against empty DB} {
|
||||
r flushdb
|
||||
r randomkey
|
||||
} {}
|
||||
|
||||
test {RANDOMKEY regression 1} {
|
||||
r flushdb
|
||||
r set x 10
|
||||
r del x
|
||||
r randomkey
|
||||
} {}
|
||||
|
||||
test {GETSET (set new value)} {
|
||||
r del foo
|
||||
list [r getset foo xyz] [r get foo]
|
||||
} {{} xyz}
|
||||
|
||||
@@ -415,6 +792,13 @@ start_server {tags {"string"}} {
|
||||
assert {$ttl <= 10 && $ttl > 5}
|
||||
}
|
||||
|
||||
test {KEYS * two times with long key, Github issue #1208} {
|
||||
r flushdb
|
||||
r set dlskeriewrioeuwqoirueioqwrueoqwrueqw test
|
||||
r keys *
|
||||
r keys *
|
||||
} {dlskeriewrioeuwqoirueioqwrueoqwrueqw}
|
||||
|
||||
test {GETRANGE with huge ranges, Github issue #1844} {
|
||||
r set foo bar
|
||||
r getrange foo 0 4294967297
|
||||
+2
-2
@@ -157,7 +157,7 @@ start_server {tags {"dump"}} {
|
||||
test {MIGRATE can correctly transfer large values} {
|
||||
set first [srv 0 client]
|
||||
r del key
|
||||
for {set j 0} {$j < 40000} {incr j} {
|
||||
for {set j 0} {$j < 5000} {incr j} {
|
||||
r rpush key 1 2 3 4 5 6 7 8 9 10
|
||||
r rpush key "item 1" "item 2" "item 3" "item 4" "item 5" \
|
||||
"item 6" "item 7" "item 8" "item 9" "item 10"
|
||||
@@ -175,7 +175,7 @@ start_server {tags {"dump"}} {
|
||||
assert {[$first exists key] == 0}
|
||||
assert {[$second exists key] == 1}
|
||||
assert {[$second ttl key] == -1}
|
||||
assert {[$second llen key] == 40000*20}
|
||||
assert {[$second llen key] == 5000*20}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
start_server {tags {"keyspace"}} {
|
||||
test {DEL against a single item} {
|
||||
r set x foo
|
||||
assert {[r get x] eq "foo"}
|
||||
r del x
|
||||
r get x
|
||||
} {}
|
||||
|
||||
test {Vararg DEL} {
|
||||
r set foo1 a
|
||||
r set foo2 b
|
||||
r set foo3 c
|
||||
list [r del foo1 foo2 foo3 foo4] [r mget foo1 foo2 foo3]
|
||||
} {3 {{} {} {}}}
|
||||
|
||||
test {KEYS with pattern} {
|
||||
foreach key {key_x key_y key_z foo_a foo_b foo_c} {
|
||||
r set $key hello
|
||||
}
|
||||
lsort [r keys foo*]
|
||||
} {foo_a foo_b foo_c}
|
||||
|
||||
test {KEYS to get all keys} {
|
||||
lsort [r keys *]
|
||||
} {foo_a foo_b foo_c key_x key_y key_z}
|
||||
|
||||
test {DBSIZE} {
|
||||
r dbsize
|
||||
} {6}
|
||||
|
||||
test {DEL all keys} {
|
||||
foreach key [r keys *] {r del $key}
|
||||
r dbsize
|
||||
} {0}
|
||||
|
||||
test "DEL against expired key" {
|
||||
r debug set-active-expire 0
|
||||
r setex keyExpire 1 valExpire
|
||||
after 1100
|
||||
assert_equal 0 [r del keyExpire]
|
||||
r debug set-active-expire 1
|
||||
}
|
||||
|
||||
test {EXISTS} {
|
||||
set res {}
|
||||
r set newkey test
|
||||
append res [r exists newkey]
|
||||
r del newkey
|
||||
append res [r exists newkey]
|
||||
} {10}
|
||||
|
||||
test {Zero length value in key. SET/GET/EXISTS} {
|
||||
r set emptykey {}
|
||||
set res [r get emptykey]
|
||||
append res [r exists emptykey]
|
||||
r del emptykey
|
||||
append res [r exists emptykey]
|
||||
} {10}
|
||||
|
||||
test {Commands pipelining} {
|
||||
set fd [r channel]
|
||||
puts -nonewline $fd "SET k1 xyzk\r\nGET k1\r\nPING\r\n"
|
||||
flush $fd
|
||||
set res {}
|
||||
append res [string match OK* [r read]]
|
||||
append res [r read]
|
||||
append res [string match PONG* [r read]]
|
||||
format $res
|
||||
} {1xyzk1}
|
||||
|
||||
test {Non existing command} {
|
||||
catch {r foobaredcommand} err
|
||||
string match ERR* $err
|
||||
} {1}
|
||||
|
||||
test {RENAME basic usage} {
|
||||
r set mykey hello
|
||||
r rename mykey mykey1
|
||||
r rename mykey1 mykey2
|
||||
r get mykey2
|
||||
} {hello}
|
||||
|
||||
test {RENAME source key should no longer exist} {
|
||||
r exists mykey
|
||||
} {0}
|
||||
|
||||
test {RENAME against already existing key} {
|
||||
r set mykey a
|
||||
r set mykey2 b
|
||||
r rename mykey2 mykey
|
||||
set res [r get mykey]
|
||||
append res [r exists mykey2]
|
||||
} {b0}
|
||||
|
||||
test {RENAMENX basic usage} {
|
||||
r del mykey
|
||||
r del mykey2
|
||||
r set mykey foobar
|
||||
r renamenx mykey mykey2
|
||||
set res [r get mykey2]
|
||||
append res [r exists mykey]
|
||||
} {foobar0}
|
||||
|
||||
test {RENAMENX against already existing key} {
|
||||
r set mykey foo
|
||||
r set mykey2 bar
|
||||
r renamenx mykey mykey2
|
||||
} {0}
|
||||
|
||||
test {RENAMENX against already existing key (2)} {
|
||||
set res [r get mykey]
|
||||
append res [r get mykey2]
|
||||
} {foobar}
|
||||
|
||||
test {RENAME against non existing source key} {
|
||||
catch {r rename nokey foobar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {RENAME where source and dest key are the same (existing)} {
|
||||
r set mykey foo
|
||||
r rename mykey mykey
|
||||
} {OK}
|
||||
|
||||
test {RENAMENX where source and dest key are the same (existing)} {
|
||||
r set mykey foo
|
||||
r renamenx mykey mykey
|
||||
} {0}
|
||||
|
||||
test {RENAME where source and dest key are the same (non existing)} {
|
||||
r del mykey
|
||||
catch {r rename mykey mykey} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {RENAME with volatile key, should move the TTL as well} {
|
||||
r del mykey mykey2
|
||||
r set mykey foo
|
||||
r expire mykey 100
|
||||
assert {[r ttl mykey] > 95 && [r ttl mykey] <= 100}
|
||||
r rename mykey mykey2
|
||||
assert {[r ttl mykey2] > 95 && [r ttl mykey2] <= 100}
|
||||
}
|
||||
|
||||
test {RENAME with volatile key, should not inherit TTL of target key} {
|
||||
r del mykey mykey2
|
||||
r set mykey foo
|
||||
r set mykey2 bar
|
||||
r expire mykey2 100
|
||||
assert {[r ttl mykey] == -1 && [r ttl mykey2] > 0}
|
||||
r rename mykey mykey2
|
||||
r ttl mykey2
|
||||
} {-1}
|
||||
|
||||
test {DEL all keys again (DB 0)} {
|
||||
foreach key [r keys *] {
|
||||
r del $key
|
||||
}
|
||||
r dbsize
|
||||
} {0}
|
||||
|
||||
test {DEL all keys again (DB 1)} {
|
||||
r select 10
|
||||
foreach key [r keys *] {
|
||||
r del $key
|
||||
}
|
||||
set res [r dbsize]
|
||||
r select 9
|
||||
format $res
|
||||
} {0}
|
||||
|
||||
test {MOVE basic usage} {
|
||||
r set mykey foobar
|
||||
r move mykey 10
|
||||
set res {}
|
||||
lappend res [r exists mykey]
|
||||
lappend res [r dbsize]
|
||||
r select 10
|
||||
lappend res [r get mykey]
|
||||
lappend res [r dbsize]
|
||||
r select 9
|
||||
format $res
|
||||
} [list 0 0 foobar 1]
|
||||
|
||||
test {MOVE against key existing in the target DB} {
|
||||
r set mykey hello
|
||||
r move mykey 10
|
||||
} {0}
|
||||
|
||||
test {MOVE against non-integer DB (#1428)} {
|
||||
r set mykey hello
|
||||
catch {r move mykey notanumber} e
|
||||
set e
|
||||
} {*ERR*index out of range}
|
||||
|
||||
test {SET/GET keys in different DBs} {
|
||||
r set a hello
|
||||
r set b world
|
||||
r select 10
|
||||
r set a foo
|
||||
r set b bared
|
||||
r select 9
|
||||
set res {}
|
||||
lappend res [r get a]
|
||||
lappend res [r get b]
|
||||
r select 10
|
||||
lappend res [r get a]
|
||||
lappend res [r get b]
|
||||
r select 9
|
||||
format $res
|
||||
} {hello world foo bared}
|
||||
|
||||
test {RANDOMKEY} {
|
||||
r flushdb
|
||||
r set foo x
|
||||
r set bar y
|
||||
set foo_seen 0
|
||||
set bar_seen 0
|
||||
for {set i 0} {$i < 100} {incr i} {
|
||||
set rkey [r randomkey]
|
||||
if {$rkey eq {foo}} {
|
||||
set foo_seen 1
|
||||
}
|
||||
if {$rkey eq {bar}} {
|
||||
set bar_seen 1
|
||||
}
|
||||
}
|
||||
list $foo_seen $bar_seen
|
||||
} {1 1}
|
||||
|
||||
test {RANDOMKEY against empty DB} {
|
||||
r flushdb
|
||||
r randomkey
|
||||
} {}
|
||||
|
||||
test {RANDOMKEY regression 1} {
|
||||
r flushdb
|
||||
r set x 10
|
||||
r del x
|
||||
r randomkey
|
||||
} {}
|
||||
|
||||
test {KEYS * two times with long key, Github issue #1208} {
|
||||
r flushdb
|
||||
r set dlskeriewrioeuwqoirueioqwrueoqwrueqw test
|
||||
r keys *
|
||||
r keys *
|
||||
} {dlskeriewrioeuwqoirueioqwrueoqwrueqw}
|
||||
}
|
||||
@@ -1,20 +1,15 @@
|
||||
proc test_memory_efficiency {range} {
|
||||
r flushall
|
||||
set rd [redis_deferring_client]
|
||||
set base_mem [s used_memory]
|
||||
set written 0
|
||||
for {set j 0} {$j < 10000} {incr j} {
|
||||
set key key:$j
|
||||
set val [string repeat A [expr {int(rand()*$range)}]]
|
||||
$rd set $key $val
|
||||
r set $key $val
|
||||
incr written [string length $key]
|
||||
incr written [string length $val]
|
||||
incr written 2 ;# A separator is the minimum to store key-value data.
|
||||
}
|
||||
for {set j 0} {$j < 10000} {incr j} {
|
||||
$rd read ; # Discard replies
|
||||
}
|
||||
|
||||
set current_mem [s used_memory]
|
||||
set used [expr {$current_mem-$base_mem}]
|
||||
set efficiency [expr {double($written)/$used}]
|
||||
|
||||
@@ -226,14 +226,4 @@ start_server {tags {"scan"}} {
|
||||
set res [r zscan mykey 0 MATCH foo* COUNT 10000]
|
||||
lsort -unique [lindex $res 1]
|
||||
}
|
||||
|
||||
test "ZSCAN scores: regression test for issue #2175" {
|
||||
r del mykey
|
||||
for {set j 0} {$j < 500} {incr j} {
|
||||
r zadd mykey 9.8813129168249309e-323 $j
|
||||
}
|
||||
set res [lindex [r zscan mykey 0] 1]
|
||||
set first_score [lindex $res 1]
|
||||
assert {$first_score != 0}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,94 +184,6 @@ start_server {tags {"scripting"}} {
|
||||
set e
|
||||
} {*against a key*}
|
||||
|
||||
test {EVAL - JSON numeric decoding} {
|
||||
# We must return the table as a string because otherwise
|
||||
# Redis converts floats to ints and we get 0 and 1023 instead
|
||||
# of 0.0003 and 1023.2 as the parsed output.
|
||||
r eval {return
|
||||
table.concat(
|
||||
cjson.decode(
|
||||
"[0.0, -5e3, -1, 0.3e-3, 1023.2, 0e10]"), " ")
|
||||
} 0
|
||||
} {0 -5000 -1 0.0003 1023.2 0}
|
||||
|
||||
test {EVAL - JSON string decoding} {
|
||||
r eval {local decoded = cjson.decode('{"keya": "a", "keyb": "b"}')
|
||||
return {decoded.keya, decoded.keyb}
|
||||
} 0
|
||||
} {a b}
|
||||
|
||||
test {EVAL - cmsgpack can pack double?} {
|
||||
r eval {local encoded = cmsgpack.pack(0.1)
|
||||
local h = ""
|
||||
for i = 1, #encoded do
|
||||
h = h .. string.format("%02x",string.byte(encoded,i))
|
||||
end
|
||||
return h
|
||||
} 0
|
||||
} {cb3fb999999999999a}
|
||||
|
||||
test {EVAL - cmsgpack can pack negative int64?} {
|
||||
r eval {local encoded = cmsgpack.pack(-1099511627776)
|
||||
local h = ""
|
||||
for i = 1, #encoded do
|
||||
h = h .. string.format("%02x",string.byte(encoded,i))
|
||||
end
|
||||
return h
|
||||
} 0
|
||||
} {d3ffffff0000000000}
|
||||
|
||||
test {EVAL - cmsgpack can pack and unpack circular references?} {
|
||||
r eval {local a = {x=nil,y=5}
|
||||
local b = {x=a}
|
||||
a['x'] = b
|
||||
local encoded = cmsgpack.pack(a)
|
||||
local h = ""
|
||||
-- cmsgpack encodes to a depth of 16, but can't encode
|
||||
-- references, so the encoded object has a deep copy recusive
|
||||
-- depth of 16.
|
||||
for i = 1, #encoded do
|
||||
h = h .. string.format("%02x",string.byte(encoded,i))
|
||||
end
|
||||
-- when unpacked, re.x.x != re because the unpack creates
|
||||
-- individual tables down to a depth of 16.
|
||||
-- (that's why the encoded output is so large)
|
||||
local re = cmsgpack.unpack(encoded)
|
||||
assert(re)
|
||||
assert(re.x)
|
||||
assert(re.x.x.y == re.y)
|
||||
assert(re.x.x.x.x.y == re.y)
|
||||
assert(re.x.x.x.x.x.x.y == re.y)
|
||||
assert(re.x.x.x.x.x.x.x.x.x.x.y == re.y)
|
||||
-- maximum working depth:
|
||||
assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.y == re.y)
|
||||
-- now the last x would be b above and has no y
|
||||
assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x)
|
||||
-- so, the final x.x is at the depth limit and was assigned nil
|
||||
assert(re.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x == nil)
|
||||
return {h, re.x.x.x.x.x.x.x.x.y == re.y, re.y == 5}
|
||||
} 0
|
||||
} {82a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a17882a17905a17881a178c0 1 1}
|
||||
|
||||
test {EVAL - Numerical sanity check from bitop} {
|
||||
r eval {assert(0x7fffffff == 2147483647, "broken hex literals");
|
||||
assert(0xffffffff == -1 or 0xffffffff == 2^32-1,
|
||||
"broken hex literals");
|
||||
assert(tostring(-1) == "-1", "broken tostring()");
|
||||
assert(tostring(0xffffffff) == "-1" or
|
||||
tostring(0xffffffff) == "4294967295",
|
||||
"broken tostring()")
|
||||
} 0
|
||||
} {}
|
||||
|
||||
test {EVAL - Verify minimal bitop functionality} {
|
||||
r eval {assert(bit.tobit(1) == 1);
|
||||
assert(bit.band(1) == 1);
|
||||
assert(bit.bxor(1,2) == 3);
|
||||
assert(bit.bor(1,2,4,8,16,32,64,128) == 255)
|
||||
} 0
|
||||
} {}
|
||||
|
||||
test {SCRIPTING FLUSH - is able to clear the scripts cache?} {
|
||||
r set mykey myval
|
||||
set v [r evalsha fd758d1589d044dd850a6f05d52f2eefd27f033f 1 mykey]
|
||||
@@ -413,7 +325,7 @@ start_server {tags {"scripting"}} {
|
||||
r sadd myset a b c
|
||||
r mset a 1 b 2 c 3 d 4
|
||||
assert {[r spop myset] ne {}}
|
||||
assert {[r spop myset 1] ne {}}
|
||||
assert {[r spop myset] ne {}}
|
||||
assert {[r spop myset] ne {}}
|
||||
assert {[r mget a b c d] eq {1 2 3 4}}
|
||||
assert {[r spop myset] eq {}}
|
||||
|
||||
+7
-24
@@ -1,7 +1,8 @@
|
||||
start_server {
|
||||
tags {"sort"}
|
||||
overrides {
|
||||
"list-max-ziplist-size" 32
|
||||
"list-max-ziplist-value" 16
|
||||
"list-max-ziplist-entries" 32
|
||||
"set-max-intset-entries" 32
|
||||
}
|
||||
} {
|
||||
@@ -35,9 +36,9 @@ start_server {
|
||||
}
|
||||
|
||||
foreach {num cmd enc title} {
|
||||
16 lpush quicklist "Old Ziplist"
|
||||
1000 lpush quicklist "Old Linked list"
|
||||
10000 lpush quicklist "Old Big Linked list"
|
||||
16 lpush ziplist "Ziplist"
|
||||
1000 lpush linkedlist "Linked list"
|
||||
10000 lpush linkedlist "Big Linked list"
|
||||
16 sadd intset "Intset"
|
||||
1000 sadd hashtable "Hash table"
|
||||
10000 sadd hashtable "Big Hash table"
|
||||
@@ -84,14 +85,14 @@ start_server {
|
||||
r sort tosort BY weight_* store sort-res
|
||||
assert_equal $result [r lrange sort-res 0 -1]
|
||||
assert_equal 16 [r llen sort-res]
|
||||
assert_encoding quicklist sort-res
|
||||
assert_encoding ziplist sort-res
|
||||
}
|
||||
|
||||
test "SORT BY hash field STORE" {
|
||||
r sort tosort BY wobj_*->weight store sort-res
|
||||
assert_equal $result [r lrange sort-res 0 -1]
|
||||
assert_equal 16 [r llen sort-res]
|
||||
assert_encoding quicklist sort-res
|
||||
assert_encoding ziplist sort-res
|
||||
}
|
||||
|
||||
test "SORT extracts STORE correctly" {
|
||||
@@ -245,24 +246,6 @@ start_server {
|
||||
r sort mylist by num get x:*->
|
||||
} {100}
|
||||
|
||||
test "SORT by nosort retains native order for lists" {
|
||||
r del testa
|
||||
r lpush testa 2 1 4 3 5
|
||||
r sort testa by nosort
|
||||
} {5 3 4 1 2}
|
||||
|
||||
test "SORT by nosort plus store retains native order for lists" {
|
||||
r del testa
|
||||
r lpush testa 2 1 4 3 5
|
||||
r sort testa by nosort store testb
|
||||
r lrange testb 0 -1
|
||||
} {5 3 4 1 2}
|
||||
|
||||
test "SORT by nosort with limit returns based on original list order" {
|
||||
r sort testa by nosort limit 0 3 store testb
|
||||
r lrange testb 0 -1
|
||||
} {5 3 4}
|
||||
|
||||
tags {"slow"} {
|
||||
set num 100
|
||||
set res [create_random_dataset $num lpush]
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
start_server {tags {"incr"}} {
|
||||
test {INCR against non existing key} {
|
||||
set res {}
|
||||
append res [r incr novar]
|
||||
append res [r get novar]
|
||||
} {11}
|
||||
|
||||
test {INCR against key created by incr itself} {
|
||||
r incr novar
|
||||
} {2}
|
||||
|
||||
test {INCR against key originally set with SET} {
|
||||
r set novar 100
|
||||
r incr novar
|
||||
} {101}
|
||||
|
||||
test {INCR over 32bit value} {
|
||||
r set novar 17179869184
|
||||
r incr novar
|
||||
} {17179869185}
|
||||
|
||||
test {INCRBY over 32bit value with over 32bit increment} {
|
||||
r set novar 17179869184
|
||||
r incrby novar 17179869184
|
||||
} {34359738368}
|
||||
|
||||
test {INCR fails against key with spaces (left)} {
|
||||
r set novar " 11"
|
||||
catch {r incr novar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {INCR fails against key with spaces (right)} {
|
||||
r set novar "11 "
|
||||
catch {r incr novar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {INCR fails against key with spaces (both)} {
|
||||
r set novar " 11 "
|
||||
catch {r incr novar} err
|
||||
format $err
|
||||
} {ERR*}
|
||||
|
||||
test {INCR fails against a key holding a list} {
|
||||
r rpush mylist 1
|
||||
catch {r incr mylist} err
|
||||
r rpop mylist
|
||||
format $err
|
||||
} {WRONGTYPE*}
|
||||
|
||||
test {DECRBY over 32bit value with over 32bit increment, negative res} {
|
||||
r set novar 17179869184
|
||||
r decrby novar 17179869185
|
||||
} {-1}
|
||||
|
||||
test {INCR uses shared objects in the 0-9999 range} {
|
||||
r set foo -1
|
||||
r incr foo
|
||||
assert {[r object refcount foo] > 1}
|
||||
r set foo 9998
|
||||
r incr foo
|
||||
assert {[r object refcount foo] > 1}
|
||||
r incr foo
|
||||
assert {[r object refcount foo] == 1}
|
||||
}
|
||||
|
||||
test {INCR can modify objects in-place} {
|
||||
r set foo 20000
|
||||
r incr foo
|
||||
assert {[r object refcount foo] == 1}
|
||||
set old [lindex [split [r debug object foo]] 1]
|
||||
r incr foo
|
||||
set new [lindex [split [r debug object foo]] 1]
|
||||
assert {[string range $old 0 2] eq "at:"}
|
||||
assert {[string range $new 0 2] eq "at:"}
|
||||
assert {$old eq $new}
|
||||
}
|
||||
|
||||
test {INCRBYFLOAT against non existing key} {
|
||||
r del novar
|
||||
list [roundFloat [r incrbyfloat novar 1]] \
|
||||
[roundFloat [r get novar]] \
|
||||
[roundFloat [r incrbyfloat novar 0.25]] \
|
||||
[roundFloat [r get novar]]
|
||||
} {1 1 1.25 1.25}
|
||||
|
||||
test {INCRBYFLOAT against key originally set with SET} {
|
||||
r set novar 1.5
|
||||
roundFloat [r incrbyfloat novar 1.5]
|
||||
} {3}
|
||||
|
||||
test {INCRBYFLOAT over 32bit value} {
|
||||
r set novar 17179869184
|
||||
r incrbyfloat novar 1.5
|
||||
} {17179869185.5}
|
||||
|
||||
test {INCRBYFLOAT over 32bit value with over 32bit increment} {
|
||||
r set novar 17179869184
|
||||
r incrbyfloat novar 17179869184
|
||||
} {34359738368}
|
||||
|
||||
test {INCRBYFLOAT fails against key with spaces (left)} {
|
||||
set err {}
|
||||
r set novar " 11"
|
||||
catch {r incrbyfloat novar 1.0} err
|
||||
format $err
|
||||
} {ERR*valid*}
|
||||
|
||||
test {INCRBYFLOAT fails against key with spaces (right)} {
|
||||
set err {}
|
||||
r set novar "11 "
|
||||
catch {r incrbyfloat novar 1.0} err
|
||||
format $err
|
||||
} {ERR*valid*}
|
||||
|
||||
test {INCRBYFLOAT fails against key with spaces (both)} {
|
||||
set err {}
|
||||
r set novar " 11 "
|
||||
catch {r incrbyfloat novar 1.0} err
|
||||
format $err
|
||||
} {ERR*valid*}
|
||||
|
||||
test {INCRBYFLOAT fails against a key holding a list} {
|
||||
r del mylist
|
||||
set err {}
|
||||
r rpush mylist 1
|
||||
catch {r incrbyfloat mylist 1.0} err
|
||||
r del mylist
|
||||
format $err
|
||||
} {WRONGTYPE*}
|
||||
|
||||
test {INCRBYFLOAT does not allow NaN or Infinity} {
|
||||
r set foo 0
|
||||
set err {}
|
||||
catch {r incrbyfloat foo +inf} err
|
||||
set err
|
||||
# p.s. no way I can force NaN to test it from the API because
|
||||
# there is no way to increment / decrement by infinity nor to
|
||||
# perform divisions.
|
||||
} {ERR*would produce*}
|
||||
|
||||
test {INCRBYFLOAT decrement} {
|
||||
r set foo 1
|
||||
roundFloat [r incrbyfloat foo -1.1]
|
||||
} {-0.1}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user