1 /* -*- Mode: C; tab-width: 2; c-basic-offset: 2; indent-tabs-mode: nil -*- */
3 * What is a library without an example to show you how to use the library?
4 * This example use both interfaces to implement a small memcached server.
5 * Please note that this is an exemple on how to use the library, not
6 * an implementation of a scalable memcached server. If you look closely
7 * at the example it isn't even multithreaded ;-)
9 * With that in mind, let me give you some pointers into the source:
10 * storage.c/h - Implements the item store for this server and not really
11 * interesting for this example.
12 * interface_v0.cc - Shows an implementation of the memcached server by using
13 * the "raw" access to the packets as they arrive
14 * interface_v1.cc - Shows an implementation of the memcached server by using
15 * the more "logical" interface.
16 * memcached_light.cc- This file sets up all of the sockets and run the main
20 * config.h is included so that I can use the ntohll/htonll on platforms that
21 * doesn't have that (this is a private function inside libmemcached, so you
22 * cannot use it directly from libmemcached without special modifications to
28 #include <libmemcachedprotocol-0.0/handler.h>
29 #include <libmemcached/socket.hpp>
30 #include <example/byteorder.h>
31 #include "example/storage.h"
32 #include "example/memcached_light.h"
34 #include "util/daemon.hpp"
35 #include "util/log.hpp"
36 #include "util/pidfile.hpp"
38 using namespace datadifferential
;
50 #include <sys/types.h>
53 extern memcached_binary_protocol_callback_st interface_v0_impl
;
54 extern memcached_binary_protocol_callback_st interface_v1_impl
;
56 static memcached_socket_t server_sockets
[1024];
57 static int num_server_sockets
= 0;
65 /* The default maximum number of connections... (change with -c) */
66 static int maxconns
= 1024;
68 static struct connection
*socket_userdata_map
;
69 static struct event_base
*event_base
= NULL
;
86 static options_st global_options
;
89 * Callback for driving a client connection
90 * @param fd the socket for the client socket
91 * @param which identifying the event that occurred (not used)
92 * @param arg the connection structure for the client
94 static void drive_client(memcached_socket_t fd
, short, void *arg
)
96 struct connection
*client
= (struct connection
*)arg
;
97 struct memcached_protocol_client_st
* c
= (struct memcached_protocol_client_st
*)client
->userdata
;
100 memcached_protocol_event_t events
= memcached_protocol_client_work(c
);
101 if (events
& MEMCACHED_PROTOCOL_ERROR_EVENT
)
103 if (global_options
.is_verbose
)
105 struct sockaddr_in sin
;
106 socklen_t addrlen
= sizeof(sin
);
108 if (getsockname(fd
, (struct sockaddr
*)&sin
, &addrlen
) != -1)
110 std::cout
<< __FILE__
<< ":" << __LINE__
111 << " close(MEMCACHED_PROTOCOL_ERROR_EVENT)"
112 << " " << inet_ntoa(sin
.sin_addr
) << ":" << sin
.sin_port
118 std::cout
<< __FILE__
<< ":" << __LINE__
<< "close() MEMCACHED_PROTOCOL_ERROR_EVENT" << std::endl
;
122 memcached_protocol_client_destroy(c
);
128 if (events
& MEMCACHED_PROTOCOL_WRITE_EVENT
)
133 if (events
& MEMCACHED_PROTOCOL_READ_EVENT
)
138 event_set(&client
->event
, (intptr_t)fd
, flags
, drive_client
, client
);
139 event_base_set(event_base
, &client
->event
);
141 if (event_add(&client
->event
, 0) == -1)
143 memcached_protocol_client_destroy(c
);
150 * Callback for accepting new connections
151 * @param fd the socket for the server socket
152 * @param which identifying the event that occurred (not used)
153 * @param arg the connection structure for the server
155 static void accept_handler(memcached_socket_t fd
, short, void *arg
)
157 struct connection
*server
= (struct connection
*)arg
;
158 /* accept new client */
159 struct sockaddr_storage addr
;
160 socklen_t addrlen
= sizeof(addr
);
161 memcached_socket_t sock
= accept(fd
, (struct sockaddr
*)&addr
, &addrlen
);
163 if (sock
== INVALID_SOCKET
)
165 perror("Failed to accept client");
169 if (sock
>= maxconns
)
176 struct memcached_protocol_client_st
* c
= memcached_protocol_create_client((memcached_protocol_st
*)server
->userdata
, sock
);
183 memcached_protocol_client_set_verbose(c
, global_options
.is_verbose
);
184 struct connection
*client
= &socket_userdata_map
[sock
];
187 event_set(&client
->event
, (intptr_t)sock
, EV_READ
, drive_client
, client
);
188 event_base_set(event_base
, &client
->event
);
189 if (event_add(&client
->event
, 0) == -1)
191 std::cerr
<< "Failed to add event for " << sock
<< std::endl
;
192 memcached_protocol_client_destroy(c
);
198 static bool server_socket(util::log_info_st
& log_file
, const std::string
& service
)
201 struct addrinfo hints
;
202 memset(&hints
, 0, sizeof(struct addrinfo
));
204 hints
.ai_flags
= AI_PASSIVE
;
205 hints
.ai_family
= AF_UNSPEC
;
206 hints
.ai_socktype
= SOCK_STREAM
;
208 int error
= getaddrinfo("127.0.0.1", service
.c_str(), &hints
, &ai
);
211 if (error
!= EAI_SYSTEM
)
213 std::string
buffer("getaddrinfo: ");
214 buffer
+= gai_strerror(error
);
215 log_file
.write(util::VERBOSE_ERROR
, buffer
.c_str());
219 std::string
buffer("getaddrinfo: ");
220 buffer
+= strerror(errno
);
221 log_file
.write(util::VERBOSE_ERROR
, buffer
.c_str());
227 struct linger ling
= {0, 0};
229 for (struct addrinfo
*next
= ai
; next
; next
= next
->ai_next
)
231 memcached_socket_t sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
232 if (sock
== INVALID_SOCKET
)
234 std::string
buffer("Failed to create socket: ");
235 buffer
+= strerror(errno
);
236 log_file
.write(util::VERBOSE_ERROR
, buffer
.c_str());
243 if (ioctlsocket(sock
, FIONBIO
, &arg
) == SOCKET_ERROR
)
245 std::cerr
<< "Failed to set nonblocking io: " << strerror(errno
) << std::endl
;
250 flags
= fcntl(sock
, F_GETFL
, 0);
253 std::string
buffer("Failed to get socket flags: ");
254 buffer
+= strerror(errno
);
255 log_file
.write(util::VERBOSE_ERROR
, buffer
.c_str());
260 if ((flags
& O_NONBLOCK
) != O_NONBLOCK
)
262 if (fcntl(sock
, F_SETFL
, flags
| O_NONBLOCK
) == -1)
264 std::string
buffer("Failed to set socket to nonblocking mode: ");
265 buffer
+= strerror(errno
);
266 log_file
.write(util::VERBOSE_ERROR
, buffer
.c_str());
274 if (setsockopt(sock
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&flags
, sizeof(flags
)) != 0)
276 std::cerr
<< "Failed to set SO_REUSEADDR: " << strerror(errno
) << std::endl
;
279 if (setsockopt(sock
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&flags
, sizeof(flags
)) != 0)
281 std::cerr
<< "Failed to set SO_KEEPALIVE: " << strerror(errno
) << std::endl
;
284 if (setsockopt(sock
, SOL_SOCKET
, SO_LINGER
, (void *)&ling
, sizeof(ling
)) != 0)
286 std::cerr
<< "Failed to set SO_LINGER: " << strerror(errno
) << std::endl
;
289 if (setsockopt(sock
, IPPROTO_TCP
, TCP_NODELAY
, (void *)&flags
, sizeof(flags
)) != 0)
291 std::cerr
<< "Failed to set TCP_NODELAY: " << strerror(errno
) << std::endl
;
294 if (bind(sock
, next
->ai_addr
, next
->ai_addrlen
) == SOCKET_ERROR
)
296 if (get_socket_errno() != EADDRINUSE
)
298 std::cerr
<< "bind(): " << strerror(errno
) << std::endl
;
305 if (listen(sock
, 1024) == SOCKET_ERROR
)
307 std::string
buffer("listen(): ");
308 buffer
+= strerror(errno
);
309 log_file
.write(util::VERBOSE_ERROR
, buffer
.c_str());
314 if (global_options
.is_verbose
)
316 std::string
buffer("Listening to: ");
317 buffer
+= global_options
.service
;
318 log_file
.write(util::VERBOSE_NOTICE
, buffer
.c_str());
321 server_sockets
[num_server_sockets
++]= sock
;
326 return (num_server_sockets
> 0) ? true : false;
330 * Convert a command code to a textual string
331 * @param cmd the comcode to convert
332 * @return a textual string with the command or NULL for unknown commands
334 static const char* comcode2str(uint8_t cmd
)
336 static const char * const text
[] = {
337 "GET", "SET", "ADD", "REPLACE", "DELETE",
338 "INCREMENT", "DECREMENT", "QUIT", "FLUSH",
339 "GETQ", "NOOP", "VERSION", "GETK", "GETKQ",
340 "APPEND", "PREPEND", "STAT", "SETQ", "ADDQ",
341 "REPLACEQ", "DELETEQ", "INCREMENTQ", "DECREMENTQ",
342 "QUITQ", "FLUSHQ", "APPENDQ", "PREPENDQ"
345 if (cmd
<= PROTOCOL_BINARY_CMD_PREPENDQ
)
354 * Print out the command we are about to execute
356 static void pre_execute(const void *cookie
,
357 protocol_binary_request_header
*header
)
359 if (global_options
.is_verbose
)
363 const char *cmd
= comcode2str(header
->request
.opcode
);
366 std::cout
<< "pre_execute from " << cookie
<< ": " << cmd
<< std::endl
;
370 std::cout
<< "pre_execute from " << cookie
<< ": " << header
->request
.opcode
<< std::endl
;
375 std::cout
<< "pre_execute from " << cookie
<< std::endl
;
381 * Print out the command we just executed
383 static void post_execute(const void *cookie
,
384 protocol_binary_request_header
*header
)
386 if (global_options
.is_verbose
)
390 const char *cmd
= comcode2str(header
->request
.opcode
);
393 std::cout
<< "post_execute from " << cookie
<< ": " << cmd
<< std::endl
;
397 std::cout
<< "post_execute from " << cookie
<< ": " << header
->request
.opcode
<< std::endl
;
402 std::cout
<< "post_execute from " << cookie
<< std::endl
;
408 * Callback handler for all unknown commands.
409 * Send an unknown command back to the client
411 static protocol_binary_response_status
unknown(const void *cookie
,
412 protocol_binary_request_header
*header
,
413 memcached_binary_protocol_raw_response_handler response_handler
)
415 protocol_binary_response_no_extras response
;
416 memset(&response
, 0, sizeof(protocol_binary_response_no_extras
));
418 response
.message
.header
.response
.magic
= PROTOCOL_BINARY_RES
;
419 response
.message
.header
.response
.opcode
= header
->request
.opcode
;
420 response
.message
.header
.response
.status
= htons(PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND
);
421 response
.message
.header
.response
.opaque
= header
->request
.opaque
;
423 return response_handler(cookie
, header
, (protocol_binary_response_header
*)&response
);
427 * Program entry point. Bind to the specified port(s) and serve clients
429 * @param argc number of items in the argument vector
430 * @param argv argument vector
431 * @return EXIT_SUCCESS on success, 1 otherwise
433 int main(int argc
, char **argv
)
435 memcached_binary_protocol_callback_st
*interface
= &interface_v0_impl
;
442 OPT_PROTOCOL_VERSION
,
450 static struct option long_options
[]=
452 { "help", no_argument
, NULL
, OPT_HELP
},
453 { "port", required_argument
, NULL
, OPT_PORT
},
454 { "verbose", no_argument
, NULL
, OPT_VERBOSE
},
455 { "daemon", no_argument
, NULL
, OPT_DAEMON
},
456 { "protocol", no_argument
, NULL
, OPT_PROTOCOL_VERSION
},
457 { "version", no_argument
, NULL
, OPT_VERSION
},
458 { "max-connections", required_argument
, NULL
, OPT_MAX_CONNECTIONS
},
459 { "pid-file", required_argument
, NULL
, OPT_PIDFILE
},
460 { "log-file", required_argument
, NULL
, OPT_LOGFILE
},
464 bool opt_help
= false;
467 while (done
== false)
469 switch (getopt_long(argc
, argv
, "", long_options
, &option_index
))
475 case OPT_PROTOCOL_VERSION
:
476 interface
= &interface_v1_impl
;
480 global_options
.pid_file
= optarg
;
484 global_options
.log_file
= optarg
;
488 global_options
.is_verbose
= true;
495 global_options
.opt_daemon
= true;
499 global_options
.service
= optarg
;
502 case OPT_MAX_CONNECTIONS
:
503 maxconns
= atoi(optarg
);
506 case OPT_HELP
: /* FALLTHROUGH */
512 std::cerr
<< "Unknown option: " << optarg
<< std::endl
;
520 std::cout
<< "Usage: " << argv
[0] << std::endl
;
521 for (struct option
*ptr_option
= long_options
; ptr_option
->name
; ptr_option
++)
523 std::cout
<< "\t" << ptr_option
->name
<< std::endl
;
529 if (global_options
.opt_daemon
)
531 util::daemonize(false, true);
534 if (initialize_storage() == false)
536 /* Error message already printed */
540 util::Pidfile
_pid_file(global_options
.pid_file
);
542 if (_pid_file
.create() == false)
544 std::cerr
<< "Failed to create pid-file" << _pid_file
.error_message() << std::endl
;
548 util::log_info_st
log_file(argv
[0], global_options
.log_file
, false);
549 log_file
.write(util::VERBOSE_NOTICE
, "starting log");
552 * We need to initialize the handlers manually due to a bug in the
553 * warnings generated by struct initialization in gcc (all the way up to 4.4)
555 initialize_interface_v0_handler(log_file
);
556 initialize_interface_v1_handler(log_file
);
559 if (server_socket(log_file
, global_options
.service
) == false)
564 if (num_server_sockets
== 0)
566 log_file
.write(util::VERBOSE_ERROR
, "No server sockets are available.");
571 * Create and initialize the handles to the protocol handlers. I want
572 * to be able to trace the traffic throught the pre/post handlers, and
573 * set up a common handler for unknown messages
575 interface
->pre_execute
= pre_execute
;
576 interface
->post_execute
= post_execute
;
577 interface
->unknown
= unknown
;
579 struct memcached_protocol_st
*protocol_handle
;
580 if ((protocol_handle
= memcached_protocol_create_instance()) == NULL
)
582 log_file
.write(util::VERBOSE_ERROR
, "No server sockets are available.");
586 socket_userdata_map
= (struct connection
*)calloc((size_t)(maxconns
), sizeof(struct connection
));
587 if (socket_userdata_map
== NULL
)
589 log_file
.write(util::VERBOSE_ERROR
, "Failed to allocate room for connections");
593 memcached_binary_protocol_set_callbacks(protocol_handle
, interface
);
594 memcached_binary_protocol_set_pedantic(protocol_handle
, true);
596 event_base
= event_init();
597 if (event_base
== NULL
)
599 std::cerr
<< "Failed to create an instance of libevent" << std::endl
;
603 for (int xx
= 0; xx
< num_server_sockets
; ++xx
)
605 struct connection
*conn
= &socket_userdata_map
[server_sockets
[xx
]];
606 conn
->userdata
= protocol_handle
;
608 event_set(&conn
->event
, (intptr_t)server_sockets
[xx
], EV_READ
| EV_PERSIST
, accept_handler
, conn
);
610 event_base_set(event_base
, &conn
->event
);
611 if (event_add(&conn
->event
, 0) == -1)
613 log_file
.write(util::VERBOSE_ERROR
, "Failed to add event");
614 closesocket(server_sockets
[xx
]);
618 if (global_options
.opt_daemon
)
620 if (util::daemon_is_ready(true) == false)
622 log_file
.write(util::VERBOSE_ERROR
, "Failed for util::daemon_is_ready()");
628 /* Serve all of the clients */
629 switch (event_base_loop(event_base
, 0))
632 log_file
.write(util::VERBOSE_ERROR
, "event_base_loop() failed");
636 log_file
.write(util::VERBOSE_ERROR
, "event_base_loop(), no events were registered");
642 log_file
.write(util::VERBOSE_NOTICE
, "exiting");