xref: /redis/
NameDateSize

..16-Mar-201612 KiB

.gitignore10-Feb-2015363

00-RELEASENOTES06-Oct-2014634

BUGS06-Oct-201453

CONTRIBUTING09-Nov-20151.8 KiB

COPYING04-May-20151.5 KiB

deps/12-Oct-20154 KiB

INSTALL29-Dec-201211

Makefile29-Dec-2012151

MANIFESTO20-Feb-20134.1 KiB

README.md09-Nov-201520 KiB

redis.conf10-Dec-201546.3 KiB

runtest20-Feb-2013271

runtest-cluster25-Apr-2014280

runtest-sentinel24-Apr-2014281

sentinel.conf06-Oct-20146.9 KiB

src/14-Dec-20154 KiB

tests/12-Oct-20154 KiB

utils/30-Nov-20154 KiB

README.md

1This README is just a fast *quick start* document. You can find more detailed documentation at http://redis.io.
2
3What is Redis?
4--------------
5
6Redis 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.
7
8Data structures implemented into Redis have a few special properties:
9
10* 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.
11* 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.
12* Redis offers a number of features that are natural to find in a database, like replication, tunable levels of durability, cluster, high availability.
13
14Another 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.
15
16If you want to know more, this is a list of selected starting points:
17
18* Introduction to Redis data types. http://redis.io/topics/data-types-intro
19* Try Redis directly inside your browser. http://try.redis.io
20* The full list of Redis commands. http://redis.io/commands
21* There is much more inside the Redis official documentation. http://redis.io/documentation
22
23Building Redis
24--------------
25
26Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD.
27We support big endian and little endian architectures, and both 32 bit
28and 64 bit systems.
29
30It may compile on Solaris derived systems (for instance SmartOS) but our
31support for this platform is *best effort* and Redis is not guaranteed to
32work as well as in Linux, OSX, and \*BSD there.
33
34It is as simple as:
35
36    % make
37
38You can run a 32 bit Redis binary using:
39
40    % make 32bit
41
42After building Redis is a good idea to test it, using:
43
44    % make test
45
46Fixing build problems with dependencies or cached build options
47---------
48
49Redis has some dependencies which are included into the `deps` directory.
50`make` does not rebuild dependencies automatically, even if something in the
51source code of dependencies is changes.
52
53When you update the source code with `git pull` or when code inside the
54dependencies tree is modified in any other way, make sure to use the following
55command in order to really clean everything and rebuild from scratch:
56
57    make distclean
58
59This will clean: jemalloc, lua, hiredis, linenoise.
60
61Also if you force certain build options like 32bit target, no C compiler
62optimizations (for debugging purposes), and other similar build time options,
63those options are cached indefinitely until you issue a `make distclean`
64command.
65
66Fixing problems building 32 bit binaries
67---------
68
69If after building Redis with a 32 bit target you need to rebuild it
70with a 64 bit target, or the other way around, you need to perform a
71`make distclean` in the root directory of the Redis distribution.
72
73In case of build errors when trying to build a 32 bit binary of Redis, try
74the following steps:
75
76* Install the packages libc6-dev-i386 (also try g++-multilib).
77* Try using the following command line instead of `make 32bit`:
78  `make CFLAGS="-m32 -march=native" LDFLAGS="-m32"`
79
80Allocator
81---------
82
83Selecting a non-default memory allocator when building Redis is done by setting
84the `MALLOC` environment variable. Redis is compiled and linked against libc
85malloc by default, with the exception of jemalloc being the default on Linux
86systems. This default was picked because jemalloc has proven to have fewer
87fragmentation problems than libc malloc.
88
89To force compiling against libc malloc, use:
90
91    % make MALLOC=libc
92
93To compile against jemalloc on Mac OS X systems, use:
94
95    % make MALLOC=jemalloc
96
97Verbose build
98-------------
99
100Redis will build with a user friendly colorized output by default.
101If you want to see a more verbose output use the following:
102
103    % make V=1
104
105Running Redis
106-------------
107
108To run Redis with the default configuration just type:
109
110    % cd src
111    % ./redis-server
112    
113If you want to provide your redis.conf, you have to run it using an additional
114parameter (the path of the configuration file):
115
116    % cd src
117    % ./redis-server /path/to/redis.conf
118
119It is possible to alter the Redis configuration passing parameters directly
120as options using the command line. Examples:
121
122    % ./redis-server --port 9999 --slaveof 127.0.0.1 6379
123    % ./redis-server /etc/redis/6379.conf --loglevel debug
124
125All the options in redis.conf are also supported as options using the command
126line, with exactly the same name.
127
128Playing with Redis
129------------------
130
131You can use redis-cli to play with Redis. Start a redis-server instance,
132then in another terminal try the following:
133
134    % cd src
135    % ./redis-cli
136    redis> ping
137    PONG
138    redis> set foo bar
139    OK
140    redis> get foo
141    "bar"
142    redis> incr mycounter
143    (integer) 1
144    redis> incr mycounter
145    (integer) 2
146    redis>
147
148You can find the list of all the available commands at http://redis.io/commands.
149
150Installing Redis
151-----------------
152
153In order to install Redis binaries into /usr/local/bin just use:
154
155    % make install
156
157You can use `make PREFIX=/some/other/directory install` if you wish to use a
158different destination.
159
160Make install will just install binaries in your system, but will not configure
161init scripts and configuration files in the appropriate place. This is not
162needed if you want just to play a bit with Redis, but if you are installing
163it the proper way for a production system, we have a script doing this
164for Ubuntu and Debian systems:
165
166    % cd utils
167    % ./install_server.sh
168
169The script will ask you a few questions and will setup everything you need
170to run Redis properly as a background daemon that will start again on
171system reboots.
172
173You'll be able to stop and start Redis using the script named
174`/etc/init.d/redis_<portnumber>`, for instance `/etc/init.d/redis_6379`.
175
176Code contributions
177---
178
179Note: by contributing code to the Redis project in any form, including sending
180a pull request via Github, a code fragment or patch via private email or
181public discussion groups, you agree to release your code under the terms
182of the BSD license that you can find in the [COPYING][1] file included in the Redis
183source distribution.
184
185Please see the [CONTRIBUTING][2] file in this source distribution for more
186information.
187
188[1]: https://github.com/antirez/redis/blob/unstable/COPYING
189[2]: https://github.com/antirez/redis/blob/unstable/CONTRIBUTING
190
191Redis internals
192===
193
194If you are reading this README you are likely in front of a Github page
195or you just untarred the Redis distribution tar ball. In both the cases
196you are basically one step away from the source code, so here we explain
197the Redis source code layout, what is in each file as a general idea, the
198most important functions and structures inside the Redis server and so forth.
199We keep all the discussion at an high level without digging into the details
200since this document would be huge otherwise, and our code base changes
201continuously, but a general idea should be a good starting point to
202understand more. Moreover most of the code is heavily commented and easy
203to follow.
204
205Source code layout
206---
207
208The Redis root directory just contains this README, the Makefile which
209actually calls the real Makefile inside the `src` directory, an example
210configuration for Redis and Sentinel. Finally you can find a few shell
211scripts that are used in order to execute the Redis, Redis Cluster and
212Redis Sentinel unit tests, which are implemented inside the `tests`
213directory.
214
215Inside the root directory the are the following important directories:
216
217* `src`: contains the Redis implementation, written in C.
218* `tests`: contains the unit tests, implemented in Tcl.
219* `deps`: contains libraries Redis uses. Everything needed to compile Redis is inside this directory, your system needs to provide just the `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 `anitrez/redis`. an exception to this rule is `deps/geohash-int` which is the low level geocoding library used by Redis: it originated from a different project, but at this point it diverged so much that it is developed as a separated entity directly inside the Redis repository.
220
221There are a few more directories but they are not very important for our goals
222here. We'll focus mostly on `src`, where the Redis implementation is contained,
223exploring what there is inside each file. The order in which files are
224exposed is the logical one to follow in order to disclose different layers
225of complexity incrementally.
226
227Note: lately Redis was refactored quite a bit. Function names and file
228names changed, so you may find that this documentation reflects the
229`unstable` branch more closely. For instance in Redis 3.0 the `server.c`
230and `server.h` files were renamed `redis.c` and `redis.h`. However the overall
231structure is the same. Keep in mind that all the new developments and pull
232requests should be performed against the `unstable` branch.
233
234server.h
235---
236
237The simplest way to understand how a program works, is to understand the
238data structures it uses. So we'll start from the main header file of
239Redis, which is `server.h`.
240
241All the server configuration and in general all the shared state is
242defined in a global structure called `server`, of type `struct redisServer`.
243A few important fields in this structure:
244
245* `server.db` is an array of Redis databases, where data is stored.
246* `server.commands` is the command table.
247* `server.clients` is a linked list of clients connected to the server.
248* `server.master` is a special client, the master, if the instance is a slave.
249
250There are tons of other fields, most fields are commented directly inside
251the structure definition.
252
253Another important Redis data structure is the one defining a client.
254In the past it was called `redisClient`, now just `client`. The structure
255has many fields, here we'll show just the main ones:
256
257    struct client {
258        int fd;
259        sds querybuf;
260        int argc;
261        robj **argv;
262        redisDb *db;
263        int flags;
264        list *reply;
265        char buf[PROTO_REPLY_CHUNK_BYTES];
266        ... many other fields ...
267    }
268
269The client structure defines a *connected client*:
270
271* The `fd` field is the client socket file descriptor.
272* `argc` and `argv` are populated with the command the client is executing, so that functions implementing a given Redis command can read the arguments.
273* `querybuf` accumulates the requests from the client, which are parsed by the Redis server according to the Redis protocol, and executed calling the implementations of the commands the client is executing.
274* `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.
275
276As you can see in the client structure above, arguments in a command
277are described as `robj` structures. The following is the full `robj`
278structure, which defines a *Redis object*:
279
280    typedef struct redisObject {
281        unsigned type:4;
282        unsigned encoding:4;
283        unsigned lru:LRU_BITS; /* lru time (relative to server.lruclock) */
284        int refcount;
285        void *ptr;
286    } robj;
287
288Basically this structure can represent all the basic Redis data types like
289strings, lists, sets, sorted sets and so forth. The interesting thing is that
290it has a `type` field, so that it is possible to know what type a given
291object is, and a `refcount`, so that the same object can be referenced
292in multiple places without allocating it multiple times. Finally the `ptr`
293field points to the actual representation of the object, that may vary
294even for the same type, depending on the `encoding` used.
295
296Redis objects are used extensively in the Redis internals, however in order
297to avoid the overhead of indirect accesses, recently in many places
298we just use plain dynamic strings not wrapped inside a Redis object.
299
300sever.c
301---
302
303This is the entry point of the Redis server, where the `main()` function
304is defined. The following are the most important steps in order to startup
305the Redis server.
306
307* `initServerConfig()` setups the default values of the `server` structure.
308* `initServer()` allocates the data structures needed to operate, setup the listening socket, and so forth.
309* `aeMain()` enters the event loop listening for new connections.
310
311There are two special functions called periodically by the event loop:
312
3131. `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.
3142. `beforeSleep()` is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.
315
316Inside server.c you can find code that handles other vital things of the Redis server:
317
318* `call()` is used in order to call a given command in the context of a given client.
319* `activeExpireCycle()` handles eviciton of keys with a time to live set via the `EXPIRE` command.
320* `freeMemoryIfNeeded()` is called when a new write command should be performed but Redis is out of memory according to the `maxmemory` directive.
321* 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.
322
323networking.c
324---
325
326This file defines all the I/O functions with clients, masters and slaves
327(which in Redis are just special clients):
328
329* `createClient()` allocates and initializes a new client.
330* 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.
331* `writeToClient()` transmits the data pending in the output buffers to the client, and is called by the *writable event handler* `sendReplyToClient()`.
332* `readQueryFromClient()` is the *readable event handler* and accumulates data from read from the client into the query buffer.
333* `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.
334* `freeClient()` deallocates, disconnects and removes a client.
335
336aof.c and rdb.c
337---
338
339As you can guess from the names these files implement the RDB and AOF
340persistence for Redis. Redis uses a persistence model based on the `fork()`
341system call in order to create a thread with the same (shared) memory
342content of the main Redis thread. This secondary thread dumps the content
343of the memory on disk. This is used by `rdb.c` to create the snapshots
344on disk and by `aof.c` in order to perform the AOF rewrite when the
345append only file gets too big.
346
347The implementation inside `aof.c` has additional functions in order to
348implement an API that allows commands to append new commands into the AOF
349file as clients execute them.
350
351The `call()` function defined inside `server.c` is responsible to call
352the functions that in turn will write the commands into the AOF.
353
354db.c
355---
356
357Certain Redis commands operate on specific data types, others are general.
358Examples of generic commands are `DEL` and `EXPIRE`. They operate on keys
359and not on their values specifically. All those generic commands are
360defined inside `db.c`.
361
362Moreover `db.c` implements an API in order to perform certain operations
363on the Redis dataset without directly accessing the internal data structures.
364
365The most important functions inside `db.c` which are used in many commands
366implementations are the following:
367
368* `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.
369* `dbAdd()` and its higher level counterpart `setKey()` create a new key in a Redis database.
370* `dbDelete()` removes a key and its associated value.
371* `emptyDb()` removes an entire single database or all the databases defined.
372
373The rest of the file implements the generic commands exposed to the client.
374
375object.c
376---
377
378The `robj` structure defining Redis objects was already described. Inside
379`object.c` there are all the functions that operate with Redis objects at
380a basic level, like functions to allocate new objects, handle the reference
381counting and so forth. Notable functions inside this file:
382
383* `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.
384* `createObject()` allocates a new object. There are also specialized functions to allocate string objects having a specific content, like `createStringObjectFromLongLong()` and similar functions.
385
386This file also implements the `OBJECT` command.
387
388replication.c
389---
390
391This is one of the most complex files inside Redis, it is recommended to
392approach it only after getting a bit familiar with the rest of the code base.
393In this file there is the implementation of both the master and slave role
394of Redis.
395
396One of the most important functions inside this file is `replicationFeedSlaves()` that writes commands to the clients representing slave instances connected
397to our master, so that the slaves can get the writes performed by the clients:
398this way their data set will remain synchronized with the one in the master.
399
400This file also implements both the `SYNC` and `PSYNC` commands that are
401used in order to perform the first synchronization between masters and
402slaves, or to continue the replication after a disconnection.
403
404Other C files
405---
406
407* `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.
408* `ae.c` implements the Redis event loop, it's a self contained library which is simple to read and understand.
409* `sds.c` is the Redis string library, check http://github.com/antirez/sds for more information.
410* `anet.c` is a library to use POSIX networking in a simpler way compared to the raw interface exposed by the kernel.
411* `dict.c` is an implementation of a non-blocking hash table which rehashes incrementally.
412* `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.
413* `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].
414
415[3]: http://redis.io/topics/cluster-spec
416
417Anatomy of a Redis command
418---
419
420All the Redis commands are defined in the following way:
421
422    void foobarCommand(client *c) {
423        printf("%s",c->argv[1]->ptr); /* Do something with the argument. */
424        addReply(c,shared.ok); /* Reply something to the client. */
425    }
426
427The command is then referenced inside `server.c` in the command table:
428
429    {"foobar",foobarCommand,2,"rtF",0,NULL,0,0,0,0,0},
430
431In the above example `2` is the number of arguments the command takes,
432while `"rtF"` are the command flags, as documented in the command table
433top comment inside `server.c`.
434
435After the command operates in some way, it returns a reply to the client,
436usually using `addReply()` or a similar function defined inside `networking.c`.
437
438There are tons of commands implementations inside th Redis source code
439that can serve as examples of actual commands implementations. To write
440a few toy commands can be a good exercise to familiarize with the code base.
441
442There are also many other files not described here,  but it is useless to
443cover everything, we want just to help you with the first steps,
444eventually you'll find your way inside the Redis code base :-)
445
446Enjoy!
447
448