3 * Author: Mingqiang Zhuang
5 * Created on February 10, 2009
7 * (c) Copyright 2009, Schooner Information Technology, Inc.
8 * http://www.schoonerinfotech.com/
12 #include "mem_config.h"
20 #include <netinet/tcp.h>
21 #include <netinet/in.h>
22 #include <arpa/inet.h>
24 #if defined(HAVE_SYS_TIME_H)
25 # include <sys/time.h>
28 #if defined(HAVE_TIME_H)
32 #include "ms_setting.h"
33 #include "ms_thread.h"
34 #include "ms_atomic.h"
37 /* /usr/include/netinet/in.h defines macros from ntohs() to _bswap_nn to
38 * optimize the conversion functions, but the prototypes generate warnings
39 * from gcc. The conversion methods isn't the bottleneck for my app, so
40 * just remove the warnings by undef'ing the optimization ..
48 /* for network write */
49 #define TRANSMIT_COMPLETE 0
50 #define TRANSMIT_INCOMPLETE 1
51 #define TRANSMIT_SOFT_ERROR 2
52 #define TRANSMIT_HARD_ERROR 3
54 /* for generating key */
55 #define KEY_PREFIX_BASE 0x1010101010101010 /* not include ' ' '\r' '\n' '\0' */
56 #define KEY_PREFIX_MASK 0x1010101010101010
58 /* For parse the value length return by server */
60 #define VALUELEN_TOKEN 3
62 /* global increasing counter, to ensure the key prefix unique */
63 static uint64_t key_prefix_seq
= KEY_PREFIX_BASE
;
65 /* global increasing counter, generating request id for UDP */
66 static volatile uint32_t udp_request_id
= 0;
68 extern pthread_key_t ms_thread_key
;
70 /* generate upd request id */
71 static uint32_t ms_get_udp_request_id(void);
74 /* connect initialize */
75 static void ms_task_init(ms_conn_t
*c
);
76 static int ms_conn_udp_init(ms_conn_t
*c
, const bool is_udp
);
77 static int ms_conn_sock_init(ms_conn_t
*c
);
78 static int ms_conn_event_init(ms_conn_t
*c
);
79 static int ms_conn_init(ms_conn_t
*c
,
81 const int read_buffer_size
,
83 static void ms_warmup_num_init(ms_conn_t
*c
);
84 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
);
92 /* create network connection */
93 static int ms_new_socket(struct addrinfo
*ai
);
94 static void ms_maximize_sndbuf(const int sfd
);
95 static int ms_network_connect(ms_conn_t
*c
,
100 static int ms_reconn(ms_conn_t
*c
);
104 static int ms_tokenize_command(char *command
,
106 const int max_tokens
);
107 static int ms_ascii_process_line(ms_conn_t
*c
, char *command
);
108 static int ms_try_read_line(ms_conn_t
*c
);
109 static int ms_sort_udp_packet(ms_conn_t
*c
, char *buf
, int rbytes
);
110 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
);
111 static int ms_try_read_network(ms_conn_t
*c
);
112 static void ms_verify_value(ms_conn_t
*c
,
113 ms_mlget_task_item_t
*mlget_item
,
116 static void ms_ascii_complete_nread(ms_conn_t
*c
);
117 static void ms_bin_complete_nread(ms_conn_t
*c
);
118 static void ms_complete_nread(ms_conn_t
*c
);
122 static int ms_add_msghdr(ms_conn_t
*c
);
123 static int ms_ensure_iov_space(ms_conn_t
*c
);
124 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
);
125 static int ms_build_udp_headers(ms_conn_t
*c
);
126 static int ms_transmit(ms_conn_t
*c
);
129 /* status adjustment */
130 static void ms_conn_shrink(ms_conn_t
*c
);
131 static void ms_conn_set_state(ms_conn_t
*c
, int state
);
132 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
);
133 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
);
134 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
);
135 static int ms_update_conn_sock_event(ms_conn_t
*c
);
136 static bool ms_need_yield(ms_conn_t
*c
);
137 static void ms_update_start_time(ms_conn_t
*c
);
141 static void ms_drive_machine(ms_conn_t
*c
);
142 void ms_event_handler(const int fd
, const short which
, void *arg
);
146 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
);
147 static int ms_build_ascii_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
);
148 static int ms_build_ascii_write_buf_mlget(ms_conn_t
*c
);
151 /* binary protocol */
152 static int ms_bin_process_response(ms_conn_t
*c
);
153 static void ms_add_bin_header(ms_conn_t
*c
,
158 static void ms_add_key_to_iov(ms_conn_t
*c
, ms_task_item_t
*item
);
159 static int ms_build_bin_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
);
160 static int ms_build_bin_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
);
161 static int ms_build_bin_write_buf_mlget(ms_conn_t
*c
);
165 * each key has two parts, prefix and suffix. The suffix is a
166 * string random get form the character table. The prefix is a
167 * uint64_t variable. And the prefix must be unique. we use the
168 * prefix to identify a key. And the prefix can't include
169 * character ' ' '\r' '\n' '\0'.
173 uint64_t ms_get_key_prefix(void)
177 pthread_mutex_lock(&ms_global
.seq_mutex
);
178 key_prefix_seq
|= KEY_PREFIX_MASK
;
179 key_prefix
= key_prefix_seq
;
181 pthread_mutex_unlock(&ms_global
.seq_mutex
);
184 } /* ms_get_key_prefix */
188 * get an unique udp request id
190 * @return an unique UDP request id
192 static uint32_t ms_get_udp_request_id(void)
194 return atomic_add_32_nv(&udp_request_id
, 1);
199 * initialize current task structure
201 * @param c, pointer of the concurrency
203 static void ms_task_init(ms_conn_t
*c
)
205 c
->curr_task
.cmd
= CMD_NULL
;
206 c
->curr_task
.item
= 0;
207 c
->curr_task
.verify
= false;
208 c
->curr_task
.finish_verify
= true;
209 c
->curr_task
.get_miss
= true;
211 c
->curr_task
.get_opt
= 0;
212 c
->curr_task
.set_opt
= 0;
213 c
->curr_task
.cycle_undo_get
= 0;
214 c
->curr_task
.cycle_undo_set
= 0;
215 c
->curr_task
.verified_get
= 0;
216 c
->curr_task
.overwrite_set
= 0;
221 * initialize udp for the connection structure
223 * @param c, pointer of the concurrency
224 * @param is_udp, whether it's udp
226 * @return int, if success, return EXIT_SUCCESS, else return -1
228 static int ms_conn_udp_init(ms_conn_t
*c
, const bool is_udp
)
234 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
245 if (c
->udp
|| (! c
->udp
&& ms_setting
.facebook_test
))
247 c
->rudpbuf
= (char *)malloc((size_t)c
->rudpsize
);
248 c
->udppkt
= (ms_udppkt_t
*)malloc(MAX_UDP_PACKET
* sizeof(ms_udppkt_t
));
250 if ((c
->rudpbuf
== NULL
) || (c
->udppkt
== NULL
))
252 if (c
->rudpbuf
!= NULL
)
254 if (c
->udppkt
!= NULL
)
256 fprintf(stderr
, "malloc()\n");
259 memset(c
->udppkt
, 0, MAX_UDP_PACKET
* sizeof(ms_udppkt_t
));
263 } /* ms_conn_udp_init */
267 * initialize the connection structure
269 * @param c, pointer of the concurrency
270 * @param init_state, (conn_read, conn_write, conn_closing)
271 * @param read_buffer_size
272 * @param is_udp, whether it's udp
274 * @return int, if success, return EXIT_SUCCESS, else return -1
276 static int ms_conn_init(ms_conn_t
*c
,
277 const int init_state
,
278 const int read_buffer_size
,
287 c
->rsize
= read_buffer_size
;
288 c
->wsize
= WRITE_BUFFER_SIZE
;
289 c
->iovsize
= IOV_LIST_INITIAL
;
290 c
->msgsize
= MSG_LIST_INITIAL
;
292 /* for replication, each connection need connect all the server */
293 if (ms_setting
.rep_write_srv
> 0)
295 c
->total_sfds
= ms_setting
.srv_cnt
* ms_setting
.sock_per_conn
;
299 c
->total_sfds
= ms_setting
.sock_per_conn
;
303 c
->rbuf
= (char *)malloc((size_t)c
->rsize
);
304 c
->wbuf
= (char *)malloc((size_t)c
->wsize
);
305 c
->iov
= (struct iovec
*)malloc(sizeof(struct iovec
) * (size_t)c
->iovsize
);
306 c
->msglist
= (struct msghdr
*)malloc(
307 sizeof(struct msghdr
) * (size_t)c
->msgsize
);
308 if (ms_setting
.mult_key_num
> 1)
310 c
->mlget_task
.mlget_item
= (ms_mlget_task_item_t
*)
312 sizeof(ms_mlget_task_item_t
) * (size_t)ms_setting
.mult_key_num
);
314 c
->tcpsfd
= (int *)malloc((size_t)c
->total_sfds
* sizeof(int));
316 if ((c
->rbuf
== NULL
) || (c
->wbuf
== NULL
) || (c
->iov
== NULL
)
317 || (c
->msglist
== NULL
) || (c
->tcpsfd
== NULL
)
318 || ((ms_setting
.mult_key_num
> 1)
319 && (c
->mlget_task
.mlget_item
== NULL
)))
327 if (c
->msglist
!= NULL
)
329 if (c
->mlget_task
.mlget_item
!= NULL
)
330 free(c
->mlget_task
.mlget_item
);
331 if (c
->tcpsfd
!= NULL
)
333 fprintf(stderr
, "malloc()\n");
337 c
->state
= init_state
;
345 c
->cur_idx
= c
->total_sfds
; /* default index is a invalid value */
349 c
->change_sfd
= false;
351 c
->precmd
.cmd
= c
->currcmd
.cmd
= CMD_NULL
;
352 c
->precmd
.isfinish
= true; /* default the previous command finished */
353 c
->currcmd
.isfinish
= false;
354 c
->precmd
.retstat
= c
->currcmd
.retstat
= MCD_FAILURE
;
355 c
->precmd
.key_prefix
= c
->currcmd
.key_prefix
= 0;
357 c
->mlget_task
.mlget_num
= 0;
358 c
->mlget_task
.value_index
= -1; /* default invalid value */
360 if (ms_setting
.binary_prot_
)
362 c
->protocol
= binary_prot
;
366 c
->protocol
= ascii_prot
;
370 if (ms_conn_udp_init(c
, is_udp
) != 0)
375 /* initialize task */
378 if (! (ms_setting
.facebook_test
&& is_udp
))
380 atomic_add_32(&ms_stats
.active_conns
, 1);
388 * when doing 100% get operation, it could preset some objects
389 * to warmup the server. this function is used to initialize the
390 * number of the objects to preset.
392 * @param c, pointer of the concurrency
394 static void ms_warmup_num_init(ms_conn_t
*c
)
396 /* no set operation, preset all the items in the window */
397 if (ms_setting
.cmd_distr
[CMD_SET
].cmd_prop
< PROP_ERROR
)
399 c
->warmup_num
= c
->win_size
;
400 c
->remain_warmup_num
= c
->warmup_num
;
405 c
->remain_warmup_num
= c
->warmup_num
;
407 } /* ms_warmup_num_init */
411 * each connection has an item window, this function initialize
412 * the window. The window is used to generate task.
414 * @param c, pointer of the concurrency
416 * @return int, if success, return EXIT_SUCCESS, else return -1
418 static int ms_item_win_init(ms_conn_t
*c
)
420 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
423 c
->win_size
= (int)ms_setting
.win_size
;
425 c
->exec_num
= ms_thread
->thread_ctx
->exec_num_perconn
;
426 c
->remain_exec_num
= c
->exec_num
;
428 c
->item_win
= (ms_task_item_t
*)malloc(
429 sizeof(ms_task_item_t
) * (size_t)c
->win_size
);
430 if (c
->item_win
== NULL
)
432 fprintf(stderr
, "Can't allocate task item array for conn.\n");
435 memset(c
->item_win
, 0, sizeof(ms_task_item_t
) * (size_t)c
->win_size
);
437 for (int i
= 0; i
< c
->win_size
; i
++)
439 c
->item_win
[i
].key_size
= (int)ms_setting
.distr
[i
].key_size
;
440 c
->item_win
[i
].key_prefix
= ms_get_key_prefix();
441 c
->item_win
[i
].key_suffix_offset
= ms_setting
.distr
[i
].key_offset
;
442 c
->item_win
[i
].value_size
= (int)ms_setting
.distr
[i
].value_size
;
443 c
->item_win
[i
].value_offset
= INVALID_OFFSET
; /* default in invalid offset */
444 c
->item_win
[i
].client_time
= 0;
446 /* set expire time base on the proportion */
447 if (exp_cnt
< ms_setting
.exp_ver_per
* i
)
449 c
->item_win
[i
].exp_time
= FIXED_EXPIRE_TIME
;
454 c
->item_win
[i
].exp_time
= 0;
458 ms_warmup_num_init(c
);
461 } /* ms_item_win_init */
465 * each connection structure can include one or more sock
466 * handlers. this function create these socks and connect the
469 * @param c, pointer of the concurrency
471 * @return int, if success, return EXIT_SUCCESS, else return -1
473 static int ms_conn_sock_init(ms_conn_t
*c
)
475 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
481 assert(c
->tcpsfd
!= NULL
);
483 for (i
= 0; i
< c
->total_sfds
; i
++)
486 if (ms_setting
.rep_write_srv
> 0)
488 /* for replication, each connection need connect all the server */
489 srv_idx
= i
% ms_setting
.srv_cnt
;
493 /* all the connections in a thread connects the same server */
494 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
497 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
498 ms_setting
.servers
[srv_idx
].srv_port
,
499 ms_setting
.udp
, &ret_sfd
) != 0)
509 if (! ms_setting
.udp
)
511 c
->tcpsfd
[i
]= ret_sfd
;
517 /* initialize udp sock handler if necessary */
518 if (ms_setting
.facebook_test
)
521 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
522 ms_setting
.servers
[srv_idx
].srv_port
,
523 true, &ret_sfd
) != 0)
533 if ((i
!= c
->total_sfds
) || (ms_setting
.facebook_test
&& (c
->udpsfd
== 0)))
541 for (uint32_t j
= 0; j
< i
; j
++)
556 } /* ms_conn_sock_init */
560 * each connection is managed by libevent, this function
561 * initialize the event of the connection structure.
563 * @param c, pointer of the concurrency
565 * @return int, if success, return EXIT_SUCCESS, else return -1
567 static int ms_conn_event_init(ms_conn_t
*c
)
569 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
570 short event_flags
= EV_WRITE
| EV_PERSIST
;
572 event_set(&c
->event
, c
->sfd
, event_flags
, ms_event_handler
, (void *)c
);
573 event_base_set(ms_thread
->base
, &c
->event
);
574 c
->ev_flags
= event_flags
;
576 if (event_add(&c
->event
, NULL
) == -1)
582 } /* ms_conn_event_init */
586 * setup a connection, each connection structure of each
587 * thread must call this function to initialize.
589 * @param c, pointer of the concurrency
591 * @return int, if success, return EXIT_SUCCESS, else return -1
593 int ms_setup_conn(ms_conn_t
*c
)
595 if (ms_item_win_init(c
) != 0)
600 if (ms_conn_init(c
, conn_write
, DATA_BUFFER_SIZE
, ms_setting
.udp
) != 0)
605 if (ms_conn_sock_init(c
) != 0)
610 if (ms_conn_event_init(c
) != 0)
616 } /* ms_setup_conn */
620 * Frees a connection.
622 * @param c, pointer of the concurrency
624 void ms_conn_free(ms_conn_t
*c
)
626 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
629 if (c
->hdrbuf
!= NULL
)
631 if (c
->msglist
!= NULL
)
639 if (c
->mlget_task
.mlget_item
!= NULL
)
640 free(c
->mlget_task
.mlget_item
);
641 if (c
->rudpbuf
!= NULL
)
643 if (c
->udppkt
!= NULL
)
645 if (c
->item_win
!= NULL
)
647 if (c
->tcpsfd
!= NULL
)
650 if (--ms_thread
->nactive_conn
== 0)
652 free(ms_thread
->conn
);
661 * @param c, pointer of the concurrency
663 static void ms_conn_close(ms_conn_t
*c
)
665 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
668 /* delete the event, the socket and the connection */
669 event_del(&c
->event
);
671 for (uint32_t i
= 0; i
< c
->total_sfds
; i
++)
673 if (c
->tcpsfd
[i
] > 0)
680 if (ms_setting
.facebook_test
)
685 atomic_dec_32(&ms_stats
.active_conns
);
689 if (ms_setting
.run_time
== 0)
691 pthread_mutex_lock(&ms_global
.run_lock
.lock
);
692 ms_global
.run_lock
.count
++;
693 pthread_cond_signal(&ms_global
.run_lock
.cond
);
694 pthread_mutex_unlock(&ms_global
.run_lock
.lock
);
697 if (ms_thread
->nactive_conn
== 0)
701 } /* ms_conn_close */
707 * @param ai, server address information
709 * @return int, if success, return EXIT_SUCCESS, else return -1
711 static int ms_new_socket(struct addrinfo
*ai
)
715 if ((sfd
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
)) == -1)
717 fprintf(stderr
, "socket() error: %s.\n", strerror(errno
));
722 } /* ms_new_socket */
726 * Sets a socket's send buffer size to the maximum allowed by the system.
728 * @param sfd, file descriptor of socket
730 static void ms_maximize_sndbuf(const int sfd
)
732 socklen_t intsize
= sizeof(int);
733 unsigned int last_good
= 0;
734 unsigned int min
, max
, avg
;
735 unsigned int old_size
;
737 /* Start with the default size. */
738 if (getsockopt(sfd
, SOL_SOCKET
, SO_SNDBUF
, &old_size
, &intsize
) != 0)
740 fprintf(stderr
, "getsockopt(SO_SNDBUF)\n");
744 /* Binary-search for the real maximum. */
746 max
= MAX_SENDBUF_SIZE
;
750 avg
= ((unsigned int)(min
+ max
)) / 2;
751 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 */
1549 return wbytes
== 0 ? -1 : wbytes
;
1550 } /* ms_sort_udp_packet */
1554 * encapsulate upd read like tcp read
1556 * @param c, pointer of the concurrency
1557 * @param buf, read buffer
1558 * @param len, length to read
1560 * @return int, if success, return the read bytes, else return
1563 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
)
1574 if (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
> c
->rudpsize
)
1576 char *new_rbuf
= realloc(c
->rudpbuf
, (size_t)c
->rudpsize
* 2);
1579 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1580 c
->rudpbytes
= 0; /* ignore what we read */
1583 c
->rudpbuf
= new_rbuf
;
1587 avail
= c
->rudpsize
- c
->rudpbytes
;
1588 /* UDP each time read a packet, 1400 bytes */
1589 res
= (int)read(c
->sfd
, c
->rudpbuf
+ c
->rudpbytes
, (size_t)avail
);
1593 atomic_add_size(&ms_stats
.bytes_read
, res
);
1608 /* "connection" closed */
1614 /* no data to read */
1619 /* copy data to read buffer */
1622 copybytes
= ms_sort_udp_packet(c
, buf
, len
);
1625 if (copybytes
== -1)
1627 atomic_add_size(&ms_stats
.pkt_disorder
, 1);
1635 * read from network as much as we can, handle buffer overflow and connection
1637 * before reading, move the remaining incomplete fragment of a command
1638 * (if any) to the beginning of the buffer.
1639 * return EXIT_SUCCESS if there's nothing to read on the first read.
1643 * read from network as much as we can, handle buffer overflow and connection
1644 * close. before reading, move the remaining incomplete fragment of a command
1645 * (if any) to the beginning of the buffer.
1647 * @param c, pointer of the concurrency
1650 * return EXIT_SUCCESS if there's nothing to read on the first read.
1651 * return EXIT_FAILURE if get data
1652 * return -1 if error happens
1654 static int ms_try_read_network(ms_conn_t
*c
)
1662 if ((c
->rcurr
!= c
->rbuf
)
1663 && (! c
->readval
|| (c
->rvbytes
> c
->rsize
- (c
->rcurr
- c
->rbuf
))
1664 || (c
->readval
&& (c
->rcurr
- c
->rbuf
> c
->rbytes
))))
1666 if (c
->rbytes
!= 0) /* otherwise there's nothing to copy */
1667 memmove(c
->rbuf
, c
->rcurr
, (size_t)c
->rbytes
);
1673 if (c
->rbytes
>= c
->rsize
)
1675 char *new_rbuf
= realloc(c
->rbuf
, (size_t)c
->rsize
* 2);
1678 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1679 c
->rbytes
= 0; /* ignore what we read */
1682 c
->rcurr
= c
->rbuf
= new_rbuf
;
1686 avail
= c
->rsize
- c
->rbytes
- (c
->rcurr
- c
->rbuf
);
1694 res
= (int32_t)ms_udp_read(c
, c
->rcurr
+ c
->rbytes
, (int32_t)avail
);
1698 res
= (int)read(c
->sfd
, c
->rcurr
+ c
->rbytes
, (size_t)avail
);
1705 atomic_add_size(&ms_stats
.bytes_read
, res
);
1720 /* connection closed */
1721 ms_conn_set_state(c
, conn_closing
);
1726 if ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
))
1728 /* Should close on unhandled errors. */
1729 ms_conn_set_state(c
, conn_closing
);
1735 } /* ms_try_read_network */
1739 * after get the object from server, verify the value if
1742 * @param c, pointer of the concurrency
1743 * @param mlget_item, pointer of mulit-get task item structure
1744 * @param value, received value string
1745 * @param vlen, received value string length
1747 static void ms_verify_value(ms_conn_t
*c
,
1748 ms_mlget_task_item_t
*mlget_item
,
1752 if (c
->curr_task
.verify
)
1754 assert(c
->curr_task
.item
->value_offset
!= INVALID_OFFSET
);
1755 char *orignval
= &ms_setting
.char_block
[c
->curr_task
.item
->value_offset
];
1757 &ms_setting
.char_block
[c
->curr_task
.item
->key_suffix_offset
];
1759 /* verify expire time if necessary */
1760 if (c
->curr_task
.item
->exp_time
> 0)
1762 struct timeval curr_time
;
1763 gettimeofday(&curr_time
, NULL
);
1765 /* object expired but get it now */
1766 if (curr_time
.tv_sec
- c
->curr_task
.item
->client_time
1767 > c
->curr_task
.item
->exp_time
+ EXPIRE_TIME_ERROR
)
1769 atomic_add_size(&ms_stats
.exp_get
, 1);
1771 if (ms_setting
.verbose
)
1775 strftime(set_time
, 64, "%Y-%m-%d %H:%M:%S",
1776 localtime(&c
->curr_task
.item
->client_time
));
1777 strftime(cur_time
, 64, "%Y-%m-%d %H:%M:%S",
1778 localtime(&curr_time
.tv_sec
));
1780 "\n<%d expire time verification failed, "
1781 "object expired but get it now\n"
1783 "\tkey: %" PRIx64
" %.*s\n"
1784 "\tset time: %s current time: %s "
1785 "diff time: %d expire time: %d\n"
1786 "\texpected data: \n"
1787 "\treceived data len: %d\n"
1788 "\treceived data: %.*s\n",
1790 c
->curr_task
.item
->key_size
,
1791 c
->curr_task
.item
->key_prefix
,
1792 c
->curr_task
.item
->key_size
- (int)KEY_PREFIX_SIZE
,
1796 (int)(curr_time
.tv_sec
- c
->curr_task
.item
->client_time
),
1797 c
->curr_task
.item
->exp_time
,
1807 if ((c
->curr_task
.item
->value_size
!= vlen
)
1808 || (memcmp(orignval
, value
, (size_t)vlen
) != 0))
1810 atomic_add_size(&ms_stats
.vef_failed
, 1);
1812 if (ms_setting
.verbose
)
1815 "\n<%d data verification failed\n"
1817 "\tkey: %" PRIx64
" %.*s\n"
1818 "\texpected data len: %d\n"
1819 "\texpected data: %.*s\n"
1820 "\treceived data len: %d\n"
1821 "\treceived data: %.*s\n",
1823 c
->curr_task
.item
->key_size
,
1824 c
->curr_task
.item
->key_prefix
,
1825 c
->curr_task
.item
->key_size
- (int)KEY_PREFIX_SIZE
,
1827 c
->curr_task
.item
->value_size
,
1828 c
->curr_task
.item
->value_size
,
1838 c
->curr_task
.finish_verify
= true;
1840 if (mlget_item
!= NULL
)
1842 mlget_item
->finish_verify
= true;
1845 } /* ms_verify_value */
1849 * For ASCII protocol, after store the data into the local
1850 * buffer, run this function to handle the data.
1852 * @param c, pointer of the concurrency
1854 static void ms_ascii_complete_nread(ms_conn_t
*c
)
1857 assert(c
->rbytes
>= c
->rvbytes
);
1858 assert(c
->protocol
== ascii_prot
);
1862 c
->rcurr
[c
->rvbytes
- 1] == '\n' && c
->rcurr
[c
->rvbytes
- 2] == '\r');
1866 ms_mlget_task_item_t
*mlget_item
= NULL
;
1867 if (((ms_setting
.mult_key_num
> 1)
1868 && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1869 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1871 c
->mlget_task
.value_index
++;
1872 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1874 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
)
1876 c
->curr_task
.item
= mlget_item
->item
;
1877 c
->curr_task
.verify
= mlget_item
->verify
;
1878 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1879 mlget_item
->get_miss
= false;
1883 /* Try to find the task item in multi-get task array */
1884 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
1886 mlget_item
= &c
->mlget_task
.mlget_item
[i
];
1887 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
)
1889 c
->curr_task
.item
= mlget_item
->item
;
1890 c
->curr_task
.verify
= mlget_item
->verify
;
1891 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1892 mlget_item
->get_miss
= false;
1900 ms_verify_value(c
, mlget_item
, c
->rcurr
, c
->rvbytes
- 2);
1902 c
->curr_task
.get_miss
= false;
1903 c
->rbytes
-= c
->rvbytes
;
1904 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1905 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1908 } /* ms_ascii_complete_nread */
1912 * For binary protocol, after store the data into the local
1913 * buffer, run this function to handle the data.
1915 * @param c, pointer of the concurrency
1917 static void ms_bin_complete_nread(ms_conn_t
*c
)
1920 assert(c
->rbytes
>= c
->rvbytes
);
1921 assert(c
->protocol
== binary_prot
);
1923 int extlen
= c
->binary_header
.response
.extlen
;
1924 int keylen
= c
->binary_header
.response
.keylen
;
1925 uint8_t opcode
= c
->binary_header
.response
.opcode
;
1927 /* not get command or not include value, just return */
1928 if (((opcode
!= PROTOCOL_BINARY_CMD_GET
)
1929 && (opcode
!= PROTOCOL_BINARY_CMD_GETQ
))
1930 || (c
->rvbytes
<= extlen
+ keylen
))
1933 if (c
->binary_header
.response
.opcode
== PROTOCOL_BINARY_CMD_GET
)
1935 c
->currcmd
.retstat
= MCD_END
;
1936 c
->curr_task
.get_miss
= true;
1941 ms_reset_conn(c
, false);
1946 ms_mlget_task_item_t
*mlget_item
= NULL
;
1947 if (((ms_setting
.mult_key_num
> 1)
1948 && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1949 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1951 c
->mlget_task
.value_index
++;
1952 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1954 c
->curr_task
.item
= mlget_item
->item
;
1955 c
->curr_task
.verify
= mlget_item
->verify
;
1956 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1957 mlget_item
->get_miss
= false;
1962 c
->rcurr
+ extlen
+ keylen
,
1963 c
->rvbytes
- extlen
- keylen
);
1965 c
->currcmd
.retstat
= MCD_END
;
1966 c
->curr_task
.get_miss
= false;
1967 c
->rbytes
-= c
->rvbytes
;
1968 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1969 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1973 if (ms_setting
.mult_key_num
> 1)
1975 /* multi-get have check all the item */
1976 if (c
->mlget_task
.value_index
== c
->mlget_task
.mlget_num
- 1)
1978 ms_reset_conn(c
, false);
1984 ms_reset_conn(c
, false);
1986 } /* ms_bin_complete_nread */
1990 * we get here after reading the value of get commands.
1992 * @param c, pointer of the concurrency
1994 static void ms_complete_nread(ms_conn_t
*c
)
1997 assert(c
->rbytes
>= c
->rvbytes
);
1998 assert(c
->protocol
== ascii_prot
1999 || c
->protocol
== binary_prot
);
2001 if (c
->protocol
== binary_prot
)
2003 ms_bin_complete_nread(c
);
2007 ms_ascii_complete_nread(c
);
2009 } /* ms_complete_nread */
2013 * Adds a message header to a connection.
2015 * @param c, pointer of the concurrency
2017 * @return int, if success, return EXIT_SUCCESS, else return -1
2019 static int ms_add_msghdr(ms_conn_t
*c
)
2025 if (c
->msgsize
== c
->msgused
)
2028 realloc(c
->msglist
, (size_t)c
->msgsize
* 2 * sizeof(struct msghdr
));
2036 msg
= c
->msglist
+ c
->msgused
;
2039 * this wipes msg_iovlen, msg_control, msg_controllen, and
2040 * msg_flags, the last 3 of which aren't defined on solaris:
2042 memset(msg
, 0, sizeof(struct msghdr
));
2044 msg
->msg_iov
= &c
->iov
[c
->iovused
];
2046 if (c
->udp
&& (c
->srv_recv_addr_size
> 0))
2048 msg
->msg_name
= &c
->srv_recv_addr
;
2049 msg
->msg_namelen
= c
->srv_recv_addr_size
;
2057 /* Leave room for the UDP header, which we'll fill in later. */
2058 return ms_add_iov(c
, NULL
, UDP_HEADER_SIZE
);
2061 return EXIT_SUCCESS
;
2062 } /* ms_add_msghdr */
2066 * Ensures that there is room for another structure iovec in a connection's
2069 * @param c, pointer of the concurrency
2071 * @return int, if success, return EXIT_SUCCESS, else return -1
2073 static int ms_ensure_iov_space(ms_conn_t
*c
)
2077 if (c
->iovused
>= c
->iovsize
)
2080 struct iovec
*new_iov
= (struct iovec
*)realloc(c
->iov
,
2083 * sizeof(struct iovec
));
2090 /* Point all the msghdr structures at the new list. */
2091 for (i
= 0, iovnum
= 0; i
< c
->msgused
; i
++)
2093 c
->msglist
[i
].msg_iov
= &c
->iov
[iovnum
];
2094 iovnum
+= (int)c
->msglist
[i
].msg_iovlen
;
2098 return EXIT_SUCCESS
;
2099 } /* ms_ensure_iov_space */
2103 * Adds data to the list of pending data that will be written out to a
2106 * @param c, pointer of the concurrency
2107 * @param buf, the buffer includes data to send
2108 * @param len, the data length in the buffer
2110 * @return int, if success, return EXIT_SUCCESS, else return -1
2112 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
)
2122 m
= &c
->msglist
[c
->msgused
- 1];
2125 * Limit UDP packets, to UDP_MAX_PAYLOAD_SIZE bytes.
2127 limit_to_mtu
= c
->udp
;
2130 /* We may need to start a new msghdr if this one is full. */
2131 if ((m
->msg_iovlen
== IOV_MAX
)
2132 || (limit_to_mtu
&& (c
->msgbytes
>= UDP_MAX_SEND_PAYLOAD_SIZE
)))
2135 m
= &c
->msglist
[c
->msgused
- 1];
2139 if (ms_ensure_iov_space(c
) != 0)
2142 /* If the fragment is too big to fit in the datagram, split it up */
2143 if (limit_to_mtu
&& (len
+ c
->msgbytes
> UDP_MAX_SEND_PAYLOAD_SIZE
))
2145 leftover
= len
+ c
->msgbytes
- UDP_MAX_SEND_PAYLOAD_SIZE
;
2153 m
= &c
->msglist
[c
->msgused
- 1];
2154 m
->msg_iov
[m
->msg_iovlen
].iov_base
= (void *)buf
;
2155 m
->msg_iov
[m
->msg_iovlen
].iov_len
= (size_t)len
;
2161 buf
= ((char *)buf
) + len
;
2164 while (leftover
> 0);
2166 return EXIT_SUCCESS
;
2171 * Constructs a set of UDP headers and attaches them to the outgoing messages.
2173 * @param c, pointer of the concurrency
2175 * @return int, if success, return EXIT_SUCCESS, else return -1
2177 static int ms_build_udp_headers(ms_conn_t
*c
)
2184 c
->request_id
= ms_get_udp_request_id();
2186 if (c
->msgused
> c
->hdrsize
)
2190 new_hdrbuf
= realloc(c
->hdrbuf
,
2191 (size_t)c
->msgused
* 2 * UDP_HEADER_SIZE
);
2193 new_hdrbuf
= malloc((size_t)c
->msgused
* 2 * UDP_HEADER_SIZE
);
2197 c
->hdrbuf
= (unsigned char *)new_hdrbuf
;
2198 c
->hdrsize
= c
->msgused
* 2;
2201 /* If this is a multi-packet request, drop it. */
2202 if (c
->udp
&& (c
->msgused
> 1))
2204 fprintf(stderr
, "multi-packet request for UDP not supported.\n");
2209 for (i
= 0; i
< c
->msgused
; i
++)
2211 c
->msglist
[i
].msg_iov
[0].iov_base
= (void *)hdr
;
2212 c
->msglist
[i
].msg_iov
[0].iov_len
= UDP_HEADER_SIZE
;
2213 *hdr
++= (unsigned char)(c
->request_id
/ 256);
2214 *hdr
++= (unsigned char)(c
->request_id
% 256);
2215 *hdr
++= (unsigned char)(i
/ 256);
2216 *hdr
++= (unsigned char)(i
% 256);
2217 *hdr
++= (unsigned char)(c
->msgused
/ 256);
2218 *hdr
++= (unsigned char)(c
->msgused
% 256);
2219 *hdr
++= (unsigned char)1; /* support facebook memcached */
2220 *hdr
++= (unsigned char)0;
2222 ((unsigned char *)c
->msglist
[i
].msg_iov
[0].iov_base
2223 + UDP_HEADER_SIZE
));
2226 return EXIT_SUCCESS
;
2227 } /* ms_build_udp_headers */
2231 * Transmit the next chunk of data from our list of msgbuf structures.
2233 * @param c, pointer of the concurrency
2235 * @return TRANSMIT_COMPLETE All done writing.
2236 * TRANSMIT_INCOMPLETE More data remaining to write.
2237 * TRANSMIT_SOFT_ERROR Can't write any more right now.
2238 * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
2240 static int ms_transmit(ms_conn_t
*c
)
2244 if ((c
->msgcurr
< c
->msgused
)
2245 && (c
->msglist
[c
->msgcurr
].msg_iovlen
== 0))
2247 /* Finished writing the current msg; advance to the next. */
2251 if (c
->msgcurr
< c
->msgused
)
2254 struct msghdr
*m
= &c
->msglist
[c
->msgcurr
];
2256 res
= sendmsg(c
->sfd
, m
, 0);
2259 atomic_add_size(&ms_stats
.bytes_written
, res
);
2261 /* We've written some of the data. Remove the completed
2262 * iovec entries from the list of pending writes. */
2263 while (m
->msg_iovlen
> 0 && res
>= (ssize_t
)m
->msg_iov
->iov_len
)
2265 res
-= (ssize_t
)m
->msg_iov
->iov_len
;
2270 /* Might have written just part of the last iovec entry;
2271 * adjust it so the next write will do the rest. */
2274 m
->msg_iov
->iov_base
= (void *)((unsigned char *)m
->msg_iov
->iov_base
+ res
);
2275 m
->msg_iov
->iov_len
-= (size_t)res
;
2277 return TRANSMIT_INCOMPLETE
;
2279 if ((res
== -1) && ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
)))
2281 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2283 fprintf(stderr
, "Couldn't update event.\n");
2284 ms_conn_set_state(c
, conn_closing
);
2285 return TRANSMIT_HARD_ERROR
;
2287 return TRANSMIT_SOFT_ERROR
;
2290 /* if res==0 or res==-1 and error is not EAGAIN or EWOULDBLOCK,
2291 * we have a real error, on which we close the connection */
2292 fprintf(stderr
, "Failed to write, and not due to blocking.\n");
2294 ms_conn_set_state(c
, conn_closing
);
2295 return TRANSMIT_HARD_ERROR
;
2299 return TRANSMIT_COMPLETE
;
2305 * Shrinks a connection's buffers if they're too big. This prevents
2306 * periodic large "mget" response from server chewing lots of client
2309 * This should only be called in between requests since it can wipe output
2312 * @param c, pointer of the concurrency
2314 static void ms_conn_shrink(ms_conn_t
*c
)
2321 if ((c
->rsize
> READ_BUFFER_HIGHWAT
) && (c
->rbytes
< DATA_BUFFER_SIZE
))
2325 if (c
->rcurr
!= c
->rbuf
)
2326 memmove(c
->rbuf
, c
->rcurr
, (size_t)c
->rbytes
);
2328 newbuf
= (char *)realloc((void *)c
->rbuf
, DATA_BUFFER_SIZE
);
2333 c
->rsize
= DATA_BUFFER_SIZE
;
2338 if (c
->udp
&& (c
->rudpsize
> UDP_DATA_BUFFER_HIGHWAT
)
2339 && (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
< UDP_DATA_BUFFER_SIZE
))
2341 char *new_rbuf
= (char *)realloc(c
->rudpbuf
, (size_t)c
->rudpsize
* 2);
2344 c
->rudpbuf
= new_rbuf
;
2345 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
2347 /* TODO check error condition? */
2350 if (c
->msgsize
> MSG_LIST_HIGHWAT
)
2352 struct msghdr
*newbuf
= (struct msghdr
*)realloc(
2355 * sizeof(c
->msglist
[0]));
2359 c
->msgsize
= MSG_LIST_INITIAL
;
2361 /* TODO check error condition? */
2364 if (c
->iovsize
> IOV_LIST_HIGHWAT
)
2366 struct iovec
*newbuf
= (struct iovec
*)realloc((void *)c
->iov
,
2368 * sizeof(c
->iov
[0]));
2372 c
->iovsize
= IOV_LIST_INITIAL
;
2374 /* TODO check return value */
2376 } /* ms_conn_shrink */
2380 * Sets a connection's current state in the state machine. Any special
2381 * processing that needs to happen on certain state transitions can
2384 * @param c, pointer of the concurrency
2385 * @param state, connection state
2387 static void ms_conn_set_state(ms_conn_t
*c
, int state
)
2391 if (state
!= c
->state
)
2393 if (state
== conn_read
)
2399 } /* ms_conn_set_state */
2403 * update the event if socks change state. for example: when
2404 * change the listen scoket read event to sock write event, or
2405 * change socket handler, we could call this function.
2407 * @param c, pointer of the concurrency
2408 * @param new_flags, new event flags
2410 * @return bool, if success, return true, else return false
2412 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
)
2416 struct event_base
*base
= c
->event
.ev_base
;
2417 if ((c
->ev_flags
== new_flags
) && (ms_setting
.rep_write_srv
== 0)
2418 && (! ms_setting
.facebook_test
|| (c
->total_sfds
== 1)))
2423 if (event_del(&c
->event
) == -1)
2425 /* try to delete the event again */
2426 if (event_del(&c
->event
) == -1)
2432 event_set(&c
->event
,
2437 event_base_set(base
, &c
->event
);
2438 c
->ev_flags
= (short)new_flags
;
2440 if (event_add(&c
->event
, NULL
) == -1)
2446 } /* ms_update_event */
2450 * If user want to get the expected throughput, we could limit
2451 * the performance of memslap. we could give up some work and
2452 * just wait a short time. The function is used to check this
2455 * @param c, pointer of the concurrency
2457 * @return bool, if success, return true, else return false
2459 static bool ms_need_yield(ms_conn_t
*c
)
2461 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
2463 int64_t time_diff
= 0;
2464 struct timeval curr_time
;
2465 ms_task_t
*task
= &c
->curr_task
;
2467 if (ms_setting
.expected_tps
> 0)
2469 gettimeofday(&curr_time
, NULL
);
2470 time_diff
= ms_time_diff(&ms_thread
->startup_time
, &curr_time
);
2471 tps
= (int64_t)(((task
->get_opt
+ task
->set_opt
) / (uint64_t)time_diff
) * 1000000);
2473 /* current throughput is greater than expected throughput */
2474 if (tps
> ms_thread
->thread_ctx
->tps_perconn
)
2481 } /* ms_need_yield */
2485 * used to update the start time of each operation
2487 * @param c, pointer of the concurrency
2489 static void ms_update_start_time(ms_conn_t
*c
)
2491 ms_task_item_t
*item
= c
->curr_task
.item
;
2493 if ((ms_setting
.stat_freq
> 0) || c
->udp
2494 || ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0)))
2496 gettimeofday(&c
->start_time
, NULL
);
2497 if ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0))
2499 /* record the current time */
2500 item
->client_time
= c
->start_time
.tv_sec
;
2503 } /* ms_update_start_time */
2507 * run the state machine
2509 * @param c, pointer of the concurrency
2511 static void ms_drive_machine(ms_conn_t
*c
)
2524 if (c
->rbytes
>= c
->rvbytes
)
2526 ms_complete_nread(c
);
2532 if (ms_try_read_line(c
) != 0)
2538 if (ms_try_read_network(c
) != 0)
2543 /* doesn't read all the response data, wait event wake up */
2544 if (! c
->currcmd
.isfinish
)
2546 if (! ms_update_event(c
, EV_READ
| EV_PERSIST
))
2548 fprintf(stderr
, "Couldn't update event.\n");
2549 ms_conn_set_state(c
, conn_closing
);
2556 /* we have no command line and no data to read from network, next write */
2557 ms_conn_set_state(c
, conn_write
);
2558 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
2563 if (! c
->ctnwrite
&& ms_need_yield(c
))
2567 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2569 fprintf(stderr
, "Couldn't update event.\n");
2570 ms_conn_set_state(c
, conn_closing
);
2577 if (! c
->ctnwrite
&& (ms_exec_task(c
) != 0))
2579 ms_conn_set_state(c
, conn_closing
);
2583 /* record the start time before starting to send data if necessary */
2584 if (! c
->ctnwrite
|| (c
->change_sfd
&& c
->ctnwrite
))
2588 c
->change_sfd
= false;
2590 ms_update_start_time(c
);
2593 /* change sfd if necessary */
2601 /* execute task until nothing need be written to network */
2602 if (! c
->ctnwrite
&& (c
->msgcurr
== c
->msgused
))
2604 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2606 fprintf(stderr
, "Couldn't update event.\n");
2607 ms_conn_set_state(c
, conn_closing
);
2614 switch (ms_transmit(c
))
2616 case TRANSMIT_COMPLETE
:
2617 /* we have no data to write to network, next wait repose */
2618 if (! ms_update_event(c
, EV_READ
| EV_PERSIST
))
2620 fprintf(stderr
, "Couldn't update event.\n");
2621 ms_conn_set_state(c
, conn_closing
);
2625 ms_conn_set_state(c
, conn_read
);
2630 case TRANSMIT_INCOMPLETE
:
2632 break; /* Continue in state machine. */
2634 case TRANSMIT_HARD_ERROR
:
2638 case TRANSMIT_SOFT_ERROR
:
2650 /* recovery mode, need reconnect if connection close */
2651 if (ms_setting
.reconnect
&& (! ms_global
.time_out
2652 || ((ms_setting
.run_time
== 0)
2653 && (c
->remain_exec_num
> 0))))
2655 if (ms_reconn(c
) != 0)
2662 ms_reset_conn(c
, false);
2664 if (c
->total_sfds
== 1)
2666 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2668 fprintf(stderr
, "Couldn't update event.\n");
2669 ms_conn_set_state(c
, conn_closing
);
2687 } /* ms_drive_machine */
2691 * the event handler of each thread
2693 * @param fd, the file descriptor of socket
2694 * @param which, event flag
2695 * @param arg, argument
2697 void ms_event_handler(const int fd
, const short which
, void *arg
)
2699 ms_conn_t
*c
= (ms_conn_t
*)arg
;
2709 "Catastrophic: event fd: %d doesn't match conn fd: %d\n",
2715 assert(fd
== c
->sfd
);
2717 ms_drive_machine(c
);
2719 /* wait for next event */
2720 } /* ms_event_handler */
2724 * get the next socket descriptor index to run for replication
2726 * @param c, pointer of the concurrency
2727 * @param cmd, command(get or set )
2729 * @return int, if success, return the index, else return EXIT_SUCCESS
2731 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
)
2733 uint32_t sock_index
= 0;
2736 if (c
->total_sfds
== 1)
2738 return EXIT_SUCCESS
;
2741 if (ms_setting
.rep_write_srv
== 0)
2750 for (i
= 0; i
< ms_setting
.rep_write_srv
; i
++)
2752 if (c
->tcpsfd
[i
] > 0)
2758 if (i
== ms_setting
.rep_write_srv
)
2760 /* random get one replication server to read */
2761 sock_index
= (uint32_t)random() % c
->total_sfds
;
2765 /* random get one replication writing server to write */
2766 sock_index
= (uint32_t)random() % ms_setting
.rep_write_srv
;
2769 else if (cmd
== CMD_GET
)
2771 /* random get one replication server to read */
2772 sock_index
= (uint32_t)random() % c
->total_sfds
;
2775 while (c
->tcpsfd
[sock_index
] == 0);
2778 } /* ms_get_rep_sock_index */
2782 * get the next socket descriptor index to run
2784 * @param c, pointer of the concurrency
2786 * @return int, return the index
2788 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
)
2790 uint32_t sock_index
= 0;
2794 sock_index
= (++c
->cur_idx
== c
->total_sfds
) ? 0 : c
->cur_idx
;
2796 while (c
->tcpsfd
[sock_index
] == 0);
2799 } /* ms_get_next_sock_index */
2803 * update socket event of the connections
2805 * @param c, pointer of the concurrency
2807 * @return int, if success, return EXIT_SUCCESS, else return -1
2809 static int ms_update_conn_sock_event(ms_conn_t
*c
)
2813 switch (c
->currcmd
.cmd
)
2816 if (ms_setting
.facebook_test
&& c
->udp
)
2818 c
->sfd
= c
->tcpsfd
[0];
2820 c
->change_sfd
= true;
2825 if (ms_setting
.facebook_test
&& ! c
->udp
)
2829 c
->change_sfd
= true;
2837 if (! c
->udp
&& (c
->total_sfds
> 1))
2839 if (c
->cur_idx
!= c
->total_sfds
)
2841 if (ms_setting
.rep_write_srv
== 0)
2843 c
->cur_idx
= ms_get_next_sock_index(c
);
2847 c
->cur_idx
= ms_get_rep_sock_index(c
, c
->currcmd
.cmd
);
2852 /* must select the first sock of the connection at the beginning */
2856 c
->sfd
= c
->tcpsfd
[c
->cur_idx
];
2857 assert(c
->sfd
!= 0);
2858 c
->change_sfd
= true;
2863 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2865 fprintf(stderr
, "Couldn't update event.\n");
2866 ms_conn_set_state(c
, conn_closing
);
2871 return EXIT_SUCCESS
;
2872 } /* ms_update_conn_sock_event */
2876 * for ASCII protocol, this function build the set command
2877 * string and send the command.
2879 * @param c, pointer of the concurrency
2880 * @param item, pointer of task item which includes the object
2883 * @return int, if success, return EXIT_SUCCESS, else return -1
2885 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
)
2889 char *buffer
= c
->wbuf
;
2891 write_len
= snprintf(buffer
,
2898 if (write_len
> c
->wsize
|| write_len
< 0)
2900 /* ought to be always enough. just fail for simplicity */
2901 fprintf(stderr
, "output command line too long.\n");
2905 if (item
->value_offset
== INVALID_OFFSET
)
2907 value_offset
= item
->key_suffix_offset
;
2911 value_offset
= item
->value_offset
;
2914 if ((ms_add_iov(c
, "set ", 4) != 0)
2915 || (ms_add_iov(c
, (char *)&item
->key_prefix
,
2916 (int)KEY_PREFIX_SIZE
) != 0)
2917 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
2918 item
->key_size
- (int)KEY_PREFIX_SIZE
) != 0)
2919 || (ms_add_iov(c
, buffer
, write_len
) != 0)
2920 || (ms_add_iov(c
, &ms_setting
.char_block
[value_offset
],
2921 item
->value_size
) != 0)
2922 || (ms_add_iov(c
, "\r\n", 2) != 0)
2923 || (c
->udp
&& (ms_build_udp_headers(c
) != 0)))
2928 return EXIT_SUCCESS
;
2929 } /* ms_build_ascii_write_buf_set */
2933 * used to send set command to server
2935 * @param c, pointer of the concurrency
2936 * @param item, pointer of task item which includes the object
2939 * @return int, if success, return EXIT_SUCCESS, else return -1
2941 int ms_mcd_set(ms_conn_t
*c
, ms_task_item_t
*item
)
2945 c
->currcmd
.cmd
= CMD_SET
;
2946 c
->currcmd
.isfinish
= false;
2947 c
->currcmd
.retstat
= MCD_FAILURE
;
2949 if (ms_update_conn_sock_event(c
) != 0)
2957 if (ms_add_msghdr(c
) != 0)
2959 fprintf(stderr
, "Out of memory preparing request.");
2963 /* binary protocol */
2964 if (c
->protocol
== binary_prot
)
2966 if (ms_build_bin_write_buf_set(c
, item
) != 0)
2973 if (ms_build_ascii_write_buf_set(c
, item
) != 0)
2979 atomic_add_size(&ms_stats
.obj_bytes
,
2980 item
->key_size
+ item
->value_size
);
2981 atomic_add_size(&ms_stats
.cmd_set
, 1);
2983 return EXIT_SUCCESS
;
2988 * for ASCII protocol, this function build the get command
2989 * string and send the command.
2991 * @param c, pointer of the concurrency
2992 * @param item, pointer of task item which includes the object
2995 * @return int, if success, return EXIT_SUCCESS, else return -1
2997 static int ms_build_ascii_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
)
2999 if ((ms_add_iov(c
, "get ", 4) != 0)
3000 || (ms_add_iov(c
, (char *)&item
->key_prefix
,
3001 (int)KEY_PREFIX_SIZE
) != 0)
3002 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
3003 item
->key_size
- (int)KEY_PREFIX_SIZE
) != 0)
3004 || (ms_add_iov(c
, "\r\n", 2) != 0)
3005 || (c
->udp
&& (ms_build_udp_headers(c
) != 0)))
3010 return EXIT_SUCCESS
;
3011 } /* ms_build_ascii_write_buf_get */
3015 * used to send the get command to server
3017 * @param c, pointer of the concurrency
3018 * @param item, pointer of task item which includes the object
3021 * @return int, if success, return EXIT_SUCCESS, else return -1
3023 int ms_mcd_get(ms_conn_t
*c
, ms_task_item_t
*item
)
3027 c
->currcmd
.cmd
= CMD_GET
;
3028 c
->currcmd
.isfinish
= false;
3029 c
->currcmd
.retstat
= MCD_FAILURE
;
3031 if (ms_update_conn_sock_event(c
) != 0)
3039 if (ms_add_msghdr(c
) != 0)
3041 fprintf(stderr
, "Out of memory preparing request.");
3045 /* binary protocol */
3046 if (c
->protocol
== binary_prot
)
3048 if (ms_build_bin_write_buf_get(c
, item
) != 0)
3055 if (ms_build_ascii_write_buf_get(c
, item
) != 0)
3061 atomic_add_size(&ms_stats
.cmd_get
, 1);
3063 return EXIT_SUCCESS
;
3068 * for ASCII protocol, this function build the multi-get command
3069 * string and send the command.
3071 * @param c, pointer of the concurrency
3073 * @return int, if success, return EXIT_SUCCESS, else return -1
3075 static int ms_build_ascii_write_buf_mlget(ms_conn_t
*c
)
3077 ms_task_item_t
*item
;
3079 if (ms_add_iov(c
, "get", 3) != 0)
3084 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
3086 item
= c
->mlget_task
.mlget_item
[i
].item
;
3087 assert(item
!= NULL
);
3088 if ((ms_add_iov(c
, " ", 1) != 0)
3089 || (ms_add_iov(c
, (char *)&item
->key_prefix
,
3090 (int)KEY_PREFIX_SIZE
) != 0)
3091 || (ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
3092 item
->key_size
- (int)KEY_PREFIX_SIZE
) != 0))
3098 if ((ms_add_iov(c
, "\r\n", 2) != 0)
3099 || (c
->udp
&& (ms_build_udp_headers(c
) != 0)))
3104 return EXIT_SUCCESS
;
3105 } /* ms_build_ascii_write_buf_mlget */
3109 * used to send the multi-get command to server
3111 * @param c, pointer of the concurrency
3113 * @return int, if success, return EXIT_SUCCESS, else return -1
3115 int ms_mcd_mlget(ms_conn_t
*c
)
3117 ms_task_item_t
*item
;
3120 assert(c
->mlget_task
.mlget_num
>= 1);
3122 c
->currcmd
.cmd
= CMD_GET
;
3123 c
->currcmd
.isfinish
= false;
3124 c
->currcmd
.retstat
= MCD_FAILURE
;
3126 if (ms_update_conn_sock_event(c
) != 0)
3134 if (ms_add_msghdr(c
) != 0)
3136 fprintf(stderr
, "Out of memory preparing request.");
3140 /* binary protocol */
3141 if (c
->protocol
== binary_prot
)
3143 if (ms_build_bin_write_buf_mlget(c
) != 0)
3150 if (ms_build_ascii_write_buf_mlget(c
) != 0)
3156 /* decrease operation time of each item */
3157 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
3159 item
= c
->mlget_task
.mlget_item
[i
].item
;
3160 atomic_add_size(&ms_stats
.cmd_get
, 1);
3165 return EXIT_SUCCESS
;
3166 } /* ms_mcd_mlget */
3170 * binary protocol support
3174 * for binary protocol, parse the response of server
3176 * @param c, pointer of the concurrency
3178 * @return int, if success, return EXIT_SUCCESS, else return -1
3180 static int ms_bin_process_response(ms_conn_t
*c
)
3182 const char *errstr
= NULL
;
3186 uint32_t bodylen
= c
->binary_header
.response
.bodylen
;
3187 uint8_t opcode
= c
->binary_header
.response
.opcode
;
3188 uint16_t status
= c
->binary_header
.response
.status
;
3192 c
->rvbytes
= (int32_t)bodylen
;
3194 return EXIT_FAILURE
;
3200 case PROTOCOL_BINARY_RESPONSE_SUCCESS
:
3201 if (opcode
== PROTOCOL_BINARY_CMD_SET
)
3203 c
->currcmd
.retstat
= MCD_STORED
;
3205 else if (opcode
== PROTOCOL_BINARY_CMD_DELETE
)
3207 c
->currcmd
.retstat
= MCD_DELETED
;
3209 else if (opcode
== PROTOCOL_BINARY_CMD_GET
)
3211 c
->currcmd
.retstat
= MCD_END
;
3215 case PROTOCOL_BINARY_RESPONSE_ENOMEM
:
3216 errstr
= "Out of memory";
3217 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
3220 case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND
:
3221 errstr
= "Unknown command";
3222 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
3225 case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT
:
3226 errstr
= "Not found";
3227 c
->currcmd
.retstat
= MCD_NOTFOUND
;
3230 case PROTOCOL_BINARY_RESPONSE_EINVAL
:
3231 errstr
= "Invalid arguments";
3232 c
->currcmd
.retstat
= MCD_PROTOCOL_ERROR
;
3235 case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS
:
3236 errstr
= "Data exists for key.";
3239 case PROTOCOL_BINARY_RESPONSE_E2BIG
:
3240 errstr
= "Too large.";
3241 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
3244 case PROTOCOL_BINARY_RESPONSE_NOT_STORED
:
3245 errstr
= "Not stored.";
3246 c
->currcmd
.retstat
= MCD_NOTSTORED
;
3250 errstr
= "Unknown error";
3251 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
3257 fprintf(stderr
, "%s\n", errstr
);
3261 return EXIT_SUCCESS
;
3262 } /* ms_bin_process_response */
3265 /* build binary header and add the header to the buffer to send */
3268 * build binary header and add the header to the buffer to send
3270 * @param c, pointer of the concurrency
3271 * @param opcode, operation code
3272 * @param hdr_len, length of header
3273 * @param key_len, length of key
3274 * @param body_len. length of body
3276 static void ms_add_bin_header(ms_conn_t
*c
,
3282 protocol_binary_request_header
*header
;
3286 header
= (protocol_binary_request_header
*)c
->wcurr
;
3288 header
->request
.magic
= (uint8_t)PROTOCOL_BINARY_REQ
;
3289 header
->request
.opcode
= (uint8_t)opcode
;
3290 header
->request
.keylen
= htons(key_len
);
3292 header
->request
.extlen
= (uint8_t)hdr_len
;
3293 header
->request
.datatype
= (uint8_t)PROTOCOL_BINARY_RAW_BYTES
;
3294 header
->request
.vbucket
= 0;
3296 header
->request
.bodylen
= htonl(body_len
);
3297 header
->request
.opaque
= 0;
3298 header
->request
.cas
= 0;
3300 ms_add_iov(c
, c
->wcurr
, sizeof(header
->request
));
3301 } /* ms_add_bin_header */
3305 * add the key to the socket write buffer array
3307 * @param c, pointer of the concurrency
3308 * @param item, pointer of task item which includes the object
3311 static void ms_add_key_to_iov(ms_conn_t
*c
, ms_task_item_t
*item
)
3313 ms_add_iov(c
, (char *)&item
->key_prefix
, (int)KEY_PREFIX_SIZE
);
3314 ms_add_iov(c
, &ms_setting
.char_block
[item
->key_suffix_offset
],
3315 item
->key_size
- (int)KEY_PREFIX_SIZE
);
3320 * for binary protocol, this function build the set command
3321 * and add the command to send buffer array.
3323 * @param c, pointer of the concurrency
3324 * @param item, pointer of task item which includes the object
3327 * @return int, if success, return EXIT_SUCCESS, else return -1
3329 static int ms_build_bin_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
)
3331 assert(c
->wbuf
== c
->wcurr
);
3334 protocol_binary_request_set
*rep
= (protocol_binary_request_set
*)c
->wcurr
;
3335 uint16_t keylen
= (uint16_t)item
->key_size
;
3336 uint32_t bodylen
= (uint32_t)sizeof(rep
->message
.body
)
3337 + (uint32_t)keylen
+ (uint32_t)item
->value_size
;
3339 ms_add_bin_header(c
,
3340 PROTOCOL_BINARY_CMD_SET
,
3341 sizeof(rep
->message
.body
),
3344 rep
->message
.body
.flags
= 0;
3345 rep
->message
.body
.expiration
= htonl((uint32_t)item
->exp_time
);
3346 ms_add_iov(c
, &rep
->message
.body
, sizeof(rep
->message
.body
));
3347 ms_add_key_to_iov(c
, item
);
3349 if (item
->value_offset
== INVALID_OFFSET
)
3351 value_offset
= item
->key_suffix_offset
;
3355 value_offset
= item
->value_offset
;
3357 ms_add_iov(c
, &ms_setting
.char_block
[value_offset
], item
->value_size
);
3359 return EXIT_SUCCESS
;
3360 } /* ms_build_bin_write_buf_set */
3364 * for binary protocol, this function build the get command and
3365 * add the command to send buffer array.
3367 * @param c, pointer of the concurrency
3368 * @param item, pointer of task item which includes the object
3371 * @return int, if success, return EXIT_SUCCESS, else return -1
3373 static int ms_build_bin_write_buf_get(ms_conn_t
*c
, ms_task_item_t
*item
)
3375 assert(c
->wbuf
== c
->wcurr
);
3377 ms_add_bin_header(c
, PROTOCOL_BINARY_CMD_GET
, 0, (uint16_t)item
->key_size
,
3378 (uint32_t)item
->key_size
);
3379 ms_add_key_to_iov(c
, item
);
3381 return EXIT_SUCCESS
;
3382 } /* ms_build_bin_write_buf_get */
3386 * for binary protocol, this function build the multi-get
3387 * command and add the command to send buffer array.
3389 * @param c, pointer of the concurrency
3390 * @param item, pointer of task item which includes the object
3393 * @return int, if success, return EXIT_SUCCESS, else return -1
3395 static int ms_build_bin_write_buf_mlget(ms_conn_t
*c
)
3397 ms_task_item_t
*item
;
3399 assert(c
->wbuf
== c
->wcurr
);
3401 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
3403 item
= c
->mlget_task
.mlget_item
[i
].item
;
3404 assert(item
!= NULL
);
3406 ms_add_bin_header(c
,
3407 PROTOCOL_BINARY_CMD_GET
,
3409 (uint16_t)item
->key_size
,
3410 (uint32_t)item
->key_size
);
3411 ms_add_key_to_iov(c
, item
);
3412 c
->wcurr
+= sizeof(protocol_binary_request_get
);
3417 return EXIT_SUCCESS
;
3418 } /* ms_build_bin_write_buf_mlget */