Compare commits
41
Commits
fix_tls_tests
...
AIO
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9142890f1f | ||
|
|
8bd56fadd6 | ||
|
|
23f9b584a8 | ||
|
|
ffabf3c5b7 | ||
|
|
9b1e95809c | ||
|
|
b8776bb001 | ||
|
|
84c20e8337 | ||
|
|
bae2409cce | ||
|
|
8f7c44257b | ||
|
|
2772ce249c | ||
|
|
bcfd9327cb | ||
|
|
01ff36fc28 | ||
|
|
6466b09fdc | ||
|
|
40d7a701fe | ||
|
|
78b9d303d3 | ||
|
|
d912013d1b | ||
|
|
898e6519d1 | ||
|
|
8c074a7d01 | ||
|
|
6e69b4a795 | ||
|
|
1c36b46cb4 | ||
|
|
73abd04b95 | ||
|
|
29d6845d1f | ||
|
|
da84b26785 | ||
|
|
eb9070c833 | ||
|
|
b7b503d3ce | ||
|
|
327bbec981 | ||
|
|
7175a8e4eb | ||
|
|
9aefc183c6 | ||
|
|
3e9b867709 | ||
|
|
e8b5bbf7a1 | ||
|
|
79ef18e885 | ||
|
|
23a91df9f6 | ||
|
|
d8741595ae | ||
|
|
3c9dd6ffc2 | ||
|
|
42d28c9ff6 | ||
|
|
82372cbce8 | ||
|
|
69b07c5cc2 | ||
|
|
a6d27dc02c | ||
|
|
bbcaf48cb0 | ||
|
|
85194d99da | ||
|
|
5c86d2faa2 |
No files matched your search
Vendored
+1
-1
@@ -53,4 +53,4 @@
|
||||
"typeinfo": "cpp",
|
||||
"utility": "cpp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
Copyright (c) 2006-2015, Salvatore Sanfilippo
|
||||
Copyright (C) 2019, John Sully
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
@@ -1,52 +1,60 @@
|
||||
This README is just a fast *quick start* document. You can find more detailed documentation at [redis.io](https://redis.io).
|
||||
|
||||
What is Redis?
|
||||
What is KeyDB?
|
||||
--------------
|
||||
|
||||
Redis is often referred as a *data structures* server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a *server-client* model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.
|
||||
KeyDB is a high performance fork of Redis focussing on multithreading, memory efficiency, and high throughput. In addition to multithreading KeyDB also has features only available in Redis Enterprise such as FLASH storage support, and some not available at all such as direct backup to AWS S3.
|
||||
|
||||
Data structures implemented into Redis have a few special properties:
|
||||
On the same hardware KeyDB can perform twice as many queries per second as Redis, with 60% lower latency.
|
||||
|
||||
* Redis cares to store them on disk, even if they are always served and modified into the server memory. This means that Redis is fast, but that is also non-volatile.
|
||||
* Implementation of data structures stress on memory efficiency, so data structures inside Redis will likely use less memory compared to the same data structure modeled using an high level programming language.
|
||||
* Redis offers a number of features that are natural to find in a database, like replication, tunable levels of durability, cluster, high availability.
|
||||
Why fork Redis?
|
||||
---------------
|
||||
|
||||
Another good example is to think of Redis as a more complex version of memcached, where the operations are not just SETs and GETs, but operations to work with complex data types like Lists, Sets, ordered data structures, and so forth.
|
||||
The Redis maintainers have continually reiterated that they do not plan to support multithreading. While we have great respect for the redis team, we feel the analysis justifying this decision is incorrect. In addition we wanted open source implementations of features currently only available in proprietary modules. We feel a fork is the best way to accelerate development in the areas of most interest to us.
|
||||
|
||||
If you want to know more, this is a list of selected starting points:
|
||||
We plan to track the Redis repo closely and hope our projects can learn from each other.
|
||||
|
||||
* Introduction to Redis data types. http://redis.io/topics/data-types-intro
|
||||
* Try Redis directly inside your browser. http://try.redis.io
|
||||
* The full list of Redis commands. http://redis.io/commands
|
||||
* There is much more inside the Redis official documentation. http://redis.io/documentation
|
||||
Benchmarking KeyDB
|
||||
------------------
|
||||
|
||||
Building Redis
|
||||
Please note keydb-benchmark and redis-benchmark are currently single threaded and too slow to properly benchmark KeyDB. We recommend using a redis cluster benchmark tool such as [memtier](https://github.com/RedisLabs/memtier_benchmark). Please ensure your machine has enough cores for both KeyDB and memteir if testing locally. KeyDB expects exclusive use of any cores assigned to it.
|
||||
|
||||
For more details on how we benchmarked KeyDB along with performance numbers check out our blog post: [Redis Should Be Multithreaded](https://medium.com/@john_63123/redis-should-be-multi-threaded-e28319cab744?source=friends_link&sk=7ce8e9fe3ec8224a4d27ef075d085457)
|
||||
|
||||
New Configuration Options
|
||||
-------------------------
|
||||
|
||||
With new features comes new options:
|
||||
|
||||
server-threads N
|
||||
|
||||
The number of threads used to serve requests. This should be related to the number of queues available in your network hardware, *not* the number of cores on your machine. Because KeyDB uses spinlocks to reduce latency; making this too high will reduce performance. We recommend using 4 here. By default this is set to one.
|
||||
|
||||
scratch-file-path /path
|
||||
|
||||
If you would like to use the FLASH backed storage this option configures the directory for KeyDB's temporary files. This feature relies on snapshotting to work so must be used on a BTRFS filesystem. ZFS may also work but is untested. With this feature KeyDB will use RAM as a cache and page to disk as necessary. NOTE: This requires special compilation options, see Building KeyDB below.
|
||||
|
||||
db-s3-object /path/to/bucket
|
||||
|
||||
If you would like KeyDB to dump directly to AWS S3 this option specifies the bucket. Using this option with the traditional RDB options will result in KeyDB backing up twice to both locations. This requires the AWS CLI tools to be installed and configured which are used under the hood to transfer the data.
|
||||
|
||||
All other configuration options behave as you'd expect. Your existing configuration files should continue to work unchanged.
|
||||
|
||||
Building KeyDB
|
||||
--------------
|
||||
|
||||
Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD.
|
||||
We support big endian and little endian architectures, and both 32 bit
|
||||
and 64 bit systems.
|
||||
KeyDB can be compiled and is tested for use on Linux. KeyDB currently relies on SO_REUSEADDR's load balancing behavior which is available only in Linux. When we support marshalling connections across threads we plan to support other operating systems such as FreeBSD.
|
||||
|
||||
It may compile on Solaris derived systems (for instance SmartOS) but our
|
||||
support for this platform is *best effort* and Redis is not guaranteed to
|
||||
work as well as in Linux, OSX, and \*BSD there.
|
||||
|
||||
It is as simple as:
|
||||
Compiling is as simple as:
|
||||
|
||||
% make
|
||||
|
||||
You can run a 32 bit Redis binary using:
|
||||
You can enable flash support with (Note: autoconf and autotools must be installed):
|
||||
|
||||
% make 32bit
|
||||
|
||||
After building Redis, it is a good idea to test it using:
|
||||
|
||||
% make test
|
||||
% make MALLOC=memkind
|
||||
|
||||
Fixing build problems with dependencies or cached build options
|
||||
---------
|
||||
|
||||
Redis has some dependencies which are included into the `deps` directory.
|
||||
KeyDB has some dependencies which are included into the `deps` directory.
|
||||
`make` does not automatically rebuild dependencies even if something in
|
||||
the source code of dependencies changes.
|
||||
|
||||
@@ -66,11 +74,11 @@ command.
|
||||
Fixing problems building 32 bit binaries
|
||||
---------
|
||||
|
||||
If after building Redis with a 32 bit target you need to rebuild it
|
||||
If after building KeyDB with a 32 bit target you need to rebuild it
|
||||
with a 64 bit target, or the other way around, you need to perform a
|
||||
`make distclean` in the root directory of the Redis distribution.
|
||||
`make distclean` in the root directory of the KeyDB distribution.
|
||||
|
||||
In case of build errors when trying to build a 32 bit binary of Redis, try
|
||||
In case of build errors when trying to build a 32 bit binary of KeyDB, try
|
||||
the following steps:
|
||||
|
||||
* Install the packages libc6-dev-i386 (also try g++-multilib).
|
||||
@@ -80,8 +88,8 @@ the following steps:
|
||||
Allocator
|
||||
---------
|
||||
|
||||
Selecting a non-default memory allocator when building Redis is done by setting
|
||||
the `MALLOC` environment variable. Redis is compiled and linked against libc
|
||||
Selecting a non-default memory allocator when building KeyDB is done by setting
|
||||
the `MALLOC` environment variable. KeyDB is compiled and linked against libc
|
||||
malloc by default, with the exception of jemalloc being the default on Linux
|
||||
systems. This default was picked because jemalloc has proven to have fewer
|
||||
fragmentation problems than libc malloc.
|
||||
@@ -97,60 +105,60 @@ To compile against jemalloc on Mac OS X systems, use:
|
||||
Verbose build
|
||||
-------------
|
||||
|
||||
Redis will build with a user friendly colorized output by default.
|
||||
KeyDB will build with a user friendly colorized output by default.
|
||||
If you want to see a more verbose output use the following:
|
||||
|
||||
% make V=1
|
||||
|
||||
Running Redis
|
||||
Running KeyDB
|
||||
-------------
|
||||
|
||||
To run Redis with the default configuration just type:
|
||||
To run KeyDB with the default configuration just type:
|
||||
|
||||
% cd src
|
||||
% ./keydb-server
|
||||
|
||||
If you want to provide your redis.conf, you have to run it using an additional
|
||||
If you want to provide your keydb.conf, you have to run it using an additional
|
||||
parameter (the path of the configuration file):
|
||||
|
||||
% cd src
|
||||
% ./keydb-server /path/to/redis.conf
|
||||
% ./keydb-server /path/to/keydb.conf
|
||||
|
||||
It is possible to alter the Redis configuration by passing parameters directly
|
||||
It is possible to alter the KeyDB configuration by passing parameters directly
|
||||
as options using the command line. Examples:
|
||||
|
||||
% ./keydb-server --port 9999 --replicaof 127.0.0.1 6379
|
||||
% ./keydb-server /etc/redis/6379.conf --loglevel debug
|
||||
% ./keydb-server /etc/keydb/6379.conf --loglevel debug
|
||||
|
||||
All the options in redis.conf are also supported as options using the command
|
||||
All the options in keydb.conf are also supported as options using the command
|
||||
line, with exactly the same name.
|
||||
|
||||
Playing with Redis
|
||||
Playing with KeyDB
|
||||
------------------
|
||||
|
||||
You can use keydb-cli to play with Redis. Start a keydb-server instance,
|
||||
You can use keydb-cli to play with KeyDB. Start a keydb-server instance,
|
||||
then in another terminal try the following:
|
||||
|
||||
% cd src
|
||||
% ./keydb-cli
|
||||
redis> ping
|
||||
keydb> ping
|
||||
PONG
|
||||
redis> set foo bar
|
||||
keydb> set foo bar
|
||||
OK
|
||||
redis> get foo
|
||||
keydb> get foo
|
||||
"bar"
|
||||
redis> incr mycounter
|
||||
keydb> incr mycounter
|
||||
(integer) 1
|
||||
redis> incr mycounter
|
||||
keydb> incr mycounter
|
||||
(integer) 2
|
||||
redis>
|
||||
keydb>
|
||||
|
||||
You can find the list of all the available commands at http://redis.io/commands.
|
||||
|
||||
Installing Redis
|
||||
Installing KeyDB
|
||||
-----------------
|
||||
|
||||
In order to install Redis binaries into /usr/local/bin just use:
|
||||
In order to install KeyDB binaries into /usr/local/bin just use:
|
||||
|
||||
% make install
|
||||
|
||||
@@ -159,7 +167,7 @@ different destination.
|
||||
|
||||
Make install will just install binaries in your system, but will not configure
|
||||
init scripts and configuration files in the appropriate place. This is not
|
||||
needed if you want just to play a bit with Redis, but if you are installing
|
||||
needed if you want just to play a bit with KeyDB, but if you are installing
|
||||
it the proper way for a production system, we have a script doing this
|
||||
for Ubuntu and Debian systems:
|
||||
|
||||
@@ -167,280 +175,22 @@ for Ubuntu and Debian systems:
|
||||
% ./install_server.sh
|
||||
|
||||
The script will ask you a few questions and will setup everything you need
|
||||
to run Redis properly as a background daemon that will start again on
|
||||
to run KeyDB properly as a background daemon that will start again on
|
||||
system reboots.
|
||||
|
||||
You'll be able to stop and start Redis using the script named
|
||||
`/etc/init.d/redis_<portnumber>`, for instance `/etc/init.d/redis_6379`.
|
||||
You'll be able to stop and start KeyDB using the script named
|
||||
`/etc/init.d/keydb_<portnumber>`, for instance `/etc/init.d/keydb_6379`.
|
||||
|
||||
Code contributions
|
||||
-----------------
|
||||
|
||||
Note: by contributing code to the Redis project in any form, including sending
|
||||
Note: by contributing code to the KeyDB project in any form, including sending
|
||||
a pull request via Github, a code fragment or patch via private email or
|
||||
public discussion groups, you agree to release your code under the terms
|
||||
of the BSD license that you can find in the [COPYING][1] file included in the Redis
|
||||
of the BSD license that you can find in the COPYING file included in the KeyDB
|
||||
source distribution.
|
||||
|
||||
Please see the [CONTRIBUTING][2] file in this source distribution for more
|
||||
Please see the CONTRIBUTING file in this source distribution for more
|
||||
information.
|
||||
|
||||
[1]: https://github.com/antirez/redis/blob/unstable/COPYING
|
||||
[2]: https://github.com/antirez/redis/blob/unstable/CONTRIBUTING
|
||||
|
||||
Redis internals
|
||||
===
|
||||
|
||||
If you are reading this README you are likely in front of a Github page
|
||||
or you just untarred the Redis distribution tar ball. In both the cases
|
||||
you are basically one step away from the source code, so here we explain
|
||||
the Redis source code layout, what is in each file as a general idea, the
|
||||
most important functions and structures inside the Redis server and so forth.
|
||||
We keep all the discussion at a high level without digging into the details
|
||||
since this document would be huge otherwise and our code base changes
|
||||
continuously, but a general idea should be a good starting point to
|
||||
understand more. Moreover most of the code is heavily commented and easy
|
||||
to follow.
|
||||
|
||||
Source code layout
|
||||
---
|
||||
|
||||
The Redis root directory just contains this README, the Makefile which
|
||||
calls the real Makefile inside the `src` directory and an example
|
||||
configuration for Redis and Sentinel. You can find a few shell
|
||||
scripts that are used in order to execute the Redis, Redis Cluster and
|
||||
Redis Sentinel unit tests, which are implemented inside the `tests`
|
||||
directory.
|
||||
|
||||
Inside the root are the following important directories:
|
||||
|
||||
* `src`: contains the Redis implementation, written in C.
|
||||
* `tests`: contains the unit tests, implemented in Tcl.
|
||||
* `deps`: contains libraries Redis uses. Everything needed to compile Redis is inside this directory; your system just needs to provide `libc`, a POSIX compatible interface and a C compiler. Notably `deps` contains a copy of `jemalloc`, which is the default allocator of Redis under Linux. Note that under `deps` there are also things which started with the Redis project, but for which the main repository is not `antirez/redis`.
|
||||
|
||||
There are a few more directories but they are not very important for our goals
|
||||
here. We'll focus mostly on `src`, where the Redis implementation is contained,
|
||||
exploring what there is inside each file. The order in which files are
|
||||
exposed is the logical one to follow in order to disclose different layers
|
||||
of complexity incrementally.
|
||||
|
||||
Note: lately Redis was refactored quite a bit. Function names and file
|
||||
names have been changed, so you may find that this documentation reflects the
|
||||
`unstable` branch more closely. For instance in Redis 3.0 the `server.c`
|
||||
and `server.h` files were named `redis.c` and `redis.h`. However the overall
|
||||
structure is the same. Keep in mind that all the new developments and pull
|
||||
requests should be performed against the `unstable` branch.
|
||||
|
||||
server.h
|
||||
---
|
||||
|
||||
The simplest way to understand how a program works is to understand the
|
||||
data structures it uses. So we'll start from the main header file of
|
||||
Redis, which is `server.h`.
|
||||
|
||||
All the server configuration and in general all the shared state is
|
||||
defined in a global structure called `server`, of type `struct redisServer`.
|
||||
A few important fields in this structure are:
|
||||
|
||||
* `server.db` is an array of Redis databases, where data is stored.
|
||||
* `server.commands` is the command table.
|
||||
* `server.clients` is a linked list of clients connected to the server.
|
||||
* `server.master` is a special client, the master, if the instance is a replica.
|
||||
|
||||
There are tons of other fields. Most fields are commented directly inside
|
||||
the structure definition.
|
||||
|
||||
Another important Redis data structure is the one defining a client.
|
||||
In the past it was called `redisClient`, now just `client`. The structure
|
||||
has many fields, here we'll just show the main ones:
|
||||
|
||||
struct client {
|
||||
int fd;
|
||||
sds querybuf;
|
||||
int argc;
|
||||
robj **argv;
|
||||
redisDb *db;
|
||||
int flags;
|
||||
list *reply;
|
||||
char buf[PROTO_REPLY_CHUNK_BYTES];
|
||||
... many other fields ...
|
||||
}
|
||||
|
||||
The client structure defines a *connected client*:
|
||||
|
||||
* The `fd` field is the client socket file descriptor.
|
||||
* `argc` and `argv` are populated with the command the client is executing, so that functions implementing a given Redis command can read the arguments.
|
||||
* `querybuf` accumulates the requests from the client, which are parsed by the Redis server according to the Redis protocol and executed by calling the implementations of the commands the client is executing.
|
||||
* `reply` and `buf` are dynamic and static buffers that accumulate the replies the server sends to the client. These buffers are incrementally written to the socket as soon as the file descriptor is writable.
|
||||
|
||||
As you can see in the client structure above, arguments in a command
|
||||
are described as `robj` structures. The following is the full `robj`
|
||||
structure, which defines a *Redis object*:
|
||||
|
||||
typedef struct redisObject {
|
||||
unsigned type:4;
|
||||
unsigned encoding:4;
|
||||
unsigned lru:LRU_BITS; /* lru time (relative to server.lruclock) */
|
||||
int refcount;
|
||||
void *ptr;
|
||||
} robj;
|
||||
|
||||
Basically this structure can represent all the basic Redis data types like
|
||||
strings, lists, sets, sorted sets and so forth. The interesting thing is that
|
||||
it has a `type` field, so that it is possible to know what type a given
|
||||
object has, and a `refcount`, so that the same object can be referenced
|
||||
in multiple places without allocating it multiple times. Finally the `ptr`
|
||||
field points to the actual representation of the object, which might vary
|
||||
even for the same type, depending on the `encoding` used.
|
||||
|
||||
Redis objects are used extensively in the Redis internals, however in order
|
||||
to avoid the overhead of indirect accesses, recently in many places
|
||||
we just use plain dynamic strings not wrapped inside a Redis object.
|
||||
|
||||
server.c
|
||||
---
|
||||
|
||||
This is the entry point of the Redis server, where the `main()` function
|
||||
is defined. The following are the most important steps in order to startup
|
||||
the Redis server.
|
||||
|
||||
* `initServerConfig()` setups the default values of the `server` structure.
|
||||
* `initServer()` allocates the data structures needed to operate, setup the listening socket, and so forth.
|
||||
* `aeMain()` starts the event loop which listens for new connections.
|
||||
|
||||
There are two special functions called periodically by the event loop:
|
||||
|
||||
1. `serverCron()` is called periodically (according to `server.hz` frequency), and performs tasks that must be performed from time to time, like checking for timedout clients.
|
||||
2. `beforeSleep()` is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.
|
||||
|
||||
Inside server.c you can find code that handles other vital things of the Redis server:
|
||||
|
||||
* `call()` is used in order to call a given command in the context of a given client.
|
||||
* `activeExpireCycle()` handles eviciton of keys with a time to live set via the `EXPIRE` command.
|
||||
* `freeMemoryIfNeeded()` is called when a new write command should be performed but Redis is out of memory according to the `maxmemory` directive.
|
||||
* The global variable `redisCommandTable` defines all the Redis commands, specifying the name of the command, the function implementing the command, the number of arguments required, and other properties of each command.
|
||||
|
||||
networking.c
|
||||
---
|
||||
|
||||
This file defines all the I/O functions with clients, masters and replicas
|
||||
(which in Redis are just special clients):
|
||||
|
||||
* `createClient()` allocates and initializes a new client.
|
||||
* the `addReply*()` family of functions are used by commands implementations in order to append data to the client structure, that will be transmitted to the client as a reply for a given command executed.
|
||||
* `writeToClient()` transmits the data pending in the output buffers to the client and is called by the *writable event handler* `sendReplyToClient()`.
|
||||
* `readQueryFromClient()` is the *readable event handler* and accumulates data from read from the client into the query buffer.
|
||||
* `processInputBuffer()` is the entry point in order to parse the client query buffer according to the Redis protocol. Once commands are ready to be processed, it calls `processCommand()` which is defined inside `server.c` in order to actually execute the command.
|
||||
* `freeClient()` deallocates, disconnects and removes a client.
|
||||
|
||||
aof.c and rdb.c
|
||||
---
|
||||
|
||||
As you can guess from the names these files implement the RDB and AOF
|
||||
persistence for Redis. Redis uses a persistence model based on the `fork()`
|
||||
system call in order to create a thread with the same (shared) memory
|
||||
content of the main Redis thread. This secondary thread dumps the content
|
||||
of the memory on disk. This is used by `rdb.c` to create the snapshots
|
||||
on disk and by `aof.c` in order to perform the AOF rewrite when the
|
||||
append only file gets too big.
|
||||
|
||||
The implementation inside `aof.c` has additional functions in order to
|
||||
implement an API that allows commands to append new commands into the AOF
|
||||
file as clients execute them.
|
||||
|
||||
The `call()` function defined inside `server.c` is responsible to call
|
||||
the functions that in turn will write the commands into the AOF.
|
||||
|
||||
db.c
|
||||
---
|
||||
|
||||
Certain Redis commands operate on specific data types, others are general.
|
||||
Examples of generic commands are `DEL` and `EXPIRE`. They operate on keys
|
||||
and not on their values specifically. All those generic commands are
|
||||
defined inside `db.c`.
|
||||
|
||||
Moreover `db.c` implements an API in order to perform certain operations
|
||||
on the Redis dataset without directly accessing the internal data structures.
|
||||
|
||||
The most important functions inside `db.c` which are used in many commands
|
||||
implementations are the following:
|
||||
|
||||
* `lookupKeyRead()` and `lookupKeyWrite()` are used in order to get a pointer to the value associated to a given key, or `NULL` if the key does not exist.
|
||||
* `dbAdd()` and its higher level counterpart `setKey()` create a new key in a Redis database.
|
||||
* `dbDelete()` removes a key and its associated value.
|
||||
* `emptyDb()` removes an entire single database or all the databases defined.
|
||||
|
||||
The rest of the file implements the generic commands exposed to the client.
|
||||
|
||||
object.c
|
||||
---
|
||||
|
||||
The `robj` structure defining Redis objects was already described. Inside
|
||||
`object.c` there are all the functions that operate with Redis objects at
|
||||
a basic level, like functions to allocate new objects, handle the reference
|
||||
counting and so forth. Notable functions inside this file:
|
||||
|
||||
* `incrRefcount()` and `decrRefCount()` are used in order to increment or decrement an object reference count. When it drops to 0 the object is finally freed.
|
||||
* `createObject()` allocates a new object. There are also specialized functions to allocate string objects having a specific content, like `createStringObjectFromLongLong()` and similar functions.
|
||||
|
||||
This file also implements the `OBJECT` command.
|
||||
|
||||
replication.c
|
||||
---
|
||||
|
||||
This is one of the most complex files inside Redis, it is recommended to
|
||||
approach it only after getting a bit familiar with the rest of the code base.
|
||||
In this file there is the implementation of both the master and replica role
|
||||
of Redis.
|
||||
|
||||
One of the most important functions inside this file is `replicationFeedSlaves()` that writes commands to the clients representing replica instances connected
|
||||
to our master, so that the replicas can get the writes performed by the clients:
|
||||
this way their data set will remain synchronized with the one in the master.
|
||||
|
||||
This file also implements both the `SYNC` and `PSYNC` commands that are
|
||||
used in order to perform the first synchronization between masters and
|
||||
replicas, or to continue the replication after a disconnection.
|
||||
|
||||
Other C files
|
||||
---
|
||||
|
||||
* `t_hash.c`, `t_list.c`, `t_set.c`, `t_string.c` and `t_zset.c` contains the implementation of the Redis data types. They implement both an API to access a given data type, and the client commands implementations for these data types.
|
||||
* `ae.c` implements the Redis event loop, it's a self contained library which is simple to read and understand.
|
||||
* `sds.c` is the Redis string library, check http://github.com/antirez/sds for more information.
|
||||
* `anet.c` is a library to use POSIX networking in a simpler way compared to the raw interface exposed by the kernel.
|
||||
* `dict.c` is an implementation of a non-blocking hash table which rehashes incrementally.
|
||||
* `scripting.c` implements Lua scripting. It is completely self contained from the rest of the Redis implementation and is simple enough to understand if you are familar with the Lua API.
|
||||
* `cluster.c` implements the Redis Cluster. Probably a good read only after being very familiar with the rest of the Redis code base. If you want to read `cluster.c` make sure to read the [Redis Cluster specification][3].
|
||||
|
||||
[3]: http://redis.io/topics/cluster-spec
|
||||
|
||||
Anatomy of a Redis command
|
||||
---
|
||||
|
||||
All the Redis commands are defined in the following way:
|
||||
|
||||
void foobarCommand(client *c) {
|
||||
printf("%s",ptrFromObj(c->argv[1])); /* Do something with the argument. */
|
||||
addReply(c,shared.ok); /* Reply something to the client. */
|
||||
}
|
||||
|
||||
The command is then referenced inside `server.c` in the command table:
|
||||
|
||||
{"foobar",foobarCommand,2,"rtF",0,NULL,0,0,0,0,0},
|
||||
|
||||
In the above example `2` is the number of arguments the command takes,
|
||||
while `"rtF"` are the command flags, as documented in the command table
|
||||
top comment inside `server.c`.
|
||||
|
||||
After the command operates in some way, it returns a reply to the client,
|
||||
usually using `addReply()` or a similar function defined inside `networking.c`.
|
||||
|
||||
There are tons of commands implementations inside the Redis source code
|
||||
that can serve as examples of actual commands implementations. To write
|
||||
a few toy commands can be a good exercise to familiarize with the code base.
|
||||
|
||||
There are also many other files not described here, but it is useless to
|
||||
cover everything. We want to just help you with the first steps.
|
||||
Eventually you'll find your way inside the Redis code base :-)
|
||||
|
||||
Enjoy!
|
||||
Vendored
-9
@@ -23,15 +23,6 @@ INSTALL_INCLUDE_PATH= $(DESTDIR)$(PREFIX)/$(INCLUDE_PATH)
|
||||
INSTALL_LIBRARY_PATH= $(DESTDIR)$(PREFIX)/$(LIBRARY_PATH)
|
||||
INSTALL_PKGCONF_PATH= $(INSTALL_LIBRARY_PATH)/$(PKGCONF_PATH)
|
||||
|
||||
# Installation related variables and target
|
||||
PREFIX?=/usr/local
|
||||
INCLUDE_PATH?=include/hiredis
|
||||
LIBRARY_PATH?=lib
|
||||
PKGCONF_PATH?=pkgconfig
|
||||
INSTALL_INCLUDE_PATH= $(DESTDIR)$(PREFIX)/$(INCLUDE_PATH)
|
||||
INSTALL_LIBRARY_PATH= $(DESTDIR)$(PREFIX)/$(LIBRARY_PATH)
|
||||
INSTALL_PKGCONF_PATH= $(INSTALL_LIBRARY_PATH)/$(PKGCONF_PATH)
|
||||
|
||||
# keydb-server configuration used for testing
|
||||
REDIS_PORT=56379
|
||||
REDIS_SERVER=keydb-server
|
||||
|
||||
@@ -1494,7 +1494,16 @@ rdb-save-incremental-fsync yes
|
||||
# the main dictionary scan
|
||||
# active-defrag-max-scan-fields 1000
|
||||
|
||||
# Path to directory for file backed scratchpad. The file backed scratchpad
|
||||
# reduces memory requirements by storing rarely accessed data on disk
|
||||
# instead of RAM. A temporary file will be created in this directory.
|
||||
# scratch-file-path /tmp/
|
||||
|
||||
# Number of worker threads serving requests. This number should be related to the performance
|
||||
# of your network hardware, not the number of cores on your machine. We don't recommend going
|
||||
# above 4 at this time. By default this is set 1.
|
||||
server-threads 2
|
||||
|
||||
# Should KeyDB pin threads to CPUs? By default this is disabled, and KeyDB will not bind threads.
|
||||
# When enabled threads are bount to cores sequentially starting at core 0.
|
||||
# server-thread-affinity true
|
||||
+20
-4
@@ -27,7 +27,7 @@ ifneq (,$(findstring FreeBSD,$(uname_S)))
|
||||
STD+=-Wno-c11-extensions
|
||||
endif
|
||||
endif
|
||||
WARN=-Wall -W -Wno-missing-field-initializers
|
||||
WARN=-Wall -Werror -W -Wno-missing-field-initializers
|
||||
OPT=$(OPTIMIZATION)
|
||||
|
||||
PREFIX?=/usr/local
|
||||
@@ -44,6 +44,18 @@ endif
|
||||
endif
|
||||
endif
|
||||
|
||||
USEASM?=true
|
||||
# Do we use our assembly spinlock?
|
||||
ifeq ($(uname_S),Linux)
|
||||
ifneq ($(@@),32bit)
|
||||
ifeq ($(USEASM),true)
|
||||
ASM_OBJ+= fastlock_x64.o
|
||||
CFLAGS+= -DASM_SPINLOCK
|
||||
CXXFLAGS+= -DASM_SPINLOCK
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
# To get ARM stack traces if Redis crashes we need a special C flag.
|
||||
ifneq (,$(filter aarch64 armv,$(uname_M)))
|
||||
CFLAGS+=-funwind-tables
|
||||
@@ -160,6 +172,7 @@ endif
|
||||
|
||||
REDIS_CC=$(QUIET_CC)$(CC) $(FINAL_CFLAGS)
|
||||
REDIS_CXX=$(QUIET_CC)$(CC) $(FINAL_CXXFLAGS)
|
||||
REDIS_NASM=$(QUIET_CC)nasm -felf64
|
||||
REDIS_LD=$(QUIET_LINK)$(CXX) $(FINAL_LDFLAGS)
|
||||
REDIS_INSTALL=$(QUIET_INSTALL)$(INSTALL)
|
||||
|
||||
@@ -178,11 +191,11 @@ endif
|
||||
|
||||
REDIS_SERVER_NAME=keydb-server
|
||||
REDIS_SENTINEL_NAME=keydb-sentinel
|
||||
REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o t_stream.o listpack.o localtime.o lolwut.o lolwut5.o acl.o storage.o rdb-s3.o fastlock.o
|
||||
REDIS_SERVER_OBJ=adlist.o quicklist.o ae.o anet.o dict.o server.o sds.o zmalloc.o lzf_c.o lzf_d.o pqsort.o zipmap.o sha1.o ziplist.o release.o networking.o util.o object.o db.o replication.o rdb.o t_string.o t_list.o t_set.o t_zset.o t_hash.o config.o aof.o pubsub.o multi.o debug.o sort.o intset.o syncio.o cluster.o crc16.o endianconv.o slowlog.o scripting.o bio.o rio.o rand.o memtest.o crc64.o bitops.o sentinel.o notify.o setproctitle.o blocked.o hyperloglog.o latency.o sparkline.o redis-check-rdb.o redis-check-aof.o geo.o lazyfree.o module.o evict.o expire.o geohash.o geohash_helper.o childinfo.o defrag.o siphash.o rax.o t_stream.o listpack.o localtime.o lolwut.o lolwut5.o acl.o storage.o rdb-s3.o fastlock.o $(ASM_OBJ)
|
||||
REDIS_CLI_NAME=keydb-cli
|
||||
REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o siphash.o crc16.o storage-lite.o fastlock.o
|
||||
REDIS_CLI_OBJ=anet.o adlist.o dict.o redis-cli.o zmalloc.o release.o anet.o ae.o crc64.o siphash.o crc16.o storage-lite.o fastlock.o $(ASM_OBJ)
|
||||
REDIS_BENCHMARK_NAME=keydb-benchmark
|
||||
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o zmalloc.o redis-benchmark.o storage-lite.o fastlock.o
|
||||
REDIS_BENCHMARK_OBJ=ae.o anet.o redis-benchmark.o adlist.o zmalloc.o redis-benchmark.o storage-lite.o fastlock.o $(ASM_OBJ)
|
||||
REDIS_CHECK_RDB_NAME=keydb-check-rdb
|
||||
REDIS_CHECK_AOF_NAME=keydb-check-aof
|
||||
|
||||
@@ -264,6 +277,9 @@ dict-benchmark: dict.c zmalloc.c sds.c siphash.c
|
||||
%.o: %.cpp .make-prerequisites
|
||||
$(REDIS_CXX) -c $<
|
||||
|
||||
%.o: %.asm .make-prerequisites
|
||||
$(REDIS_NASM) $<
|
||||
|
||||
clean:
|
||||
rm -rf $(REDIS_SERVER_NAME) $(REDIS_SENTINEL_NAME) $(REDIS_CLI_NAME) $(REDIS_BENCHMARK_NAME) $(REDIS_CHECK_RDB_NAME) $(REDIS_CHECK_AOF_NAME) *.o *.gcda *.gcno *.gcov redis.info lcov-html Makefile.dep dict-benchmark
|
||||
|
||||
|
||||
@@ -427,7 +427,6 @@ extern "C" void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
|
||||
}
|
||||
|
||||
extern "C" int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
|
||||
//AE_ASSERT(g_eventLoopThisThread == NULL || g_eventLoopThisThread == eventLoop);
|
||||
if (fd >= eventLoop->setsize) return 0;
|
||||
aeFileEvent *fe = &eventLoop->events[fd];
|
||||
|
||||
|
||||
@@ -836,6 +836,15 @@ void loadServerConfigFromString(char *config) {
|
||||
err = "Invalid number of threads specified";
|
||||
goto loaderr;
|
||||
}
|
||||
} else if (!strcasecmp(argv[0],"server-thread-affinity") && argc == 2) {
|
||||
if (strcasecmp(argv[1], "true") == 0) {
|
||||
server.fThreadAffinity = TRUE;
|
||||
} else if (strcasecmp(argv[1], "false") == 0) {
|
||||
server.fThreadAffinity = FALSE;
|
||||
} else {
|
||||
err = "Unknown argument: server-thread-affinity expects either true or false";
|
||||
goto loaderr;
|
||||
}
|
||||
} else {
|
||||
err = "Bad directive or wrong number of arguments"; goto loaderr;
|
||||
}
|
||||
|
||||
+6
-1
@@ -44,7 +44,7 @@
|
||||
|
||||
static_assert(sizeof(pid_t) <= sizeof(fastlock::m_pidOwner), "fastlock::m_pidOwner not large enough");
|
||||
|
||||
static pid_t gettid()
|
||||
extern "C" pid_t gettid()
|
||||
{
|
||||
static thread_local int pidCache = -1;
|
||||
if (pidCache == -1)
|
||||
@@ -60,6 +60,7 @@ extern "C" void fastlock_init(struct fastlock *lock)
|
||||
lock->m_pidOwner = -1;
|
||||
}
|
||||
|
||||
#ifndef ASM_SPINLOCK
|
||||
extern "C" void fastlock_lock(struct fastlock *lock)
|
||||
{
|
||||
if ((int)__atomic_load_4(&lock->m_pidOwner, __ATOMIC_ACQUIRE) == gettid())
|
||||
@@ -75,6 +76,9 @@ extern "C" void fastlock_lock(struct fastlock *lock)
|
||||
{
|
||||
if ((++cloops % 1024*1024) == 0)
|
||||
sched_yield();
|
||||
#if defined(__i386__) || defined(__amd64__)
|
||||
__asm__ ("pause");
|
||||
#endif
|
||||
}
|
||||
|
||||
lock->m_depth = 1;
|
||||
@@ -107,6 +111,7 @@ extern "C" int fastlock_trylock(struct fastlock *lock)
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
extern "C" void fastlock_unlock(struct fastlock *lock)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
section .text
|
||||
|
||||
extern gettid
|
||||
extern sched_yield
|
||||
|
||||
; This is the first use of assembly in this codebase, a valid question is WHY?
|
||||
; The spinlock we implement here is performance critical, and simply put GCC
|
||||
; emits awful code. The original C code is left in fastlock.cpp for reference
|
||||
; and x-plat. The code generated for the unlock case is reasonable and left in
|
||||
; C++.
|
||||
|
||||
ALIGN 16
|
||||
global fastlock_lock
|
||||
fastlock_lock:
|
||||
; RDI points to the struct:
|
||||
; uint16_t active
|
||||
; uint16_t avail
|
||||
; int32_t m_pidOwner
|
||||
; int32_t m_depth
|
||||
|
||||
; First get our TID and put it in ecx
|
||||
push rdi ; we need our struct pointer (also balance the stack for the call)
|
||||
call gettid ; get our thread ID (TLS is nasty in ASM so don't bother inlining)
|
||||
mov esi, eax ; back it up in esi
|
||||
mov rdi, [rsp] ; get our pointer back
|
||||
|
||||
cmp [rdi+4], esi ; Is the TID we got back the owner of the lock?
|
||||
je .LLocked ; Don't spin in that case
|
||||
|
||||
xor eax, eax ; eliminate partial register dependency
|
||||
inc eax ; we want to add one
|
||||
lock xadd [rdi+2], ax ; do the xadd, ax contains the value before the addition
|
||||
; eax now contains the ticket
|
||||
xor ecx, ecx
|
||||
ALIGN 16
|
||||
.LLoop:
|
||||
cmp [rdi], ax ; is our ticket up?
|
||||
je .LLocked ; leave the loop
|
||||
pause
|
||||
add ecx, 1000h ; Have we been waiting a long time? (oflow if we have)
|
||||
; 1000h is set so we overflow on the 1024*1024'th iteration (like the C code)
|
||||
jnc .LLoop ; If so, give up our timeslice to someone who's doing real work
|
||||
; Like the compiler, you're probably thinking: "Hey! I should take these pushs out of the loop"
|
||||
; But the compiler doesn't know that we rarely hit this, and when we do we know the lock is
|
||||
; taking a long time to be released anyways. We optimize for the common case of short
|
||||
; lock intervals. That's why we're using a spinlock in the first place
|
||||
push rsi
|
||||
push rax
|
||||
mov rax, 24 ; sys_sched_yield
|
||||
syscall ; give up our timeslice we'll be here a while
|
||||
pop rax
|
||||
pop rsi
|
||||
mov rdi, [rsp] ; our struct pointer is on the stack already
|
||||
xor ecx, ecx ; Reset our loop counter
|
||||
jmp .LLoop ; Get back in the game
|
||||
ALIGN 16
|
||||
.LLocked:
|
||||
mov [rdi+4], esi ; lock->m_pidOwner = gettid()
|
||||
inc dword [rdi+8] ; lock->m_depth++
|
||||
add rsp, 8 ; fix stack
|
||||
ret
|
||||
|
||||
ALIGN 16
|
||||
global fastlock_trylock
|
||||
fastlock_trylock:
|
||||
; RDI points to the struct:
|
||||
; uint16_t active
|
||||
; uint16_t avail
|
||||
; int32_t m_pidOwner
|
||||
; int32_t m_depth
|
||||
|
||||
; First get our TID and put it in ecx
|
||||
push rdi ; we need our struct pointer (also balance the stack for the call)
|
||||
call gettid ; get our thread ID (TLS is nasty in ASM so don't bother inlining)
|
||||
mov esi, eax ; back it up in esi
|
||||
pop rdi ; get our pointer back
|
||||
|
||||
cmp [rdi+4], esi ; Is the TID we got back the owner of the lock?
|
||||
je .LRecursive ; Don't spin in that case
|
||||
|
||||
mov eax, [rdi] ; get both active and avail counters
|
||||
mov ecx, eax ; duplicate in ecx
|
||||
ror ecx, 16 ; swap upper and lower 16-bits
|
||||
cmp eax, ecx ; are the upper and lower 16-bits the same?
|
||||
jnz .LAlreadyLocked ; If not return failure
|
||||
|
||||
; at this point we know eax+ecx have [avail][active] and they are both the same
|
||||
add ecx, 10000h ; increment avail, ecx is now our wanted value
|
||||
lock cmpxchg [rdi], ecx ; If rdi still contains the value in eax, put in ecx (inc avail)
|
||||
jnz .LAlreadyLocked ; If Z is not set then someone locked it while we were preparing
|
||||
xor eax, eax
|
||||
inc eax ; return SUCCESS! (eax=1)
|
||||
mov [rdi+4], esi ; lock->m_pidOwner = gettid()
|
||||
mov dword [rdi+8], eax ; lock->m_depth = 1
|
||||
ret
|
||||
ALIGN 16
|
||||
.LRecursive:
|
||||
xor eax, eax
|
||||
inc eax ; return SUCCESS! (eax=1)
|
||||
inc dword [rdi+8] ; lock->m_depth++
|
||||
ret
|
||||
ALIGN 16
|
||||
.LAlreadyLocked:
|
||||
xor eax, eax ; return 0;
|
||||
ret
|
||||
@@ -32,6 +32,12 @@
|
||||
#define __INTSET_H
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define ZERO_LENGTH_ARRAY_LENGTH 1
|
||||
#else
|
||||
#define ZERO_LENGTH_ARRAY_LENGTH
|
||||
#endif
|
||||
|
||||
typedef struct intset {
|
||||
uint32_t encoding;
|
||||
uint32_t length;
|
||||
|
||||
@@ -3702,7 +3702,10 @@ void moduleHandleBlockedClients(void) {
|
||||
{
|
||||
c->flags |= CLIENT_PENDING_WRITE;
|
||||
AssertCorrectThread(c);
|
||||
|
||||
fastlock_lock(&server.rgthreadvar[c->iel].lockPendingWrite);
|
||||
listAddNodeHead(server.rgthreadvar[c->iel].clients_pending_write,c);
|
||||
fastlock_unlock(&server.rgthreadvar[c->iel].lockPendingWrite);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+346
-22
@@ -35,6 +35,26 @@
|
||||
#include <ctype.h>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <sys/syscall.h>
|
||||
#include <linux/aio_abi.h>
|
||||
|
||||
inline int io_setup(unsigned nr, aio_context_t *ctxp) {
|
||||
return syscall(__NR_io_setup, nr, ctxp);
|
||||
}
|
||||
|
||||
inline int io_destroy(aio_context_t ctx) {
|
||||
return syscall(__NR_io_destroy, ctx);
|
||||
}
|
||||
|
||||
inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp) {
|
||||
return syscall(__NR_io_submit, ctx, nr, iocbpp);
|
||||
}
|
||||
|
||||
inline int io_getevents(aio_context_t ctx, long min_nr, long max_nr,
|
||||
struct io_event *events, struct timespec *timeout) {
|
||||
return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout);
|
||||
}
|
||||
|
||||
|
||||
static void setProtocolError(const char *errstr, client *c);
|
||||
void addReplyLongLongWithPrefixCore(client *c, long long ll, char prefix, bool fAsync);
|
||||
@@ -258,6 +278,7 @@ void clientInstallWriteHandler(client *c) {
|
||||
* a system call. We'll only really install the write handler if
|
||||
* we'll not be able to write the whole reply at once. */
|
||||
c->flags |= CLIENT_PENDING_WRITE;
|
||||
std::unique_lock<fastlock> lockf(server.rgthreadvar[c->iel].lockPendingWrite);
|
||||
listAddNodeHead(server.rgthreadvar[c->iel].clients_pending_write,c);
|
||||
}
|
||||
}
|
||||
@@ -1033,6 +1054,17 @@ static void acceptCommonHandler(int fd, int flags, char *ip, int iel) {
|
||||
close(fd); /* May be already closed, just ignore errors */
|
||||
return;
|
||||
}
|
||||
|
||||
// Set thread affinity
|
||||
if (server.fThreadAffinity)
|
||||
{
|
||||
int cpu = iel;
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_INCOMING_CPU, &cpu, sizeof(iel)) != 0)
|
||||
{
|
||||
serverLog(LL_WARNING, "Failed to set socket affinity");
|
||||
}
|
||||
}
|
||||
|
||||
/* If maxclient directive is set and this is one client more... close the
|
||||
* connection. Note that we create the client instead to check before
|
||||
* for this condition, since now the socket is already set in non-blocking
|
||||
@@ -1203,6 +1235,7 @@ void unlinkClient(client *c) {
|
||||
|
||||
/* Remove from the list of pending writes if needed. */
|
||||
if (c->flags & CLIENT_PENDING_WRITE) {
|
||||
std::unique_lock<fastlock> lockf(server.rgthreadvar[c->iel].lockPendingWrite);
|
||||
ln = listSearchKey(server.rgthreadvar[c->iel].clients_pending_write,c);
|
||||
serverAssert(ln != NULL);
|
||||
listDelNode(server.rgthreadvar[c->iel].clients_pending_write,ln);
|
||||
@@ -1380,6 +1413,28 @@ client *lookupClientByID(uint64_t id) {
|
||||
return (c == raxNotFound) ? NULL : c;
|
||||
}
|
||||
|
||||
bool FSentTooMuch(client *c, ssize_t totwritten)
|
||||
{
|
||||
/* Note that we avoid to send more than NET_MAX_WRITES_PER_EVENT
|
||||
* bytes, in a single threaded server it's a good idea to serve
|
||||
* other clients as well, even if a very large request comes from
|
||||
* super fast link that is always able to accept data (in real world
|
||||
* scenario think about 'KEYS *' against the loopback interface).
|
||||
*
|
||||
* However if we are over the maxmemory limit we ignore that and
|
||||
* just deliver as much data as it is possible to deliver.
|
||||
*
|
||||
* Moreover, we also send as much as possible if the client is
|
||||
* a slave (otherwise, on high-speed traffic, the replication
|
||||
* buffer will grow indefinitely) */
|
||||
if (totwritten > NET_MAX_WRITES_PER_EVENT &&
|
||||
(server.maxmemory == 0 ||
|
||||
zmalloc_used_memory() < server.maxmemory) &&
|
||||
!(c->flags & CLIENT_SLAVE)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Write data in output buffers to client. Return C_OK if the client
|
||||
* is still valid after the call, C_ERR if it was freed. */
|
||||
int writeToClient(int fd, client *c, int handler_installed) {
|
||||
@@ -1429,22 +1484,8 @@ int writeToClient(int fd, client *c, int handler_installed) {
|
||||
serverAssert(c->reply_bytes == 0);
|
||||
}
|
||||
}
|
||||
/* Note that we avoid to send more than NET_MAX_WRITES_PER_EVENT
|
||||
* bytes, in a single threaded server it's a good idea to serve
|
||||
* other clients as well, even if a very large request comes from
|
||||
* super fast link that is always able to accept data (in real world
|
||||
* scenario think about 'KEYS *' against the loopback interface).
|
||||
*
|
||||
* However if we are over the maxmemory limit we ignore that and
|
||||
* just deliver as much data as it is possible to deliver.
|
||||
*
|
||||
* Moreover, we also send as much as possible if the client is
|
||||
* a slave (otherwise, on high-speed traffic, the replication
|
||||
* buffer will grow indefinitely) */
|
||||
if (totwritten > NET_MAX_WRITES_PER_EVENT &&
|
||||
(server.maxmemory == 0 ||
|
||||
zmalloc_used_memory() < server.maxmemory) &&
|
||||
!(c->flags & CLIENT_SLAVE)) break;
|
||||
if (FSentTooMuch(c, totwritten))
|
||||
break;
|
||||
}
|
||||
|
||||
__atomic_fetch_add(&server.stat_net_output_bytes, totwritten, __ATOMIC_RELAXED);
|
||||
@@ -1462,7 +1503,6 @@ int writeToClient(int fd, client *c, int handler_installed) {
|
||||
}
|
||||
else
|
||||
{
|
||||
lock.unlock();
|
||||
freeClientAsync(c);
|
||||
}
|
||||
|
||||
@@ -1499,6 +1539,278 @@ int writeToClient(int fd, client *c, int handler_installed) {
|
||||
return C_OK;
|
||||
}
|
||||
|
||||
int aioQueueWrites(client *c, std::vector<iocb> &veciocb)
|
||||
{
|
||||
size_t sentlen = 0;
|
||||
ssize_t cbSent = 0;
|
||||
int cevt = 0;
|
||||
|
||||
AssertCorrectThread(c);
|
||||
std::unique_lock<decltype(c->lock)> lock(c->lock);
|
||||
|
||||
int fd = c->fd;
|
||||
|
||||
if (c->bufpos > 0)
|
||||
{
|
||||
struct iocb cb = {0};
|
||||
cb.aio_fildes = fd;
|
||||
cb.aio_lio_opcode = IOCB_CMD_PWRITE;
|
||||
cb.aio_buf = (uint64_t)(c->buf+sentlen);
|
||||
cb.aio_nbytes = c->bufpos-sentlen;
|
||||
veciocb.push_back(cb);
|
||||
|
||||
cbSent += cb.aio_nbytes;
|
||||
sentlen = 0;
|
||||
++cevt;
|
||||
|
||||
if (FSentTooMuch(c, cbSent))
|
||||
return cevt;
|
||||
}
|
||||
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
listRewind(c->reply, &li);
|
||||
// Ensure we only write one reply block, because if a write fails aio will happily write the next
|
||||
// reply block and it will appear out of order to the client
|
||||
while ((cevt == 0) && (ln = listNext(&li)))
|
||||
{
|
||||
clientReplyBlock* o = (clientReplyBlock*)listNodeValue(listFirst(c->reply));
|
||||
if (o->used == 0)
|
||||
{
|
||||
c->reply_bytes -= o->size;
|
||||
listDelNode(c->reply,ln);
|
||||
continue;
|
||||
}
|
||||
|
||||
struct iocb cb = {0};
|
||||
cb.aio_fildes = fd;
|
||||
cb.aio_lio_opcode = IOCB_CMD_PWRITE;
|
||||
cb.aio_buf = (uint64_t)(o->buf()+sentlen);
|
||||
cb.aio_nbytes = o->size-sentlen;
|
||||
veciocb.push_back(cb);
|
||||
|
||||
cbSent += cb.aio_nbytes;
|
||||
sentlen = 0;
|
||||
++cevt;
|
||||
|
||||
if (FSentTooMuch(c, cbSent))
|
||||
break;
|
||||
}
|
||||
|
||||
return cevt;
|
||||
}
|
||||
|
||||
int aioProcessQueuedWrites(client *c, io_event *rgevt, const int cevtIn, bool handler_installed)
|
||||
{
|
||||
int cevt = 0;
|
||||
bool fError = false;
|
||||
ssize_t totwritten = 0;
|
||||
int errnoT = 0;
|
||||
serverAssert(cevtIn > 0);
|
||||
|
||||
std::unique_lock<decltype(c->lock)> lock(c->lock);
|
||||
|
||||
if (c->bufpos > 0)
|
||||
{
|
||||
if (rgevt->res <= 0)
|
||||
{
|
||||
fError = true;
|
||||
errnoT = rgevt->res2;
|
||||
}
|
||||
else
|
||||
{
|
||||
c->sentlen += rgevt->res;
|
||||
totwritten += rgevt->res;
|
||||
|
||||
/* If the buffer was sent, set bufpos to zero to continue with
|
||||
* the remainder of the reply. */
|
||||
if ((int)c->sentlen == c->bufpos) {
|
||||
c->bufpos = 0;
|
||||
c->sentlen = 0;
|
||||
}
|
||||
}
|
||||
++rgevt;
|
||||
++cevt;
|
||||
}
|
||||
|
||||
while (listLength(c->reply) && cevt < cevtIn)
|
||||
{
|
||||
clientReplyBlock *o = (clientReplyBlock*)listNodeValue(listFirst(c->reply));
|
||||
if (rgevt->res <= 0)
|
||||
{
|
||||
fError = true;
|
||||
errnoT = rgevt->res2;
|
||||
}
|
||||
else
|
||||
{
|
||||
serverAssert(!fError); // this means we sent data out of order
|
||||
c->sentlen += rgevt->res;
|
||||
totwritten += rgevt->res;
|
||||
|
||||
/* If we fully sent the object on head go to the next one */
|
||||
if (c->sentlen == o->used) {
|
||||
c->reply_bytes -= o->size;
|
||||
listDelNode(c->reply,listFirst(c->reply));
|
||||
c->sentlen = 0;
|
||||
/* If there are no longer objects in the list, we expect
|
||||
* the count of reply bytes to be exactly zero. */
|
||||
if (listLength(c->reply) == 0)
|
||||
serverAssert(c->reply_bytes == 0);
|
||||
}
|
||||
}
|
||||
++rgevt;
|
||||
++cevt;
|
||||
}
|
||||
|
||||
__atomic_fetch_add(&server.stat_net_output_bytes, totwritten, __ATOMIC_RELAXED);
|
||||
if (fError && errnoT != EAGAIN) {
|
||||
serverLog(LL_VERBOSE,
|
||||
"Error writing to client: %s", strerror(errno));
|
||||
lock.unlock();
|
||||
if (aeTryAcquireLock())
|
||||
{
|
||||
freeClient(c);
|
||||
aeReleaseLock();
|
||||
}
|
||||
else
|
||||
{
|
||||
freeClientAsync(c);
|
||||
}
|
||||
|
||||
return C_ERR;
|
||||
}
|
||||
|
||||
if (totwritten > 0) {
|
||||
/* For clients representing masters we don't count sending data
|
||||
* as an interaction, since we always send REPLCONF ACK commands
|
||||
* that take some time to just fill the socket output buffer.
|
||||
* We just rely on data / pings received for timeout detection. */
|
||||
if (!(c->flags & CLIENT_MASTER)) c->lastinteraction = server.unixtime;
|
||||
}
|
||||
if (!clientHasPendingReplies(c)) {
|
||||
c->sentlen = 0;
|
||||
if (handler_installed) aeDeleteFileEvent(server.rgthreadvar[c->iel].el,c->fd,AE_WRITABLE);
|
||||
|
||||
/* Close connection after entire reply has been sent. */
|
||||
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) {
|
||||
lock.unlock();
|
||||
if (aeTryAcquireLock())
|
||||
{
|
||||
freeClient(c);
|
||||
aeReleaseLock();
|
||||
}
|
||||
else
|
||||
{
|
||||
lock.unlock();
|
||||
freeClientAsync(c);
|
||||
}
|
||||
return C_ERR;
|
||||
}
|
||||
}
|
||||
return C_OK;
|
||||
}
|
||||
|
||||
int aioProcessWrites(int iel)
|
||||
{
|
||||
thread_local aio_context_t ctxt = {0};
|
||||
if (ctxt == 0 && io_setup(512, &ctxt) != 0)
|
||||
{
|
||||
return C_ERR;
|
||||
}
|
||||
|
||||
std::vector<iocb> veciocb;
|
||||
std::vector<int> veccevt;
|
||||
std::vector<io_event> vecevt;
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
|
||||
std::unique_lock<fastlock> lockf(server.rgthreadvar[iel].lockPendingWrite);
|
||||
list *list = server.rgthreadvar[iel].clients_pending_write;
|
||||
serverAssert(iel == (serverTL - server.rgthreadvar));
|
||||
|
||||
/* Gather up a list of events to send to iosubmit */
|
||||
listRewind(list,&li);
|
||||
while((ln = listNext(&li)))
|
||||
{
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
int cevtT = aioQueueWrites(c, veciocb);
|
||||
veccevt.push_back(cevtT);
|
||||
}
|
||||
|
||||
/* Make an array of pointers because that's what io_submit wants */
|
||||
iocb **rgpiocb = (iocb**)alloca(sizeof(iocb*)*veciocb.size());
|
||||
for (size_t iocb = 0; iocb < veciocb.size(); ++iocb)
|
||||
{
|
||||
rgpiocb[iocb] = veciocb.data() + iocb;
|
||||
}
|
||||
|
||||
/* Do the submit and wait, may have to do this many times */
|
||||
int ciocbTx = 0;
|
||||
vecevt.resize(veciocb.size());
|
||||
while (ciocbTx < (int)veciocb.size())
|
||||
{
|
||||
int cevtWait = veciocb.size() - ciocbTx;
|
||||
int ciocbTxT = io_submit(ctxt, cevtWait, rgpiocb + ciocbTx);
|
||||
if (ciocbTxT <= 0)
|
||||
break;
|
||||
|
||||
int cevt = 0;
|
||||
while (cevt < ciocbTxT)
|
||||
{
|
||||
int offset = ciocbTx + cevt;
|
||||
int cwant = ciocbTxT - cevt;
|
||||
cevt += io_getevents(ctxt, cwant, cwant, vecevt.data() + offset, nullptr);
|
||||
}
|
||||
ciocbTx += ciocbTxT;
|
||||
}
|
||||
|
||||
|
||||
/* Finally Inform The Clients */
|
||||
listRewind(list,&li);
|
||||
int iclient = 0;
|
||||
int cevtOffset = 0;
|
||||
while((ln = listNext(&li)))
|
||||
{
|
||||
client *c = (client*)listNodeValue(ln);
|
||||
std::unique_lock<decltype(c->lock)> lock(c->lock);
|
||||
|
||||
c->flags &= ~CLIENT_PENDING_WRITE;
|
||||
listDelNode(list,ln);
|
||||
|
||||
if (cevtOffset < ciocbTx)
|
||||
{
|
||||
if (aioProcessQueuedWrites(c, vecevt.data() + cevtOffset, std::min(ciocbTx - cevtOffset, veccevt[iclient]), false) == C_ERR)
|
||||
{
|
||||
lock.release(); // client is free'd
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
/* If after the synchronous writes above we still have data to
|
||||
* output to the client, we need to install the writable handler. */
|
||||
if (clientHasPendingReplies(c)) {
|
||||
int ae_flags = AE_WRITABLE|AE_WRITE_THREADSAFE;
|
||||
/* For the fsync=always policy, we want that a given FD is never
|
||||
* served for reading and writing in the same event loop iteration,
|
||||
* so that in the middle of receiving the query, and serving it
|
||||
* to the client, we'll call beforeSleep() that will do the
|
||||
* actual fsync of AOF to disk. AE_BARRIER ensures that. */
|
||||
if (server.aof_state == AOF_ON &&
|
||||
server.aof_fsync == AOF_FSYNC_ALWAYS)
|
||||
{
|
||||
ae_flags |= AE_BARRIER;
|
||||
}
|
||||
|
||||
if (aeCreateFileEvent(server.rgthreadvar[c->iel].el, c->fd, ae_flags, sendReplyToClient, c) == AE_ERR)
|
||||
freeClientAsync(c);
|
||||
}
|
||||
cevtOffset += veccevt[iclient];
|
||||
++iclient;
|
||||
}
|
||||
|
||||
return iclient;
|
||||
}
|
||||
|
||||
/* Write event handler. Just send data to the client. */
|
||||
void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
|
||||
UNUSED(mask);
|
||||
@@ -1559,14 +1871,13 @@ void ProcessPendingAsyncWrites()
|
||||
}
|
||||
}
|
||||
|
||||
/* This function is called just before entering the event loop, in the hope
|
||||
* we can just write the replies to the client output buffer without any
|
||||
* need to use a syscall in order to install the writable event handler,
|
||||
* get it called, and so forth. */
|
||||
int handleClientsWithPendingWrites(int iel) {
|
||||
/* the slow version does multiple write() calls, vs io_submit for the fast path */
|
||||
int handleClientsWithPendingWritesSlow(int iel)
|
||||
{
|
||||
listIter li;
|
||||
listNode *ln;
|
||||
|
||||
std::unique_lock<fastlock> lockf(server.rgthreadvar[iel].lockPendingWrite);
|
||||
list *list = server.rgthreadvar[iel].clients_pending_write;
|
||||
int processed = listLength(list);
|
||||
serverAssert(iel == (serverTL - server.rgthreadvar));
|
||||
@@ -1609,6 +1920,19 @@ int handleClientsWithPendingWrites(int iel) {
|
||||
freeClientAsync(c);
|
||||
}
|
||||
}
|
||||
return processed;
|
||||
}
|
||||
|
||||
/* This function is called just before entering the event loop, in the hope
|
||||
* we can just write the replies to the client output buffer without any
|
||||
* need to use a syscall in order to install the writable event handler,
|
||||
* get it called, and so forth. */
|
||||
int handleClientsWithPendingWrites(int iel) {
|
||||
int processed;
|
||||
if (listLength(server.rgthreadvar[iel].clients_pending_write) < 10)
|
||||
processed = handleClientsWithPendingWritesSlow(iel);
|
||||
else
|
||||
processed = aioProcessWrites(iel);
|
||||
|
||||
AeLocker locker;
|
||||
locker.arm(nullptr);
|
||||
|
||||
@@ -31,6 +31,12 @@
|
||||
#ifndef __QUICKLIST_H__
|
||||
#define __QUICKLIST_H__
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define ZERO_LENGTH_ARRAY_LENGTH 1
|
||||
#else
|
||||
#define ZERO_LENGTH_ARRAY_LENGTH
|
||||
#endif
|
||||
|
||||
/* Node, quicklist, and Iterator are the only data structures used currently. */
|
||||
|
||||
/* quicklistNode is a 32 byte struct describing a ziplist for a quicklist.
|
||||
|
||||
@@ -31,6 +31,12 @@
|
||||
#ifndef RAX_H
|
||||
#define RAX_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define ZERO_LENGTH_ARRAY_LENGTH 1
|
||||
#else
|
||||
#define ZERO_LENGTH_ARRAY_LENGTH
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
|
||||
+19
-5
@@ -2109,7 +2109,9 @@ void beforeSleep(struct aeEventLoop *eventLoop) {
|
||||
flushAppendOnlyFile(0);
|
||||
|
||||
/* Handle writes with pending output buffers. */
|
||||
aeReleaseLock();
|
||||
handleClientsWithPendingWrites(IDX_EVENT_LOOP_MAIN);
|
||||
aeAcquireLock();
|
||||
|
||||
/* Before we are going to sleep, let the threads access the dataset by
|
||||
* releasing the GIL. Redis main thread will not touch anything at this
|
||||
@@ -2126,10 +2128,10 @@ void beforeSleepLite(struct aeEventLoop *eventLoop)
|
||||
if (listLength(server.rgthreadvar[iel].unblocked_clients)) {
|
||||
processUnblockedClients(iel);
|
||||
}
|
||||
aeReleaseLock();
|
||||
|
||||
/* Handle writes with pending output buffers. */
|
||||
handleClientsWithPendingWrites(iel);
|
||||
aeReleaseLock();
|
||||
}
|
||||
|
||||
/* This function is called immadiately after the event loop multiplexing
|
||||
@@ -2458,6 +2460,7 @@ void initServerConfig(void) {
|
||||
|
||||
/* Multithreading */
|
||||
server.cthreads = CONFIG_DEFAULT_THREADS;
|
||||
server.fThreadAffinity = CONFIG_DEFAULT_THREAD_AFFINITY;
|
||||
}
|
||||
|
||||
extern char **environ;
|
||||
@@ -2813,6 +2816,8 @@ static void initServerThread(struct redisServerThreadVars *pvar, int fMain)
|
||||
exit(1);
|
||||
}
|
||||
|
||||
fastlock_init(&pvar->lockPendingWrite);
|
||||
|
||||
if (!fMain)
|
||||
{
|
||||
if (aeCreateTimeEvent(pvar->el, 1, serverCronLite, NULL, NULL) == AE_ERR) {
|
||||
@@ -4063,7 +4068,6 @@ sds genRedisInfoString(char *section) {
|
||||
bytesToHuman(maxmemory_hmem,server.maxmemory);
|
||||
|
||||
if (sections++) info = sdscat(info,"\r\n");
|
||||
serverLog(LL_WARNING, "OOM max sent used_memory: %zu", zmalloc_used);
|
||||
info = sdscatprintf(info,
|
||||
"# Memory\r\n"
|
||||
"used_memory:%zu\r\n"
|
||||
@@ -4498,7 +4502,6 @@ void infoCommand(client *c) {
|
||||
return;
|
||||
}
|
||||
addReplyBulkSds(c, genRedisInfoString(section));
|
||||
serverLog(LL_WARNING, "OOM max info command %zu", zmalloc_used_memory());
|
||||
}
|
||||
|
||||
void monitorCommand(client *c) {
|
||||
@@ -5082,11 +5085,22 @@ int main(int argc, char **argv) {
|
||||
|
||||
serverAssert(server.cthreads > 0 && server.cthreads <= MAX_EVENT_LOOPS);
|
||||
pthread_t rgthread[MAX_EVENT_LOOPS];
|
||||
for (int iel = 1; iel < server.cthreads; ++iel)
|
||||
for (int iel = 0; iel < server.cthreads; ++iel)
|
||||
{
|
||||
pthread_create(rgthread + iel, NULL, workerThreadMain, (void*)((int64_t)iel));
|
||||
if (server.fThreadAffinity)
|
||||
{
|
||||
cpu_set_t cpuset;
|
||||
CPU_ZERO(&cpuset);
|
||||
CPU_SET(iel, &cpuset);
|
||||
if (pthread_setaffinity_np(rgthread[iel], sizeof(cpu_set_t), &cpuset) == 0)
|
||||
{
|
||||
serverLog(LOG_INFO, "Binding thread %d to cpu %d", iel, iel);
|
||||
}
|
||||
}
|
||||
}
|
||||
workerThreadMain((void*)((int64_t)IDX_EVENT_LOOP_MAIN));
|
||||
void *pvRet;
|
||||
pthread_join(rgthread[IDX_EVENT_LOOP_MAIN], &pvRet);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -183,6 +183,7 @@ extern "C" {
|
||||
#define CONFIG_DEFAULT_PROTO_MAX_BULK_LEN (512ll*1024*1024) /* Bulk request max size */
|
||||
|
||||
#define CONFIG_DEFAULT_THREADS 1
|
||||
#define CONFIG_DEFAULT_THREAD_AFFINITY 0
|
||||
|
||||
#define ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP 20 /* Loopkups per loop. */
|
||||
#define ACTIVE_EXPIRE_CYCLE_FAST_DURATION 1000 /* Microseconds */
|
||||
@@ -1051,6 +1052,7 @@ struct redisServerThreadVars {
|
||||
list *clients_pending_write; /* There is to write or install handler. */
|
||||
list *unblocked_clients; /* list of clients to unblock before next loop NOT THREADSAFE */
|
||||
list *clients_pending_asyncwrite;
|
||||
struct fastlock lockPendingWrite;
|
||||
};
|
||||
|
||||
struct redisServer {
|
||||
@@ -1069,6 +1071,7 @@ struct redisServer {
|
||||
dict *orig_commands; /* Command table before command renaming. */
|
||||
|
||||
int cthreads; /* Number of main worker threads */
|
||||
int fThreadAffinity; /* Should we pin threads to cores? */
|
||||
struct redisServerThreadVars rgthreadvar[MAX_EVENT_LOOPS];
|
||||
|
||||
unsigned int lruclock; /* Clock for LRU eviction */
|
||||
|
||||
+1
-2
@@ -1,6 +1,5 @@
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <memkind.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <linux/fs.h>
|
||||
#include <unistd.h>
|
||||
@@ -46,4 +45,4 @@ void *srealloc(void *pv, size_t cb, enum MALLOC_CLASS class)
|
||||
size_t salloc_usable_size(void *ptr)
|
||||
{
|
||||
return malloc_usable_size(ptr);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -268,4 +268,4 @@ void handle_postfork_child()
|
||||
close(fdOriginal);
|
||||
}
|
||||
|
||||
#endif // USE_MEMKIND
|
||||
#endif // USE_MEMKIND
|
||||
Reference in new issue
Block a user