Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
ruanhaishen
redis
Commits
bfe85f7c
Commit
bfe85f7c
authored
May 10, 2011
by
antirez
Browse files
Merge branch 'unstable'
parents
b8513c93
6b52ad87
Changes
58
Show whitespace changes
Inline
Side-by-side
src/anet.h
View file @
bfe85f7c
...
@@ -53,5 +53,6 @@ int anetWrite(int fd, char *buf, int count);
...
@@ -53,5 +53,6 @@ int anetWrite(int fd, char *buf, int count);
int
anetNonBlock
(
char
*
err
,
int
fd
);
int
anetNonBlock
(
char
*
err
,
int
fd
);
int
anetTcpNoDelay
(
char
*
err
,
int
fd
);
int
anetTcpNoDelay
(
char
*
err
,
int
fd
);
int
anetTcpKeepAlive
(
char
*
err
,
int
fd
);
int
anetTcpKeepAlive
(
char
*
err
,
int
fd
);
int
anetPeerToString
(
int
fd
,
char
*
ip
,
int
*
port
);
#endif
#endif
src/aof.c
View file @
bfe85f7c
...
@@ -284,9 +284,11 @@ int loadAppendOnlyFile(char *filename) {
...
@@ -284,9 +284,11 @@ int loadAppendOnlyFile(char *filename) {
/* The fake client should not have a reply */
/* The fake client should not have a reply */
redisAssert
(
fakeClient
->
bufpos
==
0
&&
listLength
(
fakeClient
->
reply
)
==
0
);
redisAssert
(
fakeClient
->
bufpos
==
0
&&
listLength
(
fakeClient
->
reply
)
==
0
);
/* Clean up, ready for the next command */
/* Clean up. Command code may have changed argv/argc so we use the
for
(
j
=
0
;
j
<
argc
;
j
++
)
decrRefCount
(
argv
[
j
]);
* argv/argc of the client instead of the local variables. */
zfree
(
argv
);
for
(
j
=
0
;
j
<
fakeClient
->
argc
;
j
++
)
decrRefCount
(
fakeClient
->
argv
[
j
]);
zfree
(
fakeClient
->
argv
);
}
}
/* This point can only be reached when EOF is reached without errors.
/* This point can only be reached when EOF is reached without errors.
...
@@ -346,7 +348,7 @@ int rewriteAppendOnlyFile(char *filename) {
...
@@ -346,7 +348,7 @@ int rewriteAppendOnlyFile(char *filename) {
/* Iterate this DB writing every entry */
/* Iterate this DB writing every entry */
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
sds
keystr
=
dictGetEntryKey
(
de
)
;
sds
keystr
;
robj
key
,
*
o
;
robj
key
,
*
o
;
time_t
expiretime
;
time_t
expiretime
;
...
@@ -429,12 +431,43 @@ int rewriteAppendOnlyFile(char *filename) {
...
@@ -429,12 +431,43 @@ int rewriteAppendOnlyFile(char *filename) {
}
}
}
else
if
(
o
->
type
==
REDIS_ZSET
)
{
}
else
if
(
o
->
type
==
REDIS_ZSET
)
{
/* Emit the ZADDs needed to rebuild the sorted set */
/* Emit the ZADDs needed to rebuild the sorted set */
char
cmd
[]
=
"*4
\r\n
$4
\r\n
ZADD
\r\n
"
;
if
(
o
->
encoding
==
REDIS_ENCODING_ZIPLIST
)
{
unsigned
char
*
zl
=
o
->
ptr
;
unsigned
char
*
eptr
,
*
sptr
;
unsigned
char
*
vstr
;
unsigned
int
vlen
;
long
long
vll
;
double
score
;
eptr
=
ziplistIndex
(
zl
,
0
);
redisAssert
(
eptr
!=
NULL
);
sptr
=
ziplistNext
(
zl
,
eptr
);
redisAssert
(
sptr
!=
NULL
);
while
(
eptr
!=
NULL
)
{
redisAssert
(
ziplistGet
(
eptr
,
&
vstr
,
&
vlen
,
&
vll
));
score
=
zzlGetScore
(
sptr
);
if
(
fwrite
(
cmd
,
sizeof
(
cmd
)
-
1
,
1
,
fp
)
==
0
)
goto
werr
;
if
(
fwriteBulkObject
(
fp
,
&
key
)
==
0
)
goto
werr
;
if
(
fwriteBulkDouble
(
fp
,
score
)
==
0
)
goto
werr
;
if
(
vstr
!=
NULL
)
{
if
(
fwriteBulkString
(
fp
,(
char
*
)
vstr
,
vlen
)
==
0
)
goto
werr
;
}
else
{
if
(
fwriteBulkLongLong
(
fp
,
vll
)
==
0
)
goto
werr
;
}
zzlNext
(
zl
,
&
eptr
,
&
sptr
);
}
}
else
if
(
o
->
encoding
==
REDIS_ENCODING_SKIPLIST
)
{
zset
*
zs
=
o
->
ptr
;
zset
*
zs
=
o
->
ptr
;
dictIterator
*
di
=
dictGetIterator
(
zs
->
dict
);
dictIterator
*
di
=
dictGetIterator
(
zs
->
dict
);
dictEntry
*
de
;
dictEntry
*
de
;
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
char
cmd
[]
=
"*4
\r\n
$4
\r\n
ZADD
\r\n
"
;
robj
*
eleobj
=
dictGetEntryKey
(
de
);
robj
*
eleobj
=
dictGetEntryKey
(
de
);
double
*
score
=
dictGetEntryVal
(
de
);
double
*
score
=
dictGetEntryVal
(
de
);
...
@@ -444,6 +477,9 @@ int rewriteAppendOnlyFile(char *filename) {
...
@@ -444,6 +477,9 @@ int rewriteAppendOnlyFile(char *filename) {
if
(
fwriteBulkObject
(
fp
,
eleobj
)
==
0
)
goto
werr
;
if
(
fwriteBulkObject
(
fp
,
eleobj
)
==
0
)
goto
werr
;
}
}
dictReleaseIterator
(
di
);
dictReleaseIterator
(
di
);
}
else
{
redisPanic
(
"Unknown sorted set encoding"
);
}
}
else
if
(
o
->
type
==
REDIS_HASH
)
{
}
else
if
(
o
->
type
==
REDIS_HASH
)
{
char
cmd
[]
=
"*4
\r\n
$4
\r\n
HSET
\r\n
"
;
char
cmd
[]
=
"*4
\r\n
$4
\r\n
HSET
\r\n
"
;
...
...
src/asciilogo.h
0 → 100644
View file @
bfe85f7c
char
*
ascii_logo
=
" _._
\n
"
" _.-``__ ''-._
\n
"
" _.-`` `. `_. ''-._ Redis %s (%s/%d) %s bit
\n
"
" .-`` .-```. ```
\\
/ _.,_ ''-._
\n
"
" ( ' , .-` | `, ) Running in %s mode
\n
"
" |`-._`-...-` __...-.``-._|'` _.-'| Port: %d
\n
"
" | `-._ `._ / _.-' | PID: %ld
\n
"
" `-._ `-._ `-./ _.-' _.-'
\n
"
" |`-._`-._ `-.__.-' _.-'_.-'|
\n
"
" | `-._`-._ _.-'_.-' | http://redis.io
\n
"
" `-._ `-._`-.__.-'_.-' _.-'
\n
"
" |`-._`-._ `-.__.-' _.-'_.-'|
\n
"
" | `-._`-._ _.-'_.-' |
\n
"
" `-._ `-._`-.__.-'_.-' _.-'
\n
"
" `-._ `-.__.-' _.-'
\n
"
" `-._ _.-'
\n
"
" `-.__.-'
\n\n
"
;
src/cluster.c
0 → 100644
View file @
bfe85f7c
#include "redis.h"
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
void
clusterAcceptHandler
(
aeEventLoop
*
el
,
int
fd
,
void
*
privdata
,
int
mask
);
void
clusterReadHandler
(
aeEventLoop
*
el
,
int
fd
,
void
*
privdata
,
int
mask
);
void
clusterSendPing
(
clusterLink
*
link
,
int
type
);
void
clusterSendFail
(
char
*
nodename
);
void
clusterUpdateState
(
void
);
int
clusterNodeGetSlotBit
(
clusterNode
*
n
,
int
slot
);
sds
clusterGenNodesDescription
(
void
);
clusterNode
*
clusterLookupNode
(
char
*
name
);
int
clusterNodeAddSlave
(
clusterNode
*
master
,
clusterNode
*
slave
);
int
clusterAddSlot
(
clusterNode
*
n
,
int
slot
);
/* -----------------------------------------------------------------------------
* Initialization
* -------------------------------------------------------------------------- */
void
clusterGetRandomName
(
char
*
p
)
{
FILE
*
fp
=
fopen
(
"/dev/urandom"
,
"r"
);
char
*
charset
=
"0123456789abcdef"
;
int
j
;
if
(
fp
==
NULL
||
fread
(
p
,
REDIS_CLUSTER_NAMELEN
,
1
,
fp
)
==
0
)
{
for
(
j
=
0
;
j
<
REDIS_CLUSTER_NAMELEN
;
j
++
)
p
[
j
]
=
rand
();
}
for
(
j
=
0
;
j
<
REDIS_CLUSTER_NAMELEN
;
j
++
)
p
[
j
]
=
charset
[
p
[
j
]
&
0x0F
];
fclose
(
fp
);
}
int
clusterLoadConfig
(
char
*
filename
)
{
FILE
*
fp
=
fopen
(
filename
,
"r"
);
char
*
line
;
int
maxline
,
j
;
if
(
fp
==
NULL
)
return
REDIS_ERR
;
/* Parse the file. Note that single liens of the cluster config file can
* be really long as they include all the hash slots of the node.
* This means in the worst possible case REDIS_CLUSTER_SLOTS/2 integers.
* To simplify we allocate 1024+REDIS_CLUSTER_SLOTS*16 bytes per line. */
maxline
=
1024
+
REDIS_CLUSTER_SLOTS
*
16
;
line
=
zmalloc
(
maxline
);
while
(
fgets
(
line
,
maxline
,
fp
)
!=
NULL
)
{
int
argc
;
sds
*
argv
=
sdssplitargs
(
line
,
&
argc
);
clusterNode
*
n
,
*
master
;
char
*
p
,
*
s
;
/* Create this node if it does not exist */
n
=
clusterLookupNode
(
argv
[
0
]);
if
(
!
n
)
{
n
=
createClusterNode
(
argv
[
0
],
0
);
clusterAddNode
(
n
);
}
/* Address and port */
if
((
p
=
strchr
(
argv
[
1
],
':'
))
==
NULL
)
goto
fmterr
;
*
p
=
'\0'
;
memcpy
(
n
->
ip
,
argv
[
1
],
strlen
(
argv
[
1
])
+
1
);
n
->
port
=
atoi
(
p
+
1
);
/* Parse flags */
p
=
s
=
argv
[
2
];
while
(
p
)
{
p
=
strchr
(
s
,
','
);
if
(
p
)
*
p
=
'\0'
;
if
(
!
strcasecmp
(
s
,
"myself"
))
{
redisAssert
(
server
.
cluster
.
myself
==
NULL
);
server
.
cluster
.
myself
=
n
;
n
->
flags
|=
REDIS_NODE_MYSELF
;
}
else
if
(
!
strcasecmp
(
s
,
"master"
))
{
n
->
flags
|=
REDIS_NODE_MASTER
;
}
else
if
(
!
strcasecmp
(
s
,
"slave"
))
{
n
->
flags
|=
REDIS_NODE_SLAVE
;
}
else
if
(
!
strcasecmp
(
s
,
"fail?"
))
{
n
->
flags
|=
REDIS_NODE_PFAIL
;
}
else
if
(
!
strcasecmp
(
s
,
"fail"
))
{
n
->
flags
|=
REDIS_NODE_FAIL
;
}
else
if
(
!
strcasecmp
(
s
,
"handshake"
))
{
n
->
flags
|=
REDIS_NODE_HANDSHAKE
;
}
else
if
(
!
strcasecmp
(
s
,
"noaddr"
))
{
n
->
flags
|=
REDIS_NODE_NOADDR
;
}
else
if
(
!
strcasecmp
(
s
,
"noflags"
))
{
/* nothing to do */
}
else
{
redisPanic
(
"Unknown flag in redis cluster config file"
);
}
if
(
p
)
s
=
p
+
1
;
}
/* Get master if any. Set the master and populate master's
* slave list. */
if
(
argv
[
3
][
0
]
!=
'-'
)
{
master
=
clusterLookupNode
(
argv
[
3
]);
if
(
!
master
)
{
master
=
createClusterNode
(
argv
[
3
],
0
);
clusterAddNode
(
master
);
}
n
->
slaveof
=
master
;
clusterNodeAddSlave
(
master
,
n
);
}
/* Set ping sent / pong received timestamps */
if
(
atoi
(
argv
[
4
]))
n
->
ping_sent
=
time
(
NULL
);
if
(
atoi
(
argv
[
5
]))
n
->
pong_received
=
time
(
NULL
);
/* Populate hash slots served by this instance. */
for
(
j
=
7
;
j
<
argc
;
j
++
)
{
int
start
,
stop
;
if
(
argv
[
j
][
0
]
==
'['
)
{
/* Here we handle migrating / importing slots */
int
slot
;
char
direction
;
clusterNode
*
cn
;
p
=
strchr
(
argv
[
j
],
'-'
);
redisAssert
(
p
!=
NULL
);
*
p
=
'\0'
;
direction
=
p
[
1
];
/* Either '>' or '<' */
slot
=
atoi
(
argv
[
j
]
+
1
);
p
+=
3
;
cn
=
clusterLookupNode
(
p
);
if
(
!
cn
)
{
cn
=
createClusterNode
(
p
,
0
);
clusterAddNode
(
cn
);
}
if
(
direction
==
'>'
)
{
server
.
cluster
.
migrating_slots_to
[
slot
]
=
cn
;
}
else
{
server
.
cluster
.
importing_slots_from
[
slot
]
=
cn
;
}
continue
;
}
else
if
((
p
=
strchr
(
argv
[
j
],
'-'
))
!=
NULL
)
{
*
p
=
'\0'
;
start
=
atoi
(
argv
[
j
]);
stop
=
atoi
(
p
+
1
);
}
else
{
start
=
stop
=
atoi
(
argv
[
j
]);
}
while
(
start
<=
stop
)
clusterAddSlot
(
n
,
start
++
);
}
sdssplitargs_free
(
argv
,
argc
);
}
zfree
(
line
);
fclose
(
fp
);
/* Config sanity check */
redisAssert
(
server
.
cluster
.
myself
!=
NULL
);
redisLog
(
REDIS_NOTICE
,
"Node configuration loaded, I'm %.40s"
,
server
.
cluster
.
myself
->
name
);
clusterUpdateState
();
return
REDIS_OK
;
fmterr:
redisLog
(
REDIS_WARNING
,
"Unrecovarable error: corrupted cluster config file."
);
fclose
(
fp
);
exit
(
1
);
}
/* Cluster node configuration is exactly the same as CLUSTER NODES output.
*
* This function writes the node config and returns 0, on error -1
* is returned. */
int
clusterSaveConfig
(
void
)
{
sds
ci
=
clusterGenNodesDescription
();
int
fd
;
if
((
fd
=
open
(
server
.
cluster
.
configfile
,
O_WRONLY
|
O_CREAT
|
O_TRUNC
,
0644
))
==
-
1
)
goto
err
;
if
(
write
(
fd
,
ci
,
sdslen
(
ci
))
!=
(
ssize_t
)
sdslen
(
ci
))
goto
err
;
close
(
fd
);
sdsfree
(
ci
);
return
0
;
err:
sdsfree
(
ci
);
return
-
1
;
}
void
clusterSaveConfigOrDie
(
void
)
{
if
(
clusterSaveConfig
()
==
-
1
)
{
redisLog
(
REDIS_WARNING
,
"Fatal: can't update cluster config file."
);
exit
(
1
);
}
}
void
clusterInit
(
void
)
{
int
saveconf
=
0
;
server
.
cluster
.
myself
=
NULL
;
server
.
cluster
.
state
=
REDIS_CLUSTER_FAIL
;
server
.
cluster
.
nodes
=
dictCreate
(
&
clusterNodesDictType
,
NULL
);
server
.
cluster
.
node_timeout
=
15
;
memset
(
server
.
cluster
.
migrating_slots_to
,
0
,
sizeof
(
server
.
cluster
.
migrating_slots_to
));
memset
(
server
.
cluster
.
importing_slots_from
,
0
,
sizeof
(
server
.
cluster
.
importing_slots_from
));
memset
(
server
.
cluster
.
slots
,
0
,
sizeof
(
server
.
cluster
.
slots
));
if
(
clusterLoadConfig
(
server
.
cluster
.
configfile
)
==
REDIS_ERR
)
{
/* No configuration found. We will just use the random name provided
* by the createClusterNode() function. */
server
.
cluster
.
myself
=
createClusterNode
(
NULL
,
REDIS_NODE_MYSELF
);
redisLog
(
REDIS_NOTICE
,
"No cluster configuration found, I'm %.40s"
,
server
.
cluster
.
myself
->
name
);
clusterAddNode
(
server
.
cluster
.
myself
);
saveconf
=
1
;
}
if
(
saveconf
)
clusterSaveConfigOrDie
();
/* We need a listening TCP port for our cluster messaging needs */
server
.
cfd
=
anetTcpServer
(
server
.
neterr
,
server
.
port
+
REDIS_CLUSTER_PORT_INCR
,
server
.
bindaddr
);
if
(
server
.
cfd
==
-
1
)
{
redisLog
(
REDIS_WARNING
,
"Opening cluster TCP port: %s"
,
server
.
neterr
);
exit
(
1
);
}
if
(
aeCreateFileEvent
(
server
.
el
,
server
.
cfd
,
AE_READABLE
,
clusterAcceptHandler
,
NULL
)
==
AE_ERR
)
oom
(
"creating file event"
);
server
.
cluster
.
slots_to_keys
=
zslCreate
();
}
/* -----------------------------------------------------------------------------
* CLUSTER communication link
* -------------------------------------------------------------------------- */
clusterLink
*
createClusterLink
(
clusterNode
*
node
)
{
clusterLink
*
link
=
zmalloc
(
sizeof
(
*
link
));
link
->
sndbuf
=
sdsempty
();
link
->
rcvbuf
=
sdsempty
();
link
->
node
=
node
;
link
->
fd
=
-
1
;
return
link
;
}
/* Free a cluster link, but does not free the associated node of course.
* Just this function will make sure that the original node associated
* with this link will have the 'link' field set to NULL. */
void
freeClusterLink
(
clusterLink
*
link
)
{
if
(
link
->
fd
!=
-
1
)
{
aeDeleteFileEvent
(
server
.
el
,
link
->
fd
,
AE_WRITABLE
);
aeDeleteFileEvent
(
server
.
el
,
link
->
fd
,
AE_READABLE
);
}
sdsfree
(
link
->
sndbuf
);
sdsfree
(
link
->
rcvbuf
);
if
(
link
->
node
)
link
->
node
->
link
=
NULL
;
close
(
link
->
fd
);
zfree
(
link
);
}
void
clusterAcceptHandler
(
aeEventLoop
*
el
,
int
fd
,
void
*
privdata
,
int
mask
)
{
int
cport
,
cfd
;
char
cip
[
128
];
clusterLink
*
link
;
REDIS_NOTUSED
(
el
);
REDIS_NOTUSED
(
mask
);
REDIS_NOTUSED
(
privdata
);
cfd
=
anetTcpAccept
(
server
.
neterr
,
fd
,
cip
,
&
cport
);
if
(
cfd
==
AE_ERR
)
{
redisLog
(
REDIS_VERBOSE
,
"Accepting cluster node: %s"
,
server
.
neterr
);
return
;
}
redisLog
(
REDIS_VERBOSE
,
"Accepted cluster node %s:%d"
,
cip
,
cport
);
/* We need to create a temporary node in order to read the incoming
* packet in a valid contest. This node will be released once we
* read the packet and reply. */
link
=
createClusterLink
(
NULL
);
link
->
fd
=
cfd
;
aeCreateFileEvent
(
server
.
el
,
cfd
,
AE_READABLE
,
clusterReadHandler
,
link
);
}
/* -----------------------------------------------------------------------------
* Key space handling
* -------------------------------------------------------------------------- */
/* We have 4096 hash slots. The hash slot of a given key is obtained
* as the least significant 12 bits of the crc16 of the key. */
unsigned
int
keyHashSlot
(
char
*
key
,
int
keylen
)
{
return
crc16
(
key
,
keylen
)
&
0x0FFF
;
}
/* -----------------------------------------------------------------------------
* CLUSTER node API
* -------------------------------------------------------------------------- */
/* Create a new cluster node, with the specified flags.
* If "nodename" is NULL this is considered a first handshake and a random
* node name is assigned to this node (it will be fixed later when we'll
* receive the first pong).
*
* The node is created and returned to the user, but it is not automatically
* added to the nodes hash table. */
clusterNode
*
createClusterNode
(
char
*
nodename
,
int
flags
)
{
clusterNode
*
node
=
zmalloc
(
sizeof
(
*
node
));
if
(
nodename
)
memcpy
(
node
->
name
,
nodename
,
REDIS_CLUSTER_NAMELEN
);
else
clusterGetRandomName
(
node
->
name
);
node
->
flags
=
flags
;
memset
(
node
->
slots
,
0
,
sizeof
(
node
->
slots
));
node
->
numslaves
=
0
;
node
->
slaves
=
NULL
;
node
->
slaveof
=
NULL
;
node
->
ping_sent
=
node
->
pong_received
=
0
;
node
->
configdigest
=
NULL
;
node
->
configdigest_ts
=
0
;
node
->
link
=
NULL
;
return
node
;
}
int
clusterNodeRemoveSlave
(
clusterNode
*
master
,
clusterNode
*
slave
)
{
int
j
;
for
(
j
=
0
;
j
<
master
->
numslaves
;
j
++
)
{
if
(
master
->
slaves
[
j
]
==
slave
)
{
memmove
(
master
->
slaves
+
j
,
master
->
slaves
+
(
j
+
1
),
(
master
->
numslaves
-
1
)
-
j
);
master
->
numslaves
--
;
return
REDIS_OK
;
}
}
return
REDIS_ERR
;
}
int
clusterNodeAddSlave
(
clusterNode
*
master
,
clusterNode
*
slave
)
{
int
j
;
/* If it's already a slave, don't add it again. */
for
(
j
=
0
;
j
<
master
->
numslaves
;
j
++
)
if
(
master
->
slaves
[
j
]
==
slave
)
return
REDIS_ERR
;
master
->
slaves
=
zrealloc
(
master
->
slaves
,
sizeof
(
clusterNode
*
)
*
(
master
->
numslaves
+
1
));
master
->
slaves
[
master
->
numslaves
]
=
slave
;
master
->
numslaves
++
;
return
REDIS_OK
;
}
void
clusterNodeResetSlaves
(
clusterNode
*
n
)
{
zfree
(
n
->
slaves
);
n
->
numslaves
=
0
;
}
void
freeClusterNode
(
clusterNode
*
n
)
{
sds
nodename
;
nodename
=
sdsnewlen
(
n
->
name
,
REDIS_CLUSTER_NAMELEN
);
redisAssert
(
dictDelete
(
server
.
cluster
.
nodes
,
nodename
)
==
DICT_OK
);
sdsfree
(
nodename
);
if
(
n
->
slaveof
)
clusterNodeRemoveSlave
(
n
->
slaveof
,
n
);
if
(
n
->
link
)
freeClusterLink
(
n
->
link
);
zfree
(
n
);
}
/* Add a node to the nodes hash table */
int
clusterAddNode
(
clusterNode
*
node
)
{
int
retval
;
retval
=
dictAdd
(
server
.
cluster
.
nodes
,
sdsnewlen
(
node
->
name
,
REDIS_CLUSTER_NAMELEN
),
node
);
return
(
retval
==
DICT_OK
)
?
REDIS_OK
:
REDIS_ERR
;
}
/* Node lookup by name */
clusterNode
*
clusterLookupNode
(
char
*
name
)
{
sds
s
=
sdsnewlen
(
name
,
REDIS_CLUSTER_NAMELEN
);
struct
dictEntry
*
de
;
de
=
dictFind
(
server
.
cluster
.
nodes
,
s
);
sdsfree
(
s
);
if
(
de
==
NULL
)
return
NULL
;
return
dictGetEntryVal
(
de
);
}
/* This is only used after the handshake. When we connect a given IP/PORT
* as a result of CLUSTER MEET we don't have the node name yet, so we
* pick a random one, and will fix it when we receive the PONG request using
* this function. */
void
clusterRenameNode
(
clusterNode
*
node
,
char
*
newname
)
{
int
retval
;
sds
s
=
sdsnewlen
(
node
->
name
,
REDIS_CLUSTER_NAMELEN
);
redisLog
(
REDIS_DEBUG
,
"Renaming node %.40s into %.40s"
,
node
->
name
,
newname
);
retval
=
dictDelete
(
server
.
cluster
.
nodes
,
s
);
sdsfree
(
s
);
redisAssert
(
retval
==
DICT_OK
);
memcpy
(
node
->
name
,
newname
,
REDIS_CLUSTER_NAMELEN
);
clusterAddNode
(
node
);
}
/* -----------------------------------------------------------------------------
* CLUSTER messages exchange - PING/PONG and gossip
* -------------------------------------------------------------------------- */
/* Process the gossip section of PING or PONG packets.
* Note that this function assumes that the packet is already sanity-checked
* by the caller, not in the content of the gossip section, but in the
* length. */
void
clusterProcessGossipSection
(
clusterMsg
*
hdr
,
clusterLink
*
link
)
{
uint16_t
count
=
ntohs
(
hdr
->
count
);
clusterMsgDataGossip
*
g
=
(
clusterMsgDataGossip
*
)
hdr
->
data
.
ping
.
gossip
;
clusterNode
*
sender
=
link
->
node
?
link
->
node
:
clusterLookupNode
(
hdr
->
sender
);
while
(
count
--
)
{
sds
ci
=
sdsempty
();
uint16_t
flags
=
ntohs
(
g
->
flags
);
clusterNode
*
node
;
if
(
flags
==
0
)
ci
=
sdscat
(
ci
,
"noflags,"
);
if
(
flags
&
REDIS_NODE_MYSELF
)
ci
=
sdscat
(
ci
,
"myself,"
);
if
(
flags
&
REDIS_NODE_MASTER
)
ci
=
sdscat
(
ci
,
"master,"
);
if
(
flags
&
REDIS_NODE_SLAVE
)
ci
=
sdscat
(
ci
,
"slave,"
);
if
(
flags
&
REDIS_NODE_PFAIL
)
ci
=
sdscat
(
ci
,
"fail?,"
);
if
(
flags
&
REDIS_NODE_FAIL
)
ci
=
sdscat
(
ci
,
"fail,"
);
if
(
flags
&
REDIS_NODE_HANDSHAKE
)
ci
=
sdscat
(
ci
,
"handshake,"
);
if
(
flags
&
REDIS_NODE_NOADDR
)
ci
=
sdscat
(
ci
,
"noaddr,"
);
if
(
ci
[
sdslen
(
ci
)
-
1
]
==
','
)
ci
[
sdslen
(
ci
)
-
1
]
=
' '
;
redisLog
(
REDIS_DEBUG
,
"GOSSIP %.40s %s:%d %s"
,
g
->
nodename
,
g
->
ip
,
ntohs
(
g
->
port
),
ci
);
sdsfree
(
ci
);
/* Update our state accordingly to the gossip sections */
node
=
clusterLookupNode
(
g
->
nodename
);
if
(
node
!=
NULL
)
{
/* We already know this node. Let's start updating the last
* time PONG figure if it is newer than our figure.
* Note that it's not a problem if we have a PING already
* in progress against this node. */
if
(
node
->
pong_received
<
ntohl
(
g
->
pong_received
))
{
redisLog
(
REDIS_DEBUG
,
"Node pong_received updated by gossip"
);
node
->
pong_received
=
ntohl
(
g
->
pong_received
);
}
/* Mark this node as FAILED if we think it is possibly failing
* and another node also thinks it's failing. */
if
(
node
->
flags
&
REDIS_NODE_PFAIL
&&
(
flags
&
(
REDIS_NODE_FAIL
|
REDIS_NODE_PFAIL
)))
{
redisLog
(
REDIS_NOTICE
,
"Received a PFAIL acknowledge from node %.40s, marking node %.40s as FAIL!"
,
hdr
->
sender
,
node
->
name
);
node
->
flags
&=
~
REDIS_NODE_PFAIL
;
node
->
flags
|=
REDIS_NODE_FAIL
;
/* Broadcast the failing node name to everybody */
clusterSendFail
(
node
->
name
);
clusterUpdateState
();
clusterSaveConfigOrDie
();
}
}
else
{
/* If it's not in NOADDR state and we don't have it, we
* start an handshake process against this IP/PORT pairs.
*
* Note that we require that the sender of this gossip message
* is a well known node in our cluster, otherwise we risk
* joining another cluster. */
if
(
sender
&&
!
(
flags
&
REDIS_NODE_NOADDR
))
{
clusterNode
*
newnode
;
redisLog
(
REDIS_DEBUG
,
"Adding the new node"
);
newnode
=
createClusterNode
(
NULL
,
REDIS_NODE_HANDSHAKE
);
memcpy
(
newnode
->
ip
,
g
->
ip
,
sizeof
(
g
->
ip
));
newnode
->
port
=
ntohs
(
g
->
port
);
clusterAddNode
(
newnode
);
}
}
/* Next node */
g
++
;
}
}
/* IP -> string conversion. 'buf' is supposed to at least be 16 bytes. */
void
nodeIp2String
(
char
*
buf
,
clusterLink
*
link
)
{
struct
sockaddr_in
sa
;
socklen_t
salen
=
sizeof
(
sa
);
if
(
getpeername
(
link
->
fd
,
(
struct
sockaddr
*
)
&
sa
,
&
salen
)
==
-
1
)
redisPanic
(
"getpeername() failed."
);
strncpy
(
buf
,
inet_ntoa
(
sa
.
sin_addr
),
sizeof
(
link
->
node
->
ip
));
}
/* Update the node address to the IP address that can be extracted
* from link->fd, and at the specified port. */
void
nodeUpdateAddress
(
clusterNode
*
node
,
clusterLink
*
link
,
int
port
)
{
}
/* When this function is called, there is a packet to process starting
* at node->rcvbuf. Releasing the buffer is up to the caller, so this
* function should just handle the higher level stuff of processing the
* packet, modifying the cluster state if needed.
*
* The function returns 1 if the link is still valid after the packet
* was processed, otherwise 0 if the link was freed since the packet
* processing lead to some inconsistency error (for instance a PONG
* received from the wrong sender ID). */
int
clusterProcessPacket
(
clusterLink
*
link
)
{
clusterMsg
*
hdr
=
(
clusterMsg
*
)
link
->
rcvbuf
;
uint32_t
totlen
=
ntohl
(
hdr
->
totlen
);
uint16_t
type
=
ntohs
(
hdr
->
type
);
clusterNode
*
sender
;
redisLog
(
REDIS_DEBUG
,
"--- packet to process %lu bytes (%lu) ---"
,
(
unsigned
long
)
totlen
,
sdslen
(
link
->
rcvbuf
));
if
(
totlen
<
8
)
return
1
;
if
(
totlen
>
sdslen
(
link
->
rcvbuf
))
return
1
;
if
(
type
==
CLUSTERMSG_TYPE_PING
||
type
==
CLUSTERMSG_TYPE_PONG
||
type
==
CLUSTERMSG_TYPE_MEET
)
{
uint16_t
count
=
ntohs
(
hdr
->
count
);
uint32_t
explen
;
/* expected length of this packet */
explen
=
sizeof
(
clusterMsg
)
-
sizeof
(
union
clusterMsgData
);
explen
+=
(
sizeof
(
clusterMsgDataGossip
)
*
count
);
if
(
totlen
!=
explen
)
return
1
;
}
if
(
type
==
CLUSTERMSG_TYPE_FAIL
)
{
uint32_t
explen
=
sizeof
(
clusterMsg
)
-
sizeof
(
union
clusterMsgData
);
explen
+=
sizeof
(
clusterMsgDataFail
);
if
(
totlen
!=
explen
)
return
1
;
}
sender
=
clusterLookupNode
(
hdr
->
sender
);
if
(
type
==
CLUSTERMSG_TYPE_PING
||
type
==
CLUSTERMSG_TYPE_MEET
)
{
int
update_config
=
0
;
redisLog
(
REDIS_DEBUG
,
"Ping packet received: %p"
,
link
->
node
);
/* Add this node if it is new for us and the msg type is MEET.
* In this stage we don't try to add the node with the right
* flags, slaveof pointer, and so forth, as this details will be
* resolved when we'll receive PONGs from the server. */
if
(
!
sender
&&
type
==
CLUSTERMSG_TYPE_MEET
)
{
clusterNode
*
node
;
node
=
createClusterNode
(
NULL
,
REDIS_NODE_HANDSHAKE
);
nodeIp2String
(
node
->
ip
,
link
);
node
->
port
=
ntohs
(
hdr
->
port
);
clusterAddNode
(
node
);
update_config
=
1
;
}
/* Get info from the gossip section */
clusterProcessGossipSection
(
hdr
,
link
);
/* Anyway reply with a PONG */
clusterSendPing
(
link
,
CLUSTERMSG_TYPE_PONG
);
/* Update config if needed */
if
(
update_config
)
clusterSaveConfigOrDie
();
}
else
if
(
type
==
CLUSTERMSG_TYPE_PONG
)
{
int
update_state
=
0
;
int
update_config
=
0
;
redisLog
(
REDIS_DEBUG
,
"Pong packet received: %p"
,
link
->
node
);
if
(
link
->
node
)
{
if
(
link
->
node
->
flags
&
REDIS_NODE_HANDSHAKE
)
{
/* If we already have this node, try to change the
* IP/port of the node with the new one. */
if
(
sender
)
{
redisLog
(
REDIS_WARNING
,
"Handshake error: we already know node %.40s, updating the address if needed."
,
sender
->
name
);
nodeUpdateAddress
(
sender
,
link
,
ntohs
(
hdr
->
port
));
freeClusterNode
(
link
->
node
);
/* will free the link too */
return
0
;
}
/* First thing to do is replacing the random name with the
* right node name if this was an handshake stage. */
clusterRenameNode
(
link
->
node
,
hdr
->
sender
);
redisLog
(
REDIS_DEBUG
,
"Handshake with node %.40s completed."
,
link
->
node
->
name
);
link
->
node
->
flags
&=
~
REDIS_NODE_HANDSHAKE
;
update_config
=
1
;
}
else
if
(
memcmp
(
link
->
node
->
name
,
hdr
->
sender
,
REDIS_CLUSTER_NAMELEN
)
!=
0
)
{
/* If the reply has a non matching node ID we
* disconnect this node and set it as not having an associated
* address. */
redisLog
(
REDIS_DEBUG
,
"PONG contains mismatching sender ID"
);
link
->
node
->
flags
|=
REDIS_NODE_NOADDR
;
freeClusterLink
(
link
);
update_config
=
1
;
/* FIXME: remove this node if we already have it.
*
* If we already have it but the IP is different, use
* the new one if the old node is in FAIL, PFAIL, or NOADDR
* status... */
return
0
;
}
}
/* Update our info about the node */
link
->
node
->
pong_received
=
time
(
NULL
);
/* Update master/slave info */
if
(
sender
)
{
if
(
!
memcmp
(
hdr
->
slaveof
,
REDIS_NODE_NULL_NAME
,
sizeof
(
hdr
->
slaveof
)))
{
sender
->
flags
&=
~
REDIS_NODE_SLAVE
;
sender
->
flags
|=
REDIS_NODE_MASTER
;
sender
->
slaveof
=
NULL
;
}
else
{
clusterNode
*
master
=
clusterLookupNode
(
hdr
->
slaveof
);
sender
->
flags
&=
~
REDIS_NODE_MASTER
;
sender
->
flags
|=
REDIS_NODE_SLAVE
;
if
(
sender
->
numslaves
)
clusterNodeResetSlaves
(
sender
);
if
(
master
)
clusterNodeAddSlave
(
master
,
sender
);
}
}
/* Update our info about served slots if this new node is serving
* slots that are not served from our point of view. */
if
(
sender
&&
sender
->
flags
&
REDIS_NODE_MASTER
)
{
int
newslots
,
j
;
newslots
=
memcmp
(
sender
->
slots
,
hdr
->
myslots
,
sizeof
(
hdr
->
myslots
))
!=
0
;
memcpy
(
sender
->
slots
,
hdr
->
myslots
,
sizeof
(
hdr
->
myslots
));
if
(
newslots
)
{
for
(
j
=
0
;
j
<
REDIS_CLUSTER_SLOTS
;
j
++
)
{
if
(
clusterNodeGetSlotBit
(
sender
,
j
))
{
if
(
server
.
cluster
.
slots
[
j
]
==
sender
)
continue
;
if
(
server
.
cluster
.
slots
[
j
]
==
NULL
||
server
.
cluster
.
slots
[
j
]
->
flags
&
REDIS_NODE_FAIL
)
{
server
.
cluster
.
slots
[
j
]
=
sender
;
update_state
=
update_config
=
1
;
}
}
}
}
}
/* Get info from the gossip section */
clusterProcessGossipSection
(
hdr
,
link
);
/* Update the cluster state if needed */
if
(
update_state
)
clusterUpdateState
();
if
(
update_config
)
clusterSaveConfigOrDie
();
}
else
if
(
type
==
CLUSTERMSG_TYPE_FAIL
&&
sender
)
{
clusterNode
*
failing
;
failing
=
clusterLookupNode
(
hdr
->
data
.
fail
.
about
.
nodename
);
if
(
failing
&&
!
(
failing
->
flags
&
(
REDIS_NODE_FAIL
|
REDIS_NODE_MYSELF
)))
{
redisLog
(
REDIS_NOTICE
,
"FAIL message received from %.40s about %.40s"
,
hdr
->
sender
,
hdr
->
data
.
fail
.
about
.
nodename
);
failing
->
flags
|=
REDIS_NODE_FAIL
;
failing
->
flags
&=
~
REDIS_NODE_PFAIL
;
clusterUpdateState
();
clusterSaveConfigOrDie
();
}
}
else
{
redisLog
(
REDIS_NOTICE
,
"Received unknown packet type: %d"
,
type
);
}
return
1
;
}
/* This function is called when we detect the link with this node is lost.
We set the node as no longer connected. The Cluster Cron will detect
this connection and will try to get it connected again.
Instead if the node is a temporary node used to accept a query, we
completely free the node on error. */
void
handleLinkIOError
(
clusterLink
*
link
)
{
freeClusterLink
(
link
);
}
/* Send data. This is handled using a trivial send buffer that gets
* consumed by write(). We don't try to optimize this for speed too much
* as this is a very low traffic channel. */
void
clusterWriteHandler
(
aeEventLoop
*
el
,
int
fd
,
void
*
privdata
,
int
mask
)
{
clusterLink
*
link
=
(
clusterLink
*
)
privdata
;
ssize_t
nwritten
;
REDIS_NOTUSED
(
el
);
REDIS_NOTUSED
(
mask
);
nwritten
=
write
(
fd
,
link
->
sndbuf
,
sdslen
(
link
->
sndbuf
));
if
(
nwritten
<=
0
)
{
redisLog
(
REDIS_NOTICE
,
"I/O error writing to node link: %s"
,
strerror
(
errno
));
handleLinkIOError
(
link
);
return
;
}
link
->
sndbuf
=
sdsrange
(
link
->
sndbuf
,
nwritten
,
-
1
);
if
(
sdslen
(
link
->
sndbuf
)
==
0
)
aeDeleteFileEvent
(
server
.
el
,
link
->
fd
,
AE_WRITABLE
);
}
/* Read data. Try to read the first field of the header first to check the
* full length of the packet. When a whole packet is in memory this function
* will call the function to process the packet. And so forth. */
void
clusterReadHandler
(
aeEventLoop
*
el
,
int
fd
,
void
*
privdata
,
int
mask
)
{
char
buf
[
1024
];
ssize_t
nread
;
clusterMsg
*
hdr
;
clusterLink
*
link
=
(
clusterLink
*
)
privdata
;
int
readlen
;
REDIS_NOTUSED
(
el
);
REDIS_NOTUSED
(
mask
);
again:
if
(
sdslen
(
link
->
rcvbuf
)
>=
4
)
{
hdr
=
(
clusterMsg
*
)
link
->
rcvbuf
;
readlen
=
ntohl
(
hdr
->
totlen
)
-
sdslen
(
link
->
rcvbuf
);
}
else
{
readlen
=
4
-
sdslen
(
link
->
rcvbuf
);
}
nread
=
read
(
fd
,
buf
,
readlen
);
if
(
nread
==
-
1
&&
errno
==
EAGAIN
)
return
;
/* Just no data */
if
(
nread
<=
0
)
{
/* I/O error... */
redisLog
(
REDIS_NOTICE
,
"I/O error reading from node link: %s"
,
(
nread
==
0
)
?
"connection closed"
:
strerror
(
errno
));
handleLinkIOError
(
link
);
return
;
}
else
{
/* Read data and recast the pointer to the new buffer. */
link
->
rcvbuf
=
sdscatlen
(
link
->
rcvbuf
,
buf
,
nread
);
hdr
=
(
clusterMsg
*
)
link
->
rcvbuf
;
}
/* Total length obtained? read the payload now instead of burning
* cycles waiting for a new event to fire. */
if
(
sdslen
(
link
->
rcvbuf
)
==
4
)
goto
again
;
/* Whole packet in memory? We can process it. */
if
(
sdslen
(
link
->
rcvbuf
)
==
ntohl
(
hdr
->
totlen
))
{
if
(
clusterProcessPacket
(
link
))
{
sdsfree
(
link
->
rcvbuf
);
link
->
rcvbuf
=
sdsempty
();
}
}
}
/* Put stuff into the send buffer. */
void
clusterSendMessage
(
clusterLink
*
link
,
unsigned
char
*
msg
,
size_t
msglen
)
{
if
(
sdslen
(
link
->
sndbuf
)
==
0
&&
msglen
!=
0
)
aeCreateFileEvent
(
server
.
el
,
link
->
fd
,
AE_WRITABLE
,
clusterWriteHandler
,
link
);
link
->
sndbuf
=
sdscatlen
(
link
->
sndbuf
,
msg
,
msglen
);
}
/* Build the message header */
void
clusterBuildMessageHdr
(
clusterMsg
*
hdr
,
int
type
)
{
int
totlen
;
memset
(
hdr
,
0
,
sizeof
(
*
hdr
));
hdr
->
type
=
htons
(
type
);
memcpy
(
hdr
->
sender
,
server
.
cluster
.
myself
->
name
,
REDIS_CLUSTER_NAMELEN
);
memcpy
(
hdr
->
myslots
,
server
.
cluster
.
myself
->
slots
,
sizeof
(
hdr
->
myslots
));
memset
(
hdr
->
slaveof
,
0
,
REDIS_CLUSTER_NAMELEN
);
if
(
server
.
cluster
.
myself
->
slaveof
!=
NULL
)
{
memcpy
(
hdr
->
slaveof
,
server
.
cluster
.
myself
->
slaveof
->
name
,
REDIS_CLUSTER_NAMELEN
);
}
hdr
->
port
=
htons
(
server
.
port
);
hdr
->
state
=
server
.
cluster
.
state
;
memset
(
hdr
->
configdigest
,
0
,
32
);
/* FIXME: set config digest */
if
(
type
==
CLUSTERMSG_TYPE_FAIL
)
{
totlen
=
sizeof
(
clusterMsg
)
-
sizeof
(
union
clusterMsgData
);
totlen
+=
sizeof
(
clusterMsgDataFail
);
}
hdr
->
totlen
=
htonl
(
totlen
);
/* For PING, PONG, and MEET, fixing the totlen field is up to the caller */
}
/* 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
[
1024
];
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
;
if
(
link
->
node
&&
type
==
CLUSTERMSG_TYPE_PING
)
link
->
node
->
ping_sent
=
time
(
NULL
);
clusterBuildMessageHdr
(
hdr
,
type
);
/* Populate the gossip fields */
while
(
freshnodes
>
0
&&
gossipcount
<
3
)
{
struct
dictEntry
*
de
=
dictGetRandomKey
(
server
.
cluster
.
nodes
);
clusterNode
*
this
=
dictGetEntryVal
(
de
);
clusterMsgDataGossip
*
gossip
;
int
j
;
/* Not interesting to gossip about ourself.
* Nor to send gossip info about HANDSHAKE state nodes (zero info). */
if
(
this
==
server
.
cluster
.
myself
||
this
->
flags
&
REDIS_NODE_HANDSHAKE
)
{
freshnodes
--
;
/* otherwise we may loop forever. */
continue
;
}
/* Check if we already added this node */
for
(
j
=
0
;
j
<
gossipcount
;
j
++
)
{
if
(
memcmp
(
hdr
->
data
.
ping
.
gossip
[
j
].
nodename
,
this
->
name
,
REDIS_CLUSTER_NAMELEN
)
==
0
)
break
;
}
if
(
j
!=
gossipcount
)
continue
;
/* Add it */
freshnodes
--
;
gossip
=
&
(
hdr
->
data
.
ping
.
gossip
[
gossipcount
]);
memcpy
(
gossip
->
nodename
,
this
->
name
,
REDIS_CLUSTER_NAMELEN
);
gossip
->
ping_sent
=
htonl
(
this
->
ping_sent
);
gossip
->
pong_received
=
htonl
(
this
->
pong_received
);
memcpy
(
gossip
->
ip
,
this
->
ip
,
sizeof
(
this
->
ip
));
gossip
->
port
=
htons
(
this
->
port
);
gossip
->
flags
=
htons
(
this
->
flags
);
gossipcount
++
;
}
totlen
=
sizeof
(
clusterMsg
)
-
sizeof
(
union
clusterMsgData
);
totlen
+=
(
sizeof
(
clusterMsgDataGossip
)
*
gossipcount
);
hdr
->
count
=
htons
(
gossipcount
);
hdr
->
totlen
=
htonl
(
totlen
);
clusterSendMessage
(
link
,
buf
,
totlen
);
}
/* Send a message to all the nodes with a reliable link */
void
clusterBroadcastMessage
(
void
*
buf
,
size_t
len
)
{
dictIterator
*
di
;
dictEntry
*
de
;
di
=
dictGetIterator
(
server
.
cluster
.
nodes
);
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
clusterNode
*
node
=
dictGetEntryVal
(
de
);
if
(
!
node
->
link
)
continue
;
if
(
node
->
flags
&
(
REDIS_NODE_MYSELF
|
REDIS_NODE_NOADDR
))
continue
;
clusterSendMessage
(
node
->
link
,
buf
,
len
);
}
dictReleaseIterator
(
di
);
}
/* Send a FAIL message to all the nodes we are able to contact.
* The FAIL message is sent when we detect that a node is failing
* (REDIS_NODE_PFAIL) and we also receive a gossip confirmation of this:
* we switch the node state to REDIS_NODE_FAIL and ask all the other
* nodes to do the same ASAP. */
void
clusterSendFail
(
char
*
nodename
)
{
unsigned
char
buf
[
1024
];
clusterMsg
*
hdr
=
(
clusterMsg
*
)
buf
;
clusterBuildMessageHdr
(
hdr
,
CLUSTERMSG_TYPE_FAIL
);
memcpy
(
hdr
->
data
.
fail
.
about
.
nodename
,
nodename
,
REDIS_CLUSTER_NAMELEN
);
clusterBroadcastMessage
(
buf
,
ntohl
(
hdr
->
totlen
));
}
/* -----------------------------------------------------------------------------
* CLUSTER cron job
* -------------------------------------------------------------------------- */
/* This is executed 1 time every second */
void
clusterCron
(
void
)
{
dictIterator
*
di
;
dictEntry
*
de
;
int
j
;
time_t
min_ping_sent
=
0
;
clusterNode
*
min_ping_node
=
NULL
;
/* Check if we have disconnected nodes and reestablish the connection. */
di
=
dictGetIterator
(
server
.
cluster
.
nodes
);
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
clusterNode
*
node
=
dictGetEntryVal
(
de
);
if
(
node
->
flags
&
(
REDIS_NODE_MYSELF
|
REDIS_NODE_NOADDR
))
continue
;
if
(
node
->
link
==
NULL
)
{
int
fd
;
clusterLink
*
link
;
fd
=
anetTcpNonBlockConnect
(
server
.
neterr
,
node
->
ip
,
node
->
port
+
REDIS_CLUSTER_PORT_INCR
);
if
(
fd
==
-
1
)
continue
;
link
=
createClusterLink
(
node
);
link
->
fd
=
fd
;
node
->
link
=
link
;
aeCreateFileEvent
(
server
.
el
,
link
->
fd
,
AE_READABLE
,
clusterReadHandler
,
link
);
/* If the node is flagged as MEET, we send a MEET message instead
* of a PING one, to force the receiver to add us in its node
* table. */
clusterSendPing
(
link
,
node
->
flags
&
REDIS_NODE_MEET
?
CLUSTERMSG_TYPE_MEET
:
CLUSTERMSG_TYPE_PING
);
/* We can clear the flag after the first packet is sent.
* If we'll never receive a PONG, we'll never send new packets
* to this node. Instead after the PONG is received and we
* are no longer in meet/handshake status, we want to send
* normal PING packets. */
node
->
flags
&=
~
REDIS_NODE_MEET
;
redisLog
(
REDIS_NOTICE
,
"Connecting with Node %.40s at %s:%d"
,
node
->
name
,
node
->
ip
,
node
->
port
+
REDIS_CLUSTER_PORT_INCR
);
}
}
dictReleaseIterator
(
di
);
/* Ping some random node. Check a few random nodes and ping the one with
* the oldest ping_sent time */
for
(
j
=
0
;
j
<
5
;
j
++
)
{
de
=
dictGetRandomKey
(
server
.
cluster
.
nodes
);
clusterNode
*
this
=
dictGetEntryVal
(
de
);
if
(
this
->
link
==
NULL
)
continue
;
if
(
this
->
flags
&
(
REDIS_NODE_MYSELF
|
REDIS_NODE_HANDSHAKE
))
continue
;
if
(
min_ping_node
==
NULL
||
min_ping_sent
>
this
->
ping_sent
)
{
min_ping_node
=
this
;
min_ping_sent
=
this
->
ping_sent
;
}
}
if
(
min_ping_node
)
{
redisLog
(
REDIS_DEBUG
,
"Pinging node %40s"
,
min_ping_node
->
name
);
clusterSendPing
(
min_ping_node
->
link
,
CLUSTERMSG_TYPE_PING
);
}
/* Iterate nodes to check if we need to flag something as failing */
di
=
dictGetIterator
(
server
.
cluster
.
nodes
);
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
clusterNode
*
node
=
dictGetEntryVal
(
de
);
int
delay
;
if
(
node
->
flags
&
(
REDIS_NODE_MYSELF
|
REDIS_NODE_NOADDR
|
REDIS_NODE_HANDSHAKE
))
continue
;
/* Check only if we already sent a ping and did not received
* a reply yet. */
if
(
node
->
ping_sent
==
0
||
node
->
ping_sent
<=
node
->
pong_received
)
continue
;
delay
=
time
(
NULL
)
-
node
->
pong_received
;
if
(
delay
<
server
.
cluster
.
node_timeout
)
{
/* The PFAIL condition can be reversed without external
* help if it is not transitive (that is, if it does not
* turn into a FAIL state).
*
* The FAIL condition is also reversible if there are no slaves
* for this host, so no slave election should be in progress.
*
* TODO: consider all the implications of resurrecting a
* FAIL node. */
if
(
node
->
flags
&
REDIS_NODE_PFAIL
)
{
node
->
flags
&=
~
REDIS_NODE_PFAIL
;
}
else
if
(
node
->
flags
&
REDIS_NODE_FAIL
&&
!
node
->
numslaves
)
{
node
->
flags
&=
~
REDIS_NODE_FAIL
;
clusterUpdateState
();
}
}
else
{
/* Timeout reached. Set the noad se possibly failing if it is
* not already in this state. */
if
(
!
(
node
->
flags
&
(
REDIS_NODE_PFAIL
|
REDIS_NODE_FAIL
)))
{
redisLog
(
REDIS_DEBUG
,
"*** NODE %.40s possibly failing"
,
node
->
name
);
node
->
flags
|=
REDIS_NODE_PFAIL
;
}
}
}
dictReleaseIterator
(
di
);
}
/* -----------------------------------------------------------------------------
* Slots management
* -------------------------------------------------------------------------- */
/* Set the slot bit and return the old value. */
int
clusterNodeSetSlotBit
(
clusterNode
*
n
,
int
slot
)
{
off_t
byte
=
slot
/
8
;
int
bit
=
slot
&
7
;
int
old
=
(
n
->
slots
[
byte
]
&
(
1
<<
bit
))
!=
0
;
n
->
slots
[
byte
]
|=
1
<<
bit
;
return
old
;
}
/* Clear the slot bit and return the old value. */
int
clusterNodeClearSlotBit
(
clusterNode
*
n
,
int
slot
)
{
off_t
byte
=
slot
/
8
;
int
bit
=
slot
&
7
;
int
old
=
(
n
->
slots
[
byte
]
&
(
1
<<
bit
))
!=
0
;
n
->
slots
[
byte
]
&=
~
(
1
<<
bit
);
return
old
;
}
/* Return the slot bit from the cluster node structure. */
int
clusterNodeGetSlotBit
(
clusterNode
*
n
,
int
slot
)
{
off_t
byte
=
slot
/
8
;
int
bit
=
slot
&
7
;
return
(
n
->
slots
[
byte
]
&
(
1
<<
bit
))
!=
0
;
}
/* Add the specified slot to the list of slots that node 'n' will
* serve. Return REDIS_OK if the operation ended with success.
* If the slot is already assigned to another instance this is considered
* an error and REDIS_ERR is returned. */
int
clusterAddSlot
(
clusterNode
*
n
,
int
slot
)
{
if
(
clusterNodeSetSlotBit
(
n
,
slot
)
!=
0
)
return
REDIS_ERR
;
server
.
cluster
.
slots
[
slot
]
=
n
;
return
REDIS_OK
;
}
/* Delete the specified slot marking it as unassigned.
* Returns REDIS_OK if the slot was assigned, otherwise if the slot was
* already unassigned REDIS_ERR is returned. */
int
clusterDelSlot
(
int
slot
)
{
clusterNode
*
n
=
server
.
cluster
.
slots
[
slot
];
if
(
!
n
)
return
REDIS_ERR
;
redisAssert
(
clusterNodeClearSlotBit
(
n
,
slot
)
==
1
);
server
.
cluster
.
slots
[
slot
]
=
NULL
;
return
REDIS_OK
;
}
/* -----------------------------------------------------------------------------
* Cluster state evaluation function
* -------------------------------------------------------------------------- */
void
clusterUpdateState
(
void
)
{
int
ok
=
1
;
int
j
;
for
(
j
=
0
;
j
<
REDIS_CLUSTER_SLOTS
;
j
++
)
{
if
(
server
.
cluster
.
slots
[
j
]
==
NULL
||
server
.
cluster
.
slots
[
j
]
->
flags
&
(
REDIS_NODE_FAIL
))
{
ok
=
0
;
break
;
}
}
if
(
ok
)
{
if
(
server
.
cluster
.
state
==
REDIS_CLUSTER_NEEDHELP
)
{
server
.
cluster
.
state
=
REDIS_CLUSTER_NEEDHELP
;
}
else
{
server
.
cluster
.
state
=
REDIS_CLUSTER_OK
;
}
}
else
{
server
.
cluster
.
state
=
REDIS_CLUSTER_FAIL
;
}
}
/* -----------------------------------------------------------------------------
* CLUSTER command
* -------------------------------------------------------------------------- */
sds
clusterGenNodesDescription
(
void
)
{
sds
ci
=
sdsempty
();
dictIterator
*
di
;
dictEntry
*
de
;
int
j
,
start
;
di
=
dictGetIterator
(
server
.
cluster
.
nodes
);
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
clusterNode
*
node
=
dictGetEntryVal
(
de
);
/* Node coordinates */
ci
=
sdscatprintf
(
ci
,
"%.40s %s:%d "
,
node
->
name
,
node
->
ip
,
node
->
port
);
/* Flags */
if
(
node
->
flags
==
0
)
ci
=
sdscat
(
ci
,
"noflags,"
);
if
(
node
->
flags
&
REDIS_NODE_MYSELF
)
ci
=
sdscat
(
ci
,
"myself,"
);
if
(
node
->
flags
&
REDIS_NODE_MASTER
)
ci
=
sdscat
(
ci
,
"master,"
);
if
(
node
->
flags
&
REDIS_NODE_SLAVE
)
ci
=
sdscat
(
ci
,
"slave,"
);
if
(
node
->
flags
&
REDIS_NODE_PFAIL
)
ci
=
sdscat
(
ci
,
"fail?,"
);
if
(
node
->
flags
&
REDIS_NODE_FAIL
)
ci
=
sdscat
(
ci
,
"fail,"
);
if
(
node
->
flags
&
REDIS_NODE_HANDSHAKE
)
ci
=
sdscat
(
ci
,
"handshake,"
);
if
(
node
->
flags
&
REDIS_NODE_NOADDR
)
ci
=
sdscat
(
ci
,
"noaddr,"
);
if
(
ci
[
sdslen
(
ci
)
-
1
]
==
','
)
ci
[
sdslen
(
ci
)
-
1
]
=
' '
;
/* Slave of... or just "-" */
if
(
node
->
slaveof
)
ci
=
sdscatprintf
(
ci
,
"%.40s "
,
node
->
slaveof
->
name
);
else
ci
=
sdscatprintf
(
ci
,
"- "
);
/* Latency from the POV of this node, link status */
ci
=
sdscatprintf
(
ci
,
"%ld %ld %s"
,
(
long
)
node
->
ping_sent
,
(
long
)
node
->
pong_received
,
node
->
link
?
"connected"
:
"disconnected"
);
/* Slots served by this instance */
start
=
-
1
;
for
(
j
=
0
;
j
<
REDIS_CLUSTER_SLOTS
;
j
++
)
{
int
bit
;
if
((
bit
=
clusterNodeGetSlotBit
(
node
,
j
))
!=
0
)
{
if
(
start
==
-
1
)
start
=
j
;
}
if
(
start
!=
-
1
&&
(
!
bit
||
j
==
REDIS_CLUSTER_SLOTS
-
1
))
{
if
(
j
==
REDIS_CLUSTER_SLOTS
-
1
)
j
++
;
if
(
start
==
j
-
1
)
{
ci
=
sdscatprintf
(
ci
,
" %d"
,
start
);
}
else
{
ci
=
sdscatprintf
(
ci
,
" %d-%d"
,
start
,
j
-
1
);
}
start
=
-
1
;
}
}
/* Just for MYSELF node we also dump info about slots that
* we are migrating to other instances or importing from other
* instances. */
if
(
node
->
flags
&
REDIS_NODE_MYSELF
)
{
for
(
j
=
0
;
j
<
REDIS_CLUSTER_SLOTS
;
j
++
)
{
if
(
server
.
cluster
.
migrating_slots_to
[
j
])
{
ci
=
sdscatprintf
(
ci
,
" [%d->-%.40s]"
,
j
,
server
.
cluster
.
migrating_slots_to
[
j
]
->
name
);
}
else
if
(
server
.
cluster
.
importing_slots_from
[
j
])
{
ci
=
sdscatprintf
(
ci
,
" [%d-<-%.40s]"
,
j
,
server
.
cluster
.
importing_slots_from
[
j
]
->
name
);
}
}
}
ci
=
sdscatlen
(
ci
,
"
\n
"
,
1
);
}
dictReleaseIterator
(
di
);
return
ci
;
}
int
getSlotOrReply
(
redisClient
*
c
,
robj
*
o
)
{
long
long
slot
;
if
(
getLongLongFromObject
(
o
,
&
slot
)
!=
REDIS_OK
||
slot
<
0
||
slot
>
REDIS_CLUSTER_SLOTS
)
{
addReplyError
(
c
,
"Invalid or out of range slot"
);
return
-
1
;
}
return
(
int
)
slot
;
}
void
clusterCommand
(
redisClient
*
c
)
{
if
(
server
.
cluster_enabled
==
0
)
{
addReplyError
(
c
,
"This instance has cluster support disabled"
);
return
;
}
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"meet"
)
&&
c
->
argc
==
4
)
{
clusterNode
*
n
;
struct
sockaddr_in
sa
;
long
port
;
/* Perform sanity checks on IP/port */
if
(
inet_aton
(
c
->
argv
[
2
]
->
ptr
,
&
sa
.
sin_addr
)
==
0
)
{
addReplyError
(
c
,
"Invalid IP address in MEET"
);
return
;
}
if
(
getLongFromObjectOrReply
(
c
,
c
->
argv
[
3
],
&
port
,
NULL
)
!=
REDIS_OK
||
port
<
0
||
port
>
(
65535
-
REDIS_CLUSTER_PORT_INCR
))
{
addReplyError
(
c
,
"Invalid TCP port specified"
);
return
;
}
/* Finally add the node to the cluster with a random name, this
* will get fixed in the first handshake (ping/pong). */
n
=
createClusterNode
(
NULL
,
REDIS_NODE_HANDSHAKE
|
REDIS_NODE_MEET
);
strncpy
(
n
->
ip
,
inet_ntoa
(
sa
.
sin_addr
),
sizeof
(
n
->
ip
));
n
->
port
=
port
;
clusterAddNode
(
n
);
addReply
(
c
,
shared
.
ok
);
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"nodes"
)
&&
c
->
argc
==
2
)
{
robj
*
o
;
sds
ci
=
clusterGenNodesDescription
();
o
=
createObject
(
REDIS_STRING
,
ci
);
addReplyBulk
(
c
,
o
);
decrRefCount
(
o
);
}
else
if
((
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"addslots"
)
||
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"delslots"
))
&&
c
->
argc
>=
3
)
{
int
j
,
slot
;
unsigned
char
*
slots
=
zmalloc
(
REDIS_CLUSTER_SLOTS
);
int
del
=
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"delslots"
);
memset
(
slots
,
0
,
REDIS_CLUSTER_SLOTS
);
/* Check that all the arguments are parsable and that all the
* slots are not already busy. */
for
(
j
=
2
;
j
<
c
->
argc
;
j
++
)
{
if
((
slot
=
getSlotOrReply
(
c
,
c
->
argv
[
j
]))
==
-
1
)
{
zfree
(
slots
);
return
;
}
if
(
del
&&
server
.
cluster
.
slots
[
slot
]
==
NULL
)
{
addReplyErrorFormat
(
c
,
"Slot %d is already unassigned"
,
slot
);
zfree
(
slots
);
return
;
}
else
if
(
!
del
&&
server
.
cluster
.
slots
[
slot
])
{
addReplyErrorFormat
(
c
,
"Slot %d is already busy"
,
slot
);
zfree
(
slots
);
return
;
}
if
(
slots
[
slot
]
++
==
1
)
{
addReplyErrorFormat
(
c
,
"Slot %d specified multiple times"
,
(
int
)
slot
);
zfree
(
slots
);
return
;
}
}
for
(
j
=
0
;
j
<
REDIS_CLUSTER_SLOTS
;
j
++
)
{
if
(
slots
[
j
])
{
int
retval
;
/* If this slot was set as importing we can clear this
* state as now we are the real owner of the slot. */
if
(
server
.
cluster
.
importing_slots_from
[
j
])
server
.
cluster
.
importing_slots_from
[
j
]
=
NULL
;
retval
=
del
?
clusterDelSlot
(
j
)
:
clusterAddSlot
(
server
.
cluster
.
myself
,
j
);
redisAssert
(
retval
==
REDIS_OK
);
}
}
zfree
(
slots
);
clusterUpdateState
();
clusterSaveConfigOrDie
();
addReply
(
c
,
shared
.
ok
);
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"setslot"
)
&&
c
->
argc
>=
4
)
{
/* SETSLOT 10 MIGRATING <instance ID> */
/* SETSLOT 10 IMPORTING <instance ID> */
/* SETSLOT 10 STABLE */
int
slot
;
clusterNode
*
n
;
if
((
slot
=
getSlotOrReply
(
c
,
c
->
argv
[
2
]))
==
-
1
)
return
;
if
(
!
strcasecmp
(
c
->
argv
[
3
]
->
ptr
,
"migrating"
)
&&
c
->
argc
==
5
)
{
if
(
server
.
cluster
.
slots
[
slot
]
!=
server
.
cluster
.
myself
)
{
addReplyErrorFormat
(
c
,
"I'm not the owner of hash slot %u"
,
slot
);
return
;
}
if
((
n
=
clusterLookupNode
(
c
->
argv
[
4
]
->
ptr
))
==
NULL
)
{
addReplyErrorFormat
(
c
,
"I don't know about node %s"
,
(
char
*
)
c
->
argv
[
4
]
->
ptr
);
return
;
}
server
.
cluster
.
migrating_slots_to
[
slot
]
=
n
;
}
else
if
(
!
strcasecmp
(
c
->
argv
[
3
]
->
ptr
,
"importing"
)
&&
c
->
argc
==
5
)
{
if
(
server
.
cluster
.
slots
[
slot
]
==
server
.
cluster
.
myself
)
{
addReplyErrorFormat
(
c
,
"I'm already the owner of hash slot %u"
,
slot
);
return
;
}
if
((
n
=
clusterLookupNode
(
c
->
argv
[
4
]
->
ptr
))
==
NULL
)
{
addReplyErrorFormat
(
c
,
"I don't know about node %s"
,
(
char
*
)
c
->
argv
[
3
]
->
ptr
);
return
;
}
server
.
cluster
.
importing_slots_from
[
slot
]
=
n
;
}
else
if
(
!
strcasecmp
(
c
->
argv
[
3
]
->
ptr
,
"stable"
)
&&
c
->
argc
==
4
)
{
/* CLUSTER SETSLOT <SLOT> STABLE */
server
.
cluster
.
importing_slots_from
[
slot
]
=
NULL
;
server
.
cluster
.
migrating_slots_to
[
slot
]
=
NULL
;
}
else
if
(
!
strcasecmp
(
c
->
argv
[
3
]
->
ptr
,
"node"
)
&&
c
->
argc
==
4
)
{
/* CLUSTER SETSLOT <SLOT> NODE <NODE ID> */
clusterNode
*
n
=
clusterLookupNode
(
c
->
argv
[
4
]
->
ptr
);
if
(
!
n
)
addReplyErrorFormat
(
c
,
"Unknown node %s"
,
(
char
*
)
c
->
argv
[
4
]
->
ptr
);
/* If this hash slot was served by 'myself' before to switch
* make sure there are no longer local keys for this hash slot. */
if
(
server
.
cluster
.
slots
[
slot
]
==
server
.
cluster
.
myself
&&
n
!=
server
.
cluster
.
myself
)
{
int
numkeys
;
robj
**
keys
;
keys
=
zmalloc
(
sizeof
(
robj
*
)
*
1
);
numkeys
=
GetKeysInSlot
(
slot
,
keys
,
1
);
zfree
(
keys
);
if
(
numkeys
==
0
)
{
addReplyErrorFormat
(
c
,
"Can't assign hashslot %d to a different node while I still hold keys for this hash slot."
,
slot
);
return
;
}
}
/* If this node was the slot owner and the slot was marked as
* migrating, assigning the slot to another node will clear
* the migratig status. */
if
(
server
.
cluster
.
slots
[
slot
]
==
server
.
cluster
.
myself
&&
server
.
cluster
.
migrating_slots_to
[
slot
])
server
.
cluster
.
migrating_slots_to
[
slot
]
=
NULL
;
clusterDelSlot
(
slot
);
clusterAddSlot
(
n
,
slot
);
}
else
{
addReplyError
(
c
,
"Invalid CLUSTER SETSLOT action or number of arguments"
);
return
;
}
clusterSaveConfigOrDie
();
addReply
(
c
,
shared
.
ok
);
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"info"
)
&&
c
->
argc
==
2
)
{
char
*
statestr
[]
=
{
"ok"
,
"fail"
,
"needhelp"
};
int
slots_assigned
=
0
,
slots_ok
=
0
,
slots_pfail
=
0
,
slots_fail
=
0
;
int
j
;
for
(
j
=
0
;
j
<
REDIS_CLUSTER_SLOTS
;
j
++
)
{
clusterNode
*
n
=
server
.
cluster
.
slots
[
j
];
if
(
n
==
NULL
)
continue
;
slots_assigned
++
;
if
(
n
->
flags
&
REDIS_NODE_FAIL
)
{
slots_fail
++
;
}
else
if
(
n
->
flags
&
REDIS_NODE_PFAIL
)
{
slots_pfail
++
;
}
else
{
slots_ok
++
;
}
}
sds
info
=
sdscatprintf
(
sdsempty
(),
"cluster_state:%s
\r\n
"
"cluster_slots_assigned:%d
\r\n
"
"cluster_slots_ok:%d
\r\n
"
"cluster_slots_pfail:%d
\r\n
"
"cluster_slots_fail:%d
\r\n
"
"cluster_known_nodes:%lu
\r\n
"
,
statestr
[
server
.
cluster
.
state
],
slots_assigned
,
slots_ok
,
slots_pfail
,
slots_fail
,
dictSize
(
server
.
cluster
.
nodes
)
);
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
,
"keyslot"
)
&&
c
->
argc
==
3
)
{
sds
key
=
c
->
argv
[
2
]
->
ptr
;
addReplyLongLong
(
c
,
keyHashSlot
(
key
,
sdslen
(
key
)));
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"getkeysinslot"
)
&&
c
->
argc
==
4
)
{
long
long
maxkeys
,
slot
;
unsigned
int
numkeys
,
j
;
robj
**
keys
;
if
(
getLongLongFromObjectOrReply
(
c
,
c
->
argv
[
2
],
&
slot
,
NULL
)
!=
REDIS_OK
)
return
;
if
(
getLongLongFromObjectOrReply
(
c
,
c
->
argv
[
3
],
&
maxkeys
,
NULL
)
!=
REDIS_OK
)
return
;
if
(
slot
<
0
||
slot
>=
REDIS_CLUSTER_SLOTS
||
maxkeys
<
0
||
maxkeys
>
1024
*
1024
)
{
addReplyError
(
c
,
"Invalid slot or number of keys"
);
return
;
}
keys
=
zmalloc
(
sizeof
(
robj
*
)
*
maxkeys
);
numkeys
=
GetKeysInSlot
(
slot
,
keys
,
maxkeys
);
addReplyMultiBulkLen
(
c
,
numkeys
);
for
(
j
=
0
;
j
<
numkeys
;
j
++
)
addReplyBulk
(
c
,
keys
[
j
]);
zfree
(
keys
);
}
else
{
addReplyError
(
c
,
"Wrong CLUSTER subcommand or number of arguments"
);
}
}
/* -----------------------------------------------------------------------------
* RESTORE and MIGRATE commands
* -------------------------------------------------------------------------- */
/* RESTORE key ttl serialized-value */
void
restoreCommand
(
redisClient
*
c
)
{
FILE
*
fp
;
char
buf
[
64
];
robj
*
o
;
unsigned
char
*
data
;
long
ttl
;
/* Make sure this key does not already exist here... */
if
(
dbExists
(
c
->
db
,
c
->
argv
[
1
]))
{
addReplyError
(
c
,
"Target key name is busy."
);
return
;
}
/* Check if the TTL value makes sense */
if
(
getLongFromObjectOrReply
(
c
,
c
->
argv
[
2
],
&
ttl
,
NULL
)
!=
REDIS_OK
)
{
return
;
}
else
if
(
ttl
<
0
)
{
addReplyError
(
c
,
"Invalid TTL value, must be >= 0"
);
return
;
}
/* rdbLoadObject() only works against file descriptors so we need to
* dump the serialized object into a file and reload. */
snprintf
(
buf
,
sizeof
(
buf
),
"redis-restore-%d.tmp"
,
getpid
());
fp
=
fopen
(
buf
,
"w+"
);
if
(
!
fp
)
{
redisLog
(
REDIS_WARNING
,
"Can't open tmp file for RESTORE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"RESTORE failed, tmp file creation error: %s"
,
strerror
(
errno
));
return
;
}
unlink
(
buf
);
/* Write the actual data and rewind the file */
data
=
(
unsigned
char
*
)
c
->
argv
[
3
]
->
ptr
;
if
(
fwrite
(
data
+
1
,
sdslen
((
sds
)
data
)
-
1
,
1
,
fp
)
!=
1
)
{
redisLog
(
REDIS_WARNING
,
"Can't write against tmp file for RESTORE: %s"
,
strerror
(
errno
));
addReplyError
(
c
,
"RESTORE failed, tmp file I/O error."
);
fclose
(
fp
);
return
;
}
rewind
(
fp
);
/* Finally create the object from the serialized dump and
* store it at the specified key. */
if
((
data
[
0
]
>
4
&&
data
[
0
]
<
9
)
||
data
[
0
]
>
11
||
(
o
=
rdbLoadObject
(
data
[
0
],
fp
))
==
NULL
)
{
addReplyError
(
c
,
"Bad data format."
);
fclose
(
fp
);
return
;
}
fclose
(
fp
);
/* Create the key and set the TTL if any */
dbAdd
(
c
->
db
,
c
->
argv
[
1
],
o
);
if
(
ttl
)
setExpire
(
c
->
db
,
c
->
argv
[
1
],
time
(
NULL
)
+
ttl
);
addReply
(
c
,
shared
.
ok
);
}
/* MIGRATE host port key dbid timeout */
void
migrateCommand
(
redisClient
*
c
)
{
int
fd
;
long
timeout
;
long
dbid
;
char
buf
[
64
];
FILE
*
fp
;
time_t
ttl
;
robj
*
o
;
unsigned
char
type
;
off_t
payload_len
;
/* Sanity check */
if
(
getLongFromObjectOrReply
(
c
,
c
->
argv
[
5
],
&
timeout
,
NULL
)
!=
REDIS_OK
)
return
;
if
(
getLongFromObjectOrReply
(
c
,
c
->
argv
[
4
],
&
dbid
,
NULL
)
!=
REDIS_OK
)
return
;
if
(
timeout
<=
0
)
timeout
=
1
;
/* 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
=
lookupKeyRead
(
c
->
db
,
c
->
argv
[
3
]))
==
NULL
)
{
addReplySds
(
c
,
sdsnew
(
"+NOKEY"
));
return
;
}
/* Connect */
fd
=
anetTcpNonBlockConnect
(
server
.
neterr
,
c
->
argv
[
1
]
->
ptr
,
atoi
(
c
->
argv
[
2
]
->
ptr
));
if
(
fd
==
-
1
)
{
addReplyErrorFormat
(
c
,
"Can't connect to target node: %s"
,
server
.
neterr
);
return
;
}
if
((
aeWait
(
fd
,
AE_WRITABLE
,
timeout
*
1000
)
&
AE_WRITABLE
)
==
0
)
{
addReplyError
(
c
,
"Timeout connecting to the client"
);
return
;
}
/* Create temp file */
snprintf
(
buf
,
sizeof
(
buf
),
"redis-migrate-%d.tmp"
,
getpid
());
fp
=
fopen
(
buf
,
"w+"
);
if
(
!
fp
)
{
redisLog
(
REDIS_WARNING
,
"Can't open tmp file for MIGRATE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"MIGRATE failed, tmp file creation error: %s."
,
strerror
(
errno
));
return
;
}
unlink
(
buf
);
/* Build the SELECT + RESTORE query writing it in our temp file. */
if
(
fwriteBulkCount
(
fp
,
'*'
,
2
)
==
0
)
goto
file_wr_err
;
if
(
fwriteBulkString
(
fp
,
"SELECT"
,
6
)
==
0
)
goto
file_wr_err
;
if
(
fwriteBulkLongLong
(
fp
,
dbid
)
==
0
)
goto
file_wr_err
;
ttl
=
getExpire
(
c
->
db
,
c
->
argv
[
3
]);
type
=
o
->
type
;
if
(
fwriteBulkCount
(
fp
,
'*'
,
4
)
==
0
)
goto
file_wr_err
;
if
(
fwriteBulkString
(
fp
,
"RESTORE"
,
7
)
==
0
)
goto
file_wr_err
;
if
(
fwriteBulkObject
(
fp
,
c
->
argv
[
3
])
==
0
)
goto
file_wr_err
;
if
(
fwriteBulkLongLong
(
fp
,
(
ttl
==
-
1
)
?
0
:
ttl
)
==
0
)
goto
file_wr_err
;
/* Finally the last argument that is the serailized object payload
* in the form: <type><rdb-serailized-object>. */
payload_len
=
rdbSavedObjectLen
(
o
);
if
(
fwriteBulkCount
(
fp
,
'$'
,
payload_len
+
1
)
==
0
)
goto
file_wr_err
;
if
(
fwrite
(
&
type
,
1
,
1
,
fp
)
==
0
)
goto
file_wr_err
;
if
(
rdbSaveObject
(
fp
,
o
)
==
-
1
)
goto
file_wr_err
;
if
(
fwrite
(
"
\r\n
"
,
2
,
1
,
fp
)
==
0
)
goto
file_wr_err
;
/* Tranfer the query to the other node */
rewind
(
fp
);
{
char
buf
[
4096
];
size_t
nread
;
while
((
nread
=
fread
(
buf
,
1
,
sizeof
(
buf
),
fp
))
!=
0
)
{
int
nwritten
;
nwritten
=
syncWrite
(
fd
,
buf
,
nread
,
timeout
);
if
(
nwritten
!=
(
signed
)
nread
)
goto
socket_wr_err
;
}
if
(
ferror
(
fp
))
goto
file_rd_err
;
}
/* Read back the reply */
{
char
buf1
[
1024
];
char
buf2
[
1024
];
/* Read the two replies */
if
(
syncReadLine
(
fd
,
buf1
,
sizeof
(
buf1
),
timeout
)
<=
0
)
goto
socket_rd_err
;
if
(
syncReadLine
(
fd
,
buf2
,
sizeof
(
buf2
),
timeout
)
<=
0
)
goto
socket_rd_err
;
if
(
buf1
[
0
]
==
'-'
||
buf2
[
0
]
==
'-'
)
{
addReplyErrorFormat
(
c
,
"Target instance replied with error: %s"
,
(
buf1
[
0
]
==
'-'
)
?
buf1
+
1
:
buf2
+
1
);
}
else
{
dbDelete
(
c
->
db
,
c
->
argv
[
3
]);
addReply
(
c
,
shared
.
ok
);
}
}
fclose
(
fp
);
close
(
fd
);
return
;
file_wr_err:
redisLog
(
REDIS_WARNING
,
"Can't write on tmp file for MIGRATE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"MIGRATE failed, tmp file write error: %s."
,
strerror
(
errno
));
fclose
(
fp
);
close
(
fd
);
return
;
file_rd_err:
redisLog
(
REDIS_WARNING
,
"Can't read from tmp file for MIGRATE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"MIGRATE failed, tmp file read error: %s."
,
strerror
(
errno
));
fclose
(
fp
);
close
(
fd
);
return
;
socket_wr_err:
redisLog
(
REDIS_NOTICE
,
"Can't write to target node for MIGRATE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"MIGRATE failed, writing to target node: %s."
,
strerror
(
errno
));
fclose
(
fp
);
close
(
fd
);
return
;
socket_rd_err:
redisLog
(
REDIS_NOTICE
,
"Can't read from target node for MIGRATE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"MIGRATE failed, reading from target node: %s."
,
strerror
(
errno
));
fclose
(
fp
);
close
(
fd
);
return
;
}
/* DUMP keyname
* DUMP is actually not used by Redis Cluster but it is the obvious
* complement of RESTORE and can be useful for different applications. */
void
dumpCommand
(
redisClient
*
c
)
{
char
buf
[
64
];
FILE
*
fp
;
robj
*
o
,
*
dumpobj
;
sds
dump
=
NULL
;
off_t
payload_len
;
unsigned
int
type
;
/* Check if the key is here. */
if
((
o
=
lookupKeyRead
(
c
->
db
,
c
->
argv
[
1
]))
==
NULL
)
{
addReply
(
c
,
shared
.
nullbulk
);
return
;
}
/* Create temp file */
snprintf
(
buf
,
sizeof
(
buf
),
"redis-dump-%d.tmp"
,
getpid
());
fp
=
fopen
(
buf
,
"w+"
);
if
(
!
fp
)
{
redisLog
(
REDIS_WARNING
,
"Can't open tmp file for MIGRATE: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"DUMP failed, tmp file creation error: %s."
,
strerror
(
errno
));
return
;
}
unlink
(
buf
);
/* Dump the serailized object and read it back in memory.
* We prefix it with a one byte containing the type ID.
* This is the serialization format understood by RESTORE. */
if
(
rdbSaveObject
(
fp
,
o
)
==
-
1
)
goto
file_wr_err
;
payload_len
=
ftello
(
fp
);
if
(
fseeko
(
fp
,
0
,
SEEK_SET
)
==
-
1
)
goto
file_rd_err
;
dump
=
sdsnewlen
(
NULL
,
payload_len
+
1
);
if
(
payload_len
&&
fread
(
dump
+
1
,
payload_len
,
1
,
fp
)
!=
1
)
goto
file_rd_err
;
fclose
(
fp
);
type
=
o
->
type
;
if
(
type
==
REDIS_LIST
&&
o
->
encoding
==
REDIS_ENCODING_ZIPLIST
)
type
=
REDIS_LIST_ZIPLIST
;
else
if
(
type
==
REDIS_HASH
&&
o
->
encoding
==
REDIS_ENCODING_ZIPMAP
)
type
=
REDIS_HASH_ZIPMAP
;
else
if
(
type
==
REDIS_SET
&&
o
->
encoding
==
REDIS_ENCODING_INTSET
)
type
=
REDIS_SET_INTSET
;
else
type
=
o
->
type
;
dump
[
0
]
=
type
;
/* Transfer to the client */
dumpobj
=
createObject
(
REDIS_STRING
,
dump
);
addReplyBulk
(
c
,
dumpobj
);
decrRefCount
(
dumpobj
);
return
;
file_wr_err:
redisLog
(
REDIS_WARNING
,
"Can't write on tmp file for DUMP: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"DUMP failed, tmp file write error: %s."
,
strerror
(
errno
));
sdsfree
(
dump
);
fclose
(
fp
);
return
;
file_rd_err:
redisLog
(
REDIS_WARNING
,
"Can't read from tmp file for DUMP: %s"
,
strerror
(
errno
));
addReplyErrorFormat
(
c
,
"DUMP failed, tmp file read error: %s."
,
strerror
(
errno
));
sdsfree
(
dump
);
fclose
(
fp
);
return
;
}
/* -----------------------------------------------------------------------------
* Cluster functions related to serving / redirecting clients
* -------------------------------------------------------------------------- */
/* Return the pointer to the cluster node that is able to serve the query
* as all the keys belong to hash slots for which the node is in charge.
*
* If the returned node should be used only for this request, the *ask
* integer is set to '1', otherwise to '0'. This is used in order to
* let the caller know if we should reply with -MOVED or with -ASK.
*
* If the request contains more than a single key NULL is returned,
* however a request with more then a key argument where the key is always
* the same is valid, like in: RPOPLPUSH mylist mylist.*/
clusterNode
*
getNodeByQuery
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
hashslot
,
int
*
ask
)
{
clusterNode
*
n
=
NULL
;
robj
*
firstkey
=
NULL
;
multiState
*
ms
,
_ms
;
multiCmd
mc
;
int
i
,
slot
=
0
;
/* We handle all the cases as if they were EXEC commands, so we have
* a common code path for everything */
if
(
cmd
->
proc
==
execCommand
)
{
/* If REDIS_MULTI flag is not set EXEC is just going to return an
* error. */
if
(
!
(
c
->
flags
&
REDIS_MULTI
))
return
server
.
cluster
.
myself
;
ms
=
&
c
->
mstate
;
}
else
{
/* In order to have a single codepath create a fake Multi State
* structure if the client is not in MULTI/EXEC state, this way
* we have a single codepath below. */
ms
=
&
_ms
;
_ms
.
commands
=
&
mc
;
_ms
.
count
=
1
;
mc
.
argv
=
argv
;
mc
.
argc
=
argc
;
mc
.
cmd
=
cmd
;
}
/* Check that all the keys are the same key, and get the slot and
* node for this key. */
for
(
i
=
0
;
i
<
ms
->
count
;
i
++
)
{
struct
redisCommand
*
mcmd
;
robj
**
margv
;
int
margc
,
*
keyindex
,
numkeys
,
j
;
mcmd
=
ms
->
commands
[
i
].
cmd
;
margc
=
ms
->
commands
[
i
].
argc
;
margv
=
ms
->
commands
[
i
].
argv
;
keyindex
=
getKeysFromCommand
(
mcmd
,
margv
,
margc
,
&
numkeys
,
REDIS_GETKEYS_ALL
);
for
(
j
=
0
;
j
<
numkeys
;
j
++
)
{
if
(
firstkey
==
NULL
)
{
/* This is the first key we see. Check what is the slot
* and node. */
firstkey
=
margv
[
keyindex
[
j
]];
slot
=
keyHashSlot
((
char
*
)
firstkey
->
ptr
,
sdslen
(
firstkey
->
ptr
));
n
=
server
.
cluster
.
slots
[
slot
];
redisAssert
(
n
!=
NULL
);
}
else
{
/* If it is not the first key, make sure it is exactly
* the same key as the first we saw. */
if
(
!
equalStringObjects
(
firstkey
,
margv
[
keyindex
[
j
]]))
{
decrRefCount
(
firstkey
);
getKeysFreeResult
(
keyindex
);
return
NULL
;
}
}
}
getKeysFreeResult
(
keyindex
);
}
if
(
ask
)
*
ask
=
0
;
/* This is the default. Set to 1 if needed later. */
/* No key at all in command? then we can serve the request
* without redirections. */
if
(
n
==
NULL
)
return
server
.
cluster
.
myself
;
if
(
hashslot
)
*
hashslot
=
slot
;
/* This request is about a slot we are migrating into another instance?
* Then we need to check if we have the key. If we have it we can reply.
* If instead is a new key, we pass the request to the node that is
* receiving the slot. */
if
(
n
==
server
.
cluster
.
myself
&&
server
.
cluster
.
migrating_slots_to
[
slot
]
!=
NULL
)
{
if
(
lookupKeyRead
(
&
server
.
db
[
0
],
firstkey
)
==
NULL
)
{
if
(
ask
)
*
ask
=
1
;
return
server
.
cluster
.
migrating_slots_to
[
slot
];
}
}
/* Handle the case in which we are receiving this hash slot from
* another instance, so we'll accept the query even if in the table
* it is assigned to a different node. */
if
(
server
.
cluster
.
importing_slots_from
[
slot
]
!=
NULL
)
return
server
.
cluster
.
myself
;
/* It's not a -ASK case. Base case: just return the right node. */
return
n
;
}
src/config.c
View file @
bfe85f7c
...
@@ -261,6 +261,10 @@ void loadServerConfig(char *filename) {
...
@@ -261,6 +261,10 @@ void loadServerConfig(char *filename) {
server
.
list_max_ziplist_value
=
memtoll
(
argv
[
1
],
NULL
);
server
.
list_max_ziplist_value
=
memtoll
(
argv
[
1
],
NULL
);
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"set-max-intset-entries"
)
&&
argc
==
2
)
{
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"set-max-intset-entries"
)
&&
argc
==
2
)
{
server
.
set_max_intset_entries
=
memtoll
(
argv
[
1
],
NULL
);
server
.
set_max_intset_entries
=
memtoll
(
argv
[
1
],
NULL
);
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"zset-max-ziplist-entries"
)
&&
argc
==
2
)
{
server
.
zset_max_ziplist_entries
=
memtoll
(
argv
[
1
],
NULL
);
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"zset-max-ziplist-value"
)
&&
argc
==
2
)
{
server
.
zset_max_ziplist_value
=
memtoll
(
argv
[
1
],
NULL
);
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"rename-command"
)
&&
argc
==
3
)
{
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"rename-command"
)
&&
argc
==
3
)
{
struct
redisCommand
*
cmd
=
lookupCommand
(
argv
[
1
]);
struct
redisCommand
*
cmd
=
lookupCommand
(
argv
[
1
]);
int
retval
;
int
retval
;
...
@@ -285,6 +289,13 @@ void loadServerConfig(char *filename) {
...
@@ -285,6 +289,13 @@ void loadServerConfig(char *filename) {
err
=
"Target command name already exists"
;
goto
loaderr
;
err
=
"Target command name already exists"
;
goto
loaderr
;
}
}
}
}
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"cluster-enabled"
)
&&
argc
==
2
)
{
if
((
server
.
cluster_enabled
=
yesnotoi
(
argv
[
1
]))
==
-
1
)
{
err
=
"argument must be 'yes' or 'no'"
;
goto
loaderr
;
}
}
else
if
(
!
strcasecmp
(
argv
[
0
],
"cluster-config-file"
)
&&
argc
==
2
)
{
zfree
(
server
.
cluster
.
configfile
);
server
.
cluster
.
configfile
=
zstrdup
(
argv
[
1
]);
}
else
{
}
else
{
err
=
"Bad directive or wrong number of arguments"
;
goto
loaderr
;
err
=
"Bad directive or wrong number of arguments"
;
goto
loaderr
;
}
}
...
@@ -443,6 +454,12 @@ void configSetCommand(redisClient *c) {
...
@@ -443,6 +454,12 @@ void configSetCommand(redisClient *c) {
}
else
if
(
!
strcasecmp
(
c
->
argv
[
2
]
->
ptr
,
"set-max-intset-entries"
))
{
}
else
if
(
!
strcasecmp
(
c
->
argv
[
2
]
->
ptr
,
"set-max-intset-entries"
))
{
if
(
getLongLongFromObject
(
o
,
&
ll
)
==
REDIS_ERR
||
ll
<
0
)
goto
badfmt
;
if
(
getLongLongFromObject
(
o
,
&
ll
)
==
REDIS_ERR
||
ll
<
0
)
goto
badfmt
;
server
.
set_max_intset_entries
=
ll
;
server
.
set_max_intset_entries
=
ll
;
}
else
if
(
!
strcasecmp
(
c
->
argv
[
2
]
->
ptr
,
"zset-max-ziplist-entries"
))
{
if
(
getLongLongFromObject
(
o
,
&
ll
)
==
REDIS_ERR
||
ll
<
0
)
goto
badfmt
;
server
.
zset_max_ziplist_entries
=
ll
;
}
else
if
(
!
strcasecmp
(
c
->
argv
[
2
]
->
ptr
,
"zset-max-ziplist-value"
))
{
if
(
getLongLongFromObject
(
o
,
&
ll
)
==
REDIS_ERR
||
ll
<
0
)
goto
badfmt
;
server
.
zset_max_ziplist_value
=
ll
;
}
else
{
}
else
{
addReplyErrorFormat
(
c
,
"Unsupported CONFIG parameter: %s"
,
addReplyErrorFormat
(
c
,
"Unsupported CONFIG parameter: %s"
,
(
char
*
)
c
->
argv
[
2
]
->
ptr
);
(
char
*
)
c
->
argv
[
2
]
->
ptr
);
...
@@ -594,6 +611,16 @@ void configGetCommand(redisClient *c) {
...
@@ -594,6 +611,16 @@ void configGetCommand(redisClient *c) {
addReplyBulkLongLong
(
c
,
server
.
set_max_intset_entries
);
addReplyBulkLongLong
(
c
,
server
.
set_max_intset_entries
);
matches
++
;
matches
++
;
}
}
if
(
stringmatch
(
pattern
,
"zset-max-ziplist-entries"
,
0
))
{
addReplyBulkCString
(
c
,
"zset-max-ziplist-entries"
);
addReplyBulkLongLong
(
c
,
server
.
zset_max_ziplist_entries
);
matches
++
;
}
if
(
stringmatch
(
pattern
,
"zset-max-ziplist-value"
,
0
))
{
addReplyBulkCString
(
c
,
"zset-max-ziplist-value"
);
addReplyBulkLongLong
(
c
,
server
.
zset_max_ziplist_value
);
matches
++
;
}
setDeferredMultiBulkLength
(
c
,
replylen
,
matches
*
2
);
setDeferredMultiBulkLength
(
c
,
replylen
,
matches
*
2
);
}
}
...
...
src/config.h
View file @
bfe85f7c
...
@@ -10,18 +10,31 @@
...
@@ -10,18 +10,31 @@
* this expects a different allocation scheme. Therefore, *exclusively* use
* this expects a different allocation scheme. Therefore, *exclusively* use
* either tcmalloc or OSX's malloc_size()! */
* either tcmalloc or OSX's malloc_size()! */
#if defined(USE_TCMALLOC)
#if defined(USE_TCMALLOC)
#define REDIS_MALLOC "tcmalloc"
#include <google/tcmalloc.h>
#include <google/tcmalloc.h>
#if TC_VERSION_MAJOR >= 1 && TC_VERSION_MINOR >= 6
#if TC_VERSION_MAJOR >= 1 && TC_VERSION_MINOR >= 6
#define HAVE_MALLOC_SIZE 1
#define HAVE_MALLOC_SIZE 1
#define redis_malloc_size(p) tc_malloc_size(p)
#define redis_malloc_size(p) tc_malloc_size(p)
#endif
#endif
#elif defined(USE_JEMALLOC)
#define REDIS_MALLOC "jemalloc"
#define JEMALLOC_MANGLE
#include <jemalloc/jemalloc.h>
#if JEMALLOC_VERSION_MAJOR >= 2 && JEMALLOC_VERSION_MINOR >= 1
#define HAVE_MALLOC_SIZE 1
#define redis_malloc_size(p) JEMALLOC_P(malloc_usable_size)(p)
#endif
#elif defined(__APPLE__)
#elif defined(__APPLE__)
#include <malloc/malloc.h>
#include <malloc/malloc.h>
#define HAVE_MALLOC_SIZE 1
#define HAVE_MALLOC_SIZE 1
#define redis_malloc_size(p) malloc_size(p)
#define redis_malloc_size(p) malloc_size(p)
#endif
#endif
/* Tefine redis_fstat to fstat or fstat64() */
#ifndef REDIS_MALLOC
#define REDIS_MALLOC "libc"
#endif
/* Define redis_fstat to fstat or fstat64() */
#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
#if defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
#define redis_fstat fstat64
#define redis_fstat fstat64
#define redis_stat stat64
#define redis_stat stat64
...
...
src/crc16.c
0 → 100644
View file @
bfe85f7c
#include "redis.h"
/*
* Copyright 2001-2010 Georges Menie (www.menie.org)
* Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style)
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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.
*/
/* CRC16 implementation acording to CCITT standards */
static
const
uint16_t
crc16tab
[
256
]
=
{
0x0000
,
0x1021
,
0x2042
,
0x3063
,
0x4084
,
0x50a5
,
0x60c6
,
0x70e7
,
0x8108
,
0x9129
,
0xa14a
,
0xb16b
,
0xc18c
,
0xd1ad
,
0xe1ce
,
0xf1ef
,
0x1231
,
0x0210
,
0x3273
,
0x2252
,
0x52b5
,
0x4294
,
0x72f7
,
0x62d6
,
0x9339
,
0x8318
,
0xb37b
,
0xa35a
,
0xd3bd
,
0xc39c
,
0xf3ff
,
0xe3de
,
0x2462
,
0x3443
,
0x0420
,
0x1401
,
0x64e6
,
0x74c7
,
0x44a4
,
0x5485
,
0xa56a
,
0xb54b
,
0x8528
,
0x9509
,
0xe5ee
,
0xf5cf
,
0xc5ac
,
0xd58d
,
0x3653
,
0x2672
,
0x1611
,
0x0630
,
0x76d7
,
0x66f6
,
0x5695
,
0x46b4
,
0xb75b
,
0xa77a
,
0x9719
,
0x8738
,
0xf7df
,
0xe7fe
,
0xd79d
,
0xc7bc
,
0x48c4
,
0x58e5
,
0x6886
,
0x78a7
,
0x0840
,
0x1861
,
0x2802
,
0x3823
,
0xc9cc
,
0xd9ed
,
0xe98e
,
0xf9af
,
0x8948
,
0x9969
,
0xa90a
,
0xb92b
,
0x5af5
,
0x4ad4
,
0x7ab7
,
0x6a96
,
0x1a71
,
0x0a50
,
0x3a33
,
0x2a12
,
0xdbfd
,
0xcbdc
,
0xfbbf
,
0xeb9e
,
0x9b79
,
0x8b58
,
0xbb3b
,
0xab1a
,
0x6ca6
,
0x7c87
,
0x4ce4
,
0x5cc5
,
0x2c22
,
0x3c03
,
0x0c60
,
0x1c41
,
0xedae
,
0xfd8f
,
0xcdec
,
0xddcd
,
0xad2a
,
0xbd0b
,
0x8d68
,
0x9d49
,
0x7e97
,
0x6eb6
,
0x5ed5
,
0x4ef4
,
0x3e13
,
0x2e32
,
0x1e51
,
0x0e70
,
0xff9f
,
0xefbe
,
0xdfdd
,
0xcffc
,
0xbf1b
,
0xaf3a
,
0x9f59
,
0x8f78
,
0x9188
,
0x81a9
,
0xb1ca
,
0xa1eb
,
0xd10c
,
0xc12d
,
0xf14e
,
0xe16f
,
0x1080
,
0x00a1
,
0x30c2
,
0x20e3
,
0x5004
,
0x4025
,
0x7046
,
0x6067
,
0x83b9
,
0x9398
,
0xa3fb
,
0xb3da
,
0xc33d
,
0xd31c
,
0xe37f
,
0xf35e
,
0x02b1
,
0x1290
,
0x22f3
,
0x32d2
,
0x4235
,
0x5214
,
0x6277
,
0x7256
,
0xb5ea
,
0xa5cb
,
0x95a8
,
0x8589
,
0xf56e
,
0xe54f
,
0xd52c
,
0xc50d
,
0x34e2
,
0x24c3
,
0x14a0
,
0x0481
,
0x7466
,
0x6447
,
0x5424
,
0x4405
,
0xa7db
,
0xb7fa
,
0x8799
,
0x97b8
,
0xe75f
,
0xf77e
,
0xc71d
,
0xd73c
,
0x26d3
,
0x36f2
,
0x0691
,
0x16b0
,
0x6657
,
0x7676
,
0x4615
,
0x5634
,
0xd94c
,
0xc96d
,
0xf90e
,
0xe92f
,
0x99c8
,
0x89e9
,
0xb98a
,
0xa9ab
,
0x5844
,
0x4865
,
0x7806
,
0x6827
,
0x18c0
,
0x08e1
,
0x3882
,
0x28a3
,
0xcb7d
,
0xdb5c
,
0xeb3f
,
0xfb1e
,
0x8bf9
,
0x9bd8
,
0xabbb
,
0xbb9a
,
0x4a75
,
0x5a54
,
0x6a37
,
0x7a16
,
0x0af1
,
0x1ad0
,
0x2ab3
,
0x3a92
,
0xfd2e
,
0xed0f
,
0xdd6c
,
0xcd4d
,
0xbdaa
,
0xad8b
,
0x9de8
,
0x8dc9
,
0x7c26
,
0x6c07
,
0x5c64
,
0x4c45
,
0x3ca2
,
0x2c83
,
0x1ce0
,
0x0cc1
,
0xef1f
,
0xff3e
,
0xcf5d
,
0xdf7c
,
0xaf9b
,
0xbfba
,
0x8fd9
,
0x9ff8
,
0x6e17
,
0x7e36
,
0x4e55
,
0x5e74
,
0x2e93
,
0x3eb2
,
0x0ed1
,
0x1ef0
};
uint16_t
crc16
(
const
char
*
buf
,
int
len
)
{
int
counter
;
uint16_t
crc
=
0
;
for
(
counter
=
0
;
counter
<
len
;
counter
++
)
crc
=
(
crc
<<
8
)
^
crc16tab
[((
crc
>>
8
)
^
*
buf
++
)
&
0x00FF
];
return
crc
;
}
src/db.c
View file @
bfe85f7c
...
@@ -2,6 +2,9 @@
...
@@ -2,6 +2,9 @@
#include <signal.h>
#include <signal.h>
void
SlotToKeyAdd
(
robj
*
key
);
void
SlotToKeyDel
(
robj
*
key
);
/*-----------------------------------------------------------------------------
/*-----------------------------------------------------------------------------
* C-level DB API
* C-level DB API
*----------------------------------------------------------------------------*/
*----------------------------------------------------------------------------*/
...
@@ -131,6 +134,7 @@ int dbAdd(redisDb *db, robj *key, robj *val) {
...
@@ -131,6 +134,7 @@ int dbAdd(redisDb *db, robj *key, robj *val) {
sds
copy
=
sdsdup
(
key
->
ptr
);
sds
copy
=
sdsdup
(
key
->
ptr
);
dictAdd
(
db
->
dict
,
copy
,
val
);
dictAdd
(
db
->
dict
,
copy
,
val
);
if
(
server
.
ds_enabled
)
cacheSetKeyMayExist
(
db
,
key
);
if
(
server
.
ds_enabled
)
cacheSetKeyMayExist
(
db
,
key
);
if
(
server
.
cluster_enabled
)
SlotToKeyAdd
(
key
);
return
REDIS_OK
;
return
REDIS_OK
;
}
}
}
}
...
@@ -146,6 +150,7 @@ int dbReplace(redisDb *db, robj *key, robj *val) {
...
@@ -146,6 +150,7 @@ int dbReplace(redisDb *db, robj *key, robj *val) {
if
((
oldval
=
dictFetchValue
(
db
->
dict
,
key
->
ptr
))
==
NULL
)
{
if
((
oldval
=
dictFetchValue
(
db
->
dict
,
key
->
ptr
))
==
NULL
)
{
sds
copy
=
sdsdup
(
key
->
ptr
);
sds
copy
=
sdsdup
(
key
->
ptr
);
dictAdd
(
db
->
dict
,
copy
,
val
);
dictAdd
(
db
->
dict
,
copy
,
val
);
if
(
server
.
cluster_enabled
)
SlotToKeyAdd
(
key
);
retval
=
1
;
retval
=
1
;
}
else
{
}
else
{
dictReplace
(
db
->
dict
,
key
->
ptr
,
val
);
dictReplace
(
db
->
dict
,
key
->
ptr
,
val
);
...
@@ -198,7 +203,12 @@ int dbDelete(redisDb *db, robj *key) {
...
@@ -198,7 +203,12 @@ int dbDelete(redisDb *db, robj *key) {
/* Deleting an entry from the expires dict will not free the sds of
/* Deleting an entry from the expires dict will not free the sds of
* the key, because it is shared with the main dictionary. */
* the key, because it is shared with the main dictionary. */
if
(
dictSize
(
db
->
expires
)
>
0
)
dictDelete
(
db
->
expires
,
key
->
ptr
);
if
(
dictSize
(
db
->
expires
)
>
0
)
dictDelete
(
db
->
expires
,
key
->
ptr
);
return
dictDelete
(
db
->
dict
,
key
->
ptr
)
==
DICT_OK
;
if
(
dictDelete
(
db
->
dict
,
key
->
ptr
)
==
DICT_OK
)
{
if
(
server
.
cluster_enabled
)
SlotToKeyDel
(
key
);
return
1
;
}
else
{
return
0
;
}
}
}
/* Empty the whole database.
/* Empty the whole database.
...
@@ -307,6 +317,10 @@ void existsCommand(redisClient *c) {
...
@@ -307,6 +317,10 @@ void existsCommand(redisClient *c) {
void
selectCommand
(
redisClient
*
c
)
{
void
selectCommand
(
redisClient
*
c
)
{
int
id
=
atoi
(
c
->
argv
[
1
]
->
ptr
);
int
id
=
atoi
(
c
->
argv
[
1
]
->
ptr
);
if
(
server
.
cluster_enabled
&&
id
!=
0
)
{
addReplyError
(
c
,
"SELECT is not allowed in cluster mode"
);
return
;
}
if
(
selectDb
(
c
,
id
)
==
REDIS_ERR
)
{
if
(
selectDb
(
c
,
id
)
==
REDIS_ERR
)
{
addReplyError
(
c
,
"invalid DB index"
);
addReplyError
(
c
,
"invalid DB index"
);
}
else
{
}
else
{
...
@@ -428,6 +442,11 @@ void moveCommand(redisClient *c) {
...
@@ -428,6 +442,11 @@ void moveCommand(redisClient *c) {
redisDb
*
src
,
*
dst
;
redisDb
*
src
,
*
dst
;
int
srcid
;
int
srcid
;
if
(
server
.
cluster_enabled
)
{
addReplyError
(
c
,
"MOVE is not allowed in cluster mode"
);
return
;
}
/* Obtain source and target DB pointers */
/* Obtain source and target DB pointers */
src
=
c
->
db
;
src
=
c
->
db
;
srcid
=
c
->
db
->
id
;
srcid
=
c
->
db
->
id
;
...
@@ -616,3 +635,108 @@ void persistCommand(redisClient *c) {
...
@@ -616,3 +635,108 @@ void persistCommand(redisClient *c) {
}
}
}
}
}
}
/* -----------------------------------------------------------------------------
* API to get key arguments from commands
* ---------------------------------------------------------------------------*/
int
*
getKeysUsingCommandTable
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
)
{
int
j
,
i
=
0
,
last
,
*
keys
;
REDIS_NOTUSED
(
argv
);
if
(
cmd
->
firstkey
==
0
)
{
*
numkeys
=
0
;
return
NULL
;
}
last
=
cmd
->
lastkey
;
if
(
last
<
0
)
last
=
argc
+
last
;
keys
=
zmalloc
(
sizeof
(
int
)
*
((
last
-
cmd
->
firstkey
)
+
1
));
for
(
j
=
cmd
->
firstkey
;
j
<=
last
;
j
+=
cmd
->
keystep
)
{
redisAssert
(
j
<
argc
);
keys
[
i
++
]
=
j
;
}
*
numkeys
=
i
;
return
keys
;
}
int
*
getKeysFromCommand
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
)
{
if
(
cmd
->
getkeys_proc
)
{
return
cmd
->
getkeys_proc
(
cmd
,
argv
,
argc
,
numkeys
,
flags
);
}
else
{
return
getKeysUsingCommandTable
(
cmd
,
argv
,
argc
,
numkeys
);
}
}
void
getKeysFreeResult
(
int
*
result
)
{
zfree
(
result
);
}
int
*
noPreloadGetKeys
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
)
{
if
(
flags
&
REDIS_GETKEYS_PRELOAD
)
{
*
numkeys
=
0
;
return
NULL
;
}
else
{
return
getKeysUsingCommandTable
(
cmd
,
argv
,
argc
,
numkeys
);
}
}
int
*
renameGetKeys
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
)
{
if
(
flags
&
REDIS_GETKEYS_PRELOAD
)
{
int
*
keys
=
zmalloc
(
sizeof
(
int
));
*
numkeys
=
1
;
keys
[
0
]
=
1
;
return
keys
;
}
else
{
return
getKeysUsingCommandTable
(
cmd
,
argv
,
argc
,
numkeys
);
}
}
int
*
zunionInterGetKeys
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
)
{
int
i
,
num
,
*
keys
;
REDIS_NOTUSED
(
cmd
);
REDIS_NOTUSED
(
flags
);
num
=
atoi
(
argv
[
2
]
->
ptr
);
/* Sanity check. Don't return any key if the command is going to
* reply with syntax error. */
if
(
num
>
(
argc
-
3
))
{
*
numkeys
=
0
;
return
NULL
;
}
keys
=
zmalloc
(
sizeof
(
int
)
*
num
);
for
(
i
=
0
;
i
<
num
;
i
++
)
keys
[
i
]
=
3
+
i
;
*
numkeys
=
num
;
return
keys
;
}
/* Slot to Key API. This is used by Redis Cluster in order to obtain in
* a fast way a key that belongs to a specified hash slot. This is useful
* while rehashing the cluster. */
void
SlotToKeyAdd
(
robj
*
key
)
{
unsigned
int
hashslot
=
keyHashSlot
(
key
->
ptr
,
sdslen
(
key
->
ptr
));
zslInsert
(
server
.
cluster
.
slots_to_keys
,
hashslot
,
key
);
incrRefCount
(
key
);
}
void
SlotToKeyDel
(
robj
*
key
)
{
unsigned
int
hashslot
=
keyHashSlot
(
key
->
ptr
,
sdslen
(
key
->
ptr
));
zslDelete
(
server
.
cluster
.
slots_to_keys
,
hashslot
,
key
);
}
unsigned
int
GetKeysInSlot
(
unsigned
int
hashslot
,
robj
**
keys
,
unsigned
int
count
)
{
zskiplistNode
*
n
;
zrangespec
range
;
int
j
=
0
;
range
.
min
=
range
.
max
=
hashslot
;
range
.
minex
=
range
.
maxex
=
0
;
n
=
zslFirstInRange
(
server
.
cluster
.
slots_to_keys
,
range
);
while
(
n
&&
n
->
score
==
hashslot
&&
count
--
)
{
keys
[
j
++
]
=
n
->
obj
;
n
=
n
->
level
[
0
].
forward
;
}
return
j
;
}
src/debug.c
View file @
bfe85f7c
...
@@ -100,7 +100,7 @@ void computeDatasetDigest(unsigned char *final) {
...
@@ -100,7 +100,7 @@ void computeDatasetDigest(unsigned char *final) {
mixDigest
(
digest
,
key
,
sdslen
(
key
));
mixDigest
(
digest
,
key
,
sdslen
(
key
));
/* Make sure the key is loaded if VM is active */
/* Make sure the key is loaded if VM is active */
o
=
lookupKeyRead
(
db
,
keyobj
);
o
=
dictGetEntryVal
(
de
);
aux
=
htonl
(
o
->
type
);
aux
=
htonl
(
o
->
type
);
mixDigest
(
digest
,
&
aux
,
sizeof
(
aux
));
mixDigest
(
digest
,
&
aux
,
sizeof
(
aux
));
...
@@ -127,6 +127,39 @@ void computeDatasetDigest(unsigned char *final) {
...
@@ -127,6 +127,39 @@ void computeDatasetDigest(unsigned char *final) {
}
}
setTypeReleaseIterator
(
si
);
setTypeReleaseIterator
(
si
);
}
else
if
(
o
->
type
==
REDIS_ZSET
)
{
}
else
if
(
o
->
type
==
REDIS_ZSET
)
{
unsigned
char
eledigest
[
20
];
if
(
o
->
encoding
==
REDIS_ENCODING_ZIPLIST
)
{
unsigned
char
*
zl
=
o
->
ptr
;
unsigned
char
*
eptr
,
*
sptr
;
unsigned
char
*
vstr
;
unsigned
int
vlen
;
long
long
vll
;
double
score
;
eptr
=
ziplistIndex
(
zl
,
0
);
redisAssert
(
eptr
!=
NULL
);
sptr
=
ziplistNext
(
zl
,
eptr
);
redisAssert
(
sptr
!=
NULL
);
while
(
eptr
!=
NULL
)
{
redisAssert
(
ziplistGet
(
eptr
,
&
vstr
,
&
vlen
,
&
vll
));
score
=
zzlGetScore
(
sptr
);
memset
(
eledigest
,
0
,
20
);
if
(
vstr
!=
NULL
)
{
mixDigest
(
eledigest
,
vstr
,
vlen
);
}
else
{
ll2string
(
buf
,
sizeof
(
buf
),
vll
);
mixDigest
(
eledigest
,
buf
,
strlen
(
buf
));
}
snprintf
(
buf
,
sizeof
(
buf
),
"%.17g"
,
score
);
mixDigest
(
eledigest
,
buf
,
strlen
(
buf
));
xorDigest
(
digest
,
eledigest
,
20
);
zzlNext
(
zl
,
&
eptr
,
&
sptr
);
}
}
else
if
(
o
->
encoding
==
REDIS_ENCODING_SKIPLIST
)
{
zset
*
zs
=
o
->
ptr
;
zset
*
zs
=
o
->
ptr
;
dictIterator
*
di
=
dictGetIterator
(
zs
->
dict
);
dictIterator
*
di
=
dictGetIterator
(
zs
->
dict
);
dictEntry
*
de
;
dictEntry
*
de
;
...
@@ -134,7 +167,6 @@ void computeDatasetDigest(unsigned char *final) {
...
@@ -134,7 +167,6 @@ void computeDatasetDigest(unsigned char *final) {
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
while
((
de
=
dictNext
(
di
))
!=
NULL
)
{
robj
*
eleobj
=
dictGetEntryKey
(
de
);
robj
*
eleobj
=
dictGetEntryKey
(
de
);
double
*
score
=
dictGetEntryVal
(
de
);
double
*
score
=
dictGetEntryVal
(
de
);
unsigned
char
eledigest
[
20
];
snprintf
(
buf
,
sizeof
(
buf
),
"%.17g"
,
*
score
);
snprintf
(
buf
,
sizeof
(
buf
),
"%.17g"
,
*
score
);
memset
(
eledigest
,
0
,
20
);
memset
(
eledigest
,
0
,
20
);
...
@@ -143,6 +175,9 @@ void computeDatasetDigest(unsigned char *final) {
...
@@ -143,6 +175,9 @@ void computeDatasetDigest(unsigned char *final) {
xorDigest
(
digest
,
eledigest
,
20
);
xorDigest
(
digest
,
eledigest
,
20
);
}
}
dictReleaseIterator
(
di
);
dictReleaseIterator
(
di
);
}
else
{
redisPanic
(
"Unknown sorted set encoding"
);
}
}
else
if
(
o
->
type
==
REDIS_HASH
)
{
}
else
if
(
o
->
type
==
REDIS_HASH
)
{
hashTypeIterator
*
hi
;
hashTypeIterator
*
hi
;
robj
*
obj
;
robj
*
obj
;
...
...
src/dict.c
View file @
bfe85f7c
...
@@ -245,9 +245,9 @@ int dictRehashMilliseconds(dict *d, int ms) {
...
@@ -245,9 +245,9 @@ int dictRehashMilliseconds(dict *d, int ms) {
}
}
/* This function performs just a step of rehashing, and only if there are
/* This function performs just a step of rehashing, and only if there are
* no
t
iterators bound to our hash table. When we have iterators in the
middle
* no
safe
iterators bound to our hash table. When we have iterators in the
* of a rehashing we can't mess with the two hash tables otherwise
some element
*
middle
of a rehashing we can't mess with the two hash tables otherwise
* can be missed or duplicated.
*
some element
can be missed or duplicated.
*
*
* This function is called by common lookup or update operations in the
* This function is called by common lookup or update operations in the
* dictionary so that the hash table automatically migrates from H1 to H2
* dictionary so that the hash table automatically migrates from H1 to H2
...
@@ -424,17 +424,26 @@ dictIterator *dictGetIterator(dict *d)
...
@@ -424,17 +424,26 @@ dictIterator *dictGetIterator(dict *d)
iter
->
d
=
d
;
iter
->
d
=
d
;
iter
->
table
=
0
;
iter
->
table
=
0
;
iter
->
index
=
-
1
;
iter
->
index
=
-
1
;
iter
->
safe
=
0
;
iter
->
entry
=
NULL
;
iter
->
entry
=
NULL
;
iter
->
nextEntry
=
NULL
;
iter
->
nextEntry
=
NULL
;
return
iter
;
return
iter
;
}
}
dictIterator
*
dictGetSafeIterator
(
dict
*
d
)
{
dictIterator
*
i
=
dictGetIterator
(
d
);
i
->
safe
=
1
;
return
i
;
}
dictEntry
*
dictNext
(
dictIterator
*
iter
)
dictEntry
*
dictNext
(
dictIterator
*
iter
)
{
{
while
(
1
)
{
while
(
1
)
{
if
(
iter
->
entry
==
NULL
)
{
if
(
iter
->
entry
==
NULL
)
{
dictht
*
ht
=
&
iter
->
d
->
ht
[
iter
->
table
];
dictht
*
ht
=
&
iter
->
d
->
ht
[
iter
->
table
];
if
(
iter
->
index
==
-
1
&&
iter
->
table
==
0
)
iter
->
d
->
iterators
++
;
if
(
iter
->
safe
&&
iter
->
index
==
-
1
&&
iter
->
table
==
0
)
iter
->
d
->
iterators
++
;
iter
->
index
++
;
iter
->
index
++
;
if
(
iter
->
index
>=
(
signed
)
ht
->
size
)
{
if
(
iter
->
index
>=
(
signed
)
ht
->
size
)
{
if
(
dictIsRehashing
(
iter
->
d
)
&&
iter
->
table
==
0
)
{
if
(
dictIsRehashing
(
iter
->
d
)
&&
iter
->
table
==
0
)
{
...
@@ -461,7 +470,8 @@ dictEntry *dictNext(dictIterator *iter)
...
@@ -461,7 +470,8 @@ dictEntry *dictNext(dictIterator *iter)
void
dictReleaseIterator
(
dictIterator
*
iter
)
void
dictReleaseIterator
(
dictIterator
*
iter
)
{
{
if
(
!
(
iter
->
index
==
-
1
&&
iter
->
table
==
0
))
iter
->
d
->
iterators
--
;
if
(
iter
->
safe
&&
!
(
iter
->
index
==
-
1
&&
iter
->
table
==
0
))
iter
->
d
->
iterators
--
;
zfree
(
iter
);
zfree
(
iter
);
}
}
...
...
src/dict.h
View file @
bfe85f7c
...
@@ -74,10 +74,13 @@ typedef struct dict {
...
@@ -74,10 +74,13 @@ typedef struct dict {
int
iterators
;
/* number of iterators currently running */
int
iterators
;
/* number of iterators currently running */
}
dict
;
}
dict
;
/* If safe is set to 1 this is a safe iteartor, that means, you can call
* dictAdd, dictFind, and other functions against the dictionary even while
* iterating. Otherwise it is a non safe iterator, and only dictNext()
* should be called while iterating. */
typedef
struct
dictIterator
{
typedef
struct
dictIterator
{
dict
*
d
;
dict
*
d
;
int
table
;
int
table
,
index
,
safe
;
int
index
;
dictEntry
*
entry
,
*
nextEntry
;
dictEntry
*
entry
,
*
nextEntry
;
}
dictIterator
;
}
dictIterator
;
...
@@ -132,6 +135,7 @@ dictEntry * dictFind(dict *d, const void *key);
...
@@ -132,6 +135,7 @@ dictEntry * dictFind(dict *d, const void *key);
void
*
dictFetchValue
(
dict
*
d
,
const
void
*
key
);
void
*
dictFetchValue
(
dict
*
d
,
const
void
*
key
);
int
dictResize
(
dict
*
d
);
int
dictResize
(
dict
*
d
);
dictIterator
*
dictGetIterator
(
dict
*
d
);
dictIterator
*
dictGetIterator
(
dict
*
d
);
dictIterator
*
dictGetSafeIterator
(
dict
*
d
);
dictEntry
*
dictNext
(
dictIterator
*
iter
);
dictEntry
*
dictNext
(
dictIterator
*
iter
);
void
dictReleaseIterator
(
dictIterator
*
iter
);
void
dictReleaseIterator
(
dictIterator
*
iter
);
dictEntry
*
dictGetRandomKey
(
dict
*
d
);
dictEntry
*
dictGetRandomKey
(
dict
*
d
);
...
...
src/dscache.c
View file @
bfe85f7c
...
@@ -903,59 +903,6 @@ int waitForSwappedKey(redisClient *c, robj *key) {
...
@@ -903,59 +903,6 @@ int waitForSwappedKey(redisClient *c, robj *key) {
return
1
;
return
1
;
}
}
/* Preload keys for any command with first, last and step values for
* the command keys prototype, as defined in the command table. */
void
waitForMultipleSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
int
argc
,
robj
**
argv
)
{
int
j
,
last
;
if
(
cmd
->
vm_firstkey
==
0
)
return
;
last
=
cmd
->
vm_lastkey
;
if
(
last
<
0
)
last
=
argc
+
last
;
for
(
j
=
cmd
->
vm_firstkey
;
j
<=
last
;
j
+=
cmd
->
vm_keystep
)
{
redisAssert
(
j
<
argc
);
waitForSwappedKey
(
c
,
argv
[
j
]);
}
}
/* Preload keys needed for the ZUNIONSTORE and ZINTERSTORE commands.
* Note that the number of keys to preload is user-defined, so we need to
* apply a sanity check against argc. */
void
zunionInterBlockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
int
argc
,
robj
**
argv
)
{
int
i
,
num
;
REDIS_NOTUSED
(
cmd
);
num
=
atoi
(
argv
[
2
]
->
ptr
);
if
(
num
>
(
argc
-
3
))
return
;
for
(
i
=
0
;
i
<
num
;
i
++
)
{
waitForSwappedKey
(
c
,
argv
[
3
+
i
]);
}
}
/* Preload keys needed to execute the entire MULTI/EXEC block.
*
* This function is called by blockClientOnSwappedKeys when EXEC is issued,
* and will block the client when any command requires a swapped out value. */
void
execBlockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
int
argc
,
robj
**
argv
)
{
int
i
,
margc
;
struct
redisCommand
*
mcmd
;
robj
**
margv
;
REDIS_NOTUSED
(
cmd
);
REDIS_NOTUSED
(
argc
);
REDIS_NOTUSED
(
argv
);
if
(
!
(
c
->
flags
&
REDIS_MULTI
))
return
;
for
(
i
=
0
;
i
<
c
->
mstate
.
count
;
i
++
)
{
mcmd
=
c
->
mstate
.
commands
[
i
].
cmd
;
margc
=
c
->
mstate
.
commands
[
i
].
argc
;
margv
=
c
->
mstate
.
commands
[
i
].
argv
;
if
(
mcmd
->
vm_preload_proc
!=
NULL
)
{
mcmd
->
vm_preload_proc
(
c
,
mcmd
,
margc
,
margv
);
}
else
{
waitForMultipleSwappedKeys
(
c
,
mcmd
,
margc
,
margv
);
}
}
}
/* Is this client attempting to run a command against swapped keys?
/* Is this client attempting to run a command against swapped keys?
* If so, block it ASAP, load the keys in background, then resume it.
* If so, block it ASAP, load the keys in background, then resume it.
*
*
...
@@ -967,10 +914,39 @@ void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int
...
@@ -967,10 +914,39 @@ void execBlockClientOnSwappedKeys(redisClient *c, struct redisCommand *cmd, int
* Return 1 if the client is marked as blocked, 0 if the client can
* Return 1 if the client is marked as blocked, 0 if the client can
* continue as the keys it is going to access appear to be in memory. */
* continue as the keys it is going to access appear to be in memory. */
int
blockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
)
{
int
blockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
)
{
if
(
cmd
->
vm_preload_proc
!=
NULL
)
{
int
*
keyindex
,
numkeys
,
j
,
i
;
cmd
->
vm_preload_proc
(
c
,
cmd
,
c
->
argc
,
c
->
argv
);
/* EXEC is a special case, we need to preload all the commands
* queued into the transaction */
if
(
cmd
->
proc
==
execCommand
)
{
struct
redisCommand
*
mcmd
;
robj
**
margv
;
int
margc
;
if
(
!
(
c
->
flags
&
REDIS_MULTI
))
return
0
;
for
(
i
=
0
;
i
<
c
->
mstate
.
count
;
i
++
)
{
mcmd
=
c
->
mstate
.
commands
[
i
].
cmd
;
margc
=
c
->
mstate
.
commands
[
i
].
argc
;
margv
=
c
->
mstate
.
commands
[
i
].
argv
;
keyindex
=
getKeysFromCommand
(
mcmd
,
margv
,
margc
,
&
numkeys
,
REDIS_GETKEYS_PRELOAD
);
for
(
j
=
0
;
j
<
numkeys
;
j
++
)
{
redisLog
(
REDIS_DEBUG
,
"Preloading %s"
,
(
char
*
)
margv
[
keyindex
[
j
]]
->
ptr
);
waitForSwappedKey
(
c
,
margv
[
keyindex
[
j
]]);
}
getKeysFreeResult
(
keyindex
);
}
}
else
{
}
else
{
waitForMultipleSwappedKeys
(
c
,
cmd
,
c
->
argc
,
c
->
argv
);
keyindex
=
getKeysFromCommand
(
cmd
,
c
->
argv
,
c
->
argc
,
&
numkeys
,
REDIS_GETKEYS_PRELOAD
);
for
(
j
=
0
;
j
<
numkeys
;
j
++
)
{
redisLog
(
REDIS_DEBUG
,
"Preloading %s"
,
(
char
*
)
c
->
argv
[
keyindex
[
j
]]
->
ptr
);
waitForSwappedKey
(
c
,
c
->
argv
[
keyindex
[
j
]]);
}
getKeysFreeResult
(
keyindex
);
}
}
/* If the client was blocked for at least one key, mark it as blocked. */
/* If the client was blocked for at least one key, mark it as blocked. */
...
...
src/networking.c
View file @
bfe85f7c
...
@@ -16,7 +16,6 @@ redisClient *createClient(int fd) {
...
@@ -16,7 +16,6 @@ redisClient *createClient(int fd) {
anetNonBlock
(
NULL
,
fd
);
anetNonBlock
(
NULL
,
fd
);
anetTcpNoDelay
(
NULL
,
fd
);
anetTcpNoDelay
(
NULL
,
fd
);
if
(
!
c
)
return
NULL
;
if
(
aeCreateFileEvent
(
server
.
el
,
fd
,
AE_READABLE
,
if
(
aeCreateFileEvent
(
server
.
el
,
fd
,
AE_READABLE
,
readQueryFromClient
,
c
)
==
AE_ERR
)
readQueryFromClient
,
c
)
==
AE_ERR
)
{
{
...
@@ -60,9 +59,6 @@ redisClient *createClient(int fd) {
...
@@ -60,9 +59,6 @@ redisClient *createClient(int fd) {
/* Set the event loop to listen for write events on the client's socket.
/* Set the event loop to listen for write events on the client's socket.
* Typically gets called every time a reply is built. */
* Typically gets called every time a reply is built. */
int
_installWriteEvent
(
redisClient
*
c
)
{
int
_installWriteEvent
(
redisClient
*
c
)
{
/* When CLOSE_AFTER_REPLY is set, no more replies may be added! */
redisAssert
(
!
(
c
->
flags
&
REDIS_CLOSE_AFTER_REPLY
));
if
(
c
->
fd
<=
0
)
return
REDIS_ERR
;
if
(
c
->
fd
<=
0
)
return
REDIS_ERR
;
if
(
c
->
bufpos
==
0
&&
listLength
(
c
->
reply
)
==
0
&&
if
(
c
->
bufpos
==
0
&&
listLength
(
c
->
reply
)
==
0
&&
(
c
->
replstate
==
REDIS_REPL_NONE
||
(
c
->
replstate
==
REDIS_REPL_NONE
||
...
@@ -88,9 +84,15 @@ robj *dupLastObjectIfNeeded(list *reply) {
...
@@ -88,9 +84,15 @@ robj *dupLastObjectIfNeeded(list *reply) {
return
listNodeValue
(
ln
);
return
listNodeValue
(
ln
);
}
}
/* -----------------------------------------------------------------------------
* Low level functions to add more data to output buffers.
* -------------------------------------------------------------------------- */
int
_addReplyToBuffer
(
redisClient
*
c
,
char
*
s
,
size_t
len
)
{
int
_addReplyToBuffer
(
redisClient
*
c
,
char
*
s
,
size_t
len
)
{
size_t
available
=
sizeof
(
c
->
buf
)
-
c
->
bufpos
;
size_t
available
=
sizeof
(
c
->
buf
)
-
c
->
bufpos
;
if
(
c
->
flags
&
REDIS_CLOSE_AFTER_REPLY
)
return
REDIS_OK
;
/* If there already are entries in the reply list, we cannot
/* If there already are entries in the reply list, we cannot
* add anything more to the static buffer. */
* add anything more to the static buffer. */
if
(
listLength
(
c
->
reply
)
>
0
)
return
REDIS_ERR
;
if
(
listLength
(
c
->
reply
)
>
0
)
return
REDIS_ERR
;
...
@@ -105,6 +107,9 @@ int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
...
@@ -105,6 +107,9 @@ int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
void
_addReplyObjectToList
(
redisClient
*
c
,
robj
*
o
)
{
void
_addReplyObjectToList
(
redisClient
*
c
,
robj
*
o
)
{
robj
*
tail
;
robj
*
tail
;
if
(
c
->
flags
&
REDIS_CLOSE_AFTER_REPLY
)
return
;
if
(
listLength
(
c
->
reply
)
==
0
)
{
if
(
listLength
(
c
->
reply
)
==
0
)
{
incrRefCount
(
o
);
incrRefCount
(
o
);
listAddNodeTail
(
c
->
reply
,
o
);
listAddNodeTail
(
c
->
reply
,
o
);
...
@@ -128,6 +133,12 @@ void _addReplyObjectToList(redisClient *c, robj *o) {
...
@@ -128,6 +133,12 @@ void _addReplyObjectToList(redisClient *c, robj *o) {
* needed it will be free'd, otherwise it ends up in a robj. */
* needed it will be free'd, otherwise it ends up in a robj. */
void
_addReplySdsToList
(
redisClient
*
c
,
sds
s
)
{
void
_addReplySdsToList
(
redisClient
*
c
,
sds
s
)
{
robj
*
tail
;
robj
*
tail
;
if
(
c
->
flags
&
REDIS_CLOSE_AFTER_REPLY
)
{
sdsfree
(
s
);
return
;
}
if
(
listLength
(
c
->
reply
)
==
0
)
{
if
(
listLength
(
c
->
reply
)
==
0
)
{
listAddNodeTail
(
c
->
reply
,
createObject
(
REDIS_STRING
,
s
));
listAddNodeTail
(
c
->
reply
,
createObject
(
REDIS_STRING
,
s
));
}
else
{
}
else
{
...
@@ -148,6 +159,9 @@ void _addReplySdsToList(redisClient *c, sds s) {
...
@@ -148,6 +159,9 @@ void _addReplySdsToList(redisClient *c, sds s) {
void
_addReplyStringToList
(
redisClient
*
c
,
char
*
s
,
size_t
len
)
{
void
_addReplyStringToList
(
redisClient
*
c
,
char
*
s
,
size_t
len
)
{
robj
*
tail
;
robj
*
tail
;
if
(
c
->
flags
&
REDIS_CLOSE_AFTER_REPLY
)
return
;
if
(
listLength
(
c
->
reply
)
==
0
)
{
if
(
listLength
(
c
->
reply
)
==
0
)
{
listAddNodeTail
(
c
->
reply
,
createStringObject
(
s
,
len
));
listAddNodeTail
(
c
->
reply
,
createStringObject
(
s
,
len
));
}
else
{
}
else
{
...
@@ -165,6 +179,11 @@ void _addReplyStringToList(redisClient *c, char *s, size_t len) {
...
@@ -165,6 +179,11 @@ void _addReplyStringToList(redisClient *c, char *s, size_t len) {
}
}
}
}
/* -----------------------------------------------------------------------------
* Higher level functions to queue data on the client output buffer.
* The following functions are the ones that commands implementations will call.
* -------------------------------------------------------------------------- */
void
addReply
(
redisClient
*
c
,
robj
*
obj
)
{
void
addReply
(
redisClient
*
c
,
robj
*
obj
)
{
if
(
_installWriteEvent
(
c
)
!=
REDIS_OK
)
return
;
if
(
_installWriteEvent
(
c
)
!=
REDIS_OK
)
return
;
...
@@ -301,6 +320,11 @@ void _addReplyLongLong(redisClient *c, long long ll, char prefix) {
...
@@ -301,6 +320,11 @@ void _addReplyLongLong(redisClient *c, long long ll, char prefix) {
}
}
void
addReplyLongLong
(
redisClient
*
c
,
long
long
ll
)
{
void
addReplyLongLong
(
redisClient
*
c
,
long
long
ll
)
{
if
(
ll
==
0
)
addReply
(
c
,
shared
.
czero
);
else
if
(
ll
==
1
)
addReply
(
c
,
shared
.
cone
);
else
_addReplyLongLong
(
c
,
ll
,
':'
);
_addReplyLongLong
(
c
,
ll
,
':'
);
}
}
...
@@ -395,7 +419,7 @@ void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
...
@@ -395,7 +419,7 @@ void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
cfd
=
anetTcpAccept
(
server
.
neterr
,
fd
,
cip
,
&
cport
);
cfd
=
anetTcpAccept
(
server
.
neterr
,
fd
,
cip
,
&
cport
);
if
(
cfd
==
AE_ERR
)
{
if
(
cfd
==
AE_ERR
)
{
redisLog
(
REDIS_
VERBOSE
,
"Accepting client connection: %s"
,
server
.
neterr
);
redisLog
(
REDIS_
WARNING
,
"Accepting client connection: %s"
,
server
.
neterr
);
return
;
return
;
}
}
redisLog
(
REDIS_VERBOSE
,
"Accepted %s:%d"
,
cip
,
cport
);
redisLog
(
REDIS_VERBOSE
,
"Accepted %s:%d"
,
cip
,
cport
);
...
@@ -410,7 +434,7 @@ void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
...
@@ -410,7 +434,7 @@ void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
cfd
=
anetUnixAccept
(
server
.
neterr
,
fd
);
cfd
=
anetUnixAccept
(
server
.
neterr
,
fd
);
if
(
cfd
==
AE_ERR
)
{
if
(
cfd
==
AE_ERR
)
{
redisLog
(
REDIS_
VERBOSE
,
"Accepting client connection: %s"
,
server
.
neterr
);
redisLog
(
REDIS_
WARNING
,
"Accepting client connection: %s"
,
server
.
neterr
);
return
;
return
;
}
}
redisLog
(
REDIS_VERBOSE
,
"Accepted connection to %s"
,
server
.
unixsocket
);
redisLog
(
REDIS_VERBOSE
,
"Accepted connection to %s"
,
server
.
unixsocket
);
...
@@ -502,12 +526,18 @@ void freeClient(redisClient *c) {
...
@@ -502,12 +526,18 @@ void freeClient(redisClient *c) {
* close the connection with all our slaves if we have any, so
* close the connection with all our slaves if we have any, so
* when we'll resync with the master the other slaves will sync again
* when we'll resync with the master the other slaves will sync again
* with us as well. Note that also when the slave is not connected
* with us as well. Note that also when the slave is not connected
* to the master it will keep refusing connections by other slaves. */
* to the master it will keep refusing connections by other slaves.
*
* We do this only if server.masterhost != NULL. If it is NULL this
* means the user called SLAVEOF NO ONE and we are freeing our
* link with the master, so no need to close link with slaves. */
if
(
server
.
masterhost
!=
NULL
)
{
while
(
listLength
(
server
.
slaves
))
{
while
(
listLength
(
server
.
slaves
))
{
ln
=
listFirst
(
server
.
slaves
);
ln
=
listFirst
(
server
.
slaves
);
freeClient
((
redisClient
*
)
ln
->
value
);
freeClient
((
redisClient
*
)
ln
->
value
);
}
}
}
}
}
/* Release memory */
/* Release memory */
zfree
(
c
->
argv
);
zfree
(
c
->
argv
);
freeClientMultiState
(
c
);
freeClientMultiState
(
c
);
...
@@ -670,47 +700,57 @@ static void setProtocolError(redisClient *c, int pos) {
...
@@ -670,47 +700,57 @@ static void setProtocolError(redisClient *c, int pos) {
int
processMultibulkBuffer
(
redisClient
*
c
)
{
int
processMultibulkBuffer
(
redisClient
*
c
)
{
char
*
newline
=
NULL
;
char
*
newline
=
NULL
;
char
*
eptr
;
int
pos
=
0
,
ok
;
int
pos
=
0
,
tolerr
;
long
long
ll
;
long
bulklen
;
if
(
c
->
multibulklen
==
0
)
{
if
(
c
->
multibulklen
==
0
)
{
/* The client should have been reset */
/* The client should have been reset */
redisAssert
(
c
->
argc
==
0
);
redisAssert
(
c
->
argc
==
0
);
/* Multi bulk length cannot be read without a \r\n */
/* Multi bulk length cannot be read without a \r\n */
newline
=
str
st
r
(
c
->
querybuf
,
"
\r
\n
"
);
newline
=
str
ch
r
(
c
->
querybuf
,
'
\r
'
);
if
(
newline
==
NULL
)
if
(
newline
==
NULL
)
return
REDIS_ERR
;
return
REDIS_ERR
;
/* Buffer should also contain \n */
if
(
newline
-
(
c
->
querybuf
)
>
((
signed
)
sdslen
(
c
->
querybuf
)
-
2
))
return
REDIS_ERR
;
/* We know for sure there is a whole line since newline != NULL,
/* We know for sure there is a whole line since newline != NULL,
* so go ahead and find out the multi bulk length. */
* so go ahead and find out the multi bulk length. */
redisAssert
(
c
->
querybuf
[
0
]
==
'*'
);
redisAssert
(
c
->
querybuf
[
0
]
==
'*'
);
c
->
multibulklen
=
strtol
(
c
->
querybuf
+
1
,
&
eptr
,
10
);
ok
=
string2ll
(
c
->
querybuf
+
1
,
newline
-
(
c
->
querybuf
+
1
),
&
ll
);
pos
=
(
newline
-
c
->
querybuf
)
+
2
;
if
(
!
ok
||
ll
>
1024
*
1024
)
{
if
(
c
->
multibulklen
<=
0
)
{
c
->
querybuf
=
sdsrange
(
c
->
querybuf
,
pos
,
-
1
);
return
REDIS_OK
;
}
else
if
(
c
->
multibulklen
>
1024
*
1024
)
{
addReplyError
(
c
,
"Protocol error: invalid multibulk length"
);
addReplyError
(
c
,
"Protocol error: invalid multibulk length"
);
setProtocolError
(
c
,
pos
);
setProtocolError
(
c
,
pos
);
return
REDIS_ERR
;
return
REDIS_ERR
;
}
}
pos
=
(
newline
-
c
->
querybuf
)
+
2
;
if
(
ll
<=
0
)
{
c
->
querybuf
=
sdsrange
(
c
->
querybuf
,
pos
,
-
1
);
return
REDIS_OK
;
}
c
->
multibulklen
=
ll
;
/* Setup argv array on client structure */
/* Setup argv array on client structure */
if
(
c
->
argv
)
zfree
(
c
->
argv
);
if
(
c
->
argv
)
zfree
(
c
->
argv
);
c
->
argv
=
zmalloc
(
sizeof
(
robj
*
)
*
c
->
multibulklen
);
c
->
argv
=
zmalloc
(
sizeof
(
robj
*
)
*
c
->
multibulklen
);
/* Search new newline */
newline
=
strstr
(
c
->
querybuf
+
pos
,
"
\r\n
"
);
}
}
redisAssert
(
c
->
multibulklen
>
0
);
redisAssert
(
c
->
multibulklen
>
0
);
while
(
c
->
multibulklen
)
{
while
(
c
->
multibulklen
)
{
/* Read bulk length if unknown */
/* Read bulk length if unknown */
if
(
c
->
bulklen
==
-
1
)
{
if
(
c
->
bulklen
==
-
1
)
{
newline
=
strstr
(
c
->
querybuf
+
pos
,
"
\r\n
"
);
newline
=
strchr
(
c
->
querybuf
+
pos
,
'\r'
);
if
(
newline
!=
NULL
)
{
if
(
newline
==
NULL
)
break
;
/* Buffer should also contain \n */
if
(
newline
-
(
c
->
querybuf
)
>
((
signed
)
sdslen
(
c
->
querybuf
)
-
2
))
break
;
if
(
c
->
querybuf
[
pos
]
!=
'$'
)
{
if
(
c
->
querybuf
[
pos
]
!=
'$'
)
{
addReplyErrorFormat
(
c
,
addReplyErrorFormat
(
c
,
"Protocol error: expected '$', got '%c'"
,
"Protocol error: expected '$', got '%c'"
,
...
@@ -719,21 +759,15 @@ int processMultibulkBuffer(redisClient *c) {
...
@@ -719,21 +759,15 @@ int processMultibulkBuffer(redisClient *c) {
return
REDIS_ERR
;
return
REDIS_ERR
;
}
}
bulklen
=
strtol
(
c
->
querybuf
+
pos
+
1
,
&
eptr
,
10
);
ok
=
string2ll
(
c
->
querybuf
+
pos
+
1
,
newline
-
(
c
->
querybuf
+
pos
+
1
),
&
ll
);
tolerr
=
(
eptr
[
0
]
!=
'\r'
);
if
(
!
ok
||
ll
<
0
||
ll
>
512
*
1024
*
1024
)
{
if
(
tolerr
||
bulklen
==
LONG_MIN
||
bulklen
==
LONG_MAX
||
bulklen
<
0
||
bulklen
>
512
*
1024
*
1024
)
{
addReplyError
(
c
,
"Protocol error: invalid bulk length"
);
addReplyError
(
c
,
"Protocol error: invalid bulk length"
);
setProtocolError
(
c
,
pos
);
setProtocolError
(
c
,
pos
);
return
REDIS_ERR
;
return
REDIS_ERR
;
}
}
pos
+=
eptr
-
(
c
->
querybuf
+
pos
)
+
2
;
c
->
bulklen
=
bulklen
;
pos
+=
newline
-
(
c
->
querybuf
+
pos
)
+
2
;
}
else
{
c
->
bulklen
=
ll
;
/* No newline in current buffer, so wait for more data */
break
;
}
}
}
/* Read bulk argument */
/* Read bulk argument */
...
@@ -845,3 +879,70 @@ void getClientsMaxBuffers(unsigned long *longest_output_list,
...
@@ -845,3 +879,70 @@ void getClientsMaxBuffers(unsigned long *longest_output_list,
*
biggest_input_buffer
=
bib
;
*
biggest_input_buffer
=
bib
;
}
}
void
clientCommand
(
redisClient
*
c
)
{
listNode
*
ln
;
listIter
li
;
redisClient
*
client
;
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"list"
)
&&
c
->
argc
==
2
)
{
sds
o
=
sdsempty
();
time_t
now
=
time
(
NULL
);
listRewind
(
server
.
clients
,
&
li
);
while
((
ln
=
listNext
(
&
li
))
!=
NULL
)
{
char
ip
[
32
],
flags
[
16
],
*
p
;
int
port
;
client
=
listNodeValue
(
ln
);
if
(
anetPeerToString
(
client
->
fd
,
ip
,
&
port
)
==
-
1
)
continue
;
p
=
flags
;
if
(
client
->
flags
&
REDIS_SLAVE
)
{
if
(
client
->
flags
&
REDIS_MONITOR
)
*
p
++
=
'O'
;
else
*
p
++
=
'S'
;
}
if
(
client
->
flags
&
REDIS_MASTER
)
*
p
++
=
'M'
;
if
(
p
==
flags
)
*
p
++
=
'N'
;
if
(
client
->
flags
&
REDIS_MULTI
)
*
p
++
=
'x'
;
if
(
client
->
flags
&
REDIS_BLOCKED
)
*
p
++
=
'b'
;
if
(
client
->
flags
&
REDIS_IO_WAIT
)
*
p
++
=
'i'
;
if
(
client
->
flags
&
REDIS_DIRTY_CAS
)
*
p
++
=
'd'
;
if
(
client
->
flags
&
REDIS_CLOSE_AFTER_REPLY
)
*
p
++
=
'c'
;
if
(
client
->
flags
&
REDIS_UNBLOCKED
)
*
p
++
=
'u'
;
*
p
++
=
'\0'
;
o
=
sdscatprintf
(
o
,
"addr=%s:%d fd=%d idle=%ld flags=%s db=%d sub=%d psub=%d
\n
"
,
ip
,
port
,
client
->
fd
,
(
long
)(
now
-
client
->
lastinteraction
),
flags
,
client
->
db
->
id
,
(
int
)
dictSize
(
client
->
pubsub_channels
),
(
int
)
listLength
(
client
->
pubsub_patterns
));
}
addReplyBulkCBuffer
(
c
,
o
,
sdslen
(
o
));
sdsfree
(
o
);
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"kill"
)
&&
c
->
argc
==
3
)
{
listRewind
(
server
.
clients
,
&
li
);
while
((
ln
=
listNext
(
&
li
))
!=
NULL
)
{
char
ip
[
32
],
addr
[
64
];
int
port
;
client
=
listNodeValue
(
ln
);
if
(
anetPeerToString
(
client
->
fd
,
ip
,
&
port
)
==
-
1
)
continue
;
snprintf
(
addr
,
sizeof
(
addr
),
"%s:%d"
,
ip
,
port
);
if
(
strcmp
(
addr
,
c
->
argv
[
2
]
->
ptr
)
==
0
)
{
addReply
(
c
,
shared
.
ok
);
if
(
c
==
client
)
{
client
->
flags
|=
REDIS_CLOSE_AFTER_REPLY
;
}
else
{
freeClient
(
client
);
}
return
;
}
}
addReplyError
(
c
,
"No such client"
);
}
else
{
addReplyError
(
c
,
"Syntax error, try CLIENT (LIST | KILL ip:port)"
);
}
}
src/object.c
View file @
bfe85f7c
...
@@ -93,10 +93,20 @@ robj *createHashObject(void) {
...
@@ -93,10 +93,20 @@ robj *createHashObject(void) {
robj
*
createZsetObject
(
void
)
{
robj
*
createZsetObject
(
void
)
{
zset
*
zs
=
zmalloc
(
sizeof
(
*
zs
));
zset
*
zs
=
zmalloc
(
sizeof
(
*
zs
));
robj
*
o
;
zs
->
dict
=
dictCreate
(
&
zsetDictType
,
NULL
);
zs
->
dict
=
dictCreate
(
&
zsetDictType
,
NULL
);
zs
->
zsl
=
zslCreate
();
zs
->
zsl
=
zslCreate
();
return
createObject
(
REDIS_ZSET
,
zs
);
o
=
createObject
(
REDIS_ZSET
,
zs
);
o
->
encoding
=
REDIS_ENCODING_SKIPLIST
;
return
o
;
}
robj
*
createZsetZiplistObject
(
void
)
{
unsigned
char
*
zl
=
ziplistNew
();
robj
*
o
=
createObject
(
REDIS_ZSET
,
zl
);
o
->
encoding
=
REDIS_ENCODING_ZIPLIST
;
return
o
;
}
}
void
freeStringObject
(
robj
*
o
)
{
void
freeStringObject
(
robj
*
o
)
{
...
@@ -132,11 +142,20 @@ void freeSetObject(robj *o) {
...
@@ -132,11 +142,20 @@ void freeSetObject(robj *o) {
}
}
void
freeZsetObject
(
robj
*
o
)
{
void
freeZsetObject
(
robj
*
o
)
{
zset
*
zs
=
o
->
ptr
;
zset
*
zs
;
switch
(
o
->
encoding
)
{
case
REDIS_ENCODING_SKIPLIST
:
zs
=
o
->
ptr
;
dictRelease
(
zs
->
dict
);
dictRelease
(
zs
->
dict
);
zslFree
(
zs
->
zsl
);
zslFree
(
zs
->
zsl
);
zfree
(
zs
);
zfree
(
zs
);
break
;
case
REDIS_ENCODING_ZIPLIST
:
zfree
(
o
->
ptr
);
break
;
default:
redisPanic
(
"Unknown sorted set encoding"
);
}
}
}
void
freeHashObject
(
robj
*
o
)
{
void
freeHashObject
(
robj
*
o
)
{
...
@@ -183,6 +202,16 @@ int checkType(redisClient *c, robj *o, int type) {
...
@@ -183,6 +202,16 @@ int checkType(redisClient *c, robj *o, int type) {
return
0
;
return
0
;
}
}
int
isObjectRepresentableAsLongLong
(
robj
*
o
,
long
long
*
llval
)
{
redisAssert
(
o
->
type
==
REDIS_STRING
);
if
(
o
->
encoding
==
REDIS_ENCODING_INT
)
{
if
(
llval
)
*
llval
=
(
long
)
o
->
ptr
;
return
REDIS_OK
;
}
else
{
return
string2ll
(
o
->
ptr
,
sdslen
(
o
->
ptr
),
llval
)
?
REDIS_OK
:
REDIS_ERR
;
}
}
/* Try to encode a string object in order to save space */
/* Try to encode a string object in order to save space */
robj
*
tryObjectEncoding
(
robj
*
o
)
{
robj
*
tryObjectEncoding
(
robj
*
o
)
{
long
value
;
long
value
;
...
@@ -200,7 +229,7 @@ robj *tryObjectEncoding(robj *o) {
...
@@ -200,7 +229,7 @@ robj *tryObjectEncoding(robj *o) {
redisAssert
(
o
->
type
==
REDIS_STRING
);
redisAssert
(
o
->
type
==
REDIS_STRING
);
/* Check if we can represent this string as a long integer */
/* Check if we can represent this string as a long integer */
if
(
isS
tring
RepresentableAsLong
(
s
,
&
value
)
==
REDIS_ERR
)
return
o
;
if
(
!
s
tring
2l
(
s
,
sdslen
(
s
)
,
&
value
))
return
o
;
/* Ok, this object can be encoded...
/* Ok, this object can be encoded...
*
*
...
@@ -402,6 +431,7 @@ char *strEncoding(int encoding) {
...
@@ -402,6 +431,7 @@ char *strEncoding(int encoding) {
case
REDIS_ENCODING_LINKEDLIST
:
return
"linkedlist"
;
case
REDIS_ENCODING_LINKEDLIST
:
return
"linkedlist"
;
case
REDIS_ENCODING_ZIPLIST
:
return
"ziplist"
;
case
REDIS_ENCODING_ZIPLIST
:
return
"ziplist"
;
case
REDIS_ENCODING_INTSET
:
return
"intset"
;
case
REDIS_ENCODING_INTSET
:
return
"intset"
;
case
REDIS_ENCODING_SKIPLIST
:
return
"skiplist"
;
default:
return
"unknown"
;
default:
return
"unknown"
;
}
}
}
}
...
@@ -416,3 +446,42 @@ unsigned long estimateObjectIdleTime(robj *o) {
...
@@ -416,3 +446,42 @@ unsigned long estimateObjectIdleTime(robj *o) {
REDIS_LRU_CLOCK_RESOLUTION
;
REDIS_LRU_CLOCK_RESOLUTION
;
}
}
}
}
/* This is an helper function for the DEBUG command. We need to lookup keys
* without any modification of LRU or other parameters. */
robj
*
objectCommandLookup
(
redisClient
*
c
,
robj
*
key
)
{
dictEntry
*
de
;
if
((
de
=
dictFind
(
c
->
db
->
dict
,
key
->
ptr
))
==
NULL
)
return
NULL
;
return
(
robj
*
)
dictGetEntryVal
(
de
);
}
robj
*
objectCommandLookupOrReply
(
redisClient
*
c
,
robj
*
key
,
robj
*
reply
)
{
robj
*
o
=
objectCommandLookup
(
c
,
key
);
if
(
!
o
)
addReply
(
c
,
reply
);
return
o
;
}
/* Object command allows to inspect the internals of an Redis Object.
* Usage: OBJECT <verb> ... arguments ... */
void
objectCommand
(
redisClient
*
c
)
{
robj
*
o
;
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"refcount"
)
&&
c
->
argc
==
3
)
{
if
((
o
=
objectCommandLookupOrReply
(
c
,
c
->
argv
[
2
],
shared
.
nullbulk
))
==
NULL
)
return
;
addReplyLongLong
(
c
,
o
->
refcount
);
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"encoding"
)
&&
c
->
argc
==
3
)
{
if
((
o
=
objectCommandLookupOrReply
(
c
,
c
->
argv
[
2
],
shared
.
nullbulk
))
==
NULL
)
return
;
addReplyBulkCString
(
c
,
strEncoding
(
o
->
encoding
));
}
else
if
(
!
strcasecmp
(
c
->
argv
[
1
]
->
ptr
,
"idletime"
)
&&
c
->
argc
==
3
)
{
if
((
o
=
objectCommandLookupOrReply
(
c
,
c
->
argv
[
2
],
shared
.
nullbulk
))
==
NULL
)
return
;
addReplyLongLong
(
c
,
estimateObjectIdleTime
(
o
));
}
else
{
addReplyError
(
c
,
"Syntax error. Try OBJECT (refcount|encoding|idletime)"
);
}
}
src/rdb.c
View file @
bfe85f7c
...
@@ -245,7 +245,7 @@ int rdbSaveDoubleValue(FILE *fp, double val) {
...
@@ -245,7 +245,7 @@ int rdbSaveDoubleValue(FILE *fp, double val) {
return
rdbWriteRaw
(
fp
,
buf
,
len
);
return
rdbWriteRaw
(
fp
,
buf
,
len
);
}
}
/* Save a Redis object. */
/* Save a Redis object.
Returns -1 on error, 0 on success.
*/
int
rdbSaveObject
(
FILE
*
fp
,
robj
*
o
)
{
int
rdbSaveObject
(
FILE
*
fp
,
robj
*
o
)
{
int
n
,
nwritten
=
0
;
int
n
,
nwritten
=
0
;
...
@@ -302,7 +302,13 @@ int rdbSaveObject(FILE *fp, robj *o) {
...
@@ -302,7 +302,13 @@ int rdbSaveObject(FILE *fp, robj *o) {
redisPanic
(
"Unknown set encoding"
);
redisPanic
(
"Unknown set encoding"
);
}
}
}
else
if
(
o
->
type
==
REDIS_ZSET
)
{
}
else
if
(
o
->
type
==
REDIS_ZSET
)
{
/* Save a set value */
/* Save a sorted set value */
if
(
o
->
encoding
==
REDIS_ENCODING_ZIPLIST
)
{
size_t
l
=
ziplistBlobLen
((
unsigned
char
*
)
o
->
ptr
);
if
((
n
=
rdbSaveRawString
(
fp
,
o
->
ptr
,
l
))
==
-
1
)
return
-
1
;
nwritten
+=
n
;
}
else
if
(
o
->
encoding
==
REDIS_ENCODING_SKIPLIST
)
{
zset
*
zs
=
o
->
ptr
;
zset
*
zs
=
o
->
ptr
;
dictIterator
*
di
=
dictGetIterator
(
zs
->
dict
);
dictIterator
*
di
=
dictGetIterator
(
zs
->
dict
);
dictEntry
*
de
;
dictEntry
*
de
;
...
@@ -320,6 +326,9 @@ int rdbSaveObject(FILE *fp, robj *o) {
...
@@ -320,6 +326,9 @@ int rdbSaveObject(FILE *fp, robj *o) {
nwritten
+=
n
;
nwritten
+=
n
;
}
}
dictReleaseIterator
(
di
);
dictReleaseIterator
(
di
);
}
else
{
redisPanic
(
"Unknown sorted set encoding"
);
}
}
else
if
(
o
->
type
==
REDIS_HASH
)
{
}
else
if
(
o
->
type
==
REDIS_HASH
)
{
/* Save a hash value */
/* Save a hash value */
if
(
o
->
encoding
==
REDIS_ENCODING_ZIPMAP
)
{
if
(
o
->
encoding
==
REDIS_ENCODING_ZIPMAP
)
{
...
@@ -386,6 +395,8 @@ int rdbSaveKeyValuePair(FILE *fp, robj *key, robj *val,
...
@@ -386,6 +395,8 @@ int rdbSaveKeyValuePair(FILE *fp, robj *key, robj *val,
vtype
=
REDIS_LIST_ZIPLIST
;
vtype
=
REDIS_LIST_ZIPLIST
;
else
if
(
vtype
==
REDIS_SET
&&
val
->
encoding
==
REDIS_ENCODING_INTSET
)
else
if
(
vtype
==
REDIS_SET
&&
val
->
encoding
==
REDIS_ENCODING_INTSET
)
vtype
=
REDIS_SET_INTSET
;
vtype
=
REDIS_SET_INTSET
;
else
if
(
vtype
==
REDIS_ZSET
&&
val
->
encoding
==
REDIS_ENCODING_ZIPLIST
)
vtype
=
REDIS_ZSET_ZIPLIST
;
/* Save type, key, value */
/* Save type, key, value */
if
(
rdbSaveType
(
fp
,
vtype
)
==
-
1
)
return
-
1
;
if
(
rdbSaveType
(
fp
,
vtype
)
==
-
1
)
return
-
1
;
if
(
rdbSaveStringObject
(
fp
,
key
)
==
-
1
)
return
-
1
;
if
(
rdbSaveStringObject
(
fp
,
key
)
==
-
1
)
return
-
1
;
...
@@ -414,7 +425,7 @@ int rdbSave(char *filename) {
...
@@ -414,7 +425,7 @@ int rdbSave(char *filename) {
strerror
(
errno
));
strerror
(
errno
));
return
REDIS_ERR
;
return
REDIS_ERR
;
}
}
if
(
fwrite
(
"REDIS000
1
"
,
9
,
1
,
fp
)
==
0
)
goto
werr
;
if
(
fwrite
(
"REDIS000
2
"
,
9
,
1
,
fp
)
==
0
)
goto
werr
;
for
(
j
=
0
;
j
<
server
.
dbnum
;
j
++
)
{
for
(
j
=
0
;
j
<
server
.
dbnum
;
j
++
)
{
redisDb
*
db
=
server
.
db
+
j
;
redisDb
*
db
=
server
.
db
+
j
;
dict
*
d
=
db
->
dict
;
dict
*
d
=
db
->
dict
;
...
@@ -745,11 +756,13 @@ robj *rdbLoadObject(int type, FILE *fp) {
...
@@ -745,11 +756,13 @@ robj *rdbLoadObject(int type, FILE *fp) {
}
else
if
(
type
==
REDIS_ZSET
)
{
}
else
if
(
type
==
REDIS_ZSET
)
{
/* Read list/set value */
/* Read list/set value */
size_t
zsetlen
;
size_t
zsetlen
;
size_t
maxelelen
=
0
;
zset
*
zs
;
zset
*
zs
;
if
((
zsetlen
=
rdbLoadLen
(
fp
,
NULL
))
==
REDIS_RDB_LENERR
)
return
NULL
;
if
((
zsetlen
=
rdbLoadLen
(
fp
,
NULL
))
==
REDIS_RDB_LENERR
)
return
NULL
;
o
=
createZsetObject
();
o
=
createZsetObject
();
zs
=
o
->
ptr
;
zs
=
o
->
ptr
;
/* Load every single element of the list/set */
/* Load every single element of the list/set */
while
(
zsetlen
--
)
{
while
(
zsetlen
--
)
{
robj
*
ele
;
robj
*
ele
;
...
@@ -759,10 +772,21 @@ robj *rdbLoadObject(int type, FILE *fp) {
...
@@ -759,10 +772,21 @@ robj *rdbLoadObject(int type, FILE *fp) {
if
((
ele
=
rdbLoadEncodedStringObject
(
fp
))
==
NULL
)
return
NULL
;
if
((
ele
=
rdbLoadEncodedStringObject
(
fp
))
==
NULL
)
return
NULL
;
ele
=
tryObjectEncoding
(
ele
);
ele
=
tryObjectEncoding
(
ele
);
if
(
rdbLoadDoubleValue
(
fp
,
&
score
)
==
-
1
)
return
NULL
;
if
(
rdbLoadDoubleValue
(
fp
,
&
score
)
==
-
1
)
return
NULL
;
/* Don't care about integer-encoded strings. */
if
(
ele
->
encoding
==
REDIS_ENCODING_RAW
&&
sdslen
(
ele
->
ptr
)
>
maxelelen
)
maxelelen
=
sdslen
(
ele
->
ptr
);
znode
=
zslInsert
(
zs
->
zsl
,
score
,
ele
);
znode
=
zslInsert
(
zs
->
zsl
,
score
,
ele
);
dictAdd
(
zs
->
dict
,
ele
,
&
znode
->
score
);
dictAdd
(
zs
->
dict
,
ele
,
&
znode
->
score
);
incrRefCount
(
ele
);
/* added to skiplist */
incrRefCount
(
ele
);
/* added to skiplist */
}
}
/* Convert *after* loading, since sorted sets are not stored ordered. */
if
(
zsetLength
(
o
)
<=
server
.
zset_max_ziplist_entries
&&
maxelelen
<=
server
.
zset_max_ziplist_value
)
zsetConvert
(
o
,
REDIS_ENCODING_ZIPLIST
);
}
else
if
(
type
==
REDIS_HASH
)
{
}
else
if
(
type
==
REDIS_HASH
)
{
size_t
hashlen
;
size_t
hashlen
;
...
@@ -811,7 +835,8 @@ robj *rdbLoadObject(int type, FILE *fp) {
...
@@ -811,7 +835,8 @@ robj *rdbLoadObject(int type, FILE *fp) {
}
}
}
else
if
(
type
==
REDIS_HASH_ZIPMAP
||
}
else
if
(
type
==
REDIS_HASH_ZIPMAP
||
type
==
REDIS_LIST_ZIPLIST
||
type
==
REDIS_LIST_ZIPLIST
||
type
==
REDIS_SET_INTSET
)
type
==
REDIS_SET_INTSET
||
type
==
REDIS_ZSET_ZIPLIST
)
{
{
robj
*
aux
=
rdbLoadStringObject
(
fp
);
robj
*
aux
=
rdbLoadStringObject
(
fp
);
...
@@ -846,8 +871,14 @@ robj *rdbLoadObject(int type, FILE *fp) {
...
@@ -846,8 +871,14 @@ robj *rdbLoadObject(int type, FILE *fp) {
if
(
intsetLen
(
o
->
ptr
)
>
server
.
set_max_intset_entries
)
if
(
intsetLen
(
o
->
ptr
)
>
server
.
set_max_intset_entries
)
setTypeConvert
(
o
,
REDIS_ENCODING_HT
);
setTypeConvert
(
o
,
REDIS_ENCODING_HT
);
break
;
break
;
case
REDIS_ZSET_ZIPLIST
:
o
->
type
=
REDIS_ZSET
;
o
->
encoding
=
REDIS_ENCODING_ZIPLIST
;
if
(
zsetLength
(
o
)
>
server
.
zset_max_ziplist_entries
)
zsetConvert
(
o
,
REDIS_ENCODING_SKIPLIST
);
break
;
default:
default:
redisPanic
(
"Unknown enoding"
);
redisPanic
(
"Unknown en
c
oding"
);
break
;
break
;
}
}
}
else
{
}
else
{
...
@@ -900,7 +931,7 @@ int rdbLoad(char *filename) {
...
@@ -900,7 +931,7 @@ int rdbLoad(char *filename) {
return
REDIS_ERR
;
return
REDIS_ERR
;
}
}
rdbver
=
atoi
(
buf
+
5
);
rdbver
=
atoi
(
buf
+
5
);
if
(
rdbver
!=
1
)
{
if
(
rdbver
<
1
||
rdbver
>
2
)
{
fclose
(
fp
);
fclose
(
fp
);
redisLog
(
REDIS_WARNING
,
"Can't handle RDB format version %d"
,
rdbver
);
redisLog
(
REDIS_WARNING
,
"Can't handle RDB format version %d"
,
rdbver
);
return
REDIS_ERR
;
return
REDIS_ERR
;
...
...
src/redis-cli.c
View file @
bfe85f7c
...
@@ -396,6 +396,9 @@ static sds cliFormatReplyRaw(redisReply *r) {
...
@@ -396,6 +396,9 @@ static sds cliFormatReplyRaw(redisReply *r) {
/* Nothing... */
/* Nothing... */
break
;
break
;
case
REDIS_REPLY_ERROR
:
case
REDIS_REPLY_ERROR
:
out
=
sdscatlen
(
out
,
r
->
str
,
r
->
len
);
out
=
sdscatlen
(
out
,
"
\n
"
,
1
);
break
;
case
REDIS_REPLY_STATUS
:
case
REDIS_REPLY_STATUS
:
case
REDIS_REPLY_STRING
:
case
REDIS_REPLY_STRING
:
out
=
sdscatlen
(
out
,
r
->
str
,
r
->
len
);
out
=
sdscatlen
(
out
,
r
->
str
,
r
->
len
);
...
@@ -464,7 +467,18 @@ static int cliSendCommand(int argc, char **argv, int repeat) {
...
@@ -464,7 +467,18 @@ static int cliSendCommand(int argc, char **argv, int repeat) {
return
REDIS_OK
;
return
REDIS_OK
;
}
}
output_raw
=
!
strcasecmp
(
command
,
"info"
);
output_raw
=
0
;
if
(
!
strcasecmp
(
command
,
"info"
)
||
(
argc
==
2
&&
!
strcasecmp
(
command
,
"cluster"
)
&&
(
!
strcasecmp
(
argv
[
1
],
"nodes"
)
||
!
strcasecmp
(
argv
[
1
],
"info"
)))
||
(
argc
==
2
&&
!
strcasecmp
(
command
,
"client"
)
&&
!
strcasecmp
(
argv
[
1
],
"list"
)))
{
output_raw
=
1
;
}
if
(
!
strcasecmp
(
command
,
"help"
)
||
!
strcasecmp
(
command
,
"?"
))
{
if
(
!
strcasecmp
(
command
,
"help"
)
||
!
strcasecmp
(
command
,
"?"
))
{
cliOutputHelp
(
--
argc
,
++
argv
);
cliOutputHelp
(
--
argc
,
++
argv
);
return
REDIS_OK
;
return
REDIS_OK
;
...
...
src/redis-trib.rb
0 → 100755
View file @
bfe85f7c
#!/usr/bin/env ruby
require
'rubygems'
require
'redis'
ClusterHashSlots
=
4096
def
xputs
(
s
)
printf
s
STDOUT
.
flush
end
class
ClusterNode
def
initialize
(
addr
)
s
=
addr
.
split
(
":"
)
if
s
.
length
!=
2
puts
"Invalid node name
#{
addr
}
"
exit
1
end
@r
=
nil
@host
=
s
[
0
]
@port
=
s
[
1
]
@slots
=
{}
@dirty
=
false
end
def
to_s
"
#{
@host
}
:
#{
@port
}
"
end
def
connect
(
o
=
{})
xputs
"Connecting to node
#{
self
}
: "
begin
@r
=
Redis
.
new
(
:host
=>
@host
,
:port
=>
@port
)
@r
.
ping
rescue
puts
"ERROR"
puts
"Sorry, can't connect to node
#{
self
}
"
exit
1
if
o
[
:abort
]
@r
=
nil
end
puts
"OK"
end
def
assert_cluster
info
=
@r
.
info
if
!
info
[
"cluster_enabled"
]
||
info
[
"cluster_enabled"
].
to_i
==
0
puts
"Error: Node
#{
self
}
is not configured as a cluster node."
exit
1
end
end
def
assert_empty
if
!
(
@r
.
cluster
(
"info"
).
split
(
"
\r\n
"
).
index
(
"cluster_known_nodes:1"
))
||
(
@r
.
info
[
'db0'
])
puts
"Error: Node
#{
self
}
is not empty. Either the node already knows other nodes (check with nodes-info) or contains some key in database 0."
exit
1
end
end
def
add_slots
(
slots
)
slots
.
each
{
|
s
|
@slots
[
s
]
=
:new
}
@dirty
=
true
end
def
flush_node_config
return
if
!
@dirty
new
=
[]
@slots
.
each
{
|
s
,
val
|
if
val
==
:new
new
<<
s
@slots
[
s
]
=
true
end
}
@r
.
cluster
(
"addslots"
,
*
new
)
@dirty
=
false
end
def
info_string
# We want to display the hash slots assigned to this node
# as ranges, like in: "1-5,8-9,20-25,30"
#
# 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
=
@slots
.
keys
.
sort
# As we want to aggregate adiacent slots we convert all the
# slot integers into ranges (with just one element)
# So we have something like [1..1,2..2, ... and so forth.
slots
.
map!
{
|
x
|
x
..
x
}
# Finally we group ranges with adiacent elements.
slots
=
slots
.
reduce
([])
{
|
a
,
b
|
if
!
a
.
empty?
&&
b
.
first
==
(
a
[
-
1
].
last
)
+
1
a
[
0
..-
2
]
+
[(
a
[
-
1
].
first
)
..
(
b
.
last
)]
else
a
+
[
b
]
end
}
# Now our task is easy, we just convert ranges with just one
# element into a number, and a real range into a start-end format.
# Finally we join the array using the comma as separator.
slots
=
slots
.
map
{
|
x
|
x
.
count
==
1
?
x
.
first
.
to_s
:
"
#{
x
.
first
}
-
#{
x
.
last
}
"
}.
join
(
","
)
"
#{
self
.
to_s
.
ljust
(
25
)
}
slots:
#{
slots
}
"
end
def
info
{
:host
=>
@host
,
:port
=>
@port
,
:slots
=>
@slots
,
:dirty
=>
@dirty
}
end
def
is_dirty?
@dirty
end
def
r
@r
end
end
class
RedisTrib
def
initialize
@nodes
=
[]
end
def
check_arity
(
req_args
,
num_args
)
if
((
req_args
>
0
and
num_args
!=
req_args
)
||
(
req_args
<
0
and
num_args
<
req_args
.
abs
))
puts
"Wrong number of arguments for specified sub command"
exit
1
end
end
def
add_node
(
node
)
@nodes
<<
node
end
def
check_cluster
puts
"Performing Cluster Check (using node
#{
@nodes
[
0
]
}
)"
show_nodes
end
def
alloc_slots
slots_per_node
=
ClusterHashSlots
/
@nodes
.
length
i
=
0
@nodes
.
each
{
|
n
|
first
=
i
*
slots_per_node
last
=
first
+
slots_per_node
-
1
last
=
ClusterHashSlots
-
1
if
i
==
@nodes
.
length
-
1
n
.
add_slots
first
..
last
i
+=
1
}
end
def
flush_nodes_config
@nodes
.
each
{
|
n
|
n
.
flush_node_config
}
end
def
show_nodes
@nodes
.
each
{
|
n
|
puts
n
.
info_string
}
end
def
join_cluster
# We use a brute force approach to make sure the node will meet
# each other, that is, sending CLUSTER MEET messages to all the nodes
# about the very same node.
# Thanks to gossip this information should propagate across all the
# cluster in a matter of seconds.
first
=
false
@nodes
.
each
{
|
n
|
if
!
first
then
first
=
n
.
info
;
next
;
end
# Skip the first node
n
.
r
.
cluster
(
"meet"
,
first
[
:host
],
first
[
:port
])
}
end
def
yes_or_die
(
msg
)
print
"
#{
msg
}
(type 'yes' to accept): "
STDOUT
.
flush
if
!
(
STDIN
.
gets
.
chomp
.
downcase
==
"yes"
)
puts
"Aborting..."
exit
1
end
end
# redis-trib subcommands implementations
def
check_cluster_cmd
node
=
ClusterNode
.
new
(
ARGV
[
1
])
node
.
connect
(
:abort
=>
true
)
node
.
assert_cluster
add_node
(
node
)
check_cluster
end
def
create_cluster_cmd
puts
"Creating cluster"
ARGV
[
1
..-
1
].
each
{
|
n
|
node
=
ClusterNode
.
new
(
n
)
node
.
connect
(
:abort
=>
true
)
node
.
assert_cluster
node
.
assert_empty
add_node
(
node
)
}
puts
"Performing hash slots allocation on
#{
@nodes
.
length
}
nodes..."
alloc_slots
show_nodes
yes_or_die
"Can I set the above configuration?"
flush_nodes_config
puts
"** Nodes configuration updated"
puts
"** Sending CLUSTER MEET messages to join the cluster"
join_cluster
check_cluster
end
end
COMMANDS
=
{
"create"
=>
[
"create_cluster_cmd"
,
-
2
,
"host1:port host2:port ... hostN:port"
],
"check"
=>
[
"check_cluster_cmd"
,
2
,
"host:port"
]
}
# Sanity check
if
ARGV
.
length
==
0
puts
"Usage: redis-trib <command> <arguments ...>"
puts
COMMANDS
.
each
{
|
k
,
v
|
puts
"
#{
k
.
ljust
(
20
)
}
#{
v
[
2
]
}
"
}
puts
exit
1
end
rt
=
RedisTrib
.
new
cmd_spec
=
COMMANDS
[
ARGV
[
0
].
downcase
]
if
!
cmd_spec
puts
"Unknown redis-trib subcommand '
#{
ARGV
[
0
]
}
'"
exit
1
end
rt
.
check_arity
(
cmd_spec
[
1
],
ARGV
.
length
)
# Dispatch
rt
.
send
(
cmd_spec
[
0
])
src/redis.c
View file @
bfe85f7c
...
@@ -70,12 +70,12 @@ struct redisServer server; /* server global state */
...
@@ -70,12 +70,12 @@ struct redisServer server; /* server global state */
struct
redisCommand
*
commandTable
;
struct
redisCommand
*
commandTable
;
struct
redisCommand
redisCommandTable
[]
=
{
struct
redisCommand
redisCommandTable
[]
=
{
{
"get"
,
getCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"get"
,
getCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"set"
,
setCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"set"
,
setCommand
,
3
,
REDIS_CMD_DENYOOM
,
noPreloadGetKeys
,
1
,
1
,
1
,
0
,
0
},
{
"setnx"
,
setnxCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"setnx"
,
setnxCommand
,
3
,
REDIS_CMD_DENYOOM
,
noPreloadGetKeys
,
1
,
1
,
1
,
0
,
0
},
{
"setex"
,
setexCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"setex"
,
setexCommand
,
4
,
REDIS_CMD_DENYOOM
,
noPreloadGetKeys
,
2
,
2
,
1
,
0
,
0
},
{
"append"
,
appendCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"append"
,
appendCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"strlen"
,
strlenCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"strlen"
,
strlenCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"del"
,
delCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"del"
,
delCommand
,
-
2
,
0
,
noPreloadGetKeys
,
1
,
-
1
,
1
,
0
,
0
},
{
"exists"
,
existsCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"exists"
,
existsCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"setbit"
,
setbitCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"setbit"
,
setbitCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"getbit"
,
getbitCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"getbit"
,
getbitCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
...
@@ -85,8 +85,8 @@ struct redisCommand redisCommandTable[] = {
...
@@ -85,8 +85,8 @@ struct redisCommand redisCommandTable[] = {
{
"incr"
,
incrCommand
,
2
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"incr"
,
incrCommand
,
2
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"decr"
,
decrCommand
,
2
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"decr"
,
decrCommand
,
2
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"mget"
,
mgetCommand
,
-
2
,
0
,
NULL
,
1
,
-
1
,
1
,
0
,
0
},
{
"mget"
,
mgetCommand
,
-
2
,
0
,
NULL
,
1
,
-
1
,
1
,
0
,
0
},
{
"rpush"
,
rpushCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"rpush"
,
rpushCommand
,
-
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lpush"
,
lpushCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lpush"
,
lpushCommand
,
-
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"rpushx"
,
rpushxCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"rpushx"
,
rpushxCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lpushx"
,
lpushxCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lpushx"
,
lpushxCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"linsert"
,
linsertCommand
,
5
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"linsert"
,
linsertCommand
,
5
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
...
@@ -94,7 +94,7 @@ struct redisCommand redisCommandTable[] = {
...
@@ -94,7 +94,7 @@ struct redisCommand redisCommandTable[] = {
{
"lpop"
,
lpopCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lpop"
,
lpopCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"brpop"
,
brpopCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"brpop"
,
brpopCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"brpoplpush"
,
brpoplpushCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
2
,
1
,
0
,
0
},
{
"brpoplpush"
,
brpoplpushCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
2
,
1
,
0
,
0
},
{
"blpop"
,
blpopCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"blpop"
,
blpopCommand
,
-
3
,
0
,
NULL
,
1
,
-
2
,
1
,
0
,
0
},
{
"llen"
,
llenCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"llen"
,
llenCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lindex"
,
lindexCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lindex"
,
lindexCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lset"
,
lsetCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lset"
,
lsetCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
...
@@ -102,8 +102,8 @@ struct redisCommand redisCommandTable[] = {
...
@@ -102,8 +102,8 @@ struct redisCommand redisCommandTable[] = {
{
"ltrim"
,
ltrimCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"ltrim"
,
ltrimCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lrem"
,
lremCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"lrem"
,
lremCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"rpoplpush"
,
rpoplpushCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
2
,
1
,
0
,
0
},
{
"rpoplpush"
,
rpoplpushCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
2
,
1
,
0
,
0
},
{
"sadd"
,
saddCommand
,
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"sadd"
,
saddCommand
,
-
3
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"srem"
,
sremCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"srem"
,
sremCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"smove"
,
smoveCommand
,
4
,
0
,
NULL
,
1
,
2
,
1
,
0
,
0
},
{
"smove"
,
smoveCommand
,
4
,
0
,
NULL
,
1
,
2
,
1
,
0
,
0
},
{
"sismember"
,
sismemberCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"sismember"
,
sismemberCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"scard"
,
scardCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"scard"
,
scardCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
...
@@ -121,8 +121,8 @@ struct redisCommand redisCommandTable[] = {
...
@@ -121,8 +121,8 @@ struct redisCommand redisCommandTable[] = {
{
"zrem"
,
zremCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zrem"
,
zremCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zremrangebyscore"
,
zremrangebyscoreCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zremrangebyscore"
,
zremrangebyscoreCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zremrangebyrank"
,
zremrangebyrankCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zremrangebyrank"
,
zremrangebyrankCommand
,
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zunionstore"
,
zunionstoreCommand
,
-
4
,
REDIS_CMD_DENYOOM
,
zunionInter
BlockClientOnSwapped
Keys
,
0
,
0
,
0
,
0
,
0
},
{
"zunionstore"
,
zunionstoreCommand
,
-
4
,
REDIS_CMD_DENYOOM
,
zunionInter
Get
Keys
,
0
,
0
,
0
,
0
,
0
},
{
"zinterstore"
,
zinterstoreCommand
,
-
4
,
REDIS_CMD_DENYOOM
,
zunionInter
BlockClientOnSwapped
Keys
,
0
,
0
,
0
,
0
,
0
},
{
"zinterstore"
,
zinterstoreCommand
,
-
4
,
REDIS_CMD_DENYOOM
,
zunionInter
Get
Keys
,
0
,
0
,
0
,
0
,
0
},
{
"zrange"
,
zrangeCommand
,
-
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zrange"
,
zrangeCommand
,
-
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zrangebyscore"
,
zrangebyscoreCommand
,
-
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zrangebyscore"
,
zrangebyscoreCommand
,
-
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zrevrangebyscore"
,
zrevrangebyscoreCommand
,
-
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"zrevrangebyscore"
,
zrevrangebyscoreCommand
,
-
4
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
...
@@ -138,7 +138,7 @@ struct redisCommand redisCommandTable[] = {
...
@@ -138,7 +138,7 @@ struct redisCommand redisCommandTable[] = {
{
"hmset"
,
hmsetCommand
,
-
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hmset"
,
hmsetCommand
,
-
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hmget"
,
hmgetCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hmget"
,
hmgetCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hincrby"
,
hincrbyCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hincrby"
,
hincrbyCommand
,
4
,
REDIS_CMD_DENYOOM
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hdel"
,
hdelCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hdel"
,
hdelCommand
,
-
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hlen"
,
hlenCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hlen"
,
hlenCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hkeys"
,
hkeysCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hkeys"
,
hkeysCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hvals"
,
hvalsCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"hvals"
,
hvalsCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
...
@@ -152,10 +152,10 @@ struct redisCommand redisCommandTable[] = {
...
@@ -152,10 +152,10 @@ struct redisCommand redisCommandTable[] = {
{
"randomkey"
,
randomkeyCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"randomkey"
,
randomkeyCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"select"
,
selectCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"select"
,
selectCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"move"
,
moveCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"move"
,
moveCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"rename"
,
renameCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"rename"
,
renameCommand
,
3
,
0
,
renameGetKeys
,
1
,
2
,
1
,
0
,
0
},
{
"renamenx"
,
renamenxCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"renamenx"
,
renamenxCommand
,
3
,
0
,
renameGetKeys
,
1
,
2
,
1
,
0
,
0
},
{
"expire"
,
expireCommand
,
3
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"expire"
,
expireCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"expireat"
,
expireatCommand
,
3
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"expireat"
,
expireatCommand
,
3
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"keys"
,
keysCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"keys"
,
keysCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"dbsize"
,
dbsizeCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"dbsize"
,
dbsizeCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"auth"
,
authCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"auth"
,
authCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
...
@@ -168,7 +168,7 @@ struct redisCommand redisCommandTable[] = {
...
@@ -168,7 +168,7 @@ struct redisCommand redisCommandTable[] = {
{
"lastsave"
,
lastsaveCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"lastsave"
,
lastsaveCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"type"
,
typeCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"type"
,
typeCommand
,
2
,
0
,
NULL
,
1
,
1
,
1
,
0
,
0
},
{
"multi"
,
multiCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"multi"
,
multiCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"exec"
,
execCommand
,
1
,
REDIS_CMD_DENYOOM
,
execBlockClientOnSwappedKeys
,
0
,
0
,
0
,
0
,
0
},
{
"exec"
,
execCommand
,
1
,
REDIS_CMD_DENYOOM
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"discard"
,
discardCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"discard"
,
discardCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"sync"
,
syncCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"sync"
,
syncCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"flushdb"
,
flushdbCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"flushdb"
,
flushdbCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
...
@@ -186,8 +186,14 @@ struct redisCommand redisCommandTable[] = {
...
@@ -186,8 +186,14 @@ struct redisCommand redisCommandTable[] = {
{
"psubscribe"
,
psubscribeCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"psubscribe"
,
psubscribeCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"punsubscribe"
,
punsubscribeCommand
,
-
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"punsubscribe"
,
punsubscribeCommand
,
-
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"publish"
,
publishCommand
,
3
,
REDIS_CMD_FORCE_REPLICATION
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"publish"
,
publishCommand
,
3
,
REDIS_CMD_FORCE_REPLICATION
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"watch"
,
watchCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"watch"
,
watchCommand
,
-
2
,
0
,
noPreloadGetKeys
,
1
,
-
1
,
1
,
0
,
0
},
{
"unwatch"
,
unwatchCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
}
{
"unwatch"
,
unwatchCommand
,
1
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"cluster"
,
clusterCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"restore"
,
restoreCommand
,
4
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"migrate"
,
migrateCommand
,
6
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"dump"
,
dumpCommand
,
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"object"
,
objectCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
},
{
"client"
,
clientCommand
,
-
2
,
0
,
NULL
,
0
,
0
,
0
,
0
,
0
}
};
};
/*============================ Utility functions ============================ */
/*============================ Utility functions ============================ */
...
@@ -200,14 +206,20 @@ void redisLogRaw(int level, const char *msg) {
...
@@ -200,14 +206,20 @@ void redisLogRaw(int level, const char *msg) {
time_t
now
=
time
(
NULL
);
time_t
now
=
time
(
NULL
);
FILE
*
fp
;
FILE
*
fp
;
char
buf
[
64
];
char
buf
[
64
];
int
rawmode
=
(
level
&
REDIS_LOG_RAW
);
level
&=
0xff
;
/* clear flags */
if
(
level
<
server
.
verbosity
)
return
;
if
(
level
<
server
.
verbosity
)
return
;
fp
=
(
server
.
logfile
==
NULL
)
?
stdout
:
fopen
(
server
.
logfile
,
"a"
);
fp
=
(
server
.
logfile
==
NULL
)
?
stdout
:
fopen
(
server
.
logfile
,
"a"
);
if
(
!
fp
)
return
;
if
(
!
fp
)
return
;
if
(
rawmode
)
{
fprintf
(
fp
,
"%s"
,
msg
);
}
else
{
strftime
(
buf
,
sizeof
(
buf
),
"%d %b %H:%M:%S"
,
localtime
(
&
now
));
strftime
(
buf
,
sizeof
(
buf
),
"%d %b %H:%M:%S"
,
localtime
(
&
now
));
fprintf
(
fp
,
"[%d] %s %c %s
\n
"
,(
int
)
getpid
(),
buf
,
c
[
level
],
msg
);
fprintf
(
fp
,
"[%d] %s %c %s
\n
"
,(
int
)
getpid
(),
buf
,
c
[
level
],
msg
);
}
fflush
(
fp
);
fflush
(
fp
);
if
(
server
.
logfile
)
fclose
(
fp
);
if
(
server
.
logfile
)
fclose
(
fp
);
...
@@ -222,7 +234,7 @@ void redisLog(int level, const char *fmt, ...) {
...
@@ -222,7 +234,7 @@ void redisLog(int level, const char *fmt, ...) {
va_list
ap
;
va_list
ap
;
char
msg
[
REDIS_MAX_LOGMSG_LEN
];
char
msg
[
REDIS_MAX_LOGMSG_LEN
];
if
(
level
<
server
.
verbosity
)
return
;
if
(
(
level
&
0xff
)
<
server
.
verbosity
)
return
;
va_start
(
ap
,
fmt
);
va_start
(
ap
,
fmt
);
vsnprintf
(
msg
,
sizeof
(
msg
),
fmt
,
ap
);
vsnprintf
(
msg
,
sizeof
(
msg
),
fmt
,
ap
);
...
@@ -440,6 +452,17 @@ dictType keylistDictType = {
...
@@ -440,6 +452,17 @@ dictType keylistDictType = {
dictListDestructor
/* val destructor */
dictListDestructor
/* val destructor */
};
};
/* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to
* clusterNode structures. */
dictType
clusterNodesDictType
=
{
dictSdsHash
,
/* hash function */
NULL
,
/* key dup */
NULL
,
/* val dup */
dictSdsKeyCompare
,
/* key compare */
dictSdsDestructor
,
/* key destructor */
NULL
/* val destructor */
};
int
htNeedsResize
(
dict
*
dict
)
{
int
htNeedsResize
(
dict
*
dict
)
{
long
long
size
,
used
;
long
long
size
,
used
;
...
@@ -563,6 +586,10 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
...
@@ -563,6 +586,10 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
*/
*/
updateLRUClock
();
updateLRUClock
();
/* Record the max memory used since the server was started. */
if
(
zmalloc_used_memory
()
>
server
.
stat_peak_memory
)
server
.
stat_peak_memory
=
zmalloc_used_memory
();
/* We received a SIGTERM, shutting down here in a safe way, as it is
/* We received a SIGTERM, shutting down here in a safe way, as it is
* not ok doing so inside the signal handler. */
* not ok doing so inside the signal handler. */
if
(
server
.
shutdown_asap
)
{
if
(
server
.
shutdown_asap
)
{
...
@@ -669,6 +696,9 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
...
@@ -669,6 +696,9 @@ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
* to detect transfer failures. */
* to detect transfer failures. */
if
(
!
(
loops
%
10
))
replicationCron
();
if
(
!
(
loops
%
10
))
replicationCron
();
/* Run other sub-systems specific cron jobs */
if
(
server
.
cluster_enabled
&&
!
(
loops
%
10
))
clusterCron
();
server
.
cronloops
++
;
server
.
cronloops
++
;
return
100
;
return
100
;
}
}
...
@@ -821,8 +851,12 @@ void initServerConfig() {
...
@@ -821,8 +851,12 @@ void initServerConfig() {
server
.
list_max_ziplist_entries
=
REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
server
.
list_max_ziplist_entries
=
REDIS_LIST_MAX_ZIPLIST_ENTRIES
;
server
.
list_max_ziplist_value
=
REDIS_LIST_MAX_ZIPLIST_VALUE
;
server
.
list_max_ziplist_value
=
REDIS_LIST_MAX_ZIPLIST_VALUE
;
server
.
set_max_intset_entries
=
REDIS_SET_MAX_INTSET_ENTRIES
;
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
;
server
.
shutdown_asap
=
0
;
server
.
shutdown_asap
=
0
;
server
.
cache_flush_delay
=
0
;
server
.
cache_flush_delay
=
0
;
server
.
cluster_enabled
=
0
;
server
.
cluster
.
configfile
=
zstrdup
(
"nodes.conf"
);
updateLRUClock
();
updateLRUClock
();
resetServerSaveParams
();
resetServerSaveParams
();
...
@@ -928,6 +962,7 @@ void initServer() {
...
@@ -928,6 +962,7 @@ void initServer() {
server
.
stat_starttime
=
time
(
NULL
);
server
.
stat_starttime
=
time
(
NULL
);
server
.
stat_keyspace_misses
=
0
;
server
.
stat_keyspace_misses
=
0
;
server
.
stat_keyspace_hits
=
0
;
server
.
stat_keyspace_hits
=
0
;
server
.
stat_peak_memory
=
0
;
server
.
unixtime
=
time
(
NULL
);
server
.
unixtime
=
time
(
NULL
);
aeCreateTimeEvent
(
server
.
el
,
1
,
serverCron
,
NULL
,
NULL
);
aeCreateTimeEvent
(
server
.
el
,
1
,
serverCron
,
NULL
,
NULL
);
if
(
server
.
ipfd
>
0
&&
aeCreateFileEvent
(
server
.
el
,
server
.
ipfd
,
AE_READABLE
,
if
(
server
.
ipfd
>
0
&&
aeCreateFileEvent
(
server
.
el
,
server
.
ipfd
,
AE_READABLE
,
...
@@ -945,6 +980,7 @@ void initServer() {
...
@@ -945,6 +980,7 @@ void initServer() {
}
}
if
(
server
.
ds_enabled
)
dsInit
();
if
(
server
.
ds_enabled
)
dsInit
();
if
(
server
.
cluster_enabled
)
clusterInit
();
srand
(
time
(
NULL
)
^
getpid
());
srand
(
time
(
NULL
)
^
getpid
());
}
}
...
@@ -1051,6 +1087,29 @@ int processCommand(redisClient *c) {
...
@@ -1051,6 +1087,29 @@ int processCommand(redisClient *c) {
return
REDIS_OK
;
return
REDIS_OK
;
}
}
/* If cluster is enabled, redirect here */
if
(
server
.
cluster_enabled
&&
!
(
cmd
->
getkeys_proc
==
NULL
&&
cmd
->
firstkey
==
0
))
{
int
hashslot
;
if
(
server
.
cluster
.
state
!=
REDIS_CLUSTER_OK
)
{
addReplyError
(
c
,
"The cluster is down. Check with CLUSTER INFO for more information"
);
return
REDIS_OK
;
}
else
{
int
ask
;
clusterNode
*
n
=
getNodeByQuery
(
c
,
cmd
,
c
->
argv
,
c
->
argc
,
&
hashslot
,
&
ask
);
if
(
n
==
NULL
)
{
addReplyError
(
c
,
"Multi keys request invalid in cluster"
);
return
REDIS_OK
;
}
else
if
(
n
!=
server
.
cluster
.
myself
)
{
addReplySds
(
c
,
sdscatprintf
(
sdsempty
(),
"-%s %d %s:%d
\r\n
"
,
ask
?
"ASK"
:
"MOVED"
,
hashslot
,
n
->
ip
,
n
->
port
));
return
REDIS_OK
;
}
}
}
/* Handle the maxmemory directive.
/* Handle the maxmemory directive.
*
*
* First we try to free some memory if possible (if there are volatile
* First we try to free some memory if possible (if there are volatile
...
@@ -1189,7 +1248,6 @@ sds genRedisInfoString(char *section) {
...
@@ -1189,7 +1248,6 @@ sds genRedisInfoString(char *section) {
sds
info
=
sdsempty
();
sds
info
=
sdsempty
();
time_t
uptime
=
time
(
NULL
)
-
server
.
stat_starttime
;
time_t
uptime
=
time
(
NULL
)
-
server
.
stat_starttime
;
int
j
,
numcommands
;
int
j
,
numcommands
;
char
hmem
[
64
];
struct
rusage
self_ru
,
c_ru
;
struct
rusage
self_ru
,
c_ru
;
unsigned
long
lol
,
bib
;
unsigned
long
lol
,
bib
;
int
allsections
=
0
,
defsections
=
0
;
int
allsections
=
0
,
defsections
=
0
;
...
@@ -1203,7 +1261,6 @@ sds genRedisInfoString(char *section) {
...
@@ -1203,7 +1261,6 @@ sds genRedisInfoString(char *section) {
getrusage
(
RUSAGE_SELF
,
&
self_ru
);
getrusage
(
RUSAGE_SELF
,
&
self_ru
);
getrusage
(
RUSAGE_CHILDREN
,
&
c_ru
);
getrusage
(
RUSAGE_CHILDREN
,
&
c_ru
);
getClientsMaxBuffers
(
&
lol
,
&
bib
);
getClientsMaxBuffers
(
&
lol
,
&
bib
);
bytesToHuman
(
hmem
,
zmalloc_used_memory
());
/* Server */
/* Server */
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"server"
))
{
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"server"
))
{
...
@@ -1248,23 +1305,28 @@ sds genRedisInfoString(char *section) {
...
@@ -1248,23 +1305,28 @@ sds genRedisInfoString(char *section) {
/* Memory */
/* Memory */
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"memory"
))
{
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"memory"
))
{
char
hmem
[
64
];
char
peak_hmem
[
64
];
bytesToHuman
(
hmem
,
zmalloc_used_memory
());
bytesToHuman
(
peak_hmem
,
server
.
stat_peak_memory
);
if
(
sections
++
)
info
=
sdscat
(
info
,
"
\r\n
"
);
if
(
sections
++
)
info
=
sdscat
(
info
,
"
\r\n
"
);
info
=
sdscatprintf
(
info
,
info
=
sdscatprintf
(
info
,
"# Memory
\r\n
"
"# Memory
\r\n
"
"used_memory:%zu
\r\n
"
"used_memory:%zu
\r\n
"
"used_memory_human:%s
\r\n
"
"used_memory_human:%s
\r\n
"
"used_memory_rss:%zu
\r\n
"
"used_memory_rss:%zu
\r\n
"
"used_memory_peak:%zu
\r\n
"
"used_memory_peak_human:%s
\r\n
"
"mem_fragmentation_ratio:%.2f
\r\n
"
"mem_fragmentation_ratio:%.2f
\r\n
"
"
use_tcm
alloc:%
d
\r\n
"
,
"
mem_
alloc
ator
:%
s
\r\n
"
,
zmalloc_used_memory
(),
zmalloc_used_memory
(),
hmem
,
hmem
,
zmalloc_get_rss
(),
zmalloc_get_rss
(),
server
.
stat_peak_memory
,
peak_hmem
,
zmalloc_get_fragmentation_ratio
(),
zmalloc_get_fragmentation_ratio
(),
#ifdef USE_TCMALLOC
REDIS_MALLOC
1
#else
0
#endif
);
);
}
}
...
@@ -1455,6 +1517,15 @@ sds genRedisInfoString(char *section) {
...
@@ -1455,6 +1517,15 @@ sds genRedisInfoString(char *section) {
}
}
}
}
/* Clusetr */
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"cluster"
))
{
if
(
sections
++
)
info
=
sdscat
(
info
,
"
\r\n
"
);
info
=
sdscatprintf
(
info
,
"# Cluster
\r\n
"
"cluster_enabled:%d
\r\n
"
,
server
.
cluster_enabled
);
}
/* Key space */
/* Key space */
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"keyspace"
))
{
if
(
allsections
||
defsections
||
!
strcasecmp
(
section
,
"keyspace"
))
{
if
(
sections
++
)
info
=
sdscat
(
info
,
"
\r\n
"
);
if
(
sections
++
)
info
=
sdscat
(
info
,
"
\r\n
"
);
...
@@ -1663,6 +1734,23 @@ void usage() {
...
@@ -1663,6 +1734,23 @@ void usage() {
exit
(
1
);
exit
(
1
);
}
}
void
redisAsciiArt
(
void
)
{
#include "asciilogo.h"
char
*
buf
=
zmalloc
(
1024
*
16
);
snprintf
(
buf
,
1024
*
16
,
ascii_logo
,
REDIS_VERSION
,
redisGitSHA1
(),
strtol
(
redisGitDirty
(),
NULL
,
10
)
>
0
,
(
sizeof
(
long
)
==
8
)
?
"64"
:
"32"
,
server
.
cluster_enabled
?
"cluster"
:
"stand alone"
,
server
.
port
,
(
long
)
getpid
()
);
redisLogRaw
(
REDIS_NOTICE
|
REDIS_LOG_RAW
,
buf
);
zfree
(
buf
);
}
int
main
(
int
argc
,
char
**
argv
)
{
int
main
(
int
argc
,
char
**
argv
)
{
long
long
start
;
long
long
start
;
...
@@ -1681,6 +1769,7 @@ int main(int argc, char **argv) {
...
@@ -1681,6 +1769,7 @@ int main(int argc, char **argv) {
if
(
server
.
daemonize
)
daemonize
();
if
(
server
.
daemonize
)
daemonize
();
initServer
();
initServer
();
if
(
server
.
daemonize
)
createPidFile
();
if
(
server
.
daemonize
)
createPidFile
();
redisAsciiArt
();
redisLog
(
REDIS_NOTICE
,
"Server started, Redis version "
REDIS_VERSION
);
redisLog
(
REDIS_NOTICE
,
"Server started, Redis version "
REDIS_VERSION
);
#ifdef __linux__
#ifdef __linux__
linuxOvercommitMemoryWarning
();
linuxOvercommitMemoryWarning
();
...
...
src/redis.h
View file @
bfe85f7c
...
@@ -18,6 +18,7 @@
...
@@ -18,6 +18,7 @@
#include <inttypes.h>
#include <inttypes.h>
#include <pthread.h>
#include <pthread.h>
#include <syslog.h>
#include <syslog.h>
#include <netinet/in.h>
#include "ae.h"
/* Event driven programming library */
#include "ae.h"
/* Event driven programming library */
#include "sds.h"
/* Dynamic safe strings */
#include "sds.h"
/* Dynamic safe strings */
...
@@ -29,6 +30,7 @@
...
@@ -29,6 +30,7 @@
#include "ziplist.h"
/* Compact list data structure */
#include "ziplist.h"
/* Compact list data structure */
#include "intset.h"
/* Compact integer set structure */
#include "intset.h"
/* Compact integer set structure */
#include "version.h"
#include "version.h"
#include "util.h"
/* Error codes */
/* Error codes */
#define REDIS_OK 0
#define REDIS_OK 0
...
@@ -70,10 +72,12 @@
...
@@ -70,10 +72,12 @@
#define REDIS_ZSET 3
#define REDIS_ZSET 3
#define REDIS_HASH 4
#define REDIS_HASH 4
#define REDIS_VMPOINTER 8
#define REDIS_VMPOINTER 8
/* Object types only used for persistence in .rdb files */
/* Object types only used for persistence in .rdb files */
#define REDIS_HASH_ZIPMAP 9
#define REDIS_HASH_ZIPMAP 9
#define REDIS_LIST_ZIPLIST 10
#define REDIS_LIST_ZIPLIST 10
#define REDIS_SET_INTSET 11
#define REDIS_SET_INTSET 11
#define REDIS_ZSET_ZIPLIST 12
/* Objects encoding. Some kind of objects like Strings and Hashes can be
/* Objects encoding. Some kind of objects like Strings and Hashes can be
* internally represented in multiple ways. The 'encoding' field of the object
* internally represented in multiple ways. The 'encoding' field of the object
...
@@ -85,6 +89,7 @@
...
@@ -85,6 +89,7 @@
#define REDIS_ENCODING_LINKEDLIST 4
/* Encoded as regular linked list */
#define REDIS_ENCODING_LINKEDLIST 4
/* Encoded as regular linked list */
#define REDIS_ENCODING_ZIPLIST 5
/* Encoded as ziplist */
#define REDIS_ENCODING_ZIPLIST 5
/* Encoded as ziplist */
#define REDIS_ENCODING_INTSET 6
/* Encoded as intset */
#define REDIS_ENCODING_INTSET 6
/* Encoded as intset */
#define REDIS_ENCODING_SKIPLIST 7
/* Encoded as skiplist */
/* Object types only used for dumping to disk */
/* Object types only used for dumping to disk */
#define REDIS_EXPIRETIME 253
#define REDIS_EXPIRETIME 253
...
@@ -177,6 +182,7 @@
...
@@ -177,6 +182,7 @@
#define REDIS_VERBOSE 1
#define REDIS_VERBOSE 1
#define REDIS_NOTICE 2
#define REDIS_NOTICE 2
#define REDIS_WARNING 3
#define REDIS_WARNING 3
#define REDIS_LOG_RAW (1<<10)
/* Modifier to log without timestamp */
/* Anti-warning macro... */
/* Anti-warning macro... */
#define REDIS_NOTUSED(V) ((void) V)
#define REDIS_NOTUSED(V) ((void) V)
...
@@ -195,6 +201,8 @@
...
@@ -195,6 +201,8 @@
#define REDIS_LIST_MAX_ZIPLIST_ENTRIES 512
#define REDIS_LIST_MAX_ZIPLIST_ENTRIES 512
#define REDIS_LIST_MAX_ZIPLIST_VALUE 64
#define REDIS_LIST_MAX_ZIPLIST_VALUE 64
#define REDIS_SET_MAX_INTSET_ENTRIES 512
#define REDIS_SET_MAX_INTSET_ENTRIES 512
#define REDIS_ZSET_MAX_ZIPLIST_ENTRIES 128
#define REDIS_ZSET_MAX_ZIPLIST_VALUE 64
/* Sets operations codes */
/* Sets operations codes */
#define REDIS_OP_UNION 0
#define REDIS_OP_UNION 0
...
@@ -360,7 +368,147 @@ struct sharedObjectsStruct {
...
@@ -360,7 +368,147 @@ struct sharedObjectsStruct {
*
integers
[
REDIS_SHARED_INTEGERS
];
*
integers
[
REDIS_SHARED_INTEGERS
];
};
};
/* Global server state structure */
/* ZSETs use a specialized version of Skiplists */
typedef
struct
zskiplistNode
{
robj
*
obj
;
double
score
;
struct
zskiplistNode
*
backward
;
struct
zskiplistLevel
{
struct
zskiplistNode
*
forward
;
unsigned
int
span
;
}
level
[];
}
zskiplistNode
;
typedef
struct
zskiplist
{
struct
zskiplistNode
*
header
,
*
tail
;
unsigned
long
length
;
int
level
;
}
zskiplist
;
typedef
struct
zset
{
dict
*
dict
;
zskiplist
*
zsl
;
}
zset
;
/*-----------------------------------------------------------------------------
* Redis cluster data structures
*----------------------------------------------------------------------------*/
#define REDIS_CLUSTER_SLOTS 4096
#define REDIS_CLUSTER_OK 0
/* Everything looks ok */
#define REDIS_CLUSTER_FAIL 1
/* The cluster can't work */
#define REDIS_CLUSTER_NEEDHELP 2
/* The cluster works, but needs some help */
#define REDIS_CLUSTER_NAMELEN 40
/* sha1 hex length */
#define REDIS_CLUSTER_PORT_INCR 10000
/* Cluster port = baseport + PORT_INCR */
struct
clusterNode
;
/* clusterLink encapsulates everything needed to talk with a remote node. */
typedef
struct
clusterLink
{
int
fd
;
/* TCP socket file descriptor */
sds
sndbuf
;
/* Packet send buffer */
sds
rcvbuf
;
/* Packet reception buffer */
struct
clusterNode
*
node
;
/* Node related to this link if any, or NULL */
}
clusterLink
;
/* Node flags */
#define REDIS_NODE_MASTER 1
/* The node is a master */
#define REDIS_NODE_SLAVE 2
/* The node is a slave */
#define REDIS_NODE_PFAIL 4
/* Failure? Need acknowledge */
#define REDIS_NODE_FAIL 8
/* The node is believed to be malfunctioning */
#define REDIS_NODE_MYSELF 16
/* This node is myself */
#define REDIS_NODE_HANDSHAKE 32
/* We have still to exchange the first ping */
#define REDIS_NODE_NOADDR 64
/* We don't know the address of this node */
#define REDIS_NODE_MEET 128
/* Send a MEET message to this node */
#define REDIS_NODE_NULL_NAME "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"
struct
clusterNode
{
char
name
[
REDIS_CLUSTER_NAMELEN
];
/* Node name, hex string, sha1-size */
int
flags
;
/* REDIS_NODE_... */
unsigned
char
slots
[
REDIS_CLUSTER_SLOTS
/
8
];
/* slots handled by this node */
int
numslaves
;
/* Number of slave nodes, if this is a master */
struct
clusterNode
**
slaves
;
/* pointers to slave nodes */
struct
clusterNode
*
slaveof
;
/* pointer to the master node */
time_t
ping_sent
;
/* Unix time we sent latest ping */
time_t
pong_received
;
/* Unix time we received the pong */
char
*
configdigest
;
/* Configuration digest of this node */
time_t
configdigest_ts
;
/* Configuration digest timestamp */
char
ip
[
16
];
/* Latest known IP address of this node */
int
port
;
/* Latest known port of this node */
clusterLink
*
link
;
/* TCP/IP link with this node */
};
typedef
struct
clusterNode
clusterNode
;
typedef
struct
{
char
*
configfile
;
clusterNode
*
myself
;
/* This node */
int
state
;
/* REDIS_CLUSTER_OK, REDIS_CLUSTER_FAIL, ... */
int
node_timeout
;
dict
*
nodes
;
/* Hash table of name -> clusterNode structures */
clusterNode
*
migrating_slots_to
[
REDIS_CLUSTER_SLOTS
];
clusterNode
*
importing_slots_from
[
REDIS_CLUSTER_SLOTS
];
clusterNode
*
slots
[
REDIS_CLUSTER_SLOTS
];
zskiplist
*
slots_to_keys
;
}
clusterState
;
/* Redis cluster messages header */
/* Note that the PING, PONG and MEET messages are actually the same exact
* kind of packet. PONG is the reply to ping, in the extact format as a PING,
* while MEET is a special PING that forces the receiver to add the sender
* as a node (if it is not already in the list). */
#define CLUSTERMSG_TYPE_PING 0
/* Ping */
#define CLUSTERMSG_TYPE_PONG 1
/* Pong (reply to Ping) */
#define CLUSTERMSG_TYPE_MEET 2
/* Meet "let's join" message */
#define CLUSTERMSG_TYPE_FAIL 3
/* Mark node xxx as failing */
/* Initially we don't know our "name", but we'll find it once we connect
* to the first node, using the getsockname() function. Then we'll use this
* address for all the next messages. */
typedef
struct
{
char
nodename
[
REDIS_CLUSTER_NAMELEN
];
uint32_t
ping_sent
;
uint32_t
pong_received
;
char
ip
[
16
];
/* 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
{
char
nodename
[
REDIS_CLUSTER_NAMELEN
];
}
clusterMsgDataFail
;
union
clusterMsgData
{
/* PING, MEET and PONG */
struct
{
/* Array of N clusterMsgDataGossip structures */
clusterMsgDataGossip
gossip
[
1
];
}
ping
;
/* FAIL */
struct
{
clusterMsgDataFail
about
;
}
fail
;
};
typedef
struct
{
uint32_t
totlen
;
/* Total length of this message */
uint16_t
type
;
/* Message type */
uint16_t
count
;
/* Only used for some kind of messages. */
char
sender
[
REDIS_CLUSTER_NAMELEN
];
/* Name of the sender node */
unsigned
char
myslots
[
REDIS_CLUSTER_SLOTS
/
8
];
char
slaveof
[
REDIS_CLUSTER_NAMELEN
];
char
configdigest
[
32
];
uint16_t
port
;
/* Sender TCP base port */
unsigned
char
state
;
/* Cluster state from the POV of the sender */
unsigned
char
notused
[
5
];
/* Reserved for future use. For alignment. */
union
clusterMsgData
data
;
}
clusterMsg
;
/*-----------------------------------------------------------------------------
* Global server state
*----------------------------------------------------------------------------*/
struct
redisServer
{
struct
redisServer
{
/* General */
/* General */
pthread_t
mainthread
;
pthread_t
mainthread
;
...
@@ -373,6 +521,7 @@ struct redisServer {
...
@@ -373,6 +521,7 @@ struct redisServer {
char
*
unixsocket
;
char
*
unixsocket
;
int
ipfd
;
int
ipfd
;
int
sofd
;
int
sofd
;
int
cfd
;
list
*
clients
;
list
*
clients
;
list
*
slaves
,
*
monitors
;
list
*
slaves
,
*
monitors
;
char
neterr
[
ANET_ERR_LEN
];
char
neterr
[
ANET_ERR_LEN
];
...
@@ -393,6 +542,7 @@ struct redisServer {
...
@@ -393,6 +542,7 @@ struct redisServer {
long
long
stat_evictedkeys
;
/* number of evicted keys (maxmemory) */
long
long
stat_evictedkeys
;
/* number of evicted keys (maxmemory) */
long
long
stat_keyspace_hits
;
/* number of successful lookups of keys */
long
long
stat_keyspace_hits
;
/* number of successful lookups of keys */
long
long
stat_keyspace_misses
;
/* number of failed lookups of keys */
long
long
stat_keyspace_misses
;
/* number of failed lookups of keys */
size_t
stat_peak_memory
;
/* max used memory record */
/* Configuration */
/* Configuration */
int
verbosity
;
int
verbosity
;
int
maxidletime
;
int
maxidletime
;
...
@@ -468,6 +618,8 @@ struct redisServer {
...
@@ -468,6 +618,8 @@ struct redisServer {
size_t
list_max_ziplist_entries
;
size_t
list_max_ziplist_entries
;
size_t
list_max_ziplist_value
;
size_t
list_max_ziplist_value
;
size_t
set_max_intset_entries
;
size_t
set_max_intset_entries
;
size_t
zset_max_ziplist_entries
;
size_t
zset_max_ziplist_value
;
time_t
unixtime
;
/* Unix time sampled every second. */
time_t
unixtime
;
/* Unix time sampled every second. */
/* Virtual memory I/O threads stuff */
/* Virtual memory I/O threads stuff */
/* An I/O thread process an element taken from the io_jobs queue and
/* An I/O thread process an element taken from the io_jobs queue and
...
@@ -499,6 +651,9 @@ struct redisServer {
...
@@ -499,6 +651,9 @@ struct redisServer {
/* Misc */
/* Misc */
unsigned
lruclock
:
22
;
/* clock incrementing every minute, for LRU */
unsigned
lruclock
:
22
;
/* clock incrementing every minute, for LRU */
unsigned
lruclock_padding
:
10
;
unsigned
lruclock_padding
:
10
;
/* Cluster */
int
cluster_enabled
;
clusterState
cluster
;
};
};
typedef
struct
pubsubPattern
{
typedef
struct
pubsubPattern
{
...
@@ -507,20 +662,19 @@ typedef struct pubsubPattern {
...
@@ -507,20 +662,19 @@ typedef struct pubsubPattern {
}
pubsubPattern
;
}
pubsubPattern
;
typedef
void
redisCommandProc
(
redisClient
*
c
);
typedef
void
redisCommandProc
(
redisClient
*
c
);
typedef
void
redisVmPreloadProc
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
int
argc
,
robj
**
argv
);
typedef
int
*
redisGetKeysProc
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
);
struct
redisCommand
{
struct
redisCommand
{
char
*
name
;
char
*
name
;
redisCommandProc
*
proc
;
redisCommandProc
*
proc
;
int
arity
;
int
arity
;
int
flags
;
int
flags
;
/* Use a function to determine which keys need to be loaded
/* Use a function to determine keys arguments in a command line.
* in the background prior to executing this command. Takes precedence
* Used both for diskstore preloading and Redis Cluster. */
* over vm_firstkey and others, ignored when NULL */
redisGetKeysProc
*
getkeys_proc
;
redisVmPreloadProc
*
vm_preload_proc
;
/* What keys should be loaded in background when calling this command? */
/* What keys should be loaded in background when calling this command? */
int
vm_
firstkey
;
/* The first argument that's a key (0 = no keys) */
int
firstkey
;
/* The first argument that's a key (0 = no keys) */
int
vm_
lastkey
;
/* THe last argument that's a key */
int
lastkey
;
/* THe last argument that's a key */
int
vm_
keystep
;
/* The step between first and last key */
int
keystep
;
/* The step between first and last key */
long
long
microseconds
,
calls
;
long
long
microseconds
,
calls
;
};
};
...
@@ -542,28 +696,6 @@ typedef struct _redisSortOperation {
...
@@ -542,28 +696,6 @@ typedef struct _redisSortOperation {
robj
*
pattern
;
robj
*
pattern
;
}
redisSortOperation
;
}
redisSortOperation
;
/* ZSETs use a specialized version of Skiplists */
typedef
struct
zskiplistNode
{
robj
*
obj
;
double
score
;
struct
zskiplistNode
*
backward
;
struct
zskiplistLevel
{
struct
zskiplistNode
*
forward
;
unsigned
int
span
;
}
level
[];
}
zskiplistNode
;
typedef
struct
zskiplist
{
struct
zskiplistNode
*
header
,
*
tail
;
unsigned
long
length
;
int
level
;
}
zskiplist
;
typedef
struct
zset
{
dict
*
dict
;
zskiplist
*
zsl
;
}
zset
;
/* DIsk store threaded I/O request message */
/* DIsk store threaded I/O request message */
#define REDIS_IOJOB_LOAD 0
#define REDIS_IOJOB_LOAD 0
#define REDIS_IOJOB_SAVE 1
#define REDIS_IOJOB_SAVE 1
...
@@ -634,6 +766,7 @@ extern struct redisServer server;
...
@@ -634,6 +766,7 @@ extern struct redisServer server;
extern
struct
sharedObjectsStruct
shared
;
extern
struct
sharedObjectsStruct
shared
;
extern
dictType
setDictType
;
extern
dictType
setDictType
;
extern
dictType
zsetDictType
;
extern
dictType
zsetDictType
;
extern
dictType
clusterNodesDictType
;
extern
double
R_Zero
,
R_PosInf
,
R_NegInf
,
R_Nan
;
extern
double
R_Zero
,
R_PosInf
,
R_NegInf
,
R_Nan
;
dictType
hashDictType
;
dictType
hashDictType
;
...
@@ -720,6 +853,7 @@ void freeHashObject(robj *o);
...
@@ -720,6 +853,7 @@ void freeHashObject(robj *o);
robj
*
createObject
(
int
type
,
void
*
ptr
);
robj
*
createObject
(
int
type
,
void
*
ptr
);
robj
*
createStringObject
(
char
*
ptr
,
size_t
len
);
robj
*
createStringObject
(
char
*
ptr
,
size_t
len
);
robj
*
dupStringObject
(
robj
*
o
);
robj
*
dupStringObject
(
robj
*
o
);
int
isObjectRepresentableAsLongLong
(
robj
*
o
,
long
long
*
llongval
);
robj
*
tryObjectEncoding
(
robj
*
o
);
robj
*
tryObjectEncoding
(
robj
*
o
);
robj
*
getDecodedObject
(
robj
*
o
);
robj
*
getDecodedObject
(
robj
*
o
);
size_t
stringObjectLen
(
robj
*
o
);
size_t
stringObjectLen
(
robj
*
o
);
...
@@ -730,6 +864,7 @@ robj *createSetObject(void);
...
@@ -730,6 +864,7 @@ robj *createSetObject(void);
robj
*
createIntsetObject
(
void
);
robj
*
createIntsetObject
(
void
);
robj
*
createHashObject
(
void
);
robj
*
createHashObject
(
void
);
robj
*
createZsetObject
(
void
);
robj
*
createZsetObject
(
void
);
robj
*
createZsetZiplistObject
(
void
);
int
getLongFromObjectOrReply
(
redisClient
*
c
,
robj
*
o
,
long
*
target
,
const
char
*
msg
);
int
getLongFromObjectOrReply
(
redisClient
*
c
,
robj
*
o
,
long
*
target
,
const
char
*
msg
);
int
checkType
(
redisClient
*
c
,
robj
*
o
,
int
type
);
int
checkType
(
redisClient
*
c
,
robj
*
o
,
int
type
);
int
getLongLongFromObjectOrReply
(
redisClient
*
c
,
robj
*
o
,
long
long
*
target
,
const
char
*
msg
);
int
getLongLongFromObjectOrReply
(
redisClient
*
c
,
robj
*
o
,
long
long
*
target
,
const
char
*
msg
);
...
@@ -748,6 +883,7 @@ int fwriteBulkString(FILE *fp, char *s, unsigned long len);
...
@@ -748,6 +883,7 @@ int fwriteBulkString(FILE *fp, char *s, unsigned long len);
int
fwriteBulkDouble
(
FILE
*
fp
,
double
d
);
int
fwriteBulkDouble
(
FILE
*
fp
,
double
d
);
int
fwriteBulkLongLong
(
FILE
*
fp
,
long
long
l
);
int
fwriteBulkLongLong
(
FILE
*
fp
,
long
long
l
);
int
fwriteBulkObject
(
FILE
*
fp
,
robj
*
obj
);
int
fwriteBulkObject
(
FILE
*
fp
,
robj
*
obj
);
int
fwriteBulkCount
(
FILE
*
fp
,
char
prefix
,
int
count
);
/* Replication */
/* Replication */
void
replicationFeedSlaves
(
list
*
slaves
,
int
dictid
,
robj
**
argv
,
int
argc
);
void
replicationFeedSlaves
(
list
*
slaves
,
int
dictid
,
robj
**
argv
,
int
argc
);
...
@@ -789,9 +925,24 @@ int startAppendOnly(void);
...
@@ -789,9 +925,24 @@ int startAppendOnly(void);
void
backgroundRewriteDoneHandler
(
int
exitcode
,
int
bysignal
);
void
backgroundRewriteDoneHandler
(
int
exitcode
,
int
bysignal
);
/* Sorted sets data type */
/* Sorted sets data type */
/* Struct to hold a inclusive/exclusive range spec. */
typedef
struct
{
double
min
,
max
;
int
minex
,
maxex
;
/* are min or max exclusive? */
}
zrangespec
;
zskiplist
*
zslCreate
(
void
);
zskiplist
*
zslCreate
(
void
);
void
zslFree
(
zskiplist
*
zsl
);
void
zslFree
(
zskiplist
*
zsl
);
zskiplistNode
*
zslInsert
(
zskiplist
*
zsl
,
double
score
,
robj
*
obj
);
zskiplistNode
*
zslInsert
(
zskiplist
*
zsl
,
double
score
,
robj
*
obj
);
unsigned
char
*
zzlInsert
(
unsigned
char
*
zl
,
robj
*
ele
,
double
score
);
int
zslDelete
(
zskiplist
*
zsl
,
double
score
,
robj
*
obj
);
zskiplistNode
*
zslFirstInRange
(
zskiplist
*
zsl
,
zrangespec
range
);
double
zzlGetScore
(
unsigned
char
*
sptr
);
void
zzlNext
(
unsigned
char
*
zl
,
unsigned
char
**
eptr
,
unsigned
char
**
sptr
);
void
zzlPrev
(
unsigned
char
*
zl
,
unsigned
char
**
eptr
,
unsigned
char
**
sptr
);
unsigned
int
zsetLength
(
robj
*
zobj
);
void
zsetConvert
(
robj
*
zobj
,
int
encoding
);
/* Core functions */
/* Core functions */
void
freeMemoryIfNeeded
(
void
);
void
freeMemoryIfNeeded
(
void
);
...
@@ -829,8 +980,6 @@ void freeIOJob(iojob *j);
...
@@ -829,8 +980,6 @@ void freeIOJob(iojob *j);
void
queueIOJob
(
iojob
*
j
);
void
queueIOJob
(
iojob
*
j
);
void
waitEmptyIOJobsQueue
(
void
);
void
waitEmptyIOJobsQueue
(
void
);
void
processAllPendingIOJobs
(
void
);
void
processAllPendingIOJobs
(
void
);
void
zunionInterBlockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
int
argc
,
robj
**
argv
);
void
execBlockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
int
argc
,
robj
**
argv
);
int
blockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
);
int
blockClientOnSwappedKeys
(
redisClient
*
c
,
struct
redisCommand
*
cmd
);
int
dontWaitForSwappedKey
(
redisClient
*
c
,
robj
*
key
);
int
dontWaitForSwappedKey
(
redisClient
*
c
,
robj
*
key
);
void
handleClientsBlockedOnSwappedKey
(
redisDb
*
db
,
robj
*
key
);
void
handleClientsBlockedOnSwappedKey
(
redisDb
*
db
,
robj
*
key
);
...
@@ -881,16 +1030,6 @@ int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
...
@@ -881,16 +1030,6 @@ int pubsubUnsubscribeAllPatterns(redisClient *c, int notify);
void
freePubsubPattern
(
void
*
p
);
void
freePubsubPattern
(
void
*
p
);
int
listMatchPubsubPattern
(
void
*
a
,
void
*
b
);
int
listMatchPubsubPattern
(
void
*
a
,
void
*
b
);
/* Utility functions */
int
stringmatchlen
(
const
char
*
pattern
,
int
patternLen
,
const
char
*
string
,
int
stringLen
,
int
nocase
);
int
stringmatch
(
const
char
*
pattern
,
const
char
*
string
,
int
nocase
);
long
long
memtoll
(
const
char
*
p
,
int
*
err
);
int
ll2string
(
char
*
s
,
size_t
len
,
long
long
value
);
int
isStringRepresentableAsLong
(
sds
s
,
long
*
longval
);
int
isStringRepresentableAsLongLong
(
sds
s
,
long
long
*
longval
);
int
isObjectRepresentableAsLongLong
(
robj
*
o
,
long
long
*
llongval
);
/* Configuration */
/* Configuration */
void
loadServerConfig
(
char
*
filename
);
void
loadServerConfig
(
char
*
filename
);
void
appendServerSaveParams
(
time_t
seconds
,
int
changes
);
void
appendServerSaveParams
(
time_t
seconds
,
int
changes
);
...
@@ -916,6 +1055,25 @@ long long emptyDb();
...
@@ -916,6 +1055,25 @@ long long emptyDb();
int
selectDb
(
redisClient
*
c
,
int
id
);
int
selectDb
(
redisClient
*
c
,
int
id
);
void
signalModifiedKey
(
redisDb
*
db
,
robj
*
key
);
void
signalModifiedKey
(
redisDb
*
db
,
robj
*
key
);
void
signalFlushedDb
(
int
dbid
);
void
signalFlushedDb
(
int
dbid
);
unsigned
int
GetKeysInSlot
(
unsigned
int
hashslot
,
robj
**
keys
,
unsigned
int
count
);
/* API to get key arguments from commands */
#define REDIS_GETKEYS_ALL 0
#define REDIS_GETKEYS_PRELOAD 1
int
*
getKeysFromCommand
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
);
void
getKeysFreeResult
(
int
*
result
);
int
*
noPreloadGetKeys
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
);
int
*
renameGetKeys
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
);
int
*
zunionInterGetKeys
(
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
numkeys
,
int
flags
);
/* Cluster */
void
clusterInit
(
void
);
unsigned
short
crc16
(
const
char
*
buf
,
int
len
);
unsigned
int
keyHashSlot
(
char
*
key
,
int
keylen
);
clusterNode
*
createClusterNode
(
char
*
nodename
,
int
flags
);
int
clusterAddNode
(
clusterNode
*
node
);
void
clusterCron
(
void
);
clusterNode
*
getNodeByQuery
(
redisClient
*
c
,
struct
redisCommand
*
cmd
,
robj
**
argv
,
int
argc
,
int
*
hashslot
,
int
*
ask
);
/* Git SHA1 */
/* Git SHA1 */
char
*
redisGitSHA1
(
void
);
char
*
redisGitSHA1
(
void
);
...
@@ -1039,6 +1197,12 @@ void punsubscribeCommand(redisClient *c);
...
@@ -1039,6 +1197,12 @@ void punsubscribeCommand(redisClient *c);
void
publishCommand
(
redisClient
*
c
);
void
publishCommand
(
redisClient
*
c
);
void
watchCommand
(
redisClient
*
c
);
void
watchCommand
(
redisClient
*
c
);
void
unwatchCommand
(
redisClient
*
c
);
void
unwatchCommand
(
redisClient
*
c
);
void
clusterCommand
(
redisClient
*
c
);
void
restoreCommand
(
redisClient
*
c
);
void
migrateCommand
(
redisClient
*
c
);
void
dumpCommand
(
redisClient
*
c
);
void
objectCommand
(
redisClient
*
c
);
void
clientCommand
(
redisClient
*
c
);
#if defined(__GNUC__)
#if defined(__GNUC__)
void
*
calloc
(
size_t
count
,
size_t
size
)
__attribute__
((
deprecated
));
void
*
calloc
(
size_t
count
,
size_t
size
)
__attribute__
((
deprecated
));
...
...
src/sds.c
View file @
bfe85f7c
...
@@ -36,11 +36,11 @@
...
@@ -36,11 +36,11 @@
#define SDS_ABORT_ON_OOM
#define SDS_ABORT_ON_OOM
#include "sds.h"
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <ctype.h>
#include <ctype.h>
#include "sds.h"
#include "zmalloc.h"
#include "zmalloc.h"
static
void
sdsOomAbort
(
void
)
{
static
void
sdsOomAbort
(
void
)
{
...
@@ -51,7 +51,11 @@ static void sdsOomAbort(void) {
...
@@ -51,7 +51,11 @@ static void sdsOomAbort(void) {
sds
sdsnewlen
(
const
void
*
init
,
size_t
initlen
)
{
sds
sdsnewlen
(
const
void
*
init
,
size_t
initlen
)
{
struct
sdshdr
*
sh
;
struct
sdshdr
*
sh
;
if
(
init
)
{
sh
=
zmalloc
(
sizeof
(
struct
sdshdr
)
+
initlen
+
1
);
sh
=
zmalloc
(
sizeof
(
struct
sdshdr
)
+
initlen
+
1
);
}
else
{
sh
=
zcalloc
(
sizeof
(
struct
sdshdr
)
+
initlen
+
1
);
}
#ifdef SDS_ABORT_ON_OOM
#ifdef SDS_ABORT_ON_OOM
if
(
sh
==
NULL
)
sdsOomAbort
();
if
(
sh
==
NULL
)
sdsOomAbort
();
#else
#else
...
@@ -59,10 +63,8 @@ sds sdsnewlen(const void *init, size_t initlen) {
...
@@ -59,10 +63,8 @@ sds sdsnewlen(const void *init, size_t initlen) {
#endif
#endif
sh
->
len
=
initlen
;
sh
->
len
=
initlen
;
sh
->
free
=
0
;
sh
->
free
=
0
;
if
(
initlen
)
{
if
(
initlen
&&
init
)
if
(
init
)
memcpy
(
sh
->
buf
,
init
,
initlen
);
memcpy
(
sh
->
buf
,
init
,
initlen
);
else
memset
(
sh
->
buf
,
0
,
initlen
);
}
sh
->
buf
[
initlen
]
=
'\0'
;
sh
->
buf
[
initlen
]
=
'\0'
;
return
(
char
*
)
sh
->
buf
;
return
(
char
*
)
sh
->
buf
;
}
}
...
@@ -76,11 +78,6 @@ sds sdsnew(const char *init) {
...
@@ -76,11 +78,6 @@ sds sdsnew(const char *init) {
return
sdsnewlen
(
init
,
initlen
);
return
sdsnewlen
(
init
,
initlen
);
}
}
size_t
sdslen
(
const
sds
s
)
{
struct
sdshdr
*
sh
=
(
void
*
)
(
s
-
(
sizeof
(
struct
sdshdr
)));
return
sh
->
len
;
}
sds
sdsdup
(
const
sds
s
)
{
sds
sdsdup
(
const
sds
s
)
{
return
sdsnewlen
(
s
,
sdslen
(
s
));
return
sdsnewlen
(
s
,
sdslen
(
s
));
}
}
...
@@ -90,11 +87,6 @@ void sdsfree(sds s) {
...
@@ -90,11 +87,6 @@ void sdsfree(sds s) {
zfree
(
s
-
sizeof
(
struct
sdshdr
));
zfree
(
s
-
sizeof
(
struct
sdshdr
));
}
}
size_t
sdsavail
(
sds
s
)
{
struct
sdshdr
*
sh
=
(
void
*
)
(
s
-
(
sizeof
(
struct
sdshdr
)));
return
sh
->
free
;
}
void
sdsupdatelen
(
sds
s
)
{
void
sdsupdatelen
(
sds
s
)
{
struct
sdshdr
*
sh
=
(
void
*
)
(
s
-
(
sizeof
(
struct
sdshdr
)));
struct
sdshdr
*
sh
=
(
void
*
)
(
s
-
(
sizeof
(
struct
sdshdr
)));
int
reallen
=
strlen
(
s
);
int
reallen
=
strlen
(
s
);
...
@@ -306,15 +298,17 @@ int sdscmp(sds s1, sds s2) {
...
@@ -306,15 +298,17 @@ int sdscmp(sds s1, sds s2) {
*/
*/
sds
*
sdssplitlen
(
char
*
s
,
int
len
,
char
*
sep
,
int
seplen
,
int
*
count
)
{
sds
*
sdssplitlen
(
char
*
s
,
int
len
,
char
*
sep
,
int
seplen
,
int
*
count
)
{
int
elements
=
0
,
slots
=
5
,
start
=
0
,
j
;
int
elements
=
0
,
slots
=
5
,
start
=
0
,
j
;
sds
*
tokens
;
if
(
seplen
<
1
||
len
<
0
)
return
NULL
;
sds
*
tokens
=
zmalloc
(
sizeof
(
sds
)
*
slots
);
tokens
=
zmalloc
(
sizeof
(
sds
)
*
slots
);
#ifdef SDS_ABORT_ON_OOM
#ifdef SDS_ABORT_ON_OOM
if
(
tokens
==
NULL
)
sdsOomAbort
();
if
(
tokens
==
NULL
)
sdsOomAbort
();
#else
if
(
tokens
==
NULL
)
return
NULL
;
#endif
#endif
if
(
seplen
<
1
||
len
<
0
||
tokens
==
NULL
)
{
*
count
=
0
;
return
NULL
;
}
if
(
len
==
0
)
{
if
(
len
==
0
)
{
*
count
=
0
;
*
count
=
0
;
return
tokens
;
return
tokens
;
...
@@ -552,6 +546,13 @@ err:
...
@@ -552,6 +546,13 @@ err:
return
NULL
;
return
NULL
;
}
}
void
sdssplitargs_free
(
sds
*
argv
,
int
argc
)
{
int
j
;
for
(
j
=
0
;
j
<
argc
;
j
++
)
sdsfree
(
argv
[
j
]);
zfree
(
argv
);
}
#ifdef SDS_TEST_MAIN
#ifdef SDS_TEST_MAIN
#include <stdio.h>
#include <stdio.h>
#include "testhelp.h"
#include "testhelp.h"
...
...
Prev
1
2
3
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment