2 +--------------------------------------------------------------------+
3 | libmemcached-awesome - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020 Michael Wallner <mike@php.net> |
13 +--------------------------------------------------------------------+
16 #include "mem_config.h"
24 #include <netinet/tcp.h>
25 #include <netinet/in.h>
27 #if defined(HAVE_ARPA_INET_H)
28 # include <arpa/inet.h>
31 #if defined(HAVE_SYS_TIME_H)
32 # include <sys/time.h>
36 #include "ms_setting.h"
37 #include "ms_thread.h"
38 #include "ms_atomic.h"
41 /* /usr/include/netinet/in.h defines macros from ntohs() to _bswap_nn to
42 * optimize the conversion functions, but the prototypes generate warnings
43 * from gcc. The conversion methods isn't the bottleneck for my app, so
44 * just remove the warnings by undef'ing the optimization ..
52 /* for network write */
53 #define TRANSMIT_COMPLETE 0
54 #define TRANSMIT_INCOMPLETE 1
55 #define TRANSMIT_SOFT_ERROR 2
56 #define TRANSMIT_HARD_ERROR 3
58 /* for generating key */
59 #define KEY_PREFIX_BASE 0x1010101010101010 /* not include ' ' '\r' '\n' '\0' */
60 #define KEY_PREFIX_MASK 0x1010101010101010
62 /* For parse the value length return by server */
64 #define VALUELEN_TOKEN 3
66 /* global increasing counter, to ensure the key prefix unique */
67 static uint64_t key_prefix_seq
= KEY_PREFIX_BASE
;
69 /* global increasing counter, generating request id for UDP */
70 static ATOMIC
uint32_t udp_request_id
= 0;
72 extern pthread_key_t ms_thread_key
;
74 /* generate upd request id */
75 static uint32_t ms_get_udp_request_id(void);
77 /* connect initialize */
78 static void ms_task_init(ms_conn_t
*c
);
79 static int ms_conn_udp_init(ms_conn_t
*c
, const bool is_udp
);
80 static int ms_conn_sock_init(ms_conn_t
*c
);
81 static int ms_conn_event_init(ms_conn_t
*c
);
82 static int ms_conn_init(ms_conn_t
*c
, const int init_state
, const int read_buffer_size
,
84 static void ms_warmup_num_init(ms_conn_t
*c
);
85 static int ms_item_win_init(ms_conn_t
*c
);
87 /* connection close */
88 void ms_conn_free(ms_conn_t
*c
);
89 static void ms_conn_close(ms_conn_t
*c
);
91 /* create network connection */
92 static int ms_new_socket(struct addrinfo
*ai
);
93 static void ms_maximize_sndbuf(const int sfd
);
94 static int ms_network_connect(ms_conn_t
*c
, char *srv_host_name
, const int srv_port
,
95 const bool is_udp
, int *ret_sfd
);
96 static int ms_reconn(ms_conn_t
*c
);
99 static int ms_tokenize_command(char *command
, token_t
*tokens
, const int max_tokens
);
100 static int ms_ascii_process_line(ms_conn_t
*c
, char *command
);
101 static int ms_try_read_line(ms_conn_t
*c
);
102 static int ms_sort_udp_packet(ms_conn_t
*c
, char *buf
, int rbytes
);
103 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
);
104 static int ms_try_read_network(ms_conn_t
*c
);
105 static void ms_verify_value(ms_conn_t
*c
, ms_mlget_task_item_t
*mlget_item
, char *value
, int vlen
);
106 static void ms_ascii_complete_nread(ms_conn_t
*c
);
107 static void ms_bin_complete_nread(ms_conn_t
*c
);
108 static void ms_complete_nread(ms_conn_t
*c
);
111 static int ms_add_msghdr(ms_conn_t
*c
);
112 static int ms_ensure_iov_space(ms_conn_t
*c
);
113 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
);
114 static int ms_build_udp_headers(ms_conn_t
*c
);
115 static int ms_transmit(ms_conn_t
*c
);
117 /* status adjustment */
118 static void ms_conn_shrink(ms_conn_t
*c
);
119 static void ms_conn_set_state(ms_conn_t
*c
, int state
);
120 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
);
121 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
);
122 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
);
123 static int ms_update_conn_sock_event(ms_conn_t
*c
);
124 static bool ms_need_yield(ms_conn_t
*c
);
125 static void ms_update_start_time(ms_conn_t
*c
);
128 static void ms_drive_machine(ms_conn_t
*c
);
129 void ms_event_handler(const int fd
, const short which
, void *arg
);
132 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
);
133 static int ms_build_ascii_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
);
134 static int ms_build_ascii_write_buf_mlget(ms_conn_t
*c
);
136 /* binary protocol */
137 static int ms_bin_process_response(ms_conn_t
*c
);
138 static void ms_add_bin_header(ms_conn_t
*c
, uint8_t opcode
, uint8_t hdr_len
, uint16_t key_len
,
140 static void ms_add_key_to_iov(ms_conn_t
*c
, ms_task_item_t
*item
);
141 static int ms_build_bin_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
);
142 static int ms_build_bin_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
);
143 static int ms_build_bin_write_buf_mlget(ms_conn_t
*c
);
146 * each key has two parts, prefix and suffix. The suffix is a
147 * string random get form the character table. The prefix is a
148 * uint64_t variable. And the prefix must be unique. we use the
149 * prefix to identify a key. And the prefix can't include
150 * character ' ' '\r' '\n' '\0'.
154 uint64_t ms_get_key_prefix(void) {
157 pthread_mutex_lock(&ms_global
.seq_mutex
);
158 key_prefix_seq
|= KEY_PREFIX_MASK
;
159 key_prefix
= key_prefix_seq
;
161 pthread_mutex_unlock(&ms_global
.seq_mutex
);
164 } /* ms_get_key_prefix */
167 * get an unique udp request id
169 * @return an unique UDP request id
171 static uint32_t ms_get_udp_request_id(void) {
172 return atomic_add_32_nv(&udp_request_id
, 1);
176 * initialize current task structure
178 * @param c, pointer of the concurrency
180 static void ms_task_init(ms_conn_t
*c
) {
181 c
->curr_task
.cmd
= CMD_NULL
;
182 c
->curr_task
.item
= 0;
183 c
->curr_task
.verify
= false;
184 c
->curr_task
.finish_verify
= true;
185 c
->curr_task
.get_miss
= true;
187 c
->curr_task
.get_opt
= 0;
188 c
->curr_task
.set_opt
= 0;
189 c
->curr_task
.cycle_undo_get
= 0;
190 c
->curr_task
.cycle_undo_set
= 0;
191 c
->curr_task
.verified_get
= 0;
192 c
->curr_task
.overwrite_set
= 0;
196 * initialize udp for the connection structure
198 * @param c, pointer of the concurrency
199 * @param is_udp, whether it's udp
201 * @return int, if success, return EXIT_SUCCESS, else return -1
203 static int ms_conn_udp_init(ms_conn_t
*c
, const bool is_udp
) {
208 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
219 if (c
->udp
|| (!c
->udp
&& ms_setting
.facebook_test
)) {
220 c
->rudpbuf
= (char *) malloc((size_t) c
->rudpsize
);
221 c
->udppkt
= (ms_udppkt_t
*) malloc(MAX_UDP_PACKET
* sizeof(ms_udppkt_t
));
223 if ((c
->rudpbuf
== NULL
) || (c
->udppkt
== NULL
)) {
228 fprintf(stderr
, "malloc()\n");
231 memset(c
->udppkt
, 0, MAX_UDP_PACKET
* sizeof(ms_udppkt_t
));
235 } /* ms_conn_udp_init */
238 * initialize the connection structure
240 * @param c, pointer of the concurrency
241 * @param init_state, (conn_read, conn_write, conn_closing)
242 * @param read_buffer_size
243 * @param is_udp, whether it's udp
245 * @return int, if success, return EXIT_SUCCESS, else return -1
247 static int ms_conn_init(ms_conn_t
*c
, const int init_state
, const int read_buffer_size
,
251 c
->rbuf
= c
->wbuf
= 0;
255 c
->rsize
= read_buffer_size
;
256 c
->wsize
= WRITE_BUFFER_SIZE
;
257 c
->iovsize
= IOV_LIST_INITIAL
;
258 c
->msgsize
= MSG_LIST_INITIAL
;
260 /* for replication, each connection need connect all the server */
261 if (ms_setting
.rep_write_srv
> 0) {
262 c
->total_sfds
= ms_setting
.srv_cnt
* ms_setting
.sock_per_conn
;
264 c
->total_sfds
= ms_setting
.sock_per_conn
;
268 c
->rbuf
= (char *) malloc((size_t) c
->rsize
);
269 c
->wbuf
= (char *) malloc((size_t) c
->wsize
);
270 c
->iov
= (struct iovec
*) malloc(sizeof(struct iovec
) * (size_t) c
->iovsize
);
271 c
->msglist
= (struct msghdr
*) malloc(sizeof(struct msghdr
) * (size_t) c
->msgsize
);
272 if (ms_setting
.mult_key_num
> 1) {
273 c
->mlget_task
.mlget_item
= (ms_mlget_task_item_t
*) malloc(sizeof(ms_mlget_task_item_t
)
274 * (size_t) ms_setting
.mult_key_num
);
276 c
->tcpsfd
= (int *) malloc((size_t) c
->total_sfds
* sizeof(int));
278 if ((c
->rbuf
== NULL
) || (c
->wbuf
== NULL
) || (c
->iov
== NULL
) || (c
->msglist
== NULL
)
279 || (c
->tcpsfd
== NULL
)
280 || ((ms_setting
.mult_key_num
> 1) && (c
->mlget_task
.mlget_item
== NULL
)))
290 if (c
->mlget_task
.mlget_item
)
291 free(c
->mlget_task
.mlget_item
);
294 fprintf(stderr
, "malloc()\n");
298 c
->state
= init_state
;
306 c
->cur_idx
= c
->total_sfds
; /* default index is a invalid value */
310 c
->change_sfd
= false;
312 c
->precmd
.cmd
= c
->currcmd
.cmd
= CMD_NULL
;
313 c
->precmd
.isfinish
= true; /* default the previous command finished */
314 c
->currcmd
.isfinish
= false;
315 c
->precmd
.retstat
= c
->currcmd
.retstat
= MCD_FAILURE
;
316 c
->precmd
.key_prefix
= c
->currcmd
.key_prefix
= 0;
318 c
->mlget_task
.mlget_num
= 0;
319 c
->mlget_task
.value_index
= -1; /* default invalid value */
321 if (ms_setting
.binary_prot_
) {
322 c
->protocol
= binary_prot
;
324 c
->protocol
= ascii_prot
;
328 if (ms_conn_udp_init(c
, is_udp
)) {
332 /* initialize task */
335 if (!(ms_setting
.facebook_test
&& is_udp
)) {
336 atomic_add_32(&ms_stats
.active_conns
, 1);
343 * when doing 100% get operation, it could preset some objects
344 * to warmup the server. this function is used to initialize the
345 * number of the objects to preset.
347 * @param c, pointer of the concurrency
349 static void ms_warmup_num_init(ms_conn_t
*c
) {
350 /* no set operation, preset all the items in the window */
351 if (ms_setting
.cmd_distr
[CMD_SET
].cmd_prop
< PROP_ERROR
) {
352 c
->warmup_num
= c
->win_size
;
353 c
->remain_warmup_num
= c
->warmup_num
;
356 c
->remain_warmup_num
= c
->warmup_num
;
358 } /* ms_warmup_num_init */
361 * each connection has an item window, this function initialize
362 * the window. The window is used to generate task.
364 * @param c, pointer of the concurrency
366 * @return int, if success, return EXIT_SUCCESS, else return -1
368 static int ms_item_win_init(ms_conn_t
*c
) {
369 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
372 c
->win_size
= (int) ms_setting
.win_size
;
374 c
->exec_num
= ms_thread
->thread_ctx
->exec_num_perconn
;
375 c
->remain_exec_num
= c
->exec_num
;
377 c
->item_win
= (ms_task_item_t
*) malloc(sizeof(ms_task_item_t
) * (size_t) c
->win_size
);
378 if (c
->item_win
== NULL
) {
379 fprintf(stderr
, "Can't allocate task item array for conn.\n");
382 memset(c
->item_win
, 0, sizeof(ms_task_item_t
) * (size_t) c
->win_size
);
384 for (int i
= 0; i
< c
->win_size
; i
++) {
385 c
->item_win
[i
].key_size
= (int) ms_setting
.distr
[i
].key_size
;
386 c
->item_win
[i
].key_prefix
= ms_get_key_prefix();
387 c
->item_win
[i
].key_suffix_offset
= ms_setting
.distr
[i
].key_offset
;
388 c
->item_win
[i
].value_size
= (int) ms_setting
.distr
[i
].value_size
;
389 c
->item_win
[i
].value_offset
= INVALID_OFFSET
; /* default in invalid offset */
390 c
->item_win
[i
].client_time
= 0;
392 /* set expire time base on the proportion */
393 if (exp_cnt
< ms_setting
.exp_ver_per
* i
) {
394 c
->item_win
[i
].exp_time
= FIXED_EXPIRE_TIME
;
397 c
->item_win
[i
].exp_time
= 0;
401 ms_warmup_num_init(c
);
404 } /* ms_item_win_init */
407 * each connection structure can include one or more sock
408 * handlers. this function create these socks and connect the
411 * @param c, pointer of the concurrency
413 * @return int, if success, return EXIT_SUCCESS, else return -1
415 static int ms_conn_sock_init(ms_conn_t
*c
) {
416 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
419 uint32_t srv_idx
= 0;
424 for (i
= 0; i
< c
->total_sfds
; i
++) {
426 if (ms_setting
.rep_write_srv
> 0) {
427 /* for replication, each connection need connect all the server */
428 srv_idx
= i
% ms_setting
.srv_cnt
;
430 /* all the connections in a thread connects the same server */
431 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
434 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
435 ms_setting
.servers
[srv_idx
].srv_port
, ms_setting
.udp
, &ret_sfd
)
445 if (!ms_setting
.udp
) {
446 c
->tcpsfd
[i
] = ret_sfd
;
452 /* initialize udp sock handler if necessary */
453 if (ms_setting
.facebook_test
) {
455 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
456 ms_setting
.servers
[srv_idx
].srv_port
, true, &ret_sfd
)
465 if ((i
!= c
->total_sfds
) || (ms_setting
.facebook_test
&& (c
->udpsfd
== 0))) {
466 if (ms_setting
.udp
) {
469 for (uint32_t j
= 0; j
< i
; j
++) {
482 } /* ms_conn_sock_init */
485 * each connection is managed by libevent, this function
486 * initialize the event of the connection structure.
488 * @param c, pointer of the concurrency
490 * @return int, if success, return EXIT_SUCCESS, else return -1
492 static int ms_conn_event_init(ms_conn_t
*c
) {
493 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
494 short event_flags
= EV_WRITE
| EV_PERSIST
;
496 event_set(&c
->event
, c
->sfd
, event_flags
, ms_event_handler
, (void *) c
);
497 event_base_set(ms_thread
->base
, &c
->event
);
498 c
->ev_flags
= event_flags
;
500 if (event_add(&c
->event
, NULL
) == -1) {
505 } /* ms_conn_event_init */
508 * setup a connection, each connection structure of each
509 * thread must call this function to initialize.
511 * @param c, pointer of the concurrency
513 * @return int, if success, return EXIT_SUCCESS, else return -1
515 int ms_setup_conn(ms_conn_t
*c
) {
516 if (ms_item_win_init(c
)) {
520 if (ms_conn_init(c
, conn_write
, DATA_BUFFER_SIZE
, ms_setting
.udp
)) {
524 if (ms_conn_sock_init(c
)) {
528 if (ms_conn_event_init(c
)) {
533 } /* ms_setup_conn */
536 * Frees a connection.
538 * @param c, pointer of the concurrency
540 void ms_conn_free(ms_conn_t
*c
) {
541 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
553 if (c
->mlget_task
.mlget_item
)
554 free(c
->mlget_task
.mlget_item
);
564 if (--ms_thread
->nactive_conn
== 0) {
565 free(ms_thread
->conn
);
573 * @param c, pointer of the concurrency
575 static void ms_conn_close(ms_conn_t
*c
) {
576 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
579 /* delete the event, the socket and the connection */
580 event_del(&c
->event
);
582 for (uint32_t i
= 0; i
< c
->total_sfds
; i
++) {
583 if (c
->tcpsfd
[i
] > 0) {
589 if (ms_setting
.facebook_test
) {
593 atomic_dec_32(&ms_stats
.active_conns
);
597 if (ms_setting
.run_time
== 0) {
598 pthread_mutex_lock(&ms_global
.run_lock
.lock
);
599 ms_global
.run_lock
.count
++;
600 pthread_cond_signal(&ms_global
.run_lock
.cond
);
601 pthread_mutex_unlock(&ms_global
.run_lock
.lock
);
604 if (ms_thread
->nactive_conn
== 0) {
605 event_base_loopbreak(ms_thread
->base
);
607 } /* ms_conn_close */
612 * @param ai, server address information
614 * @return int, if success, return EXIT_SUCCESS, else return -1
616 static int ms_new_socket(struct addrinfo
*ai
) {
619 if ((sfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
)) == -1) {
620 fprintf(stderr
, "socket() error: %s.\n", strerror(errno
));
625 } /* ms_new_socket */
628 * Sets a socket's send buffer size to the maximum allowed by the system.
630 * @param sfd, file descriptor of socket
632 static void ms_maximize_sndbuf(const int sfd
) {
633 socklen_t intsize
= sizeof(int);
634 unsigned int last_good
= 0;
635 unsigned int min
, max
, avg
;
636 unsigned int old_size
;
638 /* Start with the default size. */
639 if (getsockopt(sfd
, SOL_SOCKET
, SO_SNDBUF
, &old_size
, &intsize
)) {
640 fprintf(stderr
, "getsockopt(SO_SNDBUF)\n");
644 /* Binary-search for the real maximum. */
646 max
= MAX_SENDBUF_SIZE
;
649 avg
= ((unsigned int) (min
+ max
)) / 2;
650 if (setsockopt(sfd
, SOL_SOCKET
, SO_SNDBUF
, (void *) &avg
, intsize
) == 0) {
658 } /* ms_maximize_sndbuf */
661 * socket connects the server
663 * @param c, pointer of the concurrency
664 * @param srv_host_name, the host name of the server
665 * @param srv_port, port of server
666 * @param is_udp, whether it's udp
667 * @param ret_sfd, the connected socket file descriptor
669 * @return int, if success, return EXIT_SUCCESS, else return -1
671 static int ms_network_connect(ms_conn_t
*c
, char *srv_host_name
, const int srv_port
,
672 const bool is_udp
, int *ret_sfd
) {
674 struct linger ling
= {0, 0};
676 struct addrinfo
*next
;
677 struct addrinfo hints
;
678 char port_buf
[NI_MAXSERV
];
685 * the memset call clears nonstandard fields in some impementations
686 * that otherwise mess things up.
688 memset(&hints
, 0, sizeof(hints
));
690 hints
.ai_flags
= AI_PASSIVE
| AI_ADDRCONFIG
;
692 hints
.ai_flags
= AI_PASSIVE
;
693 #endif /* AI_ADDRCONFIG */
695 hints
.ai_protocol
= IPPROTO_UDP
;
696 hints
.ai_socktype
= SOCK_DGRAM
;
697 hints
.ai_family
= AF_INET
; /* This left here because of issues with OSX 10.5 */
699 hints
.ai_family
= AF_UNSPEC
;
700 hints
.ai_protocol
= IPPROTO_TCP
;
701 hints
.ai_socktype
= SOCK_STREAM
;
704 snprintf(port_buf
, NI_MAXSERV
, "%d", srv_port
);
705 error
= getaddrinfo(srv_host_name
, port_buf
, &hints
, &ai
);
707 if (error
!= EAI_SYSTEM
)
708 fprintf(stderr
, "getaddrinfo(): %s.\n", gai_strerror(error
));
710 perror("getaddrinfo()");
715 for (next
= ai
; next
; next
= next
->ai_next
) {
716 if ((sfd
= ms_new_socket(next
)) == -1) {
721 setsockopt(sfd
, SOL_SOCKET
, SO_REUSEADDR
, (void *) &flags
, sizeof(flags
));
723 ms_maximize_sndbuf(sfd
);
725 setsockopt(sfd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *) &flags
, sizeof(flags
));
726 setsockopt(sfd
, SOL_SOCKET
, SO_LINGER
, (void *) &ling
, sizeof(ling
));
727 setsockopt(sfd
, IPPROTO_TCP
, TCP_NODELAY
, (void *) &flags
, sizeof(flags
));
731 c
->srv_recv_addr_size
= sizeof(struct sockaddr
);
732 memcpy(&c
->srv_recv_addr
, next
->ai_addr
, c
->srv_recv_addr_size
);
734 if (connect(sfd
, next
->ai_addr
, next
->ai_addrlen
) == -1) {
741 if (((flags
= fcntl(sfd
, F_GETFL
, 0)) < 0) || (fcntl(sfd
, F_SETFL
, flags
| O_NONBLOCK
) < 0)) {
742 fprintf(stderr
, "setting O_NONBLOCK\n");
757 /* Return zero if we detected no errors in starting up connections */
759 } /* ms_network_connect */
762 * reconnect a disconnected sock
764 * @param c, pointer of the concurrency
766 * @return int, if success, return EXIT_SUCCESS, else return -1
768 static int ms_reconn(ms_conn_t
*c
) {
769 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
770 uint32_t srv_idx
= 0;
771 uint32_t srv_conn_cnt
= 0;
773 if (ms_setting
.rep_write_srv
> 0) {
774 srv_idx
= c
->cur_idx
% ms_setting
.srv_cnt
;
775 srv_conn_cnt
= ms_setting
.sock_per_conn
* ms_setting
.nconns
;
777 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
778 srv_conn_cnt
= ms_setting
.nconns
/ ms_setting
.srv_cnt
;
781 /* close the old socket handler */
783 c
->tcpsfd
[c
->cur_idx
] = 0;
785 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].disconn_cnt
, 1) % srv_conn_cnt
== 0) {
786 gettimeofday(&ms_setting
.servers
[srv_idx
].disconn_time
, NULL
);
787 fprintf(stderr
, "Server %s:%d disconnect\n", ms_setting
.servers
[srv_idx
].srv_host_name
,
788 ms_setting
.servers
[srv_idx
].srv_port
);
791 if (ms_setting
.rep_write_srv
> 0) {
794 for (i
= 0; i
< c
->total_sfds
; i
++) {
800 /* all socks disconnect */
801 if (i
== c
->total_sfds
) {
806 /* reconnect success, break the loop */
807 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
808 ms_setting
.servers
[srv_idx
].srv_port
, ms_setting
.udp
, &c
->sfd
)
811 c
->tcpsfd
[c
->cur_idx
] = c
->sfd
;
812 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].reconn_cnt
, 1) % (uint32_t) srv_conn_cnt
814 gettimeofday(&ms_setting
.servers
[srv_idx
].reconn_time
, NULL
);
815 int reconn_time
= (int) (ms_setting
.servers
[srv_idx
].reconn_time
.tv_sec
816 - ms_setting
.servers
[srv_idx
].disconn_time
.tv_sec
);
817 fprintf(stderr
, "Server %s:%d reconnect after %ds\n",
818 ms_setting
.servers
[srv_idx
].srv_host_name
, ms_setting
.servers
[srv_idx
].srv_port
,
824 if (ms_setting
.rep_write_srv
== 0 && c
->total_sfds
> 0) {
825 /* wait a second and reconnect */
828 } while (ms_setting
.rep_write_srv
== 0 && c
->total_sfds
> 0);
831 if ((c
->total_sfds
> 1) && (c
->tcpsfd
[c
->cur_idx
] == 0)) {
840 * reconnect several disconnected socks in the connection
841 * structure, the ever-1-second timer of the thread will check
842 * whether some socks in the connections disconnect. if
843 * disconnect, reconnect the sock.
845 * @param c, pointer of the concurrency
847 * @return int, if success, return EXIT_SUCCESS, else return -1
849 int ms_reconn_socks(ms_conn_t
*c
) {
850 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
851 uint32_t srv_idx
= 0;
853 uint32_t srv_conn_cnt
= 0;
854 struct timeval cur_time
;
858 if ((c
->total_sfds
== 1) || (c
->total_sfds
== c
->alive_sfds
)) {
862 for (uint32_t i
= 0; i
< c
->total_sfds
; i
++) {
863 if (c
->tcpsfd
[i
] == 0) {
864 gettimeofday(&cur_time
, NULL
);
867 * For failover test of replication, reconnect the socks after
868 * it disconnects more than 5 seconds, Otherwise memslap will
869 * block at connect() function and the work threads can't work
872 if (cur_time
.tv_sec
- ms_setting
.servers
[srv_idx
].disconn_time
.tv_sec
< 5) {
876 if (ms_setting
.rep_write_srv
> 0) {
877 srv_idx
= i
% ms_setting
.srv_cnt
;
878 srv_conn_cnt
= ms_setting
.sock_per_conn
* ms_setting
.nconns
;
880 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
881 srv_conn_cnt
= ms_setting
.nconns
/ ms_setting
.srv_cnt
;
884 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
885 ms_setting
.servers
[srv_idx
].srv_port
, ms_setting
.udp
, &ret_sfd
)
888 c
->tcpsfd
[i
] = ret_sfd
;
891 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].reconn_cnt
, 1) % (uint32_t) srv_conn_cnt
893 gettimeofday(&ms_setting
.servers
[srv_idx
].reconn_time
, NULL
);
894 int reconn_time
= (int) (ms_setting
.servers
[srv_idx
].reconn_time
.tv_sec
895 - ms_setting
.servers
[srv_idx
].disconn_time
.tv_sec
);
896 fprintf(stderr
, "Server %s:%d reconnect after %ds\n",
897 ms_setting
.servers
[srv_idx
].srv_host_name
, ms_setting
.servers
[srv_idx
].srv_port
,
905 } /* ms_reconn_socks */
908 * Tokenize the command string by replacing whitespace with '\0' and update
909 * the token array tokens with pointer to start of each token and length.
910 * Returns total number of tokens. The last valid token is the terminal
911 * token (value points to the first unprocessed character of the string and
916 * while(ms_tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
917 * for(int ix = 0; tokens[ix].length; ix++) {
920 * ncommand = tokens[ix].value - command;
921 * command = tokens[ix].value;
924 * @param command, the command string to token
925 * @param tokens, array to store tokens
926 * @param max_tokens, maximum tokens number
928 * @return int, the number of tokens
930 static int ms_tokenize_command(char *command
, token_t
*tokens
, const int max_tokens
) {
934 assert(command
&& tokens
&& max_tokens
> 1);
936 for (s
= e
= command
; ntokens
< max_tokens
- 1; ++e
) {
939 tokens
[ntokens
].value
= s
;
940 tokens
[ntokens
].length
= (size_t)(e
- s
);
945 } else if (*e
== '\0') {
947 tokens
[ntokens
].value
= s
;
948 tokens
[ntokens
].length
= (size_t)(e
- s
);
952 break; /* string end */
957 } /* ms_tokenize_command */
960 * parse the response of server.
962 * @param c, pointer of the concurrency
963 * @param command, the string responded by server
965 * @return int, if the command completed return EXIT_SUCCESS, else return
968 static int ms_ascii_process_line(ms_conn_t
*c
, char *command
) {
971 char *buffer
= command
;
976 * for command get, we store the returned value into local buffer
977 * then continue in ms_complete_nread().
981 case 'V': /* VALUE || VERSION */
982 if (buffer
[1] == 'A') /* VALUE */ {
983 token_t tokens
[MAX_TOKENS
];
984 ms_tokenize_command(command
, tokens
, MAX_TOKENS
);
986 value_len
= strtol(tokens
[VALUELEN_TOKEN
].value
, NULL
, 10);
988 printf("<%d ERROR %s\n", c
->sfd
, strerror(errno
));
990 memcpy(&c
->currcmd
.key_prefix
, tokens
[KEY_TOKEN
].value
, sizeof(c
->currcmd
.key_prefix
));
993 * We read the \r\n into the string since not doing so is more
994 * cycles then the waster of memory to do so.
996 * We are null terminating through, which will most likely make
997 * some people lazy about using the return length.
999 c
->rvbytes
= (int) (value_len
+ 2);
1007 c
->currcmd
.retstat
= MCD_SUCCESS
;
1010 case 'S': /* STORED STATS SERVER_ERROR */
1011 if (buffer
[2] == 'A') /* STORED STATS */ { /* STATS*/
1012 c
->currcmd
.retstat
= MCD_STAT
;
1013 } else if (buffer
[1] == 'E') {
1015 printf("<%d %s\n", c
->sfd
, buffer
);
1017 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
1018 } else if (buffer
[1] == 'T') {
1020 c
->currcmd
.retstat
= MCD_STORED
;
1022 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1026 case 'D': /* DELETED DATA */
1027 if (buffer
[1] == 'E') {
1028 c
->currcmd
.retstat
= MCD_DELETED
;
1030 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1035 case 'N': /* NOT_FOUND NOT_STORED*/
1036 if (buffer
[4] == 'F') {
1037 c
->currcmd
.retstat
= MCD_NOTFOUND
;
1038 } else if (buffer
[4] == 'S') {
1039 printf("<%d %s\n", c
->sfd
, buffer
);
1040 c
->currcmd
.retstat
= MCD_NOTSTORED
;
1042 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1046 case 'E': /* PROTOCOL ERROR or END */
1047 if (buffer
[1] == 'N') {
1049 c
->currcmd
.retstat
= MCD_END
;
1050 } else if (buffer
[1] == 'R') {
1051 printf("<%d ERROR\n", c
->sfd
);
1052 c
->currcmd
.retstat
= MCD_PROTOCOL_ERROR
;
1053 } else if (buffer
[1] == 'X') {
1054 c
->currcmd
.retstat
= MCD_DATA_EXISTS
;
1055 printf("<%d %s\n", c
->sfd
, buffer
);
1057 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1061 case 'C': /* CLIENT ERROR */
1062 printf("<%d %s\n", c
->sfd
, buffer
);
1063 c
->currcmd
.retstat
= MCD_CLIENT_ERROR
;
1067 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1072 } /* ms_ascii_process_line */
1075 * after one operation completes, reset the concurrency
1077 * @param c, pointer of the concurrency
1078 * @param timeout, whether it's timeout
1080 void ms_reset_conn(ms_conn_t
*c
, bool timeout
) {
1084 if ((c
->packets
> 0) && (c
->packets
< MAX_UDP_PACKET
)) {
1085 memset(c
->udppkt
, 0, sizeof(ms_udppkt_t
) * (size_t) c
->packets
);
1094 c
->currcmd
.isfinish
= true;
1095 c
->ctnwrite
= false;
1101 ms_conn_set_state(c
, conn_write
);
1102 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
1105 ms_drive_machine(c
);
1107 } /* ms_reset_conn */
1110 * if we have a complete line in the buffer, process it.
1112 * @param c, pointer of the concurrency
1114 * @return int, if success, return EXIT_SUCCESS, else return -1
1116 static int ms_try_read_line(ms_conn_t
*c
) {
1117 if (c
->protocol
== binary_prot
) {
1118 /* Do we have the complete packet header? */
1119 if ((uint64_t) c
->rbytes
< sizeof(c
->binary_header
)) {
1120 /* need more data! */
1121 return EXIT_SUCCESS
;
1124 if (((long) (c
->rcurr
)) % 8) {
1125 /* must realign input buffer */
1126 memmove(c
->rbuf
, c
->rcurr
, c
->rbytes
);
1128 if (settings
.verbose
) {
1129 fprintf(stderr
, "%d: Realign input buffer.\n", c
->sfd
);
1133 protocol_binary_response_header
*rsp
;
1134 rsp
= (protocol_binary_response_header
*) c
->rcurr
;
1136 c
->binary_header
= *rsp
;
1137 c
->binary_header
.response
.extlen
= rsp
->response
.extlen
;
1138 c
->binary_header
.response
.keylen
= ntohs(rsp
->response
.keylen
);
1139 c
->binary_header
.response
.bodylen
= ntohl(rsp
->response
.bodylen
);
1140 c
->binary_header
.response
.status
= ntohs(rsp
->response
.status
);
1142 if (c
->binary_header
.response
.magic
!= PROTOCOL_BINARY_RES
) {
1143 fprintf(stderr
, "Invalid magic: %x\n", c
->binary_header
.response
.magic
);
1144 ms_conn_set_state(c
, conn_closing
);
1145 return EXIT_SUCCESS
;
1148 /* process this complete response */
1149 if (ms_bin_process_response(c
) == 0) {
1150 /* current operation completed */
1151 ms_reset_conn(c
, false);
1154 c
->rbytes
-= (int32_t) sizeof(c
->binary_header
);
1155 c
->rcurr
+= sizeof(c
->binary_header
);
1162 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1165 return EXIT_SUCCESS
;
1167 el
= memchr(c
->rcurr
, '\n', (size_t) c
->rbytes
);
1169 return EXIT_SUCCESS
;
1172 if (((el
- c
->rcurr
) > 1) && (*(el
- 1) == '\r')) {
1177 assert(cont
<= (c
->rcurr
+ c
->rbytes
));
1179 /* process this complete line */
1180 if (ms_ascii_process_line(c
, c
->rcurr
) == 0) {
1181 /* current operation completed */
1182 ms_reset_conn(c
, false);
1185 /* current operation didn't complete */
1186 c
->rbytes
-= (int32_t)(cont
- c
->rcurr
);
1190 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1194 } /* ms_try_read_line */
1197 * because the packet of UDP can't ensure the order, the
1198 * function is used to sort the received udp packet.
1200 * @param c, pointer of the concurrency
1201 * @param buf, the buffer to store the ordered packages data
1202 * @param rbytes, the maximum capacity of the buffer
1204 * @return int, if success, return the copy bytes, else return
1207 static int ms_sort_udp_packet(ms_conn_t
*c
, char *buf
, int rbytes
) {
1210 uint16_t req_id
= 0;
1211 uint16_t seq_num
= 0;
1212 uint16_t packets
= 0;
1213 unsigned char *header
= NULL
;
1215 /* no enough data */
1218 assert(c
->rudpbytes
>= UDP_HEADER_SIZE
);
1220 /* calculate received packets count */
1221 if (c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
>= UDP_HEADER_SIZE
) {
1222 /* the last packet has some data */
1223 c
->recvpkt
= c
->rudpbytes
/ UDP_MAX_PAYLOAD_SIZE
+ 1;
1225 c
->recvpkt
= c
->rudpbytes
/ UDP_MAX_PAYLOAD_SIZE
;
1228 /* get the total packets count if necessary */
1229 if (c
->packets
== 0) {
1230 c
->packets
= HEADER_TO_PACKETS((unsigned char *) c
->rudpbuf
);
1233 /* build the ordered packet array */
1234 for (int i
= c
->pktcurr
; i
< c
->recvpkt
; i
++) {
1235 header
= (unsigned char *) c
->rudpbuf
+ i
* UDP_MAX_PAYLOAD_SIZE
;
1236 req_id
= (uint16_t) HEADER_TO_REQID(header
);
1237 assert(req_id
== c
->request_id
% (1 << 16));
1239 packets
= (uint16_t) HEADER_TO_PACKETS(header
);
1240 assert(c
->packets
== HEADER_TO_PACKETS(header
));
1242 seq_num
= (uint16_t) HEADER_TO_SEQNUM(header
);
1243 c
->udppkt
[seq_num
].header
= header
;
1244 c
->udppkt
[seq_num
].data
= (char *) header
+ UDP_HEADER_SIZE
;
1246 if (i
== c
->recvpkt
- 1) {
1247 /* last received packet */
1248 if (c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
== 0) {
1249 c
->udppkt
[seq_num
].rbytes
= UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1252 c
->udppkt
[seq_num
].rbytes
= c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1255 c
->udppkt
[seq_num
].rbytes
= UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1260 for (int i
= c
->ordcurr
; i
< c
->recvpkt
; i
++) {
1261 /* there is some data to copy */
1262 if ((c
->udppkt
[i
].data
) && (c
->udppkt
[i
].copybytes
< c
->udppkt
[i
].rbytes
)) {
1263 header
= c
->udppkt
[i
].header
;
1264 len
= c
->udppkt
[i
].rbytes
- c
->udppkt
[i
].copybytes
;
1265 if (len
> rbytes
- wbytes
) {
1266 len
= rbytes
- wbytes
;
1269 assert(len
<= rbytes
- wbytes
);
1270 assert(i
== HEADER_TO_SEQNUM(header
));
1272 memcpy(buf
+ wbytes
, c
->udppkt
[i
].data
+ c
->udppkt
[i
].copybytes
, (size_t) len
);
1274 c
->udppkt
[i
].copybytes
+= len
;
1276 if ((c
->udppkt
[i
].copybytes
== c
->udppkt
[i
].rbytes
)
1277 && (c
->udppkt
[i
].rbytes
== UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
))
1279 /* finish copying all the data of this packet, next */
1283 /* last received packet, and finish copying all the data */
1284 if ((c
->recvpkt
== c
->packets
) && (i
== c
->recvpkt
- 1)
1285 && (c
->udppkt
[i
].copybytes
== c
->udppkt
[i
].rbytes
))
1290 /* no space to copy data */
1291 if (wbytes
>= rbytes
) {
1295 /* it doesn't finish reading all the data of the packet from network */
1296 if ((i
!= c
->recvpkt
- 1) && (c
->udppkt
[i
].rbytes
< UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
)) {
1300 /* no data to copy */
1306 return wbytes
== 0 ? -1 : wbytes
;
1307 } /* ms_sort_udp_packet */
1310 * encapsulate upd read like tcp read
1312 * @param c, pointer of the concurrency
1313 * @param buf, read buffer
1314 * @param len, length to read
1316 * @return int, if success, return the read bytes, else return
1319 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
) {
1328 if (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
> c
->rudpsize
) {
1329 char *new_rbuf
= realloc(c
->rudpbuf
, (size_t) c
->rudpsize
* 2);
1331 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1332 c
->rudpbytes
= 0; /* ignore what we read */
1335 c
->rudpbuf
= new_rbuf
;
1339 avail
= c
->rudpsize
- c
->rudpbytes
;
1340 /* UDP each time read a packet, 1400 bytes */
1341 res
= (int) read(c
->sfd
, c
->rudpbuf
+ c
->rudpbytes
, (size_t) avail
);
1344 atomic_add_size(&ms_stats
.bytes_read
, res
);
1345 c
->rudpbytes
+= res
;
1355 /* "connection" closed */
1360 /* no data to read */
1365 /* copy data to read buffer */
1367 copybytes
= ms_sort_udp_packet(c
, buf
, len
);
1370 if (copybytes
== -1) {
1371 atomic_add_size(&ms_stats
.pkt_disorder
, 1);
1378 * read from network as much as we can, handle buffer overflow and connection
1380 * before reading, move the remaining incomplete fragment of a command
1381 * (if any) to the beginning of the buffer.
1382 * return EXIT_SUCCESS if there's nothing to read on the first read.
1386 * read from network as much as we can, handle buffer overflow and connection
1387 * close. before reading, move the remaining incomplete fragment of a command
1388 * (if any) to the beginning of the buffer.
1390 * @param c, pointer of the concurrency
1393 * return EXIT_SUCCESS if there's nothing to read on the first read.
1394 * return EXIT_FAILURE if get data
1395 * return -1 if error happens
1397 static int ms_try_read_network(ms_conn_t
*c
) {
1404 if ((c
->rcurr
!= c
->rbuf
)
1405 && (!c
->readval
|| (c
->rvbytes
> c
->rsize
- (c
->rcurr
- c
->rbuf
))
1406 || (c
->readval
&& (c
->rcurr
- c
->rbuf
> c
->rbytes
))))
1408 if (c
->rbytes
) /* otherwise there's nothing to copy */
1409 memmove(c
->rbuf
, c
->rcurr
, (size_t) c
->rbytes
);
1414 if (c
->rbytes
>= c
->rsize
) {
1415 char *new_rbuf
= realloc(c
->rbuf
, (size_t) c
->rsize
* 2);
1417 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1418 c
->rbytes
= 0; /* ignore what we read */
1421 c
->rcurr
= c
->rbuf
= new_rbuf
;
1425 avail
= c
->rsize
- c
->rbytes
- (c
->rcurr
- c
->rbuf
);
1431 res
= (int32_t) ms_udp_read(c
, c
->rcurr
+ c
->rbytes
, (int32_t) avail
);
1433 res
= (int) read(c
->sfd
, c
->rcurr
+ c
->rbytes
, (size_t) avail
);
1438 atomic_add_size(&ms_stats
.bytes_read
, res
);
1449 /* connection closed */
1450 ms_conn_set_state(c
, conn_closing
);
1454 if ((errno
== EAGAIN
) || (EAGAIN
!= EWOULDBLOCK
&& errno
== EWOULDBLOCK
))
1456 /* Should close on unhandled errors. */
1457 ms_conn_set_state(c
, conn_closing
);
1463 } /* ms_try_read_network */
1466 * after get the object from server, verify the value if
1469 * @param c, pointer of the concurrency
1470 * @param mlget_item, pointer of mulit-get task item structure
1471 * @param value, received value string
1472 * @param vlen, received value string length
1474 static void ms_verify_value(ms_conn_t
*c
, ms_mlget_task_item_t
*mlget_item
, char *value
, int vlen
) {
1475 if (c
->curr_task
.verify
) {
1476 assert(c
->curr_task
.item
->value_offset
!= INVALID_OFFSET
);
1477 char *orignval
= &ms_setting
.char_block
[c
->curr_task
.item
->value_offset
];
1478 char *orignkey
= &ms_setting
.char_block
[c
->curr_task
.item
->key_suffix_offset
];
1480 /* verify expire time if necessary */
1481 if (c
->curr_task
.item
->exp_time
> 0) {
1482 struct timeval curr_time
;
1483 gettimeofday(&curr_time
, NULL
);
1485 /* object expired but get it now */
1486 if (curr_time
.tv_sec
- c
->curr_task
.item
->client_time
1487 > c
->curr_task
.item
->exp_time
+ EXPIRE_TIME_ERROR
)
1489 atomic_add_size(&ms_stats
.exp_get
, 1);
1491 if (ms_setting
.verbose
) {
1494 strftime(set_time
, 64, "%Y-%m-%d %H:%M:%S", localtime(&c
->curr_task
.item
->client_time
));
1495 strftime(cur_time
, 64, "%Y-%m-%d %H:%M:%S", localtime(&curr_time
.tv_sec
));
1497 "\n<%d expire time verification failed, "
1498 "object expired but get it now\n"
1500 "\tkey: %" PRIx64
" %.*s\n"
1501 "\tset time: %s current time: %s "
1502 "diff time: %d expire time: %d\n"
1503 "\texpected data: \n"
1504 "\treceived data len: %d\n"
1505 "\treceived data: %.*s\n",
1506 c
->sfd
, c
->curr_task
.item
->key_size
, c
->curr_task
.item
->key_prefix
,
1507 c
->curr_task
.item
->key_size
- (int) KEY_PREFIX_SIZE
, orignkey
, set_time
, cur_time
,
1508 (int) (curr_time
.tv_sec
- c
->curr_task
.item
->client_time
),
1509 c
->curr_task
.item
->exp_time
, vlen
, vlen
, value
);
1514 if ((c
->curr_task
.item
->value_size
!= vlen
) || (memcmp(orignval
, value
, (size_t) vlen
)))
1516 atomic_add_size(&ms_stats
.vef_failed
, 1);
1518 if (ms_setting
.verbose
) {
1520 "\n<%d data verification failed\n"
1522 "\tkey: %" PRIx64
" %.*s\n"
1523 "\texpected data len: %d\n"
1524 "\texpected data: %.*s\n"
1525 "\treceived data len: %d\n"
1526 "\treceived data: %.*s\n",
1527 c
->sfd
, c
->curr_task
.item
->key_size
, c
->curr_task
.item
->key_prefix
,
1528 c
->curr_task
.item
->key_size
- (int) KEY_PREFIX_SIZE
, orignkey
,
1529 c
->curr_task
.item
->value_size
, c
->curr_task
.item
->value_size
, orignval
, vlen
,
1536 c
->curr_task
.finish_verify
= true;
1539 mlget_item
->finish_verify
= true;
1542 } /* ms_verify_value */
1545 * For ASCII protocol, after store the data into the local
1546 * buffer, run this function to handle the data.
1548 * @param c, pointer of the concurrency
1550 static void ms_ascii_complete_nread(ms_conn_t
*c
) {
1552 assert(c
->rbytes
>= c
->rvbytes
);
1553 assert(c
->protocol
== ascii_prot
);
1554 if (c
->rvbytes
> 2) {
1555 assert(c
->rcurr
[c
->rvbytes
- 1] == '\n' && c
->rcurr
[c
->rvbytes
- 2] == '\r');
1559 ms_mlget_task_item_t
*mlget_item
= NULL
;
1560 if (((ms_setting
.mult_key_num
> 1) && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1561 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1563 c
->mlget_task
.value_index
++;
1564 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1566 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
) {
1567 c
->curr_task
.item
= mlget_item
->item
;
1568 c
->curr_task
.verify
= mlget_item
->verify
;
1569 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1570 mlget_item
->get_miss
= false;
1572 /* Try to find the task item in multi-get task array */
1573 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++) {
1574 mlget_item
= &c
->mlget_task
.mlget_item
[i
];
1575 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
) {
1576 c
->curr_task
.item
= mlget_item
->item
;
1577 c
->curr_task
.verify
= mlget_item
->verify
;
1578 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1579 mlget_item
->get_miss
= false;
1587 ms_verify_value(c
, mlget_item
, c
->rcurr
, c
->rvbytes
- 2);
1589 c
->curr_task
.get_miss
= false;
1590 c
->rbytes
-= c
->rvbytes
;
1591 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1592 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1595 } /* ms_ascii_complete_nread */
1598 * For binary protocol, after store the data into the local
1599 * buffer, run this function to handle the data.
1601 * @param c, pointer of the concurrency
1603 static void ms_bin_complete_nread(ms_conn_t
*c
) {
1605 assert(c
->rbytes
>= c
->rvbytes
);
1606 assert(c
->protocol
== binary_prot
);
1608 int extlen
= c
->binary_header
.response
.extlen
;
1609 int keylen
= c
->binary_header
.response
.keylen
;
1610 uint8_t opcode
= c
->binary_header
.response
.opcode
;
1612 /* not get command or not include value, just return */
1613 if (((opcode
!= PROTOCOL_BINARY_CMD_GET
) && (opcode
!= PROTOCOL_BINARY_CMD_GETQ
))
1614 || (c
->rvbytes
<= extlen
+ keylen
))
1617 if (c
->binary_header
.response
.opcode
== PROTOCOL_BINARY_CMD_GET
) {
1618 c
->currcmd
.retstat
= MCD_END
;
1619 c
->curr_task
.get_miss
= true;
1624 ms_reset_conn(c
, false);
1629 ms_mlget_task_item_t
*mlget_item
= NULL
;
1630 if (((ms_setting
.mult_key_num
> 1) && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1631 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1633 c
->mlget_task
.value_index
++;
1634 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1636 c
->curr_task
.item
= mlget_item
->item
;
1637 c
->curr_task
.verify
= mlget_item
->verify
;
1638 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1639 mlget_item
->get_miss
= false;
1642 ms_verify_value(c
, mlget_item
, c
->rcurr
+ extlen
+ keylen
, c
->rvbytes
- extlen
- keylen
);
1644 c
->currcmd
.retstat
= MCD_END
;
1645 c
->curr_task
.get_miss
= false;
1646 c
->rbytes
-= c
->rvbytes
;
1647 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1648 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1652 if (ms_setting
.mult_key_num
> 1) {
1653 /* multi-get have check all the item */
1654 if (c
->mlget_task
.value_index
== c
->mlget_task
.mlget_num
- 1) {
1655 ms_reset_conn(c
, false);
1659 ms_reset_conn(c
, false);
1661 } /* ms_bin_complete_nread */
1664 * we get here after reading the value of get commands.
1666 * @param c, pointer of the concurrency
1668 static void ms_complete_nread(ms_conn_t
*c
) {
1670 assert(c
->rbytes
>= c
->rvbytes
);
1671 assert(c
->protocol
== ascii_prot
|| c
->protocol
== binary_prot
);
1673 if (c
->protocol
== binary_prot
) {
1674 ms_bin_complete_nread(c
);
1676 ms_ascii_complete_nread(c
);
1678 } /* ms_complete_nread */
1681 * Adds a message header to a connection.
1683 * @param c, pointer of the concurrency
1685 * @return int, if success, return EXIT_SUCCESS, else return -1
1687 static int ms_add_msghdr(ms_conn_t
*c
) {
1692 if (c
->msgsize
== c
->msgused
) {
1693 msg
= realloc(c
->msglist
, (size_t) c
->msgsize
* 2 * sizeof(struct msghdr
));
1701 msg
= c
->msglist
+ c
->msgused
;
1704 * this wipes msg_iovlen, msg_control, msg_controllen, and
1705 * msg_flags, the last 3 of which aren't defined on solaris:
1707 memset(msg
, 0, sizeof(struct msghdr
));
1709 msg
->msg_iov
= &c
->iov
[c
->iovused
];
1711 if (c
->udp
&& (c
->srv_recv_addr_size
> 0)) {
1712 msg
->msg_name
= &c
->srv_recv_addr
;
1713 msg
->msg_namelen
= c
->srv_recv_addr_size
;
1720 /* Leave room for the UDP header, which we'll fill in later. */
1721 return ms_add_iov(c
, NULL
, UDP_HEADER_SIZE
);
1724 return EXIT_SUCCESS
;
1725 } /* ms_add_msghdr */
1728 * Ensures that there is room for another structure iovec in a connection's
1731 * @param c, pointer of the concurrency
1733 * @return int, if success, return EXIT_SUCCESS, else return -1
1735 static int ms_ensure_iov_space(ms_conn_t
*c
) {
1738 if (c
->iovused
>= c
->iovsize
) {
1740 struct iovec
*new_iov
=
1741 (struct iovec
*) realloc(c
->iov
, ((size_t) c
->iovsize
* 2) * sizeof(struct iovec
));
1748 /* Point all the msghdr structures at the new list. */
1749 for (i
= 0, iovnum
= 0; i
< c
->msgused
; i
++) {
1750 c
->msglist
[i
].msg_iov
= &c
->iov
[iovnum
];
1751 iovnum
+= (int) c
->msglist
[i
].msg_iovlen
;
1755 return EXIT_SUCCESS
;
1756 } /* ms_ensure_iov_space */
1759 * Adds data to the list of pending data that will be written out to a
1762 * @param c, pointer of the concurrency
1763 * @param buf, the buffer includes data to send
1764 * @param len, the data length in the buffer
1766 * @return int, if success, return EXIT_SUCCESS, else return -1
1768 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
) {
1776 m
= &c
->msglist
[c
->msgused
- 1];
1779 * Limit UDP packets, to UDP_MAX_PAYLOAD_SIZE bytes.
1781 limit_to_mtu
= c
->udp
;
1784 /* We may need to start a new msghdr if this one is full. */
1785 if ((m
->msg_iovlen
== IOV_MAX
) || (limit_to_mtu
&& (c
->msgbytes
>= UDP_MAX_SEND_PAYLOAD_SIZE
)))
1788 m
= &c
->msglist
[c
->msgused
- 1];
1792 if (ms_ensure_iov_space(c
))
1795 /* If the fragment is too big to fit in the datagram, split it up */
1796 if (limit_to_mtu
&& (len
+ c
->msgbytes
> UDP_MAX_SEND_PAYLOAD_SIZE
)) {
1797 leftover
= len
+ c
->msgbytes
- UDP_MAX_SEND_PAYLOAD_SIZE
;
1803 m
= &c
->msglist
[c
->msgused
- 1];
1804 m
->msg_iov
[m
->msg_iovlen
].iov_base
= (void *) buf
;
1805 m
->msg_iov
[m
->msg_iovlen
].iov_len
= (size_t) len
;
1811 buf
= ((char *) buf
) + len
;
1813 } while (leftover
> 0);
1815 return EXIT_SUCCESS
;
1819 * Constructs a set of UDP headers and attaches them to the outgoing messages.
1821 * @param c, pointer of the concurrency
1823 * @return int, if success, return EXIT_SUCCESS, else return -1
1825 static int ms_build_udp_headers(ms_conn_t
*c
) {
1831 c
->request_id
= ms_get_udp_request_id();
1833 if (c
->msgused
> c
->hdrsize
) {
1836 new_hdrbuf
= realloc(c
->hdrbuf
, (size_t) c
->msgused
* 2 * UDP_HEADER_SIZE
);
1838 new_hdrbuf
= malloc((size_t) c
->msgused
* 2 * UDP_HEADER_SIZE
);
1842 c
->hdrbuf
= (unsigned char *) new_hdrbuf
;
1843 c
->hdrsize
= c
->msgused
* 2;
1846 /* If this is a multi-packet request, drop it. */
1847 if (c
->udp
&& (c
->msgused
> 1)) {
1848 fprintf(stderr
, "multi-packet request for UDP not supported.\n");
1853 for (i
= 0; i
< c
->msgused
; i
++) {
1854 c
->msglist
[i
].msg_iov
[0].iov_base
= (void *) hdr
;
1855 c
->msglist
[i
].msg_iov
[0].iov_len
= UDP_HEADER_SIZE
;
1856 *hdr
++ = (unsigned char) (c
->request_id
/ 256);
1857 *hdr
++ = (unsigned char) (c
->request_id
% 256);
1858 *hdr
++ = (unsigned char) (i
/ 256);
1859 *hdr
++ = (unsigned char) (i
% 256);
1860 *hdr
++ = (unsigned char) (c
->msgused
/ 256);
1861 *hdr
++ = (unsigned char) (c
->msgused
% 256);
1862 *hdr
++ = (unsigned char) 1; /* support facebook memcached */
1863 *hdr
++ = (unsigned char) 0;
1864 assert(hdr
== ((unsigned char *) c
->msglist
[i
].msg_iov
[0].iov_base
+ UDP_HEADER_SIZE
));
1867 return EXIT_SUCCESS
;
1868 } /* ms_build_udp_headers */
1871 * Transmit the next chunk of data from our list of msgbuf structures.
1873 * @param c, pointer of the concurrency
1875 * @return TRANSMIT_COMPLETE All done writing.
1876 * TRANSMIT_INCOMPLETE More data remaining to write.
1877 * TRANSMIT_SOFT_ERROR Can't write any more right now.
1878 * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
1880 static int ms_transmit(ms_conn_t
*c
) {
1883 if ((c
->msgcurr
< c
->msgused
) && (c
->msglist
[c
->msgcurr
].msg_iovlen
== 0)) {
1884 /* Finished writing the current msg; advance to the next. */
1888 if (c
->msgcurr
< c
->msgused
) {
1890 struct msghdr
*m
= &c
->msglist
[c
->msgcurr
];
1892 res
= sendmsg(c
->sfd
, m
, 0);
1894 atomic_add_size(&ms_stats
.bytes_written
, res
);
1896 /* We've written some of the data. Remove the completed
1897 * iovec entries from the list of pending writes. */
1898 while (m
->msg_iovlen
> 0 && res
>= (ssize_t
) m
->msg_iov
->iov_len
) {
1899 res
-= (ssize_t
) m
->msg_iov
->iov_len
;
1904 /* Might have written just part of the last iovec entry;
1905 * adjust it so the next write will do the rest. */
1907 m
->msg_iov
->iov_base
= (void *) ((unsigned char *) m
->msg_iov
->iov_base
+ res
);
1908 m
->msg_iov
->iov_len
-= (size_t) res
;
1910 return TRANSMIT_INCOMPLETE
;
1912 if ((res
== -1) && ((errno
== EAGAIN
) || (EAGAIN
!= EWOULDBLOCK
&& errno
== EWOULDBLOCK
))) {
1913 if (!ms_update_event(c
, EV_WRITE
| EV_PERSIST
)) {
1914 fprintf(stderr
, "Couldn't update event.\n");
1915 ms_conn_set_state(c
, conn_closing
);
1916 return TRANSMIT_HARD_ERROR
;
1918 return TRANSMIT_SOFT_ERROR
;
1921 /* if res==0 or res==-1 and error is not EAGAIN or EWOULDBLOCK,
1922 * we have a real error, on which we close the connection */
1923 fprintf(stderr
, "Failed to write, and not due to blocking.\n");
1925 ms_conn_set_state(c
, conn_closing
);
1926 return TRANSMIT_HARD_ERROR
;
1928 return TRANSMIT_COMPLETE
;
1933 * Shrinks a connection's buffers if they're too big. This prevents
1934 * periodic large "mget" response from server chewing lots of client
1937 * This should only be called in between requests since it can wipe output
1940 * @param c, pointer of the concurrency
1942 static void ms_conn_shrink(ms_conn_t
*c
) {
1948 if ((c
->rsize
> READ_BUFFER_HIGHWAT
) && (c
->rbytes
< DATA_BUFFER_SIZE
)) {
1951 if (c
->rcurr
!= c
->rbuf
)
1952 memmove(c
->rbuf
, c
->rcurr
, (size_t) c
->rbytes
);
1954 newbuf
= (char *) realloc((void *) c
->rbuf
, DATA_BUFFER_SIZE
);
1958 c
->rsize
= DATA_BUFFER_SIZE
;
1963 if (c
->udp
&& (c
->rudpsize
> UDP_DATA_BUFFER_HIGHWAT
)
1964 && (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
< UDP_DATA_BUFFER_SIZE
))
1966 char *new_rbuf
= (char *) realloc(c
->rudpbuf
, (size_t) c
->rudpsize
* 2);
1968 c
->rudpbuf
= new_rbuf
;
1969 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
1971 /* TODO check error condition? */
1974 if (c
->msgsize
> MSG_LIST_HIGHWAT
) {
1975 struct msghdr
*newbuf
=
1976 (struct msghdr
*) realloc((void *) c
->msglist
, MSG_LIST_INITIAL
* sizeof(c
->msglist
[0]));
1978 c
->msglist
= newbuf
;
1979 c
->msgsize
= MSG_LIST_INITIAL
;
1981 /* TODO check error condition? */
1984 if (c
->iovsize
> IOV_LIST_HIGHWAT
) {
1985 struct iovec
*newbuf
=
1986 (struct iovec
*) realloc((void *) c
->iov
, IOV_LIST_INITIAL
* sizeof(c
->iov
[0]));
1989 c
->iovsize
= IOV_LIST_INITIAL
;
1991 /* TODO check return value */
1993 } /* ms_conn_shrink */
1996 * Sets a connection's current state in the state machine. Any special
1997 * processing that needs to happen on certain state transitions can
2000 * @param c, pointer of the concurrency
2001 * @param state, connection state
2003 static void ms_conn_set_state(ms_conn_t
*c
, int state
) {
2006 if (state
!= c
->state
) {
2007 if (state
== conn_read
) {
2012 } /* ms_conn_set_state */
2015 * update the event if socks change state. for example: when
2016 * change the listen scoket read event to sock write event, or
2017 * change socket handler, we could call this function.
2019 * @param c, pointer of the concurrency
2020 * @param new_flags, new event flags
2022 * @return bool, if success, return true, else return false
2024 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
) {
2027 struct event_base
*base
= c
->event
.ev_base
;
2028 if ((c
->ev_flags
== new_flags
) && (ms_setting
.rep_write_srv
== 0)
2029 && (!ms_setting
.facebook_test
|| (c
->total_sfds
== 1)))
2034 if (event_del(&c
->event
) == -1) {
2035 /* try to delete the event again */
2036 if (event_del(&c
->event
) == -1) {
2041 event_set(&c
->event
, c
->sfd
, (short) new_flags
, ms_event_handler
, (void *) c
);
2042 event_base_set(base
, &c
->event
);
2043 c
->ev_flags
= (short) new_flags
;
2045 if (event_add(&c
->event
, NULL
) == -1) {
2050 } /* ms_update_event */
2053 * If user want to get the expected throughput, we could limit
2054 * the performance of memslap. we could give up some work and
2055 * just wait a short time. The function is used to check this
2058 * @param c, pointer of the concurrency
2060 * @return bool, if success, return true, else return false
2062 static bool ms_need_yield(ms_conn_t
*c
) {
2063 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
2065 int64_t time_diff
= 0;
2066 struct timeval curr_time
;
2067 ms_task_t
*task
= &c
->curr_task
;
2069 if (ms_setting
.expected_tps
> 0) {
2070 gettimeofday(&curr_time
, NULL
);
2071 time_diff
= ms_time_diff(&ms_thread
->startup_time
, &curr_time
);
2072 tps
= (int64_t)(((task
->get_opt
+ task
->set_opt
) / (uint64_t) time_diff
) * 1000000);
2074 /* current throughput is greater than expected throughput */
2075 if (tps
> ms_thread
->thread_ctx
->tps_perconn
) {
2081 } /* ms_need_yield */
2084 * used to update the start time of each operation
2086 * @param c, pointer of the concurrency
2088 static void ms_update_start_time(ms_conn_t
*c
) {
2089 ms_task_item_t
*item
= c
->curr_task
.item
;
2091 if ((ms_setting
.stat_freq
> 0) || c
->udp
|| ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0)))
2093 gettimeofday(&c
->start_time
, NULL
);
2094 if ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0)) {
2095 /* record the current time */
2096 item
->client_time
= c
->start_time
.tv_sec
;
2099 } /* ms_update_start_time */
2102 * run the state machine
2104 * @param c, pointer of the concurrency
2106 static void ms_drive_machine(ms_conn_t
*c
) {
2115 if (c
->rbytes
>= c
->rvbytes
) {
2116 ms_complete_nread(c
);
2120 if (ms_try_read_line(c
)) {
2125 if (ms_try_read_network(c
)) {
2129 /* doesn't read all the response data, wait event wake up */
2130 if (!c
->currcmd
.isfinish
) {
2131 if (!ms_update_event(c
, EV_READ
| EV_PERSIST
)) {
2132 fprintf(stderr
, "Couldn't update event.\n");
2133 ms_conn_set_state(c
, conn_closing
);
2140 /* we have no command line and no data to read from network, next write */
2141 ms_conn_set_state(c
, conn_write
);
2142 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
2147 if (!c
->ctnwrite
&& ms_need_yield(c
)) {
2150 if (!ms_update_event(c
, EV_WRITE
| EV_PERSIST
)) {
2151 fprintf(stderr
, "Couldn't update event.\n");
2152 ms_conn_set_state(c
, conn_closing
);
2159 if (!c
->ctnwrite
&& (ms_exec_task(c
))) {
2160 ms_conn_set_state(c
, conn_closing
);
2164 /* record the start time before starting to send data if necessary */
2165 if (!c
->ctnwrite
|| (c
->change_sfd
&& c
->ctnwrite
)) {
2166 if (c
->change_sfd
) {
2167 c
->change_sfd
= false;
2169 ms_update_start_time(c
);
2172 /* change sfd if necessary */
2173 if (c
->change_sfd
) {
2179 /* execute task until nothing need be written to network */
2180 if (!c
->ctnwrite
&& (c
->msgcurr
== c
->msgused
)) {
2181 if (!ms_update_event(c
, EV_WRITE
| EV_PERSIST
)) {
2182 fprintf(stderr
, "Couldn't update event.\n");
2183 ms_conn_set_state(c
, conn_closing
);
2190 switch (ms_transmit(c
)) {
2191 case TRANSMIT_COMPLETE
:
2192 /* we have no data to write to network, next wait repose */
2193 if (!ms_update_event(c
, EV_READ
| EV_PERSIST
)) {
2194 fprintf(stderr
, "Couldn't update event.\n");
2195 ms_conn_set_state(c
, conn_closing
);
2196 c
->ctnwrite
= false;
2199 ms_conn_set_state(c
, conn_read
);
2200 c
->ctnwrite
= false;
2204 case TRANSMIT_INCOMPLETE
:
2206 break; /* Continue in state machine. */
2208 case TRANSMIT_HARD_ERROR
:
2209 c
->ctnwrite
= false;
2212 case TRANSMIT_SOFT_ERROR
:
2224 /* recovery mode, need reconnect if connection close */
2225 if (ms_setting
.reconnect
2226 && (!ms_global
.time_out
|| ((ms_setting
.run_time
== 0) && (c
->remain_exec_num
> 0))))
2234 ms_reset_conn(c
, false);
2236 if (c
->total_sfds
== 1) {
2237 if (!ms_update_event(c
, EV_WRITE
| EV_PERSIST
)) {
2238 fprintf(stderr
, "Couldn't update event.\n");
2239 ms_conn_set_state(c
, conn_closing
);
2255 } /* ms_drive_machine */
2258 * the event handler of each thread
2260 * @param fd, the file descriptor of socket
2261 * @param which, event flag
2262 * @param arg, argument
2264 void ms_event_handler(const int fd
, const short which
, void *arg
) {
2265 ms_conn_t
*c
= (ms_conn_t
*) arg
;
2273 fprintf(stderr
, "Catastrophic: event fd: %d doesn't match conn fd: %d\n", fd
, c
->sfd
);
2277 assert(fd
== c
->sfd
);
2279 ms_drive_machine(c
);
2281 /* wait for next event */
2282 } /* ms_event_handler */
2285 * get the next socket descriptor index to run for replication
2287 * @param c, pointer of the concurrency
2288 * @param cmd, command(get or set )
2290 * @return int, if success, return the index, else return EXIT_SUCCESS
2292 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
) {
2293 uint32_t sock_index
= 0;
2296 if (c
->total_sfds
== 1) {
2297 return EXIT_SUCCESS
;
2300 if (ms_setting
.rep_write_srv
== 0) {
2305 if (cmd
== CMD_SET
) {
2306 for (i
= 0; i
< ms_setting
.rep_write_srv
; i
++) {
2307 if (c
->tcpsfd
[i
] > 0) {
2312 if (i
== ms_setting
.rep_write_srv
) {
2313 /* random get one replication server to read */
2314 sock_index
= (uint32_t) random() % c
->total_sfds
;
2316 /* random get one replication writing server to write */
2317 sock_index
= (uint32_t) random() % ms_setting
.rep_write_srv
;
2319 } else if (cmd
== CMD_GET
) {
2320 /* random get one replication server to read */
2321 sock_index
= (uint32_t) random() % c
->total_sfds
;
2323 } while (c
->tcpsfd
[sock_index
] == 0);
2326 } /* ms_get_rep_sock_index */
2329 * get the next socket descriptor index to run
2331 * @param c, pointer of the concurrency
2333 * @return int, return the index
2335 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
) {
2336 uint32_t sock_index
= 0;
2339 sock_index
= (++c
->cur_idx
== c
->total_sfds
) ? 0 : c
->cur_idx
;
2340 } while (c
->tcpsfd
[sock_index
] == 0);
2343 } /* ms_get_next_sock_index */
2346 * update socket event of the connections
2348 * @param c, pointer of the concurrency
2350 * @return int, if success, return EXIT_SUCCESS, else return -1
2352 static int ms_update_conn_sock_event(ms_conn_t
*c
) {
2355 switch (c
->currcmd
.cmd
) {
2357 if (ms_setting
.facebook_test
&& c
->udp
) {
2358 c
->sfd
= c
->tcpsfd
[0];
2360 c
->change_sfd
= true;
2365 if (ms_setting
.facebook_test
&& !c
->udp
) {
2368 c
->change_sfd
= true;
2376 if (!c
->udp
&& (c
->total_sfds
> 1)) {
2377 if (c
->cur_idx
!= c
->total_sfds
) {
2378 if (ms_setting
.rep_write_srv
== 0) {
2379 c
->cur_idx
= ms_get_next_sock_index(c
);
2381 c
->cur_idx
= ms_get_rep_sock_index(c
, c
->currcmd
.cmd
);
2384 /* must select the first sock of the connection at the beginning */
2388 c
->sfd
= c
->tcpsfd
[c
->cur_idx
];
2390 c
->change_sfd
= true;
2393 if (c
->change_sfd
) {
2394 if (!ms_update_event(c
, EV_WRITE
| EV_PERSIST
)) {
2395 fprintf(stderr
, "Couldn't update event.\n");
2396 ms_conn_set_state(c
, conn_closing
);
2401 return EXIT_SUCCESS
;
2402 } /* ms_update_conn_sock_event */
2405 * for ASCII protocol, this function build the set command
2406 * string and send the command.
2408 * @param c, pointer of the concurrency
2409 * @param item, pointer of task item which includes the object
2412 * @return int, if success, return EXIT_SUCCESS, else return -1
2414 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
) {
2417 char *buffer
= c
->wbuf
;
2419 write_len
= snprintf(buffer
, c
->wsize
, " %u %d %d\r\n", 0, item
->exp_time
, item
->value_size
);
2421 if (write_len
> c
->wsize
|| write_len
< 0) {
2422 /* ought to be always enough. just fail for simplicity */
2423 fprintf(stderr
, "output command line too long.\n");
2427 if (item
->value_offset
== INVALID_OFFSET
) {
2428 value_offset
= item
->key_suffix_offset
;
2430 value_offset
= item
->value_offset
;
2433 if ((ms_add_iov(c
, "set ", 4))
2434 || (ms_add_iov(c
, (char *) &item
->key_prefix
, (int) KEY_PREFIX_SIZE
))
2435 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
2436 item
->key_size
- (int) KEY_PREFIX_SIZE
)
2438 || (ms_add_iov(c
, buffer
, write_len
))
2439 || (ms_add_iov(c
, &ms_setting
.char_block
[value_offset
], item
->value_size
))
2440 || (ms_add_iov(c
, "\r\n", 2)) || (c
->udp
&& (ms_build_udp_headers(c
))))
2445 return EXIT_SUCCESS
;
2446 } /* ms_build_ascii_write_buf_set */
2449 * used to send set command to server
2451 * @param c, pointer of the concurrency
2452 * @param item, pointer of task item which includes the object
2455 * @return int, if success, return EXIT_SUCCESS, else return -1
2457 int ms_mcd_set(ms_conn_t
*c
, ms_task_item_t
*item
) {
2460 c
->currcmd
.cmd
= CMD_SET
;
2461 c
->currcmd
.isfinish
= false;
2462 c
->currcmd
.retstat
= MCD_FAILURE
;
2464 if (ms_update_conn_sock_event(c
)) {
2471 if (ms_add_msghdr(c
)) {
2472 fprintf(stderr
, "Out of memory preparing request.");
2476 /* binary protocol */
2477 if (c
->protocol
== binary_prot
) {
2478 if (ms_build_bin_write_buf_set(c
, item
)) {
2482 if (ms_build_ascii_write_buf_set(c
, item
)) {
2487 atomic_add_size(&ms_stats
.obj_bytes
, item
->key_size
+ item
->value_size
);
2488 atomic_add_size(&ms_stats
.cmd_set
, 1);
2490 return EXIT_SUCCESS
;
2494 * for ASCII protocol, this function build the get command
2495 * string and send the command.
2497 * @param c, pointer of the concurrency
2498 * @param item, pointer of task item which includes the object
2501 * @return int, if success, return EXIT_SUCCESS, else return -1
2503 static int ms_build_ascii_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
) {
2504 if ((ms_add_iov(c
, "get ", 4))
2505 || (ms_add_iov(c
, (char *) &item
->key_prefix
, (int) KEY_PREFIX_SIZE
))
2506 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
2507 item
->key_size
- (int) KEY_PREFIX_SIZE
)
2509 || (ms_add_iov(c
, "\r\n", 2)) || (c
->udp
&& (ms_build_udp_headers(c
))))
2514 return EXIT_SUCCESS
;
2515 } /* ms_build_ascii_write_buf_get */
2518 * used to send the get command to server
2520 * @param c, pointer of the concurrency
2521 * @param item, pointer of task item which includes the object
2524 * @return int, if success, return EXIT_SUCCESS, else return -1
2526 int ms_mcd_get(ms_conn_t
*c
, ms_task_item_t
*item
) {
2529 c
->currcmd
.cmd
= CMD_GET
;
2530 c
->currcmd
.isfinish
= false;
2531 c
->currcmd
.retstat
= MCD_FAILURE
;
2533 if (ms_update_conn_sock_event(c
)) {
2540 if (ms_add_msghdr(c
)) {
2541 fprintf(stderr
, "Out of memory preparing request.");
2545 /* binary protocol */
2546 if (c
->protocol
== binary_prot
) {
2547 if (ms_build_bin_write_buf_get(c
, item
)) {
2551 if (ms_build_ascii_write_buf_get(c
, item
)) {
2556 atomic_add_size(&ms_stats
.cmd_get
, 1);
2558 return EXIT_SUCCESS
;
2562 * for ASCII protocol, this function build the multi-get command
2563 * string and send the command.
2565 * @param c, pointer of the concurrency
2567 * @return int, if success, return EXIT_SUCCESS, else return -1
2569 static int ms_build_ascii_write_buf_mlget(ms_conn_t
*c
) {
2570 ms_task_item_t
*item
;
2572 if (ms_add_iov(c
, "get", 3)) {
2576 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++) {
2577 item
= c
->mlget_task
.mlget_item
[i
].item
;
2579 if ((ms_add_iov(c
, " ", 1))
2580 || (ms_add_iov(c
, (char *) &item
->key_prefix
, (int) KEY_PREFIX_SIZE
))
2581 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
2582 item
->key_size
- (int) KEY_PREFIX_SIZE
)
2589 if ((ms_add_iov(c
, "\r\n", 2)) || (c
->udp
&& (ms_build_udp_headers(c
)))) {
2593 return EXIT_SUCCESS
;
2594 } /* ms_build_ascii_write_buf_mlget */
2597 * used to send the multi-get command to server
2599 * @param c, pointer of the concurrency
2601 * @return int, if success, return EXIT_SUCCESS, else return -1
2603 int ms_mcd_mlget(ms_conn_t
*c
) {
2604 ms_task_item_t
*item
;
2607 assert(c
->mlget_task
.mlget_num
>= 1);
2609 c
->currcmd
.cmd
= CMD_GET
;
2610 c
->currcmd
.isfinish
= false;
2611 c
->currcmd
.retstat
= MCD_FAILURE
;
2613 if (ms_update_conn_sock_event(c
)) {
2620 if (ms_add_msghdr(c
)) {
2621 fprintf(stderr
, "Out of memory preparing request.");
2625 /* binary protocol */
2626 if (c
->protocol
== binary_prot
) {
2627 if (ms_build_bin_write_buf_mlget(c
)) {
2631 if (ms_build_ascii_write_buf_mlget(c
)) {
2636 /* decrease operation time of each item */
2637 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++) {
2638 item
= c
->mlget_task
.mlget_item
[i
].item
;
2639 atomic_add_size(&ms_stats
.cmd_get
, 1);
2644 return EXIT_SUCCESS
;
2645 } /* ms_mcd_mlget */
2648 * binary protocol support
2652 * for binary protocol, parse the response of server
2654 * @param c, pointer of the concurrency
2656 * @return int, if success, return EXIT_SUCCESS, else return -1
2658 static int ms_bin_process_response(ms_conn_t
*c
) {
2659 const char *errstr
= NULL
;
2663 uint32_t bodylen
= c
->binary_header
.response
.bodylen
;
2664 uint8_t opcode
= c
->binary_header
.response
.opcode
;
2665 uint16_t status
= c
->binary_header
.response
.status
;
2668 c
->rvbytes
= (int32_t) bodylen
;
2670 return EXIT_FAILURE
;
2673 case PROTOCOL_BINARY_RESPONSE_SUCCESS
:
2674 if (opcode
== PROTOCOL_BINARY_CMD_SET
) {
2675 c
->currcmd
.retstat
= MCD_STORED
;
2676 } else if (opcode
== PROTOCOL_BINARY_CMD_DELETE
) {
2677 c
->currcmd
.retstat
= MCD_DELETED
;
2678 } else if (opcode
== PROTOCOL_BINARY_CMD_GET
) {
2679 c
->currcmd
.retstat
= MCD_END
;
2683 case PROTOCOL_BINARY_RESPONSE_ENOMEM
:
2684 errstr
= "Out of memory";
2685 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
2688 case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND
:
2689 errstr
= "Unknown command";
2690 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
2693 case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT
:
2694 errstr
= "Not found";
2695 c
->currcmd
.retstat
= MCD_NOTFOUND
;
2698 case PROTOCOL_BINARY_RESPONSE_EINVAL
:
2699 errstr
= "Invalid arguments";
2700 c
->currcmd
.retstat
= MCD_PROTOCOL_ERROR
;
2703 case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS
:
2704 errstr
= "Data exists for key.";
2707 case PROTOCOL_BINARY_RESPONSE_E2BIG
:
2708 errstr
= "Too large.";
2709 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
2712 case PROTOCOL_BINARY_RESPONSE_NOT_STORED
:
2713 errstr
= "Not stored.";
2714 c
->currcmd
.retstat
= MCD_NOTSTORED
;
2718 errstr
= "Unknown error";
2719 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
2724 fprintf(stderr
, "%s\n", errstr
);
2728 return EXIT_SUCCESS
;
2729 } /* ms_bin_process_response */
2731 /* build binary header and add the header to the buffer to send */
2734 * build binary header and add the header to the buffer to send
2736 * @param c, pointer of the concurrency
2737 * @param opcode, operation code
2738 * @param hdr_len, length of header
2739 * @param key_len, length of key
2740 * @param body_len. length of body
2742 static void ms_add_bin_header(ms_conn_t
*c
, uint8_t opcode
, uint8_t hdr_len
, uint16_t key_len
,
2743 uint32_t body_len
) {
2744 protocol_binary_request_header
*header
;
2748 header
= (protocol_binary_request_header
*) c
->wcurr
;
2750 header
->request
.magic
= (uint8_t) PROTOCOL_BINARY_REQ
;
2751 header
->request
.opcode
= (uint8_t) opcode
;
2752 header
->request
.keylen
= htons(key_len
);
2754 header
->request
.extlen
= (uint8_t) hdr_len
;
2755 header
->request
.datatype
= (uint8_t) PROTOCOL_BINARY_RAW_BYTES
;
2756 header
->request
.vbucket
= 0;
2758 header
->request
.bodylen
= htonl(body_len
);
2759 header
->request
.opaque
= 0;
2760 header
->request
.cas
= 0;
2762 ms_add_iov(c
, c
->wcurr
, sizeof(header
->request
));
2763 } /* ms_add_bin_header */
2766 * add the key to the socket write buffer array
2768 * @param c, pointer of the concurrency
2769 * @param item, pointer of task item which includes the object
2772 static void ms_add_key_to_iov(ms_conn_t
*c
, ms_task_item_t
*item
) {
2773 ms_add_iov(c
, (char *) &item
->key_prefix
, (int) KEY_PREFIX_SIZE
);
2774 ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
2775 item
->key_size
- (int) KEY_PREFIX_SIZE
);
2779 * for binary protocol, this function build the set command
2780 * and add the command to send buffer array.
2782 * @param c, pointer of the concurrency
2783 * @param item, pointer of task item which includes the object
2786 * @return int, if success, return EXIT_SUCCESS, else return -1
2788 static int ms_build_bin_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
) {
2789 assert(c
->wbuf
== c
->wcurr
);
2792 protocol_binary_request_set
*rep
= (protocol_binary_request_set
*) c
->wcurr
;
2793 uint16_t keylen
= (uint16_t) item
->key_size
;
2795 (uint32_t) sizeof(rep
->message
.body
) + (uint32_t) keylen
+ (uint32_t) item
->value_size
;
2797 ms_add_bin_header(c
, PROTOCOL_BINARY_CMD_SET
, sizeof(rep
->message
.body
), keylen
, bodylen
);
2798 rep
->message
.body
.flags
= 0;
2799 rep
->message
.body
.expiration
= htonl((uint32_t) item
->exp_time
);
2800 ms_add_iov(c
, &rep
->message
.body
, sizeof(rep
->message
.body
));
2801 ms_add_key_to_iov(c
, item
);
2803 if (item
->value_offset
== INVALID_OFFSET
) {
2804 value_offset
= item
->key_suffix_offset
;
2806 value_offset
= item
->value_offset
;
2808 ms_add_iov(c
, &ms_setting
.char_block
[value_offset
], item
->value_size
);
2810 return EXIT_SUCCESS
;
2811 } /* ms_build_bin_write_buf_set */
2814 * for binary protocol, this function build the get command and
2815 * add the command to send buffer array.
2817 * @param c, pointer of the concurrency
2818 * @param item, pointer of task item which includes the object
2821 * @return int, if success, return EXIT_SUCCESS, else return -1
2823 static int ms_build_bin_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
) {
2824 assert(c
->wbuf
== c
->wcurr
);
2826 ms_add_bin_header(c
, PROTOCOL_BINARY_CMD_GET
, 0, (uint16_t) item
->key_size
,
2827 (uint32_t) item
->key_size
);
2828 ms_add_key_to_iov(c
, item
);
2830 return EXIT_SUCCESS
;
2831 } /* ms_build_bin_write_buf_get */
2834 * for binary protocol, this function build the multi-get
2835 * command and add the command to send buffer array.
2837 * @param c, pointer of the concurrency
2838 * @param item, pointer of task item which includes the object
2841 * @return int, if success, return EXIT_SUCCESS, else return -1
2843 static int ms_build_bin_write_buf_mlget(ms_conn_t
*c
) {
2844 ms_task_item_t
*item
;
2846 assert(c
->wbuf
== c
->wcurr
);
2848 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++) {
2849 item
= c
->mlget_task
.mlget_item
[i
].item
;
2852 ms_add_bin_header(c
, PROTOCOL_BINARY_CMD_GET
, 0, (uint16_t) item
->key_size
,
2853 (uint32_t) item
->key_size
);
2854 ms_add_key_to_iov(c
, item
);
2855 c
->wcurr
+= sizeof(protocol_binary_request_get
);
2860 return EXIT_SUCCESS
;
2861 } /* ms_build_bin_write_buf_mlget */