3 * Author: Mingqiang Zhuang
5 * Created on February 10, 2009
7 * (c) Copyright 2009, Schooner Information Technology, Inc.
8 * http://www.schoonerinfotech.com/
20 #include <netinet/tcp.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
23 #if TIME_WITH_SYS_TIME
24 # include <sys/time.h>
28 # include <sys/time.h>
33 #include "ms_setting.h"
34 #include "ms_thread.h"
35 #include "ms_atomic.h"
38 /* /usr/include/netinet/in.h defines macros from ntohs() to _bswap_nn to
39 * optimize the conversion functions, but the prototypes generate warnings
40 * from gcc. The conversion methods isn't the bottleneck for my app, so
41 * just remove the warnings by undef'ing the optimization ..
49 /* for network write */
50 #define TRANSMIT_COMPLETE 0
51 #define TRANSMIT_INCOMPLETE 1
52 #define TRANSMIT_SOFT_ERROR 2
53 #define TRANSMIT_HARD_ERROR 3
55 /* for generating key */
56 #define KEY_PREFIX_BASE 0x1010101010101010 /* not include ' ' '\r' '\n' '\0' */
57 #define KEY_PREFIX_MASK 0x1010101010101010
59 /* For parse the value length return by server */
61 #define VALUELEN_TOKEN 3
63 /* global increasing counter, to ensure the key prefix unique */
64 static uint64_t key_prefix_seq
= KEY_PREFIX_BASE
;
66 /* global increasing counter, generating request id for UDP */
67 static volatile uint32_t udp_request_id
= 0;
69 extern pthread_key_t ms_thread_key
;
71 /* generate upd request id */
72 static uint32_t ms_get_udp_request_id(void);
75 /* connect initialize */
76 static void ms_task_init(ms_conn_t
*c
);
77 static int ms_conn_udp_init(ms_conn_t
*c
, const bool is_udp
);
78 static int ms_conn_sock_init(ms_conn_t
*c
);
79 static int ms_conn_event_init(ms_conn_t
*c
);
80 static int ms_conn_init(ms_conn_t
*c
,
82 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
);
88 /* connection close */
89 void ms_conn_free(ms_conn_t
*c
);
90 static void ms_conn_close(ms_conn_t
*c
);
93 /* create network connection */
94 static int ms_new_socket(struct addrinfo
*ai
);
95 static void ms_maximize_sndbuf(const int sfd
);
96 static int ms_network_connect(ms_conn_t
*c
,
101 static int ms_reconn(ms_conn_t
*c
);
105 static int ms_tokenize_command(char *command
,
107 const int max_tokens
);
108 static int ms_ascii_process_line(ms_conn_t
*c
, char *command
);
109 static int ms_try_read_line(ms_conn_t
*c
);
110 static int ms_sort_udp_packet(ms_conn_t
*c
, char *buf
, int rbytes
);
111 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
);
112 static int ms_try_read_network(ms_conn_t
*c
);
113 static void ms_verify_value(ms_conn_t
*c
,
114 ms_mlget_task_item_t
*mlget_item
,
117 static void ms_ascii_complete_nread(ms_conn_t
*c
);
118 static void ms_bin_complete_nread(ms_conn_t
*c
);
119 static void ms_complete_nread(ms_conn_t
*c
);
123 static int ms_add_msghdr(ms_conn_t
*c
);
124 static int ms_ensure_iov_space(ms_conn_t
*c
);
125 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
);
126 static int ms_build_udp_headers(ms_conn_t
*c
);
127 static int ms_transmit(ms_conn_t
*c
);
130 /* status adjustment */
131 static void ms_conn_shrink(ms_conn_t
*c
);
132 static void ms_conn_set_state(ms_conn_t
*c
, int state
);
133 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
);
134 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
);
135 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
);
136 static int ms_update_conn_sock_event(ms_conn_t
*c
);
137 static bool ms_need_yield(ms_conn_t
*c
);
138 static void ms_update_start_time(ms_conn_t
*c
);
142 static void ms_drive_machine(ms_conn_t
*c
);
143 void ms_event_handler(const int fd
, const short which
, void *arg
);
147 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
);
148 static int ms_build_ascii_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
);
149 static int ms_build_ascii_write_buf_mlget(ms_conn_t
*c
);
152 /* binary protocol */
153 static int ms_bin_process_response(ms_conn_t
*c
);
154 static void ms_add_bin_header(ms_conn_t
*c
,
159 static void ms_add_key_to_iov(ms_conn_t
*c
, ms_task_item_t
*item
);
160 static int ms_build_bin_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
);
161 static int ms_build_bin_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
);
162 static int ms_build_bin_write_buf_mlget(ms_conn_t
*c
);
166 * each key has two parts, prefix and suffix. The suffix is a
167 * string random get form the character table. The prefix is a
168 * uint64_t variable. And the prefix must be unique. we use the
169 * prefix to identify a key. And the prefix can't include
170 * character ' ' '\r' '\n' '\0'.
174 uint64_t ms_get_key_prefix(void)
178 pthread_mutex_lock(&ms_global
.seq_mutex
);
179 key_prefix_seq
|= KEY_PREFIX_MASK
;
180 key_prefix
= key_prefix_seq
;
182 pthread_mutex_unlock(&ms_global
.seq_mutex
);
185 } /* ms_get_key_prefix */
189 * get an unique udp request id
191 * @return an unique UDP request id
193 static uint32_t ms_get_udp_request_id(void)
195 return atomic_add_32_nv(&udp_request_id
, 1);
200 * initialize current task structure
202 * @param c, pointer of the concurrency
204 static void ms_task_init(ms_conn_t
*c
)
206 c
->curr_task
.cmd
= CMD_NULL
;
207 c
->curr_task
.item
= 0;
208 c
->curr_task
.verify
= false;
209 c
->curr_task
.finish_verify
= true;
210 c
->curr_task
.get_miss
= true;
212 c
->curr_task
.get_opt
= 0;
213 c
->curr_task
.set_opt
= 0;
214 c
->curr_task
.cycle_undo_get
= 0;
215 c
->curr_task
.cycle_undo_set
= 0;
216 c
->curr_task
.verified_get
= 0;
217 c
->curr_task
.overwrite_set
= 0;
222 * initialize udp for the connection structure
224 * @param c, pointer of the concurrency
225 * @param is_udp, whether it's udp
227 * @return int, if success, return EXIT_SUCCESS, else return -1
229 static int ms_conn_udp_init(ms_conn_t
*c
, const bool is_udp
)
235 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
246 if (c
->udp
|| (! c
->udp
&& ms_setting
.facebook_test
))
248 c
->rudpbuf
= (char *)malloc((size_t)c
->rudpsize
);
249 c
->udppkt
= (ms_udppkt_t
*)malloc(MAX_UDP_PACKET
* sizeof(ms_udppkt_t
));
251 if ((c
->rudpbuf
== NULL
) || (c
->udppkt
== NULL
))
253 if (c
->rudpbuf
!= NULL
)
255 if (c
->udppkt
!= NULL
)
257 fprintf(stderr
, "malloc()\n");
260 memset(c
->udppkt
, 0, MAX_UDP_PACKET
* sizeof(ms_udppkt_t
));
264 } /* ms_conn_udp_init */
268 * initialize the connection structure
270 * @param c, pointer of the concurrency
271 * @param init_state, (conn_read, conn_write, conn_closing)
272 * @param read_buffer_size
273 * @param is_udp, whether it's udp
275 * @return int, if success, return EXIT_SUCCESS, else return -1
277 static int ms_conn_init(ms_conn_t
*c
,
278 const int init_state
,
279 const int read_buffer_size
,
288 c
->rsize
= read_buffer_size
;
289 c
->wsize
= WRITE_BUFFER_SIZE
;
290 c
->iovsize
= IOV_LIST_INITIAL
;
291 c
->msgsize
= MSG_LIST_INITIAL
;
293 /* for replication, each connection need connect all the server */
294 if (ms_setting
.rep_write_srv
> 0)
296 c
->total_sfds
= ms_setting
.srv_cnt
* ms_setting
.sock_per_conn
;
300 c
->total_sfds
= ms_setting
.sock_per_conn
;
304 c
->rbuf
= (char *)malloc((size_t)c
->rsize
);
305 c
->wbuf
= (char *)malloc((size_t)c
->wsize
);
306 c
->iov
= (struct iovec
*)malloc(sizeof(struct iovec
) * (size_t)c
->iovsize
);
307 c
->msglist
= (struct msghdr
*)malloc(
308 sizeof(struct msghdr
) * (size_t)c
->msgsize
);
309 if (ms_setting
.mult_key_num
> 1)
311 c
->mlget_task
.mlget_item
= (ms_mlget_task_item_t
*)
313 sizeof(ms_mlget_task_item_t
) * (size_t)ms_setting
.mult_key_num
);
315 c
->tcpsfd
= (int *)malloc((size_t)c
->total_sfds
* sizeof(int));
317 if ((c
->rbuf
== NULL
) || (c
->wbuf
== NULL
) || (c
->iov
== NULL
)
318 || (c
->msglist
== NULL
) || (c
->tcpsfd
== NULL
)
319 || ((ms_setting
.mult_key_num
> 1)
320 && (c
->mlget_task
.mlget_item
== NULL
)))
328 if (c
->msglist
!= NULL
)
330 if (c
->mlget_task
.mlget_item
!= NULL
)
331 free(c
->mlget_task
.mlget_item
);
332 if (c
->tcpsfd
!= NULL
)
334 fprintf(stderr
, "malloc()\n");
338 c
->state
= init_state
;
346 c
->cur_idx
= c
->total_sfds
; /* default index is a invalid value */
350 c
->change_sfd
= false;
352 c
->precmd
.cmd
= c
->currcmd
.cmd
= CMD_NULL
;
353 c
->precmd
.isfinish
= true; /* default the previous command finished */
354 c
->currcmd
.isfinish
= false;
355 c
->precmd
.retstat
= c
->currcmd
.retstat
= MCD_FAILURE
;
356 c
->precmd
.key_prefix
= c
->currcmd
.key_prefix
= 0;
358 c
->mlget_task
.mlget_num
= 0;
359 c
->mlget_task
.value_index
= -1; /* default invalid value */
361 if (ms_setting
.binary_prot
)
363 c
->protocol
= binary_prot
;
367 c
->protocol
= ascii_prot
;
371 if (ms_conn_udp_init(c
, is_udp
) != 0)
376 /* initialize task */
379 if (! (ms_setting
.facebook_test
&& is_udp
))
381 atomic_add_32(&ms_stats
.active_conns
, 1);
389 * when doing 100% get operation, it could preset some objects
390 * to warmup the server. this function is used to initialize the
391 * number of the objects to preset.
393 * @param c, pointer of the concurrency
395 static void ms_warmup_num_init(ms_conn_t
*c
)
397 /* no set operation, preset all the items in the window */
398 if (ms_setting
.cmd_distr
[CMD_SET
].cmd_prop
< PROP_ERROR
)
400 c
->warmup_num
= c
->win_size
;
401 c
->remain_warmup_num
= c
->warmup_num
;
406 c
->remain_warmup_num
= c
->warmup_num
;
408 } /* ms_warmup_num_init */
412 * each connection has an item window, this function initialize
413 * the window. The window is used to generate task.
415 * @param c, pointer of the concurrency
417 * @return int, if success, return EXIT_SUCCESS, else return -1
419 static int ms_item_win_init(ms_conn_t
*c
)
421 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
424 c
->win_size
= (int)ms_setting
.win_size
;
426 c
->exec_num
= ms_thread
->thread_ctx
->exec_num_perconn
;
427 c
->remain_exec_num
= c
->exec_num
;
429 c
->item_win
= (ms_task_item_t
*)malloc(
430 sizeof(ms_task_item_t
) * (size_t)c
->win_size
);
431 if (c
->item_win
== NULL
)
433 fprintf(stderr
, "Can't allocate task item array for conn.\n");
436 memset(c
->item_win
, 0, sizeof(ms_task_item_t
) * (size_t)c
->win_size
);
438 for (int i
= 0; i
< c
->win_size
; i
++)
440 c
->item_win
[i
].key_size
= (int)ms_setting
.distr
[i
].key_size
;
441 c
->item_win
[i
].key_prefix
= ms_get_key_prefix();
442 c
->item_win
[i
].key_suffix_offset
= ms_setting
.distr
[i
].key_offset
;
443 c
->item_win
[i
].value_size
= (int)ms_setting
.distr
[i
].value_size
;
444 c
->item_win
[i
].value_offset
= INVALID_OFFSET
; /* default in invalid offset */
445 c
->item_win
[i
].client_time
= 0;
447 /* set expire time base on the proportion */
448 if (exp_cnt
< ms_setting
.exp_ver_per
* i
)
450 c
->item_win
[i
].exp_time
= FIXED_EXPIRE_TIME
;
455 c
->item_win
[i
].exp_time
= 0;
459 ms_warmup_num_init(c
);
462 } /* ms_item_win_init */
466 * each connection structure can include one or more sock
467 * handlers. this function create these socks and connect the
470 * @param c, pointer of the concurrency
472 * @return int, if success, return EXIT_SUCCESS, else return -1
474 static int ms_conn_sock_init(ms_conn_t
*c
)
476 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
482 assert(c
->tcpsfd
!= NULL
);
484 for (i
= 0; i
< c
->total_sfds
; i
++)
487 if (ms_setting
.rep_write_srv
> 0)
489 /* for replication, each connection need connect all the server */
490 srv_idx
= i
% ms_setting
.srv_cnt
;
494 /* all the connections in a thread connects the same server */
495 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
498 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
499 ms_setting
.servers
[srv_idx
].srv_port
,
500 ms_setting
.udp
, &ret_sfd
) != 0)
510 if (! ms_setting
.udp
)
512 c
->tcpsfd
[i
]= ret_sfd
;
518 /* initialize udp sock handler if necessary */
519 if (ms_setting
.facebook_test
)
522 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
523 ms_setting
.servers
[srv_idx
].srv_port
,
524 true, &ret_sfd
) != 0)
534 if ((i
!= c
->total_sfds
) || (ms_setting
.facebook_test
&& (c
->udpsfd
== 0)))
542 for (uint32_t j
= 0; j
< i
; j
++)
557 } /* ms_conn_sock_init */
561 * each connection is managed by libevent, this function
562 * initialize the event of the connection structure.
564 * @param c, pointer of the concurrency
566 * @return int, if success, return EXIT_SUCCESS, else return -1
568 static int ms_conn_event_init(ms_conn_t
*c
)
570 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
571 short event_flags
= EV_WRITE
| EV_PERSIST
;
573 event_set(&c
->event
, c
->sfd
, event_flags
, ms_event_handler
, (void *)c
);
574 event_base_set(ms_thread
->base
, &c
->event
);
575 c
->ev_flags
= event_flags
;
577 if (event_add(&c
->event
, NULL
) == -1)
583 } /* ms_conn_event_init */
587 * setup a connection, each connection structure of each
588 * thread must call this function to initialize.
590 * @param c, pointer of the concurrency
592 * @return int, if success, return EXIT_SUCCESS, else return -1
594 int ms_setup_conn(ms_conn_t
*c
)
596 if (ms_item_win_init(c
) != 0)
601 if (ms_conn_init(c
, conn_write
, DATA_BUFFER_SIZE
, ms_setting
.udp
) != 0)
606 if (ms_conn_sock_init(c
) != 0)
611 if (ms_conn_event_init(c
) != 0)
617 } /* ms_setup_conn */
621 * Frees a connection.
623 * @param c, pointer of the concurrency
625 void ms_conn_free(ms_conn_t
*c
)
627 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
630 if (c
->hdrbuf
!= NULL
)
632 if (c
->msglist
!= NULL
)
640 if (c
->mlget_task
.mlget_item
!= NULL
)
641 free(c
->mlget_task
.mlget_item
);
642 if (c
->rudpbuf
!= NULL
)
644 if (c
->udppkt
!= NULL
)
646 if (c
->item_win
!= NULL
)
648 if (c
->tcpsfd
!= NULL
)
651 if (--ms_thread
->nactive_conn
== 0)
653 free(ms_thread
->conn
);
662 * @param c, pointer of the concurrency
664 static void ms_conn_close(ms_conn_t
*c
)
666 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
669 /* delete the event, the socket and the connection */
670 event_del(&c
->event
);
672 for (uint32_t i
= 0; i
< c
->total_sfds
; i
++)
674 if (c
->tcpsfd
[i
] > 0)
681 if (ms_setting
.facebook_test
)
686 atomic_dec_32(&ms_stats
.active_conns
);
690 if (ms_setting
.run_time
== 0)
692 pthread_mutex_lock(&ms_global
.run_lock
.lock
);
693 ms_global
.run_lock
.count
++;
694 pthread_cond_signal(&ms_global
.run_lock
.cond
);
695 pthread_mutex_unlock(&ms_global
.run_lock
.lock
);
698 if (ms_thread
->nactive_conn
== 0)
702 } /* ms_conn_close */
708 * @param ai, server address information
710 * @return int, if success, return EXIT_SUCCESS, else return -1
712 static int ms_new_socket(struct addrinfo
*ai
)
716 if ((sfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
)) == -1)
718 fprintf(stderr
, "socket() error: %s.\n", strerror(errno
));
723 } /* ms_new_socket */
727 * Sets a socket's send buffer size to the maximum allowed by the system.
729 * @param sfd, file descriptor of socket
731 static void ms_maximize_sndbuf(const int sfd
)
733 socklen_t intsize
= sizeof(int);
734 unsigned int last_good
= 0;
735 unsigned int min
, max
, avg
;
736 unsigned int old_size
;
738 /* Start with the default size. */
739 if (getsockopt(sfd
, SOL_SOCKET
, SO_SNDBUF
, &old_size
, &intsize
) != 0)
741 fprintf(stderr
, "getsockopt(SO_SNDBUF)\n");
745 /* Binary-search for the real maximum. */
747 max
= MAX_SENDBUF_SIZE
;
751 avg
= ((unsigned int)(min
+ max
)) / 2;
752 if (setsockopt(sfd
, SOL_SOCKET
, SO_SNDBUF
, (void *)&avg
, intsize
) == 0)
762 } /* ms_maximize_sndbuf */
766 * socket connects the server
768 * @param c, pointer of the concurrency
769 * @param srv_host_name, the host name of the server
770 * @param srv_port, port of server
771 * @param is_udp, whether it's udp
772 * @param ret_sfd, the connected socket file descriptor
774 * @return int, if success, return EXIT_SUCCESS, else return -1
776 static int ms_network_connect(ms_conn_t
*c
,
788 struct addrinfo
*next
;
789 struct addrinfo hints
;
790 char port_buf
[NI_MAXSERV
];
797 * the memset call clears nonstandard fields in some impementations
798 * that otherwise mess things up.
800 memset(&hints
, 0, sizeof(hints
));
802 hints
.ai_flags
= AI_PASSIVE
| AI_ADDRCONFIG
;
804 hints
.ai_flags
= AI_PASSIVE
;
805 #endif /* AI_ADDRCONFIG */
808 hints
.ai_protocol
= IPPROTO_UDP
;
809 hints
.ai_socktype
= SOCK_DGRAM
;
810 hints
.ai_family
= AF_INET
; /* This left here because of issues with OSX 10.5 */
814 hints
.ai_family
= AF_UNSPEC
;
815 hints
.ai_protocol
= IPPROTO_TCP
;
816 hints
.ai_socktype
= SOCK_STREAM
;
819 snprintf(port_buf
, NI_MAXSERV
, "%d", srv_port
);
820 error
= getaddrinfo(srv_host_name
, port_buf
, &hints
, &ai
);
823 if (error
!= EAI_SYSTEM
)
824 fprintf(stderr
, "getaddrinfo(): %s.\n", gai_strerror(error
));
826 perror("getaddrinfo()\n");
831 for (next
= ai
; next
; next
= next
->ai_next
)
833 if ((sfd
= ms_new_socket(next
)) == -1)
839 setsockopt(sfd
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&flags
, sizeof(flags
));
842 ms_maximize_sndbuf(sfd
);
846 setsockopt(sfd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&flags
,
848 setsockopt(sfd
, SOL_SOCKET
, SO_LINGER
, (void *)&ling
, sizeof(ling
));
849 setsockopt(sfd
, IPPROTO_TCP
, TCP_NODELAY
, (void *)&flags
,
855 c
->srv_recv_addr_size
= sizeof(struct sockaddr
);
856 memcpy(&c
->srv_recv_addr
, next
->ai_addr
, c
->srv_recv_addr_size
);
860 if (connect(sfd
, next
->ai_addr
, next
->ai_addrlen
) == -1)
868 if (((flags
= fcntl(sfd
, F_GETFL
, 0)) < 0)
869 || (fcntl(sfd
, F_SETFL
, flags
| O_NONBLOCK
) < 0))
871 fprintf(stderr
, "setting O_NONBLOCK\n");
887 /* Return zero if we detected no errors in starting up connections */
889 } /* ms_network_connect */
893 * reconnect a disconnected sock
895 * @param c, pointer of the concurrency
897 * @return int, if success, return EXIT_SUCCESS, else return -1
899 static int ms_reconn(ms_conn_t
*c
)
901 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
903 uint32_t srv_conn_cnt
= 0;
905 if (ms_setting
.rep_write_srv
> 0)
907 srv_idx
= c
->cur_idx
% ms_setting
.srv_cnt
;
908 srv_conn_cnt
= ms_setting
.sock_per_conn
* ms_setting
.nconns
;
912 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
913 srv_conn_cnt
= ms_setting
.nconns
/ ms_setting
.srv_cnt
;
916 /* close the old socket handler */
918 c
->tcpsfd
[c
->cur_idx
]= 0;
920 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].disconn_cnt
, 1)
923 gettimeofday(&ms_setting
.servers
[srv_idx
].disconn_time
, NULL
);
924 fprintf(stderr
, "Server %s:%d disconnect\n",
925 ms_setting
.servers
[srv_idx
].srv_host_name
,
926 ms_setting
.servers
[srv_idx
].srv_port
);
929 if (ms_setting
.rep_write_srv
> 0)
933 for (i
= 0; i
< c
->total_sfds
; i
++)
935 if (c
->tcpsfd
[i
] != 0)
941 /* all socks disconnect */
942 if (i
== c
->total_sfds
)
951 /* reconnect success, break the loop */
952 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
953 ms_setting
.servers
[srv_idx
].srv_port
,
954 ms_setting
.udp
, &c
->sfd
) == 0)
956 c
->tcpsfd
[c
->cur_idx
]= c
->sfd
;
957 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].reconn_cnt
, 1)
958 % (uint32_t)srv_conn_cnt
== 0)
960 gettimeofday(&ms_setting
.servers
[srv_idx
].reconn_time
, NULL
);
962 (int)(ms_setting
.servers
[srv_idx
].reconn_time
.tv_sec
963 - ms_setting
.servers
[srv_idx
].disconn_time
965 fprintf(stderr
, "Server %s:%d reconnect after %ds\n",
966 ms_setting
.servers
[srv_idx
].srv_host_name
,
967 ms_setting
.servers
[srv_idx
].srv_port
, reconn_time
);
972 if (ms_setting
.rep_write_srv
== 0 && c
->total_sfds
> 0)
974 /* wait a second and reconnect */
978 while (ms_setting
.rep_write_srv
== 0 && c
->total_sfds
> 0);
981 if ((c
->total_sfds
> 1) && (c
->tcpsfd
[c
->cur_idx
] == 0))
992 * reconnect several disconnected socks in the connection
993 * structure, the ever-1-second timer of the thread will check
994 * whether some socks in the connections disconnect. if
995 * disconnect, reconnect the sock.
997 * @param c, pointer of the concurrency
999 * @return int, if success, return EXIT_SUCCESS, else return -1
1001 int ms_reconn_socks(ms_conn_t
*c
)
1003 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
1004 uint32_t srv_idx
= 0;
1006 uint32_t srv_conn_cnt
= 0;
1007 struct timeval cur_time
;
1011 if ((c
->total_sfds
== 1) || (c
->total_sfds
== c
->alive_sfds
))
1013 return EXIT_SUCCESS
;
1016 for (uint32_t i
= 0; i
< c
->total_sfds
; i
++)
1018 if (c
->tcpsfd
[i
] == 0)
1020 gettimeofday(&cur_time
, NULL
);
1023 * For failover test of replication, reconnect the socks after
1024 * it disconnects more than 5 seconds, Otherwise memslap will
1025 * block at connect() function and the work threads can't work
1029 - ms_setting
.servers
[srv_idx
].disconn_time
.tv_sec
< 5)
1034 if (ms_setting
.rep_write_srv
> 0)
1036 srv_idx
= i
% ms_setting
.srv_cnt
;
1037 srv_conn_cnt
= ms_setting
.sock_per_conn
* ms_setting
.nconns
;
1041 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
1042 srv_conn_cnt
= ms_setting
.nconns
/ ms_setting
.srv_cnt
;
1045 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
1046 ms_setting
.servers
[srv_idx
].srv_port
,
1047 ms_setting
.udp
, &ret_sfd
) == 0)
1049 c
->tcpsfd
[i
]= ret_sfd
;
1052 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].reconn_cnt
, 1)
1053 % (uint32_t)srv_conn_cnt
== 0)
1055 gettimeofday(&ms_setting
.servers
[srv_idx
].reconn_time
, NULL
);
1057 (int)(ms_setting
.servers
[srv_idx
].reconn_time
.tv_sec
1058 - ms_setting
.servers
[srv_idx
].disconn_time
1060 fprintf(stderr
, "Server %s:%d reconnect after %ds\n",
1061 ms_setting
.servers
[srv_idx
].srv_host_name
,
1062 ms_setting
.servers
[srv_idx
].srv_port
, reconn_time
);
1068 return EXIT_SUCCESS
;
1069 } /* ms_reconn_socks */
1073 * Tokenize the command string by replacing whitespace with '\0' and update
1074 * the token array tokens with pointer to start of each token and length.
1075 * Returns total number of tokens. The last valid token is the terminal
1076 * token (value points to the first unprocessed character of the string and
1081 * while(ms_tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
1082 * for(int ix = 0; tokens[ix].length != 0; ix++) {
1085 * ncommand = tokens[ix].value - command;
1086 * command = tokens[ix].value;
1089 * @param command, the command string to token
1090 * @param tokens, array to store tokens
1091 * @param max_tokens, maximum tokens number
1093 * @return int, the number of tokens
1095 static int ms_tokenize_command(char *command
,
1097 const int max_tokens
)
1102 assert(command
!= NULL
&& tokens
!= NULL
&& max_tokens
> 1);
1104 for (s
= e
= command
; ntokens
< max_tokens
- 1; ++e
)
1110 tokens
[ntokens
].value
= s
;
1111 tokens
[ntokens
].length
= (size_t)(e
- s
);
1117 else if (*e
== '\0')
1121 tokens
[ntokens
].value
= s
;
1122 tokens
[ntokens
].length
= (size_t)(e
- s
);
1126 break; /* string end */
1131 } /* ms_tokenize_command */
1135 * parse the response of server.
1137 * @param c, pointer of the concurrency
1138 * @param command, the string responded by server
1140 * @return int, if the command completed return EXIT_SUCCESS, else return
1143 static int ms_ascii_process_line(ms_conn_t
*c
, char *command
)
1147 char *buffer
= command
;
1152 * for command get, we store the returned value into local buffer
1153 * then continue in ms_complete_nread().
1158 case 'V': /* VALUE || VERSION */
1159 if (buffer
[1] == 'A') /* VALUE */
1161 token_t tokens
[MAX_TOKENS
];
1162 ms_tokenize_command(command
, tokens
, MAX_TOKENS
);
1163 value_len
= strtol(tokens
[VALUELEN_TOKEN
].value
, NULL
, 10);
1164 c
->currcmd
.key_prefix
= *(uint64_t *)tokens
[KEY_TOKEN
].value
;
1167 * We read the \r\n into the string since not doing so is more
1168 * cycles then the waster of memory to do so.
1170 * We are null terminating through, which will most likely make
1171 * some people lazy about using the return length.
1173 c
->rvbytes
= (int)(value_len
+ 2);
1181 c
->currcmd
.retstat
= MCD_SUCCESS
;
1183 case 'S': /* STORED STATS SERVER_ERROR */
1184 if (buffer
[2] == 'A') /* STORED STATS */
1186 c
->currcmd
.retstat
= MCD_STAT
;
1188 else if (buffer
[1] == 'E')
1191 printf("<%d %s\n", c
->sfd
, buffer
);
1193 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
1195 else if (buffer
[1] == 'T')
1198 c
->currcmd
.retstat
= MCD_STORED
;
1202 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1206 case 'D': /* DELETED DATA */
1207 if (buffer
[1] == 'E')
1209 c
->currcmd
.retstat
= MCD_DELETED
;
1213 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1218 case 'N': /* NOT_FOUND NOT_STORED*/
1219 if (buffer
[4] == 'F')
1221 c
->currcmd
.retstat
= MCD_NOTFOUND
;
1223 else if (buffer
[4] == 'S')
1225 printf("<%d %s\n", c
->sfd
, buffer
);
1226 c
->currcmd
.retstat
= MCD_NOTSTORED
;
1230 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1234 case 'E': /* PROTOCOL ERROR or END */
1235 if (buffer
[1] == 'N')
1238 c
->currcmd
.retstat
= MCD_END
;
1240 else if (buffer
[1] == 'R')
1242 printf("<%d ERROR\n", c
->sfd
);
1243 c
->currcmd
.retstat
= MCD_PROTOCOL_ERROR
;
1245 else if (buffer
[1] == 'X')
1247 c
->currcmd
.retstat
= MCD_DATA_EXISTS
;
1248 printf("<%d %s\n", c
->sfd
, buffer
);
1252 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1256 case 'C': /* CLIENT ERROR */
1257 printf("<%d %s\n", c
->sfd
, buffer
);
1258 c
->currcmd
.retstat
= MCD_CLIENT_ERROR
;
1262 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1267 } /* ms_ascii_process_line */
1271 * after one operation completes, reset the concurrency
1273 * @param c, pointer of the concurrency
1274 * @param timeout, whether it's timeout
1276 void ms_reset_conn(ms_conn_t
*c
, bool timeout
)
1282 if ((c
->packets
> 0) && (c
->packets
< MAX_UDP_PACKET
))
1284 memset(c
->udppkt
, 0, sizeof(ms_udppkt_t
) * (size_t)c
->packets
);
1293 c
->currcmd
.isfinish
= true;
1300 ms_conn_set_state(c
, conn_write
);
1301 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
1305 ms_drive_machine(c
);
1307 } /* ms_reset_conn */
1311 * if we have a complete line in the buffer, process it.
1313 * @param c, pointer of the concurrency
1315 * @return int, if success, return EXIT_SUCCESS, else return -1
1317 static int ms_try_read_line(ms_conn_t
*c
)
1319 if (c
->protocol
== binary_prot
)
1321 /* Do we have the complete packet header? */
1322 if ((uint64_t)c
->rbytes
< sizeof(c
->binary_header
))
1324 /* need more data! */
1325 return EXIT_SUCCESS
;
1330 if (((long)(c
->rcurr
)) % 8 != 0)
1332 /* must realign input buffer */
1333 memmove(c
->rbuf
, c
->rcurr
, c
->rbytes
);
1335 if (settings
.verbose
)
1337 fprintf(stderr
, "%d: Realign input buffer.\n", c
->sfd
);
1341 protocol_binary_response_header
*rsp
;
1342 rsp
= (protocol_binary_response_header
*)c
->rcurr
;
1344 c
->binary_header
= *rsp
;
1345 c
->binary_header
.response
.extlen
= rsp
->response
.extlen
;
1346 c
->binary_header
.response
.keylen
= ntohs(rsp
->response
.keylen
);
1347 c
->binary_header
.response
.bodylen
= ntohl(rsp
->response
.bodylen
);
1348 c
->binary_header
.response
.status
= ntohs(rsp
->response
.status
);
1350 if (c
->binary_header
.response
.magic
!= PROTOCOL_BINARY_RES
)
1352 fprintf(stderr
, "Invalid magic: %x\n",
1353 c
->binary_header
.response
.magic
);
1354 ms_conn_set_state(c
, conn_closing
);
1355 return EXIT_SUCCESS
;
1358 /* process this complete response */
1359 if (ms_bin_process_response(c
) == 0)
1361 /* current operation completed */
1362 ms_reset_conn(c
, false);
1367 c
->rbytes
-= (int32_t)sizeof(c
->binary_header
);
1368 c
->rcurr
+= sizeof(c
->binary_header
);
1377 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1380 return EXIT_SUCCESS
;
1382 el
= memchr(c
->rcurr
, '\n', (size_t)c
->rbytes
);
1384 return EXIT_SUCCESS
;
1387 if (((el
- c
->rcurr
) > 1) && (*(el
- 1) == '\r'))
1393 assert(cont
<= (c
->rcurr
+ c
->rbytes
));
1395 /* process this complete line */
1396 if (ms_ascii_process_line(c
, c
->rcurr
) == 0)
1398 /* current operation completed */
1399 ms_reset_conn(c
, false);
1404 /* current operation didn't complete */
1405 c
->rbytes
-= (int32_t)(cont
- c
->rcurr
);
1409 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1413 } /* ms_try_read_line */
1417 * because the packet of UDP can't ensure the order, the
1418 * function is used to sort the received udp packet.
1420 * @param c, pointer of the concurrency
1421 * @param buf, the buffer to store the ordered packages data
1422 * @param rbytes, the maximum capacity of the buffer
1424 * @return int, if success, return the copy bytes, else return
1427 static int ms_sort_udp_packet(ms_conn_t
*c
, char *buf
, int rbytes
)
1432 uint16_t seq_num
= 0;
1433 uint16_t packets
= 0;
1434 unsigned char *header
= NULL
;
1436 /* no enough data */
1438 assert(buf
!= NULL
);
1439 assert(c
->rudpbytes
>= UDP_HEADER_SIZE
);
1441 /* calculate received packets count */
1442 if (c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
>= UDP_HEADER_SIZE
)
1444 /* the last packet has some data */
1445 c
->recvpkt
= c
->rudpbytes
/ UDP_MAX_PAYLOAD_SIZE
+ 1;
1449 c
->recvpkt
= c
->rudpbytes
/ UDP_MAX_PAYLOAD_SIZE
;
1452 /* get the total packets count if necessary */
1453 if (c
->packets
== 0)
1455 c
->packets
= HEADER_TO_PACKETS((unsigned char *)c
->rudpbuf
);
1458 /* build the ordered packet array */
1459 for (int i
= c
->pktcurr
; i
< c
->recvpkt
; i
++)
1461 header
= (unsigned char *)c
->rudpbuf
+ i
* UDP_MAX_PAYLOAD_SIZE
;
1462 req_id
= (uint16_t)HEADER_TO_REQID(header
);
1463 assert(req_id
== c
->request_id
% (1 << 16));
1465 packets
= (uint16_t)HEADER_TO_PACKETS(header
);
1466 assert(c
->packets
== HEADER_TO_PACKETS(header
));
1468 seq_num
= (uint16_t)HEADER_TO_SEQNUM(header
);
1469 c
->udppkt
[seq_num
].header
= header
;
1470 c
->udppkt
[seq_num
].data
= (char *)header
+ UDP_HEADER_SIZE
;
1472 if (i
== c
->recvpkt
- 1)
1474 /* last received packet */
1475 if (c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
== 0)
1477 c
->udppkt
[seq_num
].rbytes
= UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1482 c
->udppkt
[seq_num
].rbytes
= c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
1488 c
->udppkt
[seq_num
].rbytes
= UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1493 for (int i
= c
->ordcurr
; i
< c
->recvpkt
; i
++)
1495 /* there is some data to copy */
1496 if ((c
->udppkt
[i
].data
!= NULL
)
1497 && (c
->udppkt
[i
].copybytes
< c
->udppkt
[i
].rbytes
))
1499 header
= c
->udppkt
[i
].header
;
1500 len
= c
->udppkt
[i
].rbytes
- c
->udppkt
[i
].copybytes
;
1501 if (len
> rbytes
- wbytes
)
1503 len
= rbytes
- wbytes
;
1506 assert(len
<= rbytes
- wbytes
);
1507 assert(i
== HEADER_TO_SEQNUM(header
));
1509 memcpy(buf
+ wbytes
, c
->udppkt
[i
].data
+ c
->udppkt
[i
].copybytes
,
1512 c
->udppkt
[i
].copybytes
+= len
;
1514 if ((c
->udppkt
[i
].copybytes
== c
->udppkt
[i
].rbytes
)
1515 && (c
->udppkt
[i
].rbytes
== UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
))
1517 /* finish copying all the data of this packet, next */
1521 /* last received packet, and finish copying all the data */
1522 if ((c
->recvpkt
== c
->packets
) && (i
== c
->recvpkt
- 1)
1523 && (c
->udppkt
[i
].copybytes
== c
->udppkt
[i
].rbytes
))
1528 /* no space to copy data */
1529 if (wbytes
>= rbytes
)
1534 /* it doesn't finish reading all the data of the packet from network */
1535 if ((i
!= c
->recvpkt
- 1)
1536 && (c
->udppkt
[i
].rbytes
< UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
))
1543 /* no data to copy */
1548 return wbytes
== 0 ? -1 : wbytes
;
1549 } /* ms_sort_udp_packet */
1553 * encapsulate upd read like tcp read
1555 * @param c, pointer of the concurrency
1556 * @param buf, read buffer
1557 * @param len, length to read
1559 * @return int, if success, return the read bytes, else return
1562 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
)
1573 if (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
> c
->rudpsize
)
1575 char *new_rbuf
= realloc(c
->rudpbuf
, (size_t)c
->rudpsize
* 2);
1578 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1579 c
->rudpbytes
= 0; /* ignore what we read */
1582 c
->rudpbuf
= new_rbuf
;
1586 avail
= c
->rudpsize
- c
->rudpbytes
;
1587 /* UDP each time read a packet, 1400 bytes */
1588 res
= (int)read(c
->sfd
, c
->rudpbuf
+ c
->rudpbytes
, (size_t)avail
);
1592 atomic_add_size(&ms_stats
.bytes_read
, res
);
1607 /* "connection" closed */
1613 /* no data to read */
1618 /* copy data to read buffer */
1621 copybytes
= ms_sort_udp_packet(c
, buf
, len
);
1624 if (copybytes
== -1)
1626 atomic_add_size(&ms_stats
.pkt_disorder
, 1);
1634 * read from network as much as we can, handle buffer overflow and connection
1636 * before reading, move the remaining incomplete fragment of a command
1637 * (if any) to the beginning of the buffer.
1638 * return EXIT_SUCCESS if there's nothing to read on the first read.
1642 * read from network as much as we can, handle buffer overflow and connection
1643 * close. before reading, move the remaining incomplete fragment of a command
1644 * (if any) to the beginning of the buffer.
1646 * @param c, pointer of the concurrency
1649 * return EXIT_SUCCESS if there's nothing to read on the first read.
1650 * return EXIT_FAILURE if get data
1651 * return -1 if error happens
1653 static int ms_try_read_network(ms_conn_t
*c
)
1661 if ((c
->rcurr
!= c
->rbuf
)
1662 && (! c
->readval
|| (c
->rvbytes
> c
->rsize
- (c
->rcurr
- c
->rbuf
))
1663 || (c
->readval
&& (c
->rcurr
- c
->rbuf
> c
->rbytes
))))
1665 if (c
->rbytes
!= 0) /* otherwise there's nothing to copy */
1666 memmove(c
->rbuf
, c
->rcurr
, (size_t)c
->rbytes
);
1672 if (c
->rbytes
>= c
->rsize
)
1674 char *new_rbuf
= realloc(c
->rbuf
, (size_t)c
->rsize
* 2);
1677 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1678 c
->rbytes
= 0; /* ignore what we read */
1681 c
->rcurr
= c
->rbuf
= new_rbuf
;
1685 avail
= c
->rsize
- c
->rbytes
- (c
->rcurr
- c
->rbuf
);
1693 res
= (int32_t)ms_udp_read(c
, c
->rcurr
+ c
->rbytes
, (int32_t)avail
);
1697 res
= (int)read(c
->sfd
, c
->rcurr
+ c
->rbytes
, (size_t)avail
);
1704 atomic_add_size(&ms_stats
.bytes_read
, res
);
1719 /* connection closed */
1720 ms_conn_set_state(c
, conn_closing
);
1725 if ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
))
1727 /* Should close on unhandled errors. */
1728 ms_conn_set_state(c
, conn_closing
);
1734 } /* ms_try_read_network */
1738 * after get the object from server, verify the value if
1741 * @param c, pointer of the concurrency
1742 * @param mlget_item, pointer of mulit-get task item structure
1743 * @param value, received value string
1744 * @param vlen, received value string length
1746 static void ms_verify_value(ms_conn_t
*c
,
1747 ms_mlget_task_item_t
*mlget_item
,
1751 if (c
->curr_task
.verify
)
1753 assert(c
->curr_task
.item
->value_offset
!= INVALID_OFFSET
);
1754 char *orignval
= &ms_setting
.char_block
[c
->curr_task
.item
->value_offset
];
1756 &ms_setting
.char_block
[c
->curr_task
.item
->key_suffix_offset
];
1758 /* verify expire time if necessary */
1759 if (c
->curr_task
.item
->exp_time
> 0)
1761 struct timeval curr_time
;
1762 gettimeofday(&curr_time
, NULL
);
1764 /* object expired but get it now */
1765 if (curr_time
.tv_sec
- c
->curr_task
.item
->client_time
1766 > c
->curr_task
.item
->exp_time
+ EXPIRE_TIME_ERROR
)
1768 atomic_add_size(&ms_stats
.exp_get
, 1);
1770 if (ms_setting
.verbose
)
1774 strftime(set_time
, 64, "%Y-%m-%d %H:%M:%S",
1775 localtime(&c
->curr_task
.item
->client_time
));
1776 strftime(cur_time
, 64, "%Y-%m-%d %H:%M:%S",
1777 localtime(&curr_time
.tv_sec
));
1779 "\n<%d expire time verification failed, "
1780 "object expired but get it now\n"
1782 "\tkey: %" PRIx64
" %.*s\n"
1783 "\tset time: %s current time: %s "
1784 "diff time: %d expire time: %d\n"
1785 "\texpected data: \n"
1786 "\treceived data len: %d\n"
1787 "\treceived data: %.*s\n",
1789 c
->curr_task
.item
->key_size
,
1790 c
->curr_task
.item
->key_prefix
,
1791 c
->curr_task
.item
->key_size
- (int)KEY_PREFIX_SIZE
,
1795 (int)(curr_time
.tv_sec
- c
->curr_task
.item
->client_time
),
1796 c
->curr_task
.item
->exp_time
,
1806 if ((c
->curr_task
.item
->value_size
!= vlen
)
1807 || (memcmp(orignval
, value
, (size_t)vlen
) != 0))
1809 atomic_add_size(&ms_stats
.vef_failed
, 1);
1811 if (ms_setting
.verbose
)
1814 "\n<%d data verification failed\n"
1816 "\tkey: %" PRIx64
" %.*s\n"
1817 "\texpected data len: %d\n"
1818 "\texpected data: %.*s\n"
1819 "\treceived data len: %d\n"
1820 "\treceived data: %.*s\n",
1822 c
->curr_task
.item
->key_size
,
1823 c
->curr_task
.item
->key_prefix
,
1824 c
->curr_task
.item
->key_size
- (int)KEY_PREFIX_SIZE
,
1826 c
->curr_task
.item
->value_size
,
1827 c
->curr_task
.item
->value_size
,
1837 c
->curr_task
.finish_verify
= true;
1839 if (mlget_item
!= NULL
)
1841 mlget_item
->finish_verify
= true;
1844 } /* ms_verify_value */
1848 * For ASCII protocol, after store the data into the local
1849 * buffer, run this function to handle the data.
1851 * @param c, pointer of the concurrency
1853 static void ms_ascii_complete_nread(ms_conn_t
*c
)
1856 assert(c
->rbytes
>= c
->rvbytes
);
1857 assert(c
->protocol
== ascii_prot
);
1861 c
->rcurr
[c
->rvbytes
- 1] == '\n' && c
->rcurr
[c
->rvbytes
- 2] == '\r');
1865 ms_mlget_task_item_t
*mlget_item
= NULL
;
1866 if (((ms_setting
.mult_key_num
> 1)
1867 && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1868 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1870 c
->mlget_task
.value_index
++;
1871 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1873 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
)
1875 c
->curr_task
.item
= mlget_item
->item
;
1876 c
->curr_task
.verify
= mlget_item
->verify
;
1877 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1878 mlget_item
->get_miss
= false;
1882 /* Try to find the task item in multi-get task array */
1883 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
1885 mlget_item
= &c
->mlget_task
.mlget_item
[i
];
1886 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
)
1888 c
->curr_task
.item
= mlget_item
->item
;
1889 c
->curr_task
.verify
= mlget_item
->verify
;
1890 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1891 mlget_item
->get_miss
= false;
1899 ms_verify_value(c
, mlget_item
, c
->rcurr
, c
->rvbytes
- 2);
1901 c
->curr_task
.get_miss
= false;
1902 c
->rbytes
-= c
->rvbytes
;
1903 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1904 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1907 } /* ms_ascii_complete_nread */
1911 * For binary protocol, after store the data into the local
1912 * buffer, run this function to handle the data.
1914 * @param c, pointer of the concurrency
1916 static void ms_bin_complete_nread(ms_conn_t
*c
)
1919 assert(c
->rbytes
>= c
->rvbytes
);
1920 assert(c
->protocol
== binary_prot
);
1922 int extlen
= c
->binary_header
.response
.extlen
;
1923 int keylen
= c
->binary_header
.response
.keylen
;
1924 uint8_t opcode
= c
->binary_header
.response
.opcode
;
1926 /* not get command or not include value, just return */
1927 if (((opcode
!= PROTOCOL_BINARY_CMD_GET
)
1928 && (opcode
!= PROTOCOL_BINARY_CMD_GETQ
))
1929 || (c
->rvbytes
<= extlen
+ keylen
))
1932 if (c
->binary_header
.response
.opcode
== PROTOCOL_BINARY_CMD_GET
)
1934 c
->currcmd
.retstat
= MCD_END
;
1935 c
->curr_task
.get_miss
= true;
1940 ms_reset_conn(c
, false);
1945 ms_mlget_task_item_t
*mlget_item
= NULL
;
1946 if (((ms_setting
.mult_key_num
> 1)
1947 && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1948 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1950 c
->mlget_task
.value_index
++;
1951 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1953 c
->curr_task
.item
= mlget_item
->item
;
1954 c
->curr_task
.verify
= mlget_item
->verify
;
1955 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1956 mlget_item
->get_miss
= false;
1961 c
->rcurr
+ extlen
+ keylen
,
1962 c
->rvbytes
- extlen
- keylen
);
1964 c
->currcmd
.retstat
= MCD_END
;
1965 c
->curr_task
.get_miss
= false;
1966 c
->rbytes
-= c
->rvbytes
;
1967 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1968 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1972 if (ms_setting
.mult_key_num
> 1)
1974 /* multi-get have check all the item */
1975 if (c
->mlget_task
.value_index
== c
->mlget_task
.mlget_num
- 1)
1977 ms_reset_conn(c
, false);
1983 ms_reset_conn(c
, false);
1985 } /* ms_bin_complete_nread */
1989 * we get here after reading the value of get commands.
1991 * @param c, pointer of the concurrency
1993 static void ms_complete_nread(ms_conn_t
*c
)
1996 assert(c
->rbytes
>= c
->rvbytes
);
1997 assert(c
->protocol
== ascii_prot
1998 || c
->protocol
== binary_prot
);
2000 if (c
->protocol
== binary_prot
)
2002 ms_bin_complete_nread(c
);
2006 ms_ascii_complete_nread(c
);
2008 } /* ms_complete_nread */
2012 * Adds a message header to a connection.
2014 * @param c, pointer of the concurrency
2016 * @return int, if success, return EXIT_SUCCESS, else return -1
2018 static int ms_add_msghdr(ms_conn_t
*c
)
2024 if (c
->msgsize
== c
->msgused
)
2027 realloc(c
->msglist
, (size_t)c
->msgsize
* 2 * sizeof(struct msghdr
));
2035 msg
= c
->msglist
+ c
->msgused
;
2038 * this wipes msg_iovlen, msg_control, msg_controllen, and
2039 * msg_flags, the last 3 of which aren't defined on solaris:
2041 memset(msg
, 0, sizeof(struct msghdr
));
2043 msg
->msg_iov
= &c
->iov
[c
->iovused
];
2045 if (c
->udp
&& (c
->srv_recv_addr_size
> 0))
2047 msg
->msg_name
= &c
->srv_recv_addr
;
2048 msg
->msg_namelen
= c
->srv_recv_addr_size
;
2056 /* Leave room for the UDP header, which we'll fill in later. */
2057 return ms_add_iov(c
, NULL
, UDP_HEADER_SIZE
);
2060 return EXIT_SUCCESS
;
2061 } /* ms_add_msghdr */
2065 * Ensures that there is room for another structure iovec in a connection's
2068 * @param c, pointer of the concurrency
2070 * @return int, if success, return EXIT_SUCCESS, else return -1
2072 static int ms_ensure_iov_space(ms_conn_t
*c
)
2076 if (c
->iovused
>= c
->iovsize
)
2079 struct iovec
*new_iov
= (struct iovec
*)realloc(c
->iov
,
2082 * sizeof(struct iovec
));
2089 /* Point all the msghdr structures at the new list. */
2090 for (i
= 0, iovnum
= 0; i
< c
->msgused
; i
++)
2092 c
->msglist
[i
].msg_iov
= &c
->iov
[iovnum
];
2093 iovnum
+= (int)c
->msglist
[i
].msg_iovlen
;
2097 return EXIT_SUCCESS
;
2098 } /* ms_ensure_iov_space */
2102 * Adds data to the list of pending data that will be written out to a
2105 * @param c, pointer of the concurrency
2106 * @param buf, the buffer includes data to send
2107 * @param len, the data length in the buffer
2109 * @return int, if success, return EXIT_SUCCESS, else return -1
2111 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
)
2121 m
= &c
->msglist
[c
->msgused
- 1];
2124 * Limit UDP packets, to UDP_MAX_PAYLOAD_SIZE bytes.
2126 limit_to_mtu
= c
->udp
;
2128 /* We may need to start a new msghdr if this one is full. */
2129 if ((m
->msg_iovlen
== IOV_MAX
)
2130 || (limit_to_mtu
&& (c
->msgbytes
>= UDP_MAX_SEND_PAYLOAD_SIZE
)))
2133 m
= &c
->msglist
[c
->msgused
- 1];
2136 if (ms_ensure_iov_space(c
) != 0)
2139 /* If the fragment is too big to fit in the datagram, split it up */
2140 if (limit_to_mtu
&& (len
+ c
->msgbytes
> UDP_MAX_SEND_PAYLOAD_SIZE
))
2142 leftover
= len
+ c
->msgbytes
- UDP_MAX_SEND_PAYLOAD_SIZE
;
2150 m
= &c
->msglist
[c
->msgused
- 1];
2151 m
->msg_iov
[m
->msg_iovlen
].iov_base
= (void *)buf
;
2152 m
->msg_iov
[m
->msg_iovlen
].iov_len
= (size_t)len
;
2158 buf
= ((char *)buf
) + len
;
2161 while (leftover
> 0);
2163 return EXIT_SUCCESS
;
2168 * Constructs a set of UDP headers and attaches them to the outgoing messages.
2170 * @param c, pointer of the concurrency
2172 * @return int, if success, return EXIT_SUCCESS, else return -1
2174 static int ms_build_udp_headers(ms_conn_t
*c
)
2181 c
->request_id
= ms_get_udp_request_id();
2183 if (c
->msgused
> c
->hdrsize
)
2187 new_hdrbuf
= realloc(c
->hdrbuf
,
2188 (size_t)c
->msgused
* 2 * UDP_HEADER_SIZE
);
2190 new_hdrbuf
= malloc((size_t)c
->msgused
* 2 * UDP_HEADER_SIZE
);
2194 c
->hdrbuf
= (unsigned char *)new_hdrbuf
;
2195 c
->hdrsize
= c
->msgused
* 2;
2198 /* If this is a multi-packet request, drop it. */
2199 if (c
->udp
&& (c
->msgused
> 1))
2201 fprintf(stderr
, "multi-packet request for UDP not supported.\n");
2206 for (i
= 0; i
< c
->msgused
; i
++)
2208 c
->msglist
[i
].msg_iov
[0].iov_base
= (void *)hdr
;
2209 c
->msglist
[i
].msg_iov
[0].iov_len
= UDP_HEADER_SIZE
;
2210 *hdr
++= (unsigned char)(c
->request_id
/ 256);
2211 *hdr
++= (unsigned char)(c
->request_id
% 256);
2212 *hdr
++= (unsigned char)(i
/ 256);
2213 *hdr
++= (unsigned char)(i
% 256);
2214 *hdr
++= (unsigned char)(c
->msgused
/ 256);
2215 *hdr
++= (unsigned char)(c
->msgused
% 256);
2216 *hdr
++= (unsigned char)1; /* support facebook memcached */
2217 *hdr
++= (unsigned char)0;
2219 ((unsigned char *)c
->msglist
[i
].msg_iov
[0].iov_base
2220 + UDP_HEADER_SIZE
));
2223 return EXIT_SUCCESS
;
2224 } /* ms_build_udp_headers */
2228 * Transmit the next chunk of data from our list of msgbuf structures.
2230 * @param c, pointer of the concurrency
2232 * @return TRANSMIT_COMPLETE All done writing.
2233 * TRANSMIT_INCOMPLETE More data remaining to write.
2234 * TRANSMIT_SOFT_ERROR Can't write any more right now.
2235 * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
2237 static int ms_transmit(ms_conn_t
*c
)
2241 if ((c
->msgcurr
< c
->msgused
)
2242 && (c
->msglist
[c
->msgcurr
].msg_iovlen
== 0))
2244 /* Finished writing the current msg; advance to the next. */
2248 if (c
->msgcurr
< c
->msgused
)
2251 struct msghdr
*m
= &c
->msglist
[c
->msgcurr
];
2253 res
= sendmsg(c
->sfd
, m
, 0);
2256 atomic_add_size(&ms_stats
.bytes_written
, res
);
2258 /* We've written some of the data. Remove the completed
2259 * iovec entries from the list of pending writes. */
2260 while (m
->msg_iovlen
> 0 && res
>= (ssize_t
)m
->msg_iov
->iov_len
)
2262 res
-= (ssize_t
)m
->msg_iov
->iov_len
;
2267 /* Might have written just part of the last iovec entry;
2268 * adjust it so the next write will do the rest. */
2271 m
->msg_iov
->iov_base
= (void *)((unsigned char *)m
->msg_iov
->iov_base
+ res
);
2272 m
->msg_iov
->iov_len
-= (size_t)res
;
2274 return TRANSMIT_INCOMPLETE
;
2276 if ((res
== -1) && ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
)))
2278 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2280 fprintf(stderr
, "Couldn't update event.\n");
2281 ms_conn_set_state(c
, conn_closing
);
2282 return TRANSMIT_HARD_ERROR
;
2284 return TRANSMIT_SOFT_ERROR
;
2287 /* if res==0 or res==-1 and error is not EAGAIN or EWOULDBLOCK,
2288 * we have a real error, on which we close the connection */
2289 fprintf(stderr
, "Failed to write, and not due to blocking.\n");
2291 ms_conn_set_state(c
, conn_closing
);
2292 return TRANSMIT_HARD_ERROR
;
2296 return TRANSMIT_COMPLETE
;
2302 * Shrinks a connection's buffers if they're too big. This prevents
2303 * periodic large "mget" response from server chewing lots of client
2306 * This should only be called in between requests since it can wipe output
2309 * @param c, pointer of the concurrency
2311 static void ms_conn_shrink(ms_conn_t
*c
)
2318 if ((c
->rsize
> READ_BUFFER_HIGHWAT
) && (c
->rbytes
< DATA_BUFFER_SIZE
))
2322 if (c
->rcurr
!= c
->rbuf
)
2323 memmove(c
->rbuf
, c
->rcurr
, (size_t)c
->rbytes
);
2325 newbuf
= (char *)realloc((void *)c
->rbuf
, DATA_BUFFER_SIZE
);
2330 c
->rsize
= DATA_BUFFER_SIZE
;
2335 if (c
->udp
&& (c
->rudpsize
> UDP_DATA_BUFFER_HIGHWAT
)
2336 && (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
< UDP_DATA_BUFFER_SIZE
))
2338 char *new_rbuf
= (char *)realloc(c
->rudpbuf
, (size_t)c
->rudpsize
* 2);
2341 c
->rudpbuf
= new_rbuf
;
2342 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
2344 /* TODO check error condition? */
2347 if (c
->msgsize
> MSG_LIST_HIGHWAT
)
2349 struct msghdr
*newbuf
= (struct msghdr
*)realloc(
2352 * sizeof(c
->msglist
[0]));
2356 c
->msgsize
= MSG_LIST_INITIAL
;
2358 /* TODO check error condition? */
2361 if (c
->iovsize
> IOV_LIST_HIGHWAT
)
2363 struct iovec
*newbuf
= (struct iovec
*)realloc((void *)c
->iov
,
2365 * sizeof(c
->iov
[0]));
2369 c
->iovsize
= IOV_LIST_INITIAL
;
2371 /* TODO check return value */
2373 } /* ms_conn_shrink */
2377 * Sets a connection's current state in the state machine. Any special
2378 * processing that needs to happen on certain state transitions can
2381 * @param c, pointer of the concurrency
2382 * @param state, connection state
2384 static void ms_conn_set_state(ms_conn_t
*c
, int state
)
2388 if (state
!= c
->state
)
2390 if (state
== conn_read
)
2396 } /* ms_conn_set_state */
2400 * update the event if socks change state. for example: when
2401 * change the listen scoket read event to sock write event, or
2402 * change socket handler, we could call this function.
2404 * @param c, pointer of the concurrency
2405 * @param new_flags, new event flags
2407 * @return bool, if success, return true, else return false
2409 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
)
2413 struct event_base
*base
= c
->event
.ev_base
;
2414 if ((c
->ev_flags
== new_flags
) && (ms_setting
.rep_write_srv
== 0)
2415 && (! ms_setting
.facebook_test
|| (c
->total_sfds
== 1)))
2420 if (event_del(&c
->event
) == -1)
2422 /* try to delete the event again */
2423 if (event_del(&c
->event
) == -1)
2429 event_set(&c
->event
,
2434 event_base_set(base
, &c
->event
);
2435 c
->ev_flags
= (short)new_flags
;
2437 if (event_add(&c
->event
, NULL
) == -1)
2443 } /* ms_update_event */
2447 * If user want to get the expected throughput, we could limit
2448 * the performance of memslap. we could give up some work and
2449 * just wait a short time. The function is used to check this
2452 * @param c, pointer of the concurrency
2454 * @return bool, if success, return true, else return false
2456 static bool ms_need_yield(ms_conn_t
*c
)
2458 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
2460 int64_t time_diff
= 0;
2461 struct timeval curr_time
;
2462 ms_task_t
*task
= &c
->curr_task
;
2464 if (ms_setting
.expected_tps
> 0)
2466 gettimeofday(&curr_time
, NULL
);
2467 time_diff
= ms_time_diff(&ms_thread
->startup_time
, &curr_time
);
2468 tps
= (int64_t)(((task
->get_opt
+ task
->set_opt
) / (uint64_t)time_diff
) * 1000000);
2470 /* current throughput is greater than expected throughput */
2471 if (tps
> ms_thread
->thread_ctx
->tps_perconn
)
2478 } /* ms_need_yield */
2482 * used to update the start time of each operation
2484 * @param c, pointer of the concurrency
2486 static void ms_update_start_time(ms_conn_t
*c
)
2488 ms_task_item_t
*item
= c
->curr_task
.item
;
2490 if ((ms_setting
.stat_freq
> 0) || c
->udp
2491 || ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0)))
2493 gettimeofday(&c
->start_time
, NULL
);
2494 if ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0))
2496 /* record the current time */
2497 item
->client_time
= c
->start_time
.tv_sec
;
2500 } /* ms_update_start_time */
2504 * run the state machine
2506 * @param c, pointer of the concurrency
2508 static void ms_drive_machine(ms_conn_t
*c
)
2521 if (c
->rbytes
>= c
->rvbytes
)
2523 ms_complete_nread(c
);
2529 if (ms_try_read_line(c
) != 0)
2535 if (ms_try_read_network(c
) != 0)
2540 /* doesn't read all the response data, wait event wake up */
2541 if (! c
->currcmd
.isfinish
)
2543 if (! ms_update_event(c
, EV_READ
| EV_PERSIST
))
2545 fprintf(stderr
, "Couldn't update event.\n");
2546 ms_conn_set_state(c
, conn_closing
);
2553 /* we have no command line and no data to read from network, next write */
2554 ms_conn_set_state(c
, conn_write
);
2555 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
2560 if (! c
->ctnwrite
&& ms_need_yield(c
))
2564 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2566 fprintf(stderr
, "Couldn't update event.\n");
2567 ms_conn_set_state(c
, conn_closing
);
2574 if (! c
->ctnwrite
&& (ms_exec_task(c
) != 0))
2576 ms_conn_set_state(c
, conn_closing
);
2580 /* record the start time before starting to send data if necessary */
2581 if (! c
->ctnwrite
|| (c
->change_sfd
&& c
->ctnwrite
))
2585 c
->change_sfd
= false;
2587 ms_update_start_time(c
);
2590 /* change sfd if necessary */
2598 /* execute task until nothing need be written to network */
2599 if (! c
->ctnwrite
&& (c
->msgcurr
== c
->msgused
))
2601 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2603 fprintf(stderr
, "Couldn't update event.\n");
2604 ms_conn_set_state(c
, conn_closing
);
2611 switch (ms_transmit(c
))
2613 case TRANSMIT_COMPLETE
:
2614 /* we have no data to write to network, next wait repose */
2615 if (! ms_update_event(c
, EV_READ
| EV_PERSIST
))
2617 fprintf(stderr
, "Couldn't update event.\n");
2618 ms_conn_set_state(c
, conn_closing
);
2622 ms_conn_set_state(c
, conn_read
);
2627 case TRANSMIT_INCOMPLETE
:
2629 break; /* Continue in state machine. */
2631 case TRANSMIT_HARD_ERROR
:
2635 case TRANSMIT_SOFT_ERROR
:
2647 /* recovery mode, need reconnect if connection close */
2648 if (ms_setting
.reconnect
&& (! ms_global
.time_out
2649 || ((ms_setting
.run_time
== 0)
2650 && (c
->remain_exec_num
> 0))))
2652 if (ms_reconn(c
) != 0)
2659 ms_reset_conn(c
, false);
2661 if (c
->total_sfds
== 1)
2663 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2665 fprintf(stderr
, "Couldn't update event.\n");
2666 ms_conn_set_state(c
, conn_closing
);
2684 } /* ms_drive_machine */
2688 * the event handler of each thread
2690 * @param fd, the file descriptor of socket
2691 * @param which, event flag
2692 * @param arg, argument
2694 void ms_event_handler(const int fd
, const short which
, void *arg
)
2696 ms_conn_t
*c
= (ms_conn_t
*)arg
;
2706 "Catastrophic: event fd: %d doesn't match conn fd: %d\n",
2712 assert(fd
== c
->sfd
);
2714 ms_drive_machine(c
);
2716 /* wait for next event */
2717 } /* ms_event_handler */
2721 * get the next socket descriptor index to run for replication
2723 * @param c, pointer of the concurrency
2724 * @param cmd, command(get or set )
2726 * @return int, if success, return the index, else return EXIT_SUCCESS
2728 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
)
2730 uint32_t sock_index
= 0;
2733 if (c
->total_sfds
== 1)
2735 return EXIT_SUCCESS
;
2738 if (ms_setting
.rep_write_srv
== 0)
2747 for (i
= 0; i
< ms_setting
.rep_write_srv
; i
++)
2749 if (c
->tcpsfd
[i
] > 0)
2755 if (i
== ms_setting
.rep_write_srv
)
2757 /* random get one replication server to read */
2758 sock_index
= (uint32_t)random() % c
->total_sfds
;
2762 /* random get one replication writing server to write */
2763 sock_index
= (uint32_t)random() % ms_setting
.rep_write_srv
;
2766 else if (cmd
== CMD_GET
)
2768 /* random get one replication server to read */
2769 sock_index
= (uint32_t)random() % c
->total_sfds
;
2772 while (c
->tcpsfd
[sock_index
] == 0);
2775 } /* ms_get_rep_sock_index */
2779 * get the next socket descriptor index to run
2781 * @param c, pointer of the concurrency
2783 * @return int, return the index
2785 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
)
2787 uint32_t sock_index
= 0;
2791 sock_index
= (++c
->cur_idx
== c
->total_sfds
) ? 0 : c
->cur_idx
;
2793 while (c
->tcpsfd
[sock_index
] == 0);
2796 } /* ms_get_next_sock_index */
2800 * update socket event of the connections
2802 * @param c, pointer of the concurrency
2804 * @return int, if success, return EXIT_SUCCESS, else return -1
2806 static int ms_update_conn_sock_event(ms_conn_t
*c
)
2810 switch (c
->currcmd
.cmd
)
2813 if (ms_setting
.facebook_test
&& c
->udp
)
2815 c
->sfd
= c
->tcpsfd
[0];
2817 c
->change_sfd
= true;
2822 if (ms_setting
.facebook_test
&& ! c
->udp
)
2826 c
->change_sfd
= true;
2834 if (! c
->udp
&& (c
->total_sfds
> 1))
2836 if (c
->cur_idx
!= c
->total_sfds
)
2838 if (ms_setting
.rep_write_srv
== 0)
2840 c
->cur_idx
= ms_get_next_sock_index(c
);
2844 c
->cur_idx
= ms_get_rep_sock_index(c
, c
->currcmd
.cmd
);
2849 /* must select the first sock of the connection at the beginning */
2853 c
->sfd
= c
->tcpsfd
[c
->cur_idx
];
2854 assert(c
->sfd
!= 0);
2855 c
->change_sfd
= true;
2860 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2862 fprintf(stderr
, "Couldn't update event.\n");
2863 ms_conn_set_state(c
, conn_closing
);
2868 return EXIT_SUCCESS
;
2869 } /* ms_update_conn_sock_event */
2873 * for ASCII protocol, this function build the set command
2874 * string and send the command.
2876 * @param c, pointer of the concurrency
2877 * @param item, pointer of task item which includes the object
2880 * @return int, if success, return EXIT_SUCCESS, else return -1
2882 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
)
2886 char *buffer
= c
->wbuf
;
2888 write_len
= snprintf(buffer
,
2895 if (write_len
> c
->wsize
|| write_len
< 0)
2897 /* ought to be always enough. just fail for simplicity */
2898 fprintf(stderr
, "output command line too long.\n");
2902 if (item
->value_offset
== INVALID_OFFSET
)
2904 value_offset
= item
->key_suffix_offset
;
2908 value_offset
= item
->value_offset
;
2911 if ((ms_add_iov(c
, "set ", 4) != 0)
2912 || (ms_add_iov(c
, (char *)&item
->key_prefix
,
2913 (int)KEY_PREFIX_SIZE
) != 0)
2914 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
2915 item
->key_size
- (int)KEY_PREFIX_SIZE
) != 0)
2916 || (ms_add_iov(c
, buffer
, write_len
) != 0)
2917 || (ms_add_iov(c
, &ms_setting
.char_block
[value_offset
],
2918 item
->value_size
) != 0)
2919 || (ms_add_iov(c
, "\r\n", 2) != 0)
2920 || (c
->udp
&& (ms_build_udp_headers(c
) != 0)))
2925 return EXIT_SUCCESS
;
2926 } /* ms_build_ascii_write_buf_set */
2930 * used to send set command to server
2932 * @param c, pointer of the concurrency
2933 * @param item, pointer of task item which includes the object
2936 * @return int, if success, return EXIT_SUCCESS, else return -1
2938 int ms_mcd_set(ms_conn_t
*c
, ms_task_item_t
*item
)
2942 c
->currcmd
.cmd
= CMD_SET
;
2943 c
->currcmd
.isfinish
= false;
2944 c
->currcmd
.retstat
= MCD_FAILURE
;
2946 if (ms_update_conn_sock_event(c
) != 0)
2954 if (ms_add_msghdr(c
) != 0)
2956 fprintf(stderr
, "Out of memory preparing request.");
2960 /* binary protocol */
2961 if (c
->protocol
== binary_prot
)
2963 if (ms_build_bin_write_buf_set(c
, item
) != 0)
2970 if (ms_build_ascii_write_buf_set(c
, item
) != 0)
2976 atomic_add_size(&ms_stats
.obj_bytes
,
2977 item
->key_size
+ item
->value_size
);
2978 atomic_add_size(&ms_stats
.cmd_set
, 1);
2980 return EXIT_SUCCESS
;
2985 * for ASCII protocol, this function build the get command
2986 * string and send the command.
2988 * @param c, pointer of the concurrency
2989 * @param item, pointer of task item which includes the object
2992 * @return int, if success, return EXIT_SUCCESS, else return -1
2994 static int ms_build_ascii_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
)
2996 if ((ms_add_iov(c
, "get ", 4) != 0)
2997 || (ms_add_iov(c
, (char *)&item
->key_prefix
,
2998 (int)KEY_PREFIX_SIZE
) != 0)
2999 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
3000 item
->key_size
- (int)KEY_PREFIX_SIZE
) != 0)
3001 || (ms_add_iov(c
, "\r\n", 2) != 0)
3002 || (c
->udp
&& (ms_build_udp_headers(c
) != 0)))
3007 return EXIT_SUCCESS
;
3008 } /* ms_build_ascii_write_buf_get */
3012 * used to send the get command to server
3014 * @param c, pointer of the concurrency
3015 * @param item, pointer of task item which includes the object
3018 * @return int, if success, return EXIT_SUCCESS, else return -1
3020 int ms_mcd_get(ms_conn_t
*c
, ms_task_item_t
*item
)
3024 c
->currcmd
.cmd
= CMD_GET
;
3025 c
->currcmd
.isfinish
= false;
3026 c
->currcmd
.retstat
= MCD_FAILURE
;
3028 if (ms_update_conn_sock_event(c
) != 0)
3036 if (ms_add_msghdr(c
) != 0)
3038 fprintf(stderr
, "Out of memory preparing request.");
3042 /* binary protocol */
3043 if (c
->protocol
== binary_prot
)
3045 if (ms_build_bin_write_buf_get(c
, item
) != 0)
3052 if (ms_build_ascii_write_buf_get(c
, item
) != 0)
3058 atomic_add_size(&ms_stats
.cmd_get
, 1);
3060 return EXIT_SUCCESS
;
3065 * for ASCII protocol, this function build the multi-get command
3066 * string and send the command.
3068 * @param c, pointer of the concurrency
3070 * @return int, if success, return EXIT_SUCCESS, else return -1
3072 static int ms_build_ascii_write_buf_mlget(ms_conn_t
*c
)
3074 ms_task_item_t
*item
;
3076 if (ms_add_iov(c
, "get", 3) != 0)
3081 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
3083 item
= c
->mlget_task
.mlget_item
[i
].item
;
3084 assert(item
!= NULL
);
3085 if ((ms_add_iov(c
, " ", 1) != 0)
3086 || (ms_add_iov(c
, (char *)&item
->key_prefix
,
3087 (int)KEY_PREFIX_SIZE
) != 0)
3088 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
3089 item
->key_size
- (int)KEY_PREFIX_SIZE
) != 0))
3095 if ((ms_add_iov(c
, "\r\n", 2) != 0)
3096 || (c
->udp
&& (ms_build_udp_headers(c
) != 0)))
3101 return EXIT_SUCCESS
;
3102 } /* ms_build_ascii_write_buf_mlget */
3106 * used to send the multi-get command to server
3108 * @param c, pointer of the concurrency
3110 * @return int, if success, return EXIT_SUCCESS, else return -1
3112 int ms_mcd_mlget(ms_conn_t
*c
)
3114 ms_task_item_t
*item
;
3117 assert(c
->mlget_task
.mlget_num
>= 1);
3119 c
->currcmd
.cmd
= CMD_GET
;
3120 c
->currcmd
.isfinish
= false;
3121 c
->currcmd
.retstat
= MCD_FAILURE
;
3123 if (ms_update_conn_sock_event(c
) != 0)
3131 if (ms_add_msghdr(c
) != 0)
3133 fprintf(stderr
, "Out of memory preparing request.");
3137 /* binary protocol */
3138 if (c
->protocol
== binary_prot
)
3140 if (ms_build_bin_write_buf_mlget(c
) != 0)
3147 if (ms_build_ascii_write_buf_mlget(c
) != 0)
3153 /* decrease operation time of each item */
3154 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
3156 item
= c
->mlget_task
.mlget_item
[i
].item
;
3157 atomic_add_size(&ms_stats
.cmd_get
, 1);
3160 return EXIT_SUCCESS
;
3161 } /* ms_mcd_mlget */
3165 * binary protocol support
3169 * for binary protocol, parse the response of server
3171 * @param c, pointer of the concurrency
3173 * @return int, if success, return EXIT_SUCCESS, else return -1
3175 static int ms_bin_process_response(ms_conn_t
*c
)
3177 const char *errstr
= NULL
;
3181 uint32_t bodylen
= c
->binary_header
.response
.bodylen
;
3182 uint8_t opcode
= c
->binary_header
.response
.opcode
;
3183 uint16_t status
= c
->binary_header
.response
.status
;
3187 c
->rvbytes
= (int32_t)bodylen
;
3189 return EXIT_FAILURE
;
3195 case PROTOCOL_BINARY_RESPONSE_SUCCESS
:
3196 if (opcode
== PROTOCOL_BINARY_CMD_SET
)
3198 c
->currcmd
.retstat
= MCD_STORED
;
3200 else if (opcode
== PROTOCOL_BINARY_CMD_DELETE
)
3202 c
->currcmd
.retstat
= MCD_DELETED
;
3204 else if (opcode
== PROTOCOL_BINARY_CMD_GET
)
3206 c
->currcmd
.retstat
= MCD_END
;
3210 case PROTOCOL_BINARY_RESPONSE_ENOMEM
:
3211 errstr
= "Out of memory";
3212 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
3215 case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND
:
3216 errstr
= "Unknown command";
3217 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
3220 case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT
:
3221 errstr
= "Not found";
3222 c
->currcmd
.retstat
= MCD_NOTFOUND
;
3225 case PROTOCOL_BINARY_RESPONSE_EINVAL
:
3226 errstr
= "Invalid arguments";
3227 c
->currcmd
.retstat
= MCD_PROTOCOL_ERROR
;
3230 case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS
:
3231 errstr
= "Data exists for key.";
3234 case PROTOCOL_BINARY_RESPONSE_E2BIG
:
3235 errstr
= "Too large.";
3236 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
3239 case PROTOCOL_BINARY_RESPONSE_NOT_STORED
:
3240 errstr
= "Not stored.";
3241 c
->currcmd
.retstat
= MCD_NOTSTORED
;
3245 errstr
= "Unknown error";
3246 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
3252 fprintf(stderr
, "%s\n", errstr
);
3256 return EXIT_SUCCESS
;
3257 } /* ms_bin_process_response */
3260 /* build binary header and add the header to the buffer to send */
3263 * build binary header and add the header to the buffer to send
3265 * @param c, pointer of the concurrency
3266 * @param opcode, operation code
3267 * @param hdr_len, length of header
3268 * @param key_len, length of key
3269 * @param body_len. length of body
3271 static void ms_add_bin_header(ms_conn_t
*c
,
3277 protocol_binary_request_header
*header
;
3281 header
= (protocol_binary_request_header
*)c
->wcurr
;
3283 header
->request
.magic
= (uint8_t)PROTOCOL_BINARY_REQ
;
3284 header
->request
.opcode
= (uint8_t)opcode
;
3285 header
->request
.keylen
= htons(key_len
);
3287 header
->request
.extlen
= (uint8_t)hdr_len
;
3288 header
->request
.datatype
= (uint8_t)PROTOCOL_BINARY_RAW_BYTES
;
3289 header
->request
.vbucket
= 0;
3291 header
->request
.bodylen
= htonl(body_len
);
3292 header
->request
.opaque
= 0;
3293 header
->request
.cas
= 0;
3295 ms_add_iov(c
, c
->wcurr
, sizeof(header
->request
));
3296 } /* ms_add_bin_header */
3300 * add the key to the socket write buffer array
3302 * @param c, pointer of the concurrency
3303 * @param item, pointer of task item which includes the object
3306 static void ms_add_key_to_iov(ms_conn_t
*c
, ms_task_item_t
*item
)
3308 ms_add_iov(c
, (char *)&item
->key_prefix
, (int)KEY_PREFIX_SIZE
);
3309 ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
3310 item
->key_size
- (int)KEY_PREFIX_SIZE
);
3315 * for binary protocol, this function build the set command
3316 * and add the command to send buffer array.
3318 * @param c, pointer of the concurrency
3319 * @param item, pointer of task item which includes the object
3322 * @return int, if success, return EXIT_SUCCESS, else return -1
3324 static int ms_build_bin_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
)
3326 assert(c
->wbuf
== c
->wcurr
);
3329 protocol_binary_request_set
*rep
= (protocol_binary_request_set
*)c
->wcurr
;
3330 uint16_t keylen
= (uint16_t)item
->key_size
;
3331 uint32_t bodylen
= (uint32_t)sizeof(rep
->message
.body
)
3332 + (uint32_t)keylen
+ (uint32_t)item
->value_size
;
3334 ms_add_bin_header(c
,
3335 PROTOCOL_BINARY_CMD_SET
,
3336 sizeof(rep
->message
.body
),
3339 rep
->message
.body
.flags
= 0;
3340 rep
->message
.body
.expiration
= htonl((uint32_t)item
->exp_time
);
3341 ms_add_iov(c
, &rep
->message
.body
, sizeof(rep
->message
.body
));
3342 ms_add_key_to_iov(c
, item
);
3344 if (item
->value_offset
== INVALID_OFFSET
)
3346 value_offset
= item
->key_suffix_offset
;
3350 value_offset
= item
->value_offset
;
3352 ms_add_iov(c
, &ms_setting
.char_block
[value_offset
], item
->value_size
);
3354 return EXIT_SUCCESS
;
3355 } /* ms_build_bin_write_buf_set */
3359 * for binary protocol, this function build the get command and
3360 * add the command to send buffer array.
3362 * @param c, pointer of the concurrency
3363 * @param item, pointer of task item which includes the object
3366 * @return int, if success, return EXIT_SUCCESS, else return -1
3368 static int ms_build_bin_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
)
3370 assert(c
->wbuf
== c
->wcurr
);
3372 ms_add_bin_header(c
, PROTOCOL_BINARY_CMD_GET
, 0, (uint16_t)item
->key_size
,
3373 (uint32_t)item
->key_size
);
3374 ms_add_key_to_iov(c
, item
);
3376 return EXIT_SUCCESS
;
3377 } /* ms_build_bin_write_buf_get */
3381 * for binary protocol, this function build the multi-get
3382 * command and add the command to send buffer array.
3384 * @param c, pointer of the concurrency
3385 * @param item, pointer of task item which includes the object
3388 * @return int, if success, return EXIT_SUCCESS, else return -1
3390 static int ms_build_bin_write_buf_mlget(ms_conn_t
*c
)
3392 ms_task_item_t
*item
;
3394 assert(c
->wbuf
== c
->wcurr
);
3396 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
3398 item
= c
->mlget_task
.mlget_item
[i
].item
;
3399 assert(item
!= NULL
);
3401 ms_add_bin_header(c
,
3402 PROTOCOL_BINARY_CMD_GET
,
3404 (uint16_t)item
->key_size
,
3405 (uint32_t)item
->key_size
);
3406 ms_add_key_to_iov(c
, item
);
3407 c
->wcurr
+= sizeof(protocol_binary_request_get
);
3412 return EXIT_SUCCESS
;
3413 } /* ms_build_bin_write_buf_mlget */