Skip to content

Commit

Permalink
add tcpkeepalive, tcpkeepidle, tcpkeepcnt and tcpkeepintvl for conf f…
Browse files Browse the repository at this point in the history
…ile.
  • Loading branch information
deep011 committed Apr 19, 2016
1 parent 2515d3c commit 0d35acb
Show file tree
Hide file tree
Showing 11 changed files with 172 additions and 171 deletions.
46 changes: 25 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
# twemproxys (nutcrackers) [![Build Status](https://secure.travis-ci.org/twitter/twemproxys.png)](http://travis-ci.org/twitter/twemproxys)
# twemproxies (nutcrackers) [![Build Status](https://secure.travis-ci.org/twitter/twemproxies.png)](http://travis-ci.org/twitter/twemproxies)

**twemproxys** (pronounced "two-em-proxy"), aka **nutcrackers** is a fast and lightweight proxy for [memcached](http://www.memcached.org/) and [redis](http://redis.io/) protocol. It was built primarily to reduce the number of connections to the caching servers on the backend. This, together with protocol pipelining and sharding enables you to horizontally scale your distributed caching architecture.
**twemproxies** (pronounced "two-em-proxy"), aka **nutcrackers** is a multithread, fast and lightweight proxy for [memcached](http://www.memcached.org/) and [redis](http://redis.io/) protocol. It was built primarily to reduce the number of connections to the caching servers on the backend. This, together with protocol pipelining and sharding enables you to horizontally scale your distributed caching architecture.

## Build

To build twemproxys from [distribution tarball](https://drive.google.com/open?id=0B6pVMMV5F5dfMUdJV25abllhUWM&authuser=0):
To build twemproxies from [distribution tarball](https://drive.google.com/open?id=0B6pVMMV5F5dfMUdJV25abllhUWM&authuser=0):

$ ./configure
$ make
$ sudo make install

To build twemproxys from [distribution tarball](https://drive.google.com/open?id=0B6pVMMV5F5dfMUdJV25abllhUWM&authuser=0) in _debug mode_:
To build twemproxies from [distribution tarball](https://drive.google.com/open?id=0B6pVMMV5F5dfMUdJV25abllhUWM&authuser=0) in _debug mode_:

$ CFLAGS="-ggdb3 -O0" ./configure --enable-debug=full
$ make
$ sudo make install

To build twemproxys from source with _debug logs enabled_ and _assertions enabled_:
To build twemproxies from source with _debug logs enabled_ and _assertions enabled_:

$ git clone [email protected]:twitter/twemproxys.git
$ cd twemproxys
$ git clone [email protected]:twitter/twemproxies.git
$ cd twemproxies
$ autoreconf -fvi
$ ./configure --enable-debug=full
$ make
Expand All @@ -34,7 +34,7 @@ A quick checklist:

## Note

Try the follow command to get the twemproxys status:
Try the follow command to get the twemproxies status:

printf "status\r\n" | nc manage_ip manage_port

Expand Down Expand Up @@ -81,13 +81,13 @@ Try the follow command to get the twemproxys status:

## Zero Copy

In twemproxys, all the memory for incoming requests and outgoing responses is allocated in mbuf. Mbuf enables zero-copy because the same buffer on which a request was received from the client is used for forwarding it to the server. Similarly the same mbuf on which a response was received from the server is used for forwarding it to the client.
In twemproxies, all the memory for incoming requests and outgoing responses is allocated in mbuf. Mbuf enables zero-copy because the same buffer on which a request was received from the client is used for forwarding it to the server. Similarly the same mbuf on which a response was received from the server is used for forwarding it to the client.

Furthermore, memory for mbufs is managed using a reuse pool. This means that once mbuf is allocated, it is not deallocated, but just put back into the reuse pool. By default each mbuf chunk is set to 16K bytes in size. There is a trade-off between the mbuf size and number of concurrent connections twemproxys can support. A large mbuf size reduces the number of read syscalls made by twemproxys when reading requests or responses. However, with a large mbuf size, every active connection would use up 16K bytes of buffer which might be an issue when twemproxys is handling large number of concurrent connections from clients. When twemproxys is meant to handle a large number of concurrent client connections, you should set chunk size to a small value like 512 bytes using the -m or --mbuf-size=N argument.
Furthermore, memory for mbufs is managed using a reuse pool. This means that once mbuf is allocated, it is not deallocated, but just put back into the reuse pool. By default each mbuf chunk is set to 16K bytes in size. There is a trade-off between the mbuf size and number of concurrent connections twemproxies can support. A large mbuf size reduces the number of read syscalls made by twemproxies when reading requests or responses. However, with a large mbuf size, every active connection would use up 16K bytes of buffer which might be an issue when twemproxies is handling large number of concurrent connections from clients. When twemproxies is meant to handle a large number of concurrent client connections, you should set chunk size to a small value like 512 bytes using the -m or --mbuf-size=N argument.

## Configuration

twemproxys can be configured through a YAML file specified by the -c or --conf-file command-line argument on process start. The configuration file is used to specify the server pools and the servers within each pool that twemproxys manages. The configuration files parses and understands the following keys:
twemproxies can be configured through a YAML file specified by the -c or --conf-file command-line argument on process start. The configuration file is used to specify the server pools and the servers within each pool that twemproxies manages. The configuration files parses and understands the following keys:

+ **listen**: The listening address and port (name:port or ip:port) or an absolute path to sock file (e.g. /var/run/nutcrackers.sock) for this server pool.
+ **hash**: The name of the hash function. Possible values are:
Expand All @@ -110,10 +110,14 @@ twemproxys can be configured through a YAML file specified by the -c or --conf-f
+ random
+ **timeout**: The timeout value in msec that we wait for to establish a connection to the server or receive a response from a server. By default, we wait indefinitely.
+ **backlog**: The TCP backlog argument. Defaults to 512.
+ **preconnect**: A boolean value that controls if twemproxys should preconnect to all the servers in this pool on process start. Defaults to false.
+ **tcpkeepalive**: A boolean value that controls if tcp keepalive enabled. Defaults to false.
+ **tcpkeepidle**: The time value in msec that a connection is in idle, and then twemproxy check this connection whether dead or not.
+ **tcpkeepcnt**: The number of tcpkeepalive attempt check if one idle connection dead times when the client always had no reply.
+ **tcpkeepintvl**: The time value in msec that the interval between every tcpkeepalive check when the client always had no reply.
+ **preconnect**: A boolean value that controls if twemproxies should preconnect to all the servers in this pool on process start. Defaults to false.
+ **redis**: A boolean value that controls if a server pool speaks redis or memcached protocol. Defaults to false.
+ **redis_auth**: Authenticate to the Redis server on connect.
+ **redis_db**: The DB number to use on the pool servers. Defaults to 0. Note: twemproxys will always present itself to clients as DB 0.
+ **redis_db**: The DB number to use on the pool servers. Defaults to 0. Note: twemproxies will always present itself to clients as DB 0.
+ **server_connections**: The maximum number of connections that can be opened to each server. By default, we open at most 1 server connection.
+ **auto_eject_hosts**: A boolean value that controls if server should be ejected temporarily when it fails consecutively server_failure_limit times. See [liveness recommendations](notes/recommendation.md#liveness) for information. Defaults to false.
+ **server_retry_timeout**: The timeout value in msec to wait for before retrying on a temporarily ejected server, when auto_eject_host is set to true. Defaults to 30000 msec.
Expand Down Expand Up @@ -191,13 +195,13 @@ For example, the configuration file in [conf/nutcrackers.yml](conf/nutcrackers.y
- 127.0.0.1:11214:100000
- 127.0.0.1:11215:1

Finally, to make writing a syntactically correct configuration file easier, twemproxys provides a command-line argument -t or --test-conf that can be used to test the YAML configuration file for any syntax error.
Finally, to make writing a syntactically correct configuration file easier, twemproxies provides a command-line argument -t or --test-conf that can be used to test the YAML configuration file for any syntax error.

## Observability

Observability in twemproxys is through logs and stats.
Observability in twemproxies is through logs and stats.

twemproxys exposes stats at the granularity of server pool and servers per pool through the stats monitoring port. The stats are essentially JSON formatted key-value pairs, with the keys corresponding to counter names. By default stats are exposed on port 22222 and aggregated every 30 seconds. Both these values can be configured on program start using the -c or --conf-file and -i or --stats-interval command-line arguments respectively. You can print the description of all stats exported by using the -D or --describe-stats command-line argument.
twemproxies exposes stats at the granularity of server pool and servers per pool through the stats monitoring port. The stats are essentially JSON formatted key-value pairs, with the keys corresponding to counter names. By default stats are exposed on port 22222 and aggregated every 30 seconds. Both these values can be configured on program start using the -c or --conf-file and -i or --stats-interval command-line arguments respectively. You can print the description of all stats exported by using the -D or --describe-stats command-line argument.

$ nutcrackers --describe-stats

Expand All @@ -223,19 +227,19 @@ twemproxys exposes stats at the granularity of server pool and servers per pool
out_queue "# requests in outgoing queue"
out_queue_bytes "current request bytes in outgoing queue"

Logging in twemproxys is only available when twemproxys is built with logging enabled. By default logs are written to stderr. twemproxys can also be configured to write logs to a specific file through the -o or --output command-line argument. On a running twemproxys, we can turn log levels up and down by sending it SIGTTIN and SIGTTOU signals respectively and reopen log files by sending it SIGHUP signal.
Logging in twemproxies is only available when twemproxies is built with logging enabled. By default logs are written to stderr. twemproxies can also be configured to write logs to a specific file through the -o or --output command-line argument. On a running twemproxies, we can turn log levels up and down by sending it SIGTTIN and SIGTTOU signals respectively and reopen log files by sending it SIGHUP signal.

## Pipelining

twemproxys enables proxying multiple client connections onto one or few server connections. This architectural setup makes it ideal for pipelining requests and responses and hence saving on the round trip time.
twemproxies enables proxying multiple client connections onto one or few server connections. This architectural setup makes it ideal for pipelining requests and responses and hence saving on the round trip time.

For example, if twemproxys is proxying three client connections onto a single server and we get requests - 'get key\r\n', 'set key 0 0 3\r\nval\r\n' and 'delete key\r\n' on these three connections respectively, twemproxys would try to batch these requests and send them as a single message onto the server connection as 'get key\r\nset key 0 0 3\r\nval\r\ndelete key\r\n'.
For example, if twemproxies is proxying three client connections onto a single server and we get requests - 'get key\r\n', 'set key 0 0 3\r\nval\r\n' and 'delete key\r\n' on these three connections respectively, twemproxies would try to batch these requests and send them as a single message onto the server connection as 'get key\r\nset key 0 0 3\r\nval\r\ndelete key\r\n'.

Pipelining is the reason why twemproxys ends up doing better in terms of throughput even though it introduces an extra hop between the client and server.
Pipelining is the reason why twemproxies ends up doing better in terms of throughput even though it introduces an extra hop between the client and server.

## Deployment

If you are deploying twemproxys in production, you might consider reading through the [recommendation document](notes/recommendation.md) to understand the parameters you could tune in twemproxys to run it efficiently in the production environment.
If you are deploying twemproxies in production, you might consider reading through the [recommendation document](notes/recommendation.md) to understand the parameters you could tune in twemproxies to run it efficiently in the production environment.

## License

Expand Down
21 changes: 14 additions & 7 deletions src/nc.c
Original file line number Diff line number Diff line change
Expand Up @@ -465,21 +465,23 @@ nc_get_options(int argc, char **argv, struct instance *nci)
* returns false
*/
static bool
nc_test_conf(struct instance *nci)
nc_test_conf(struct instance *nci, bool test)
{
struct conf *cf;

cf = conf_create(nci->conf_filename);
if (cf == NULL) {
log_stderr("nutcrackers: configuration file '%s' syntax is invalid",
nci->conf_filename);
if (test)
log_stderr("nutcrackers: configuration file '%s' syntax is invalid",
nci->conf_filename);
return false;
}

conf_destroy(cf);

log_stderr("nutcrackers: configuration file '%s' syntax is ok",
nci->conf_filename);
if (test)
log_stderr("nutcrackers: configuration file '%s' syntax is ok",
nci->conf_filename);
return true;
}

Expand All @@ -493,6 +495,11 @@ nc_pre_run(struct instance *nci)
return status;
}

if (!nc_test_conf(nci, false)) {
log_error("conf file %s is error", nci->conf_filename);
return NC_ERROR;
}

if (daemonize) {
status = nc_daemonize(1);
if (status != NC_OK) {
Expand Down Expand Up @@ -556,7 +563,7 @@ nc_run(struct instance *nci)
if (status != NC_OK) {
return;
}

/* init the workers */
for (i = 0; i < worker_count; i ++) {
worker = array_push(&workers);
Expand Down Expand Up @@ -617,7 +624,7 @@ main(int argc, char **argv)
}

if (test_conf) {
if (!nc_test_conf(&nci)) {
if (!nc_test_conf(&nci, true)) {
exit(1);
}
exit(0);
Expand Down
40 changes: 40 additions & 0 deletions src/nc_conf.c
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,19 @@ static struct command conf_commands[] = {
conf_add_server,
offsetof(struct conf_pool, server) },

{ string("tcpkeepalive"),
conf_set_bool,
offsetof(struct conf_pool, tcpkeepalive) },
{ string("tcpkeepidle"),
conf_set_num,
offsetof(struct conf_pool, tcpkeepidle) },
{ string("tcpkeepintvl"),
conf_set_num,
offsetof(struct conf_pool, tcpkeepintvl) },
{ string("tcpkeepcnt"),
conf_set_num,
offsetof(struct conf_pool, tcpkeepcnt) },

null_command
};

Expand Down Expand Up @@ -205,6 +218,11 @@ conf_pool_init(struct conf_pool *cp, struct string *name)

cp->valid = 0;

cp->tcpkeepalive = CONF_UNSET_NUM;
cp->tcpkeepidle = CONF_UNSET_NUM;
cp->tcpkeepintvl = CONF_UNSET_NUM;
cp->tcpkeepcnt = CONF_UNSET_NUM;

status = string_duplicate(&cp->name, name);
if (status != NC_OK) {
return status;
Expand Down Expand Up @@ -296,6 +314,11 @@ conf_pool_each_transform(void *elem, void *data)
sp->auto_eject_hosts = cp->auto_eject_hosts ? 1 : 0;
sp->preconnect = cp->preconnect ? 1 : 0;

sp->tcpkeepalive = cp->tcpkeepalive ? 1 : 0;
sp->tcpkeepidle = cp->tcpkeepidle;
sp->tcpkeepintvl = cp->tcpkeepintvl;
sp->tcpkeepcnt = cp->tcpkeepcnt;

status = server_init(&sp->server, &cp->server, sp);
if (status != NC_OK) {
return status;
Expand Down Expand Up @@ -1267,6 +1290,19 @@ conf_validate_pool(struct conf *cf, struct conf_pool *cp)

cp->valid = 1;

if (cp->tcpkeepalive == CONF_UNSET_NUM) {
cp->tcpkeepalive = CONF_DEFAULT_TCPKEEPALIVE;
}
if (cp->tcpkeepidle == CONF_UNSET_NUM) {
cp->tcpkeepidle = CONF_DEFAULT_TCPKEEPIDLE;
}
if (cp->tcpkeepintvl == CONF_UNSET_NUM) {
cp->tcpkeepintvl = CONF_DEFAULT_TCPKEEPINTVL;
}
if (cp->tcpkeepcnt == CONF_UNSET_NUM) {
cp->tcpkeepcnt = CONF_DEFAULT_TCPKEEPCNT;
}

return NC_OK;
}

Expand Down Expand Up @@ -1385,6 +1421,10 @@ conf_create(char *filename)
void
conf_destroy(struct conf *cf)
{
if (cf == NULL) {
return;
}

while (array_n(&cf->arg) != 0) {
conf_pop_scalar(cf);
}
Expand Down
10 changes: 10 additions & 0 deletions src/nc_conf.h
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@
#define CONF_DEFAULT_SERVER_CONNECTIONS 1
#define CONF_DEFAULT_KETAMA_PORT 11211

#define CONF_DEFAULT_TCPKEEPALIVE 0
#define CONF_DEFAULT_TCPKEEPIDLE -1
#define CONF_DEFAULT_TCPKEEPINTVL -1
#define CONF_DEFAULT_TCPKEEPCNT -1

struct conf_listen {
struct string pname; /* listen: as "hostname:port" */
struct string name; /* hostname:port */
Expand Down Expand Up @@ -93,6 +98,11 @@ struct conf_pool {
int server_failure_limit; /* server_failure_limit: */
struct array server; /* servers: conf_server[] */
unsigned valid:1; /* valid? */

int tcpkeepalive; /* tcpkeepalive: */
int tcpkeepidle; /* tcpkeepidle: */
int tcpkeepintvl; /* tcpkeepintvl: */
int tcpkeepcnt; /* tcpkeepcnt: */
};

struct conf {
Expand Down
12 changes: 11 additions & 1 deletion src/nc_manage.c
Original file line number Diff line number Diff line change
Expand Up @@ -515,11 +515,12 @@ manage_init(struct context *ctx, char *addr, uint16_t port)

manager->nc_conn_q = 0;
TAILQ_INIT(&manager->c_conn_q);
string_init(&manager->addrstr);

ctx->manager = manager;
manager->ctx = ctx;

string_set_raw(&manager->addrstr,addr);
string_copy(&manager->addrstr, (uint8_t *)addr, (uint32_t)strlen(addr));
manager->port = port;

memset(&manager->info, 0, sizeof(manager->info));
Expand Down Expand Up @@ -550,10 +551,19 @@ manage_deinit(struct context *ctx)
struct manage *manager = ctx->manager;
struct conn *p;

if (manager == NULL) {
return;
}

p = manager->p_conn;
if (p != NULL) {
p->close(ctx, p);
}

string_deinit(&manager->addrstr);

nc_free(manager);
ctx->manager = NULL;
}

void
Expand Down
3 changes: 2 additions & 1 deletion src/nc_proxy.c
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,6 @@ proxy_accept(struct context *ctx, struct conn *p)
return NC_OK;
}


if (p->source_type == NC_SOURCE_TYPE_PROXY) {
c = conn_get(p->owner, true, NC_SOURCE_TYPE_PROXY, ctx->cb);
if (c == NULL) {
Expand All @@ -357,6 +356,8 @@ proxy_accept(struct context *ctx, struct conn *p)
return status;
}

nc_set_tcpkeepalive(c->sd, 0, 0, 0);

if (p->family == AF_INET || p->family == AF_INET6) {
status = nc_set_tcpnodelay(c->sd);
if (status < 0) {
Expand Down
4 changes: 4 additions & 0 deletions src/nc_server.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ struct server_pool {
unsigned auto_eject_hosts:1; /* auto_eject_hosts? */
unsigned preconnect:1; /* preconnect? */
unsigned redis:1; /* redis? */
unsigned tcpkeepalive:1; /* tcp keepalive? */
int tcpkeepidle; /* tcpkeep idle */
int tcpkeepintvl; /* tcpkeep interval */
int tcpkeepcnt; /* tcpkeep count */
};

void server_ref(struct conn *conn, void *owner);
Expand Down
Loading

0 comments on commit 0d35acb

Please sign in to comment.