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 <arpa/inet.h>
22 #if TIME_WITH_SYS_TIME
23 # include <sys/time.h>
27 # include <sys/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 0, 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 0, 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 0, 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 0, 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 0, 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 0, 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 0, 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)
761 } /* ms_maximize_sndbuf */
765 * socket connects the server
767 * @param c, pointer of the concurrency
768 * @param srv_host_name, the host name of the server
769 * @param srv_port, port of server
770 * @param is_udp, whether it's udp
771 * @param ret_sfd, the connected socket file descriptor
773 * @return int, if success, return 0, else return -1
775 static int ms_network_connect(ms_conn_t
*c
,
787 struct addrinfo
*next
;
788 struct addrinfo hints
;
789 char port_buf
[NI_MAXSERV
];
796 * the memset call clears nonstandard fields in some impementations
797 * that otherwise mess things up.
799 memset(&hints
, 0, sizeof(hints
));
801 hints
.ai_flags
= AI_PASSIVE
| AI_ADDRCONFIG
;
803 + hints
.ai_flags
= AI_PASSIVE
;
804 #endif /* AI_ADDRCONFIG */
807 hints
.ai_protocol
= IPPROTO_UDP
;
808 hints
.ai_socktype
= SOCK_DGRAM
;
809 hints
.ai_family
= AF_INET
; /* This left here because of issues with OSX 10.5 */
813 hints
.ai_family
= AF_UNSPEC
;
814 hints
.ai_protocol
= IPPROTO_TCP
;
815 hints
.ai_socktype
= SOCK_STREAM
;
818 snprintf(port_buf
, NI_MAXSERV
, "%d", srv_port
);
819 error
= getaddrinfo(srv_host_name
, port_buf
, &hints
, &ai
);
822 if (error
!= EAI_SYSTEM
)
823 fprintf(stderr
, "getaddrinfo(): %s.\n", gai_strerror(error
));
825 perror("getaddrinfo()\n");
830 for (next
= ai
; next
; next
= next
->ai_next
)
832 if ((sfd
= ms_new_socket(next
)) == -1)
838 setsockopt(sfd
, SOL_SOCKET
, SO_REUSEADDR
, (void *)&flags
, sizeof(flags
));
841 ms_maximize_sndbuf(sfd
);
845 setsockopt(sfd
, SOL_SOCKET
, SO_KEEPALIVE
, (void *)&flags
,
847 setsockopt(sfd
, SOL_SOCKET
, SO_LINGER
, (void *)&ling
, sizeof(ling
));
848 setsockopt(sfd
, IPPROTO_TCP
, TCP_NODELAY
, (void *)&flags
,
854 c
->srv_recv_addr_size
= sizeof(struct sockaddr
);
855 memcpy(&c
->srv_recv_addr
, next
->ai_addr
, c
->srv_recv_addr_size
);
859 if (connect(sfd
, next
->ai_addr
, next
->ai_addrlen
) == -1)
867 if (((flags
= fcntl(sfd
, F_GETFL
, 0)) < 0)
868 || (fcntl(sfd
, F_SETFL
, flags
| O_NONBLOCK
) < 0))
870 fprintf(stderr
, "setting O_NONBLOCK\n");
886 /* Return zero if we detected no errors in starting up connections */
888 } /* ms_network_connect */
892 * reconnect a disconnected sock
894 * @param c, pointer of the concurrency
896 * @return int, if success, return 0, else return -1
898 static int ms_reconn(ms_conn_t
*c
)
900 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
902 uint32_t srv_conn_cnt
= 0;
904 if (ms_setting
.rep_write_srv
> 0)
906 srv_idx
= c
->cur_idx
% ms_setting
.srv_cnt
;
907 srv_conn_cnt
= ms_setting
.sock_per_conn
* ms_setting
.nconns
;
911 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
912 srv_conn_cnt
= ms_setting
.nconns
/ ms_setting
.srv_cnt
;
915 /* close the old socket handler */
917 c
->tcpsfd
[c
->cur_idx
]= 0;
919 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].disconn_cnt
, 1)
922 gettimeofday(&ms_setting
.servers
[srv_idx
].disconn_time
, NULL
);
923 fprintf(stderr
, "Server %s:%d disconnect\n",
924 ms_setting
.servers
[srv_idx
].srv_host_name
,
925 ms_setting
.servers
[srv_idx
].srv_port
);
928 if (ms_setting
.rep_write_srv
> 0)
932 for (i
= 0; i
< c
->total_sfds
; i
++)
934 if (c
->tcpsfd
[i
] != 0)
940 /* all socks disconnect */
941 if (i
== c
->total_sfds
)
950 /* reconnect success, break the loop */
951 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
952 ms_setting
.servers
[srv_idx
].srv_port
,
953 ms_setting
.udp
, &c
->sfd
) == 0)
955 c
->tcpsfd
[c
->cur_idx
]= c
->sfd
;
956 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].reconn_cnt
, 1)
957 % (uint32_t)srv_conn_cnt
== 0)
959 gettimeofday(&ms_setting
.servers
[srv_idx
].reconn_time
, NULL
);
961 (int)(ms_setting
.servers
[srv_idx
].reconn_time
.tv_sec
962 - ms_setting
.servers
[srv_idx
].disconn_time
964 fprintf(stderr
, "Server %s:%d reconnect after %ds\n",
965 ms_setting
.servers
[srv_idx
].srv_host_name
,
966 ms_setting
.servers
[srv_idx
].srv_port
, reconn_time
);
971 if (ms_setting
.rep_write_srv
== 0 && c
->total_sfds
> 0)
973 /* wait a second and reconnect */
977 while (ms_setting
.rep_write_srv
== 0 && c
->total_sfds
> 0);
980 if ((c
->total_sfds
> 1) && (c
->tcpsfd
[c
->cur_idx
] == 0))
991 * reconnect several disconnected socks in the connection
992 * structure, the ever-1-second timer of the thread will check
993 * whether some socks in the connections disconnect. if
994 * disconnect, reconnect the sock.
996 * @param c, pointer of the concurrency
998 * @return int, if success, return 0, else return -1
1000 int ms_reconn_socks(ms_conn_t
*c
)
1002 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
1003 uint32_t srv_idx
= 0;
1005 uint32_t srv_conn_cnt
= 0;
1006 struct timeval cur_time
;
1010 if ((c
->total_sfds
== 1) || (c
->total_sfds
== c
->alive_sfds
))
1015 for (uint32_t i
= 0; i
< c
->total_sfds
; i
++)
1017 if (c
->tcpsfd
[i
] == 0)
1019 gettimeofday(&cur_time
, NULL
);
1022 * For failover test of replication, reconnect the socks after
1023 * it disconnects more than 5 seconds, Otherwise memslap will
1024 * block at connect() function and the work threads can't work
1028 - ms_setting
.servers
[srv_idx
].disconn_time
.tv_sec
< 5)
1033 if (ms_setting
.rep_write_srv
> 0)
1035 srv_idx
= i
% ms_setting
.srv_cnt
;
1036 srv_conn_cnt
= ms_setting
.sock_per_conn
* ms_setting
.nconns
;
1040 srv_idx
= ms_thread
->thread_ctx
->srv_idx
;
1041 srv_conn_cnt
= ms_setting
.nconns
/ ms_setting
.srv_cnt
;
1044 if (ms_network_connect(c
, ms_setting
.servers
[srv_idx
].srv_host_name
,
1045 ms_setting
.servers
[srv_idx
].srv_port
,
1046 ms_setting
.udp
, &ret_sfd
) == 0)
1048 c
->tcpsfd
[i
]= ret_sfd
;
1051 if (atomic_add_32_nv(&ms_setting
.servers
[srv_idx
].reconn_cnt
, 1)
1052 % (uint32_t)srv_conn_cnt
== 0)
1054 gettimeofday(&ms_setting
.servers
[srv_idx
].reconn_time
, NULL
);
1056 (int)(ms_setting
.servers
[srv_idx
].reconn_time
.tv_sec
1057 - ms_setting
.servers
[srv_idx
].disconn_time
1059 fprintf(stderr
, "Server %s:%d reconnect after %ds\n",
1060 ms_setting
.servers
[srv_idx
].srv_host_name
,
1061 ms_setting
.servers
[srv_idx
].srv_port
, reconn_time
);
1068 } /* ms_reconn_socks */
1072 * Tokenize the command string by replacing whitespace with '\0' and update
1073 * the token array tokens with pointer to start of each token and length.
1074 * Returns total number of tokens. The last valid token is the terminal
1075 * token (value points to the first unprocessed character of the string and
1080 * while(ms_tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
1081 * for(int ix = 0; tokens[ix].length != 0; ix++) {
1084 * ncommand = tokens[ix].value - command;
1085 * command = tokens[ix].value;
1088 * @param command, the command string to token
1089 * @param tokens, array to store tokens
1090 * @param max_tokens, maximum tokens number
1092 * @return int, the number of tokens
1094 static int ms_tokenize_command(char *command
,
1096 const int max_tokens
)
1101 assert(command
!= NULL
&& tokens
!= NULL
&& max_tokens
> 1);
1103 for (s
= e
= command
; ntokens
< max_tokens
- 1; ++e
)
1109 tokens
[ntokens
].value
= s
;
1110 tokens
[ntokens
].length
= (size_t)(e
- s
);
1116 else if (*e
== '\0')
1120 tokens
[ntokens
].value
= s
;
1121 tokens
[ntokens
].length
= (size_t)(e
- s
);
1125 break; /* string end */
1130 } /* ms_tokenize_command */
1134 * parse the response of server.
1136 * @param c, pointer of the concurrency
1137 * @param command, the string responded by server
1139 * @return int, if the command completed return 0, else return
1142 static int ms_ascii_process_line(ms_conn_t
*c
, char *command
)
1146 char *buffer
= command
;
1151 * for command get, we store the returned value into local buffer
1152 * then continue in ms_complete_nread().
1157 case 'V': /* VALUE || VERSION */
1158 if (buffer
[1] == 'A') /* VALUE */
1160 token_t tokens
[MAX_TOKENS
];
1161 ms_tokenize_command(command
, tokens
, MAX_TOKENS
);
1162 value_len
= strtol(tokens
[VALUELEN_TOKEN
].value
, NULL
, 10);
1163 c
->currcmd
.key_prefix
= *(uint64_t *)tokens
[KEY_TOKEN
].value
;
1166 * We read the \r\n into the string since not doing so is more
1167 * cycles then the waster of memory to do so.
1169 * We are null terminating through, which will most likely make
1170 * some people lazy about using the return length.
1172 c
->rvbytes
= (int)(value_len
+ 2);
1180 c
->currcmd
.retstat
= MCD_SUCCESS
;
1182 case 'S': /* STORED STATS SERVER_ERROR */
1183 if (buffer
[2] == 'A') /* STORED STATS */
1185 c
->currcmd
.retstat
= MCD_STAT
;
1187 else if (buffer
[1] == 'E')
1190 printf("<%d %s\n", c
->sfd
, buffer
);
1192 c
->currcmd
.retstat
= MCD_SERVER_ERROR
;
1194 else if (buffer
[1] == 'T')
1197 c
->currcmd
.retstat
= MCD_STORED
;
1201 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1205 case 'D': /* DELETED DATA */
1206 if (buffer
[1] == 'E')
1208 c
->currcmd
.retstat
= MCD_DELETED
;
1212 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1217 case 'N': /* NOT_FOUND NOT_STORED*/
1218 if (buffer
[4] == 'F')
1220 c
->currcmd
.retstat
= MCD_NOTFOUND
;
1222 else if (buffer
[4] == 'S')
1224 printf("<%d %s\n", c
->sfd
, buffer
);
1225 c
->currcmd
.retstat
= MCD_NOTSTORED
;
1229 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1233 case 'E': /* PROTOCOL ERROR or END */
1234 if (buffer
[1] == 'N')
1237 c
->currcmd
.retstat
= MCD_END
;
1239 else if (buffer
[1] == 'R')
1241 printf("<%d ERROR\n", c
->sfd
);
1242 c
->currcmd
.retstat
= MCD_PROTOCOL_ERROR
;
1244 else if (buffer
[1] == 'X')
1246 c
->currcmd
.retstat
= MCD_DATA_EXISTS
;
1247 printf("<%d %s\n", c
->sfd
, buffer
);
1251 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1255 case 'C': /* CLIENT ERROR */
1256 printf("<%d %s\n", c
->sfd
, buffer
);
1257 c
->currcmd
.retstat
= MCD_CLIENT_ERROR
;
1261 c
->currcmd
.retstat
= MCD_UNKNOWN_READ_FAILURE
;
1266 } /* ms_ascii_process_line */
1270 * after one operation completes, reset the concurrency
1272 * @param c, pointer of the concurrency
1273 * @param timeout, whether it's timeout
1275 void ms_reset_conn(ms_conn_t
*c
, bool timeout
)
1281 if ((c
->packets
> 0) && (c
->packets
< MAX_UDP_PACKET
))
1283 memset(c
->udppkt
, 0, sizeof(ms_udppkt_t
) * (size_t)c
->packets
);
1292 c
->currcmd
.isfinish
= true;
1299 ms_conn_set_state(c
, conn_write
);
1300 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
1304 ms_drive_machine(c
);
1306 } /* ms_reset_conn */
1310 * if we have a complete line in the buffer, process it.
1312 * @param c, pointer of the concurrency
1314 * @return int, if success, return 0, else return -1
1316 static int ms_try_read_line(ms_conn_t
*c
)
1318 if (c
->protocol
== binary_prot
)
1320 /* Do we have the complete packet header? */
1321 if ((uint64_t)c
->rbytes
< sizeof(c
->binary_header
))
1323 /* need more data! */
1329 if (((long)(c
->rcurr
)) % 8 != 0)
1331 /* must realign input buffer */
1332 memmove(c
->rbuf
, c
->rcurr
, c
->rbytes
);
1334 if (settings
.verbose
)
1336 fprintf(stderr
, "%d: Realign input buffer.\n", c
->sfd
);
1340 protocol_binary_response_header
*rsp
;
1341 rsp
= (protocol_binary_response_header
*)c
->rcurr
;
1343 c
->binary_header
= *rsp
;
1344 c
->binary_header
.response
.extlen
= rsp
->response
.extlen
;
1345 c
->binary_header
.response
.keylen
= ntohs(rsp
->response
.keylen
);
1346 c
->binary_header
.response
.bodylen
= ntohl(rsp
->response
.bodylen
);
1347 c
->binary_header
.response
.status
= ntohs(rsp
->response
.status
);
1349 if (c
->binary_header
.response
.magic
!= PROTOCOL_BINARY_RES
)
1351 fprintf(stderr
, "Invalid magic: %x\n",
1352 c
->binary_header
.response
.magic
);
1353 ms_conn_set_state(c
, conn_closing
);
1357 /* process this complete response */
1358 if (ms_bin_process_response(c
) == 0)
1360 /* current operation completed */
1361 ms_reset_conn(c
, false);
1366 c
->rbytes
-= (int32_t)sizeof(c
->binary_header
);
1367 c
->rcurr
+= sizeof(c
->binary_header
);
1376 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1381 el
= memchr(c
->rcurr
, '\n', (size_t)c
->rbytes
);
1386 if (((el
- c
->rcurr
) > 1) && (*(el
- 1) == '\r'))
1392 assert(cont
<= (c
->rcurr
+ c
->rbytes
));
1394 /* process this complete line */
1395 if (ms_ascii_process_line(c
, c
->rcurr
) == 0)
1397 /* current operation completed */
1398 ms_reset_conn(c
, false);
1403 /* current operation didn't complete */
1404 c
->rbytes
-= (int32_t)(cont
- c
->rcurr
);
1408 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1412 } /* ms_try_read_line */
1416 * because the packet of UDP can't ensure the order, the
1417 * function is used to sort the received udp packet.
1419 * @param c, pointer of the concurrency
1420 * @param buf, the buffer to store the ordered packages data
1421 * @param rbytes, the maximum capacity of the buffer
1423 * @return int, if success, return the copy bytes, else return
1426 static int ms_sort_udp_packet(ms_conn_t
*c
, char *buf
, int rbytes
)
1431 uint16_t seq_num
= 0;
1432 uint16_t packets
= 0;
1433 unsigned char *header
= NULL
;
1435 /* no enough data */
1437 assert(buf
!= NULL
);
1438 assert(c
->rudpbytes
>= UDP_HEADER_SIZE
);
1440 /* calculate received packets count */
1441 if (c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
>= UDP_HEADER_SIZE
)
1443 /* the last packet has some data */
1444 c
->recvpkt
= c
->rudpbytes
/ UDP_MAX_PAYLOAD_SIZE
+ 1;
1448 c
->recvpkt
= c
->rudpbytes
/ UDP_MAX_PAYLOAD_SIZE
;
1451 /* get the total packets count if necessary */
1452 if (c
->packets
== 0)
1454 c
->packets
= HEADER_TO_PACKETS((unsigned char *)c
->rudpbuf
);
1457 /* build the ordered packet array */
1458 for (int i
= c
->pktcurr
; i
< c
->recvpkt
; i
++)
1460 header
= (unsigned char *)c
->rudpbuf
+ i
* UDP_MAX_PAYLOAD_SIZE
;
1461 req_id
= (uint16_t)HEADER_TO_REQID(header
);
1462 assert(req_id
== c
->request_id
% (1 << 16));
1464 packets
= (uint16_t)HEADER_TO_PACKETS(header
);
1465 assert(c
->packets
== HEADER_TO_PACKETS(header
));
1467 seq_num
= (uint16_t)HEADER_TO_SEQNUM(header
);
1468 c
->udppkt
[seq_num
].header
= header
;
1469 c
->udppkt
[seq_num
].data
= (char *)header
+ UDP_HEADER_SIZE
;
1471 if (i
== c
->recvpkt
- 1)
1473 /* last received packet */
1474 if (c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
== 0)
1476 c
->udppkt
[seq_num
].rbytes
= UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1481 c
->udppkt
[seq_num
].rbytes
= c
->rudpbytes
% UDP_MAX_PAYLOAD_SIZE
1487 c
->udppkt
[seq_num
].rbytes
= UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
;
1492 for (int i
= c
->ordcurr
; i
< c
->recvpkt
; i
++)
1494 /* there is some data to copy */
1495 if ((c
->udppkt
[i
].data
!= NULL
)
1496 && (c
->udppkt
[i
].copybytes
< c
->udppkt
[i
].rbytes
))
1498 header
= c
->udppkt
[i
].header
;
1499 len
= c
->udppkt
[i
].rbytes
- c
->udppkt
[i
].copybytes
;
1500 if (len
> rbytes
- wbytes
)
1502 len
= rbytes
- wbytes
;
1505 assert(len
<= rbytes
- wbytes
);
1506 assert(i
== HEADER_TO_SEQNUM(header
));
1508 memcpy(buf
+ wbytes
, c
->udppkt
[i
].data
+ c
->udppkt
[i
].copybytes
,
1511 c
->udppkt
[i
].copybytes
+= len
;
1513 if ((c
->udppkt
[i
].copybytes
== c
->udppkt
[i
].rbytes
)
1514 && (c
->udppkt
[i
].rbytes
== UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
))
1516 /* finish copying all the data of this packet, next */
1520 /* last received packet, and finish copying all the data */
1521 if ((c
->recvpkt
== c
->packets
) && (i
== c
->recvpkt
- 1)
1522 && (c
->udppkt
[i
].copybytes
== c
->udppkt
[i
].rbytes
))
1527 /* no space to copy data */
1528 if (wbytes
>= rbytes
)
1533 /* it doesn't finish reading all the data of the packet from network */
1534 if ((i
!= c
->recvpkt
- 1)
1535 && (c
->udppkt
[i
].rbytes
< UDP_MAX_PAYLOAD_SIZE
- UDP_HEADER_SIZE
))
1542 /* no data to copy */
1547 return wbytes
== 0 ? -1 : wbytes
;
1548 } /* ms_sort_udp_packet */
1552 * encapsulate upd read like tcp read
1554 * @param c, pointer of the concurrency
1555 * @param buf, read buffer
1556 * @param len, length to read
1558 * @return int, if success, return the read bytes, else return
1561 static int ms_udp_read(ms_conn_t
*c
, char *buf
, int len
)
1572 if (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
> c
->rudpsize
)
1574 char *new_rbuf
= realloc(c
->rudpbuf
, (size_t)c
->rudpsize
* 2);
1577 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1578 c
->rudpbytes
= 0; /* ignore what we read */
1581 c
->rudpbuf
= new_rbuf
;
1585 avail
= c
->rudpsize
- c
->rudpbytes
;
1586 /* UDP each time read a packet, 1400 bytes */
1587 res
= (int)read(c
->sfd
, c
->rudpbuf
+ c
->rudpbytes
, (size_t)avail
);
1591 atomic_add_size(&ms_stats
.bytes_read
, res
);
1606 /* "connection" closed */
1612 /* no data to read */
1617 /* copy data to read buffer */
1620 copybytes
= ms_sort_udp_packet(c
, buf
, len
);
1623 if (copybytes
== -1)
1625 atomic_add_size(&ms_stats
.pkt_disorder
, 1);
1633 * read from network as much as we can, handle buffer overflow and connection
1635 * before reading, move the remaining incomplete fragment of a command
1636 * (if any) to the beginning of the buffer.
1637 * return 0 if there's nothing to read on the first read.
1641 * read from network as much as we can, handle buffer overflow and connection
1642 * close. before reading, move the remaining incomplete fragment of a command
1643 * (if any) to the beginning of the buffer.
1645 * @param c, pointer of the concurrency
1648 * return 0 if there's nothing to read on the first read.
1649 * return 1 if get data
1650 * return -1 if error happens
1652 static int ms_try_read_network(ms_conn_t
*c
)
1660 if ((c
->rcurr
!= c
->rbuf
)
1661 && (! c
->readval
|| (c
->rvbytes
> c
->rsize
- (c
->rcurr
- c
->rbuf
))
1662 || (c
->readval
&& (c
->rcurr
- c
->rbuf
> c
->rbytes
))))
1664 if (c
->rbytes
!= 0) /* otherwise there's nothing to copy */
1665 memmove(c
->rbuf
, c
->rcurr
, (size_t)c
->rbytes
);
1671 if (c
->rbytes
>= c
->rsize
)
1673 char *new_rbuf
= realloc(c
->rbuf
, (size_t)c
->rsize
* 2);
1676 fprintf(stderr
, "Couldn't realloc input buffer.\n");
1677 c
->rbytes
= 0; /* ignore what we read */
1680 c
->rcurr
= c
->rbuf
= new_rbuf
;
1684 avail
= c
->rsize
- c
->rbytes
- (c
->rcurr
- c
->rbuf
);
1692 res
= (int32_t)ms_udp_read(c
, c
->rcurr
+ c
->rbytes
, (int32_t)avail
);
1696 res
= (int)read(c
->sfd
, c
->rcurr
+ c
->rbytes
, (size_t)avail
);
1703 atomic_add_size(&ms_stats
.bytes_read
, res
);
1718 /* connection closed */
1719 ms_conn_set_state(c
, conn_closing
);
1724 if ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
))
1726 /* Should close on unhandled errors. */
1727 ms_conn_set_state(c
, conn_closing
);
1733 } /* ms_try_read_network */
1737 * after get the object from server, verify the value if
1740 * @param c, pointer of the concurrency
1741 * @param mlget_item, pointer of mulit-get task item structure
1742 * @param value, received value string
1743 * @param vlen, received value string length
1745 static void ms_verify_value(ms_conn_t
*c
,
1746 ms_mlget_task_item_t
*mlget_item
,
1750 if (c
->curr_task
.verify
)
1752 assert(c
->curr_task
.item
->value_offset
!= INVALID_OFFSET
);
1753 char *orignval
= &ms_setting
.char_block
[c
->curr_task
.item
->value_offset
];
1755 &ms_setting
.char_block
[c
->curr_task
.item
->key_suffix_offset
];
1757 /* verify expire time if necessary */
1758 if (c
->curr_task
.item
->exp_time
> 0)
1760 struct timeval curr_time
;
1761 gettimeofday(&curr_time
, NULL
);
1763 /* object expired but get it now */
1764 if (curr_time
.tv_sec
- c
->curr_task
.item
->client_time
1765 > c
->curr_task
.item
->exp_time
+ EXPIRE_TIME_ERROR
)
1767 atomic_add_size(&ms_stats
.exp_get
, 1);
1769 if (ms_setting
.verbose
)
1773 strftime(set_time
, 64, "%Y-%m-%d %H:%M:%S",
1774 localtime(&c
->curr_task
.item
->client_time
));
1775 strftime(cur_time
, 64, "%Y-%m-%d %H:%M:%S",
1776 localtime(&curr_time
.tv_sec
));
1778 "\n<%d expire time verification failed, "
1779 "object expired but get it now\n"
1781 "\tkey: %" PRIx64
" %.*s\n"
1782 "\tset time: %s current time: %s "
1783 "diff time: %d expire time: %d\n"
1784 "\texpected data: \n"
1785 "\treceived data len: %d\n"
1786 "\treceived data: %.*s\n",
1788 c
->curr_task
.item
->key_size
,
1789 c
->curr_task
.item
->key_prefix
,
1790 c
->curr_task
.item
->key_size
- (int)KEY_PREFIX_SIZE
,
1794 (int)(curr_time
.tv_sec
- c
->curr_task
.item
->client_time
),
1795 c
->curr_task
.item
->exp_time
,
1805 if ((c
->curr_task
.item
->value_size
!= vlen
)
1806 || (memcmp(orignval
, value
, (size_t)vlen
) != 0))
1808 atomic_add_size(&ms_stats
.vef_failed
, 1);
1810 if (ms_setting
.verbose
)
1813 "\n<%d data verification failed\n"
1815 "\tkey: %" PRIx64
" %.*s\n"
1816 "\texpected data len: %d\n"
1817 "\texpected data: %.*s\n"
1818 "\treceived data len: %d\n"
1819 "\treceived data: %.*s\n",
1821 c
->curr_task
.item
->key_size
,
1822 c
->curr_task
.item
->key_prefix
,
1823 c
->curr_task
.item
->key_size
- (int)KEY_PREFIX_SIZE
,
1825 c
->curr_task
.item
->value_size
,
1826 c
->curr_task
.item
->value_size
,
1836 c
->curr_task
.finish_verify
= true;
1838 if (mlget_item
!= NULL
)
1840 mlget_item
->finish_verify
= true;
1843 } /* ms_verify_value */
1847 * For ASCII protocol, after store the data into the local
1848 * buffer, run this function to handle the data.
1850 * @param c, pointer of the concurrency
1852 static void ms_ascii_complete_nread(ms_conn_t
*c
)
1855 assert(c
->rbytes
>= c
->rvbytes
);
1856 assert(c
->protocol
== ascii_prot
);
1860 c
->rcurr
[c
->rvbytes
- 1] == '\n' && c
->rcurr
[c
->rvbytes
- 2] == '\r');
1864 ms_mlget_task_item_t
*mlget_item
= NULL
;
1865 if (((ms_setting
.mult_key_num
> 1)
1866 && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1867 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1869 c
->mlget_task
.value_index
++;
1870 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1872 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
)
1874 c
->curr_task
.item
= mlget_item
->item
;
1875 c
->curr_task
.verify
= mlget_item
->verify
;
1876 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1877 mlget_item
->get_miss
= false;
1881 /* Try to find the task item in multi-get task array */
1882 for (int i
= 0; i
< c
->mlget_task
.mlget_num
; i
++)
1884 mlget_item
= &c
->mlget_task
.mlget_item
[i
];
1885 if (mlget_item
->item
->key_prefix
== c
->currcmd
.key_prefix
)
1887 c
->curr_task
.item
= mlget_item
->item
;
1888 c
->curr_task
.verify
= mlget_item
->verify
;
1889 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1890 mlget_item
->get_miss
= false;
1898 ms_verify_value(c
, mlget_item
, c
->rcurr
, c
->rvbytes
- 2);
1900 c
->curr_task
.get_miss
= false;
1901 c
->rbytes
-= c
->rvbytes
;
1902 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1903 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1906 } /* ms_ascii_complete_nread */
1910 * For binary protocol, after store the data into the local
1911 * buffer, run this function to handle the data.
1913 * @param c, pointer of the concurrency
1915 static void ms_bin_complete_nread(ms_conn_t
*c
)
1918 assert(c
->rbytes
>= c
->rvbytes
);
1919 assert(c
->protocol
== binary_prot
);
1921 int extlen
= c
->binary_header
.response
.extlen
;
1922 int keylen
= c
->binary_header
.response
.keylen
;
1923 uint8_t opcode
= c
->binary_header
.response
.opcode
;
1925 /* not get command or not include value, just return */
1926 if (((opcode
!= PROTOCOL_BINARY_CMD_GET
)
1927 && (opcode
!= PROTOCOL_BINARY_CMD_GETQ
))
1928 || (c
->rvbytes
<= extlen
+ keylen
))
1931 if (c
->binary_header
.response
.opcode
== PROTOCOL_BINARY_CMD_GET
)
1933 c
->currcmd
.retstat
= MCD_END
;
1934 c
->curr_task
.get_miss
= true;
1939 ms_reset_conn(c
, false);
1944 ms_mlget_task_item_t
*mlget_item
= NULL
;
1945 if (((ms_setting
.mult_key_num
> 1)
1946 && (c
->mlget_task
.mlget_num
>= ms_setting
.mult_key_num
))
1947 || ((c
->remain_exec_num
== 0) && (c
->mlget_task
.mlget_num
> 0)))
1949 c
->mlget_task
.value_index
++;
1950 mlget_item
= &c
->mlget_task
.mlget_item
[c
->mlget_task
.value_index
];
1952 c
->curr_task
.item
= mlget_item
->item
;
1953 c
->curr_task
.verify
= mlget_item
->verify
;
1954 c
->curr_task
.finish_verify
= mlget_item
->finish_verify
;
1955 mlget_item
->get_miss
= false;
1960 c
->rcurr
+ extlen
+ keylen
,
1961 c
->rvbytes
- extlen
- keylen
);
1963 c
->currcmd
.retstat
= MCD_END
;
1964 c
->curr_task
.get_miss
= false;
1965 c
->rbytes
-= c
->rvbytes
;
1966 c
->rcurr
= c
->rcurr
+ c
->rvbytes
;
1967 assert(c
->rcurr
<= (c
->rbuf
+ c
->rsize
));
1971 if (ms_setting
.mult_key_num
> 1)
1973 /* multi-get have check all the item */
1974 if (c
->mlget_task
.value_index
== c
->mlget_task
.mlget_num
- 1)
1976 ms_reset_conn(c
, false);
1982 ms_reset_conn(c
, false);
1984 } /* ms_bin_complete_nread */
1988 * we get here after reading the value of get commands.
1990 * @param c, pointer of the concurrency
1992 static void ms_complete_nread(ms_conn_t
*c
)
1995 assert(c
->rbytes
>= c
->rvbytes
);
1996 assert(c
->protocol
== ascii_prot
1997 || c
->protocol
== binary_prot
);
1999 if (c
->protocol
== binary_prot
)
2001 ms_bin_complete_nread(c
);
2005 ms_ascii_complete_nread(c
);
2007 } /* ms_complete_nread */
2011 * Adds a message header to a connection.
2013 * @param c, pointer of the concurrency
2015 * @return int, if success, return 0, else return -1
2017 static int ms_add_msghdr(ms_conn_t
*c
)
2023 if (c
->msgsize
== c
->msgused
)
2026 realloc(c
->msglist
, (size_t)c
->msgsize
* 2 * sizeof(struct msghdr
));
2034 msg
= c
->msglist
+ c
->msgused
;
2037 * this wipes msg_iovlen, msg_control, msg_controllen, and
2038 * msg_flags, the last 3 of which aren't defined on solaris:
2040 memset(msg
, 0, sizeof(struct msghdr
));
2042 msg
->msg_iov
= &c
->iov
[c
->iovused
];
2044 if (c
->udp
&& (c
->srv_recv_addr_size
> 0))
2046 msg
->msg_name
= &c
->srv_recv_addr
;
2047 msg
->msg_namelen
= c
->srv_recv_addr_size
;
2055 /* Leave room for the UDP header, which we'll fill in later. */
2056 return ms_add_iov(c
, NULL
, UDP_HEADER_SIZE
);
2060 } /* ms_add_msghdr */
2064 * Ensures that there is room for another structure iovec in a connection's
2067 * @param c, pointer of the concurrency
2069 * @return int, if success, return 0, else return -1
2071 static int ms_ensure_iov_space(ms_conn_t
*c
)
2075 if (c
->iovused
>= c
->iovsize
)
2078 struct iovec
*new_iov
= (struct iovec
*)realloc(c
->iov
,
2081 * sizeof(struct iovec
));
2088 /* Point all the msghdr structures at the new list. */
2089 for (i
= 0, iovnum
= 0; i
< c
->msgused
; i
++)
2091 c
->msglist
[i
].msg_iov
= &c
->iov
[iovnum
];
2092 iovnum
+= (int)c
->msglist
[i
].msg_iovlen
;
2097 } /* ms_ensure_iov_space */
2101 * Adds data to the list of pending data that will be written out to a
2104 * @param c, pointer of the concurrency
2105 * @param buf, the buffer includes data to send
2106 * @param len, the data length in the buffer
2108 * @return int, if success, return 0, else return -1
2110 static int ms_add_iov(ms_conn_t
*c
, const void *buf
, int len
)
2120 m
= &c
->msglist
[c
->msgused
- 1];
2123 * Limit UDP packets, to UDP_MAX_PAYLOAD_SIZE bytes.
2125 limit_to_mtu
= c
->udp
;
2127 /* We may need to start a new msghdr if this one is full. */
2128 if ((m
->msg_iovlen
== IOV_MAX
)
2129 || (limit_to_mtu
&& (c
->msgbytes
>= UDP_MAX_SEND_PAYLOAD_SIZE
)))
2132 m
= &c
->msglist
[c
->msgused
- 1];
2135 if (ms_ensure_iov_space(c
) != 0)
2138 /* If the fragment is too big to fit in the datagram, split it up */
2139 if (limit_to_mtu
&& (len
+ c
->msgbytes
> UDP_MAX_SEND_PAYLOAD_SIZE
))
2141 leftover
= len
+ c
->msgbytes
- UDP_MAX_SEND_PAYLOAD_SIZE
;
2149 m
= &c
->msglist
[c
->msgused
- 1];
2150 m
->msg_iov
[m
->msg_iovlen
].iov_base
= (void *)buf
;
2151 m
->msg_iov
[m
->msg_iovlen
].iov_len
= (size_t)len
;
2157 buf
= ((char *)buf
) + len
;
2160 while (leftover
> 0);
2167 * Constructs a set of UDP headers and attaches them to the outgoing messages.
2169 * @param c, pointer of the concurrency
2171 * @return int, if success, return 0, else return -1
2173 static int ms_build_udp_headers(ms_conn_t
*c
)
2180 c
->request_id
= ms_get_udp_request_id();
2182 if (c
->msgused
> c
->hdrsize
)
2186 new_hdrbuf
= realloc(c
->hdrbuf
,
2187 (size_t)c
->msgused
* 2 * UDP_HEADER_SIZE
);
2189 new_hdrbuf
= malloc((size_t)c
->msgused
* 2 * UDP_HEADER_SIZE
);
2193 c
->hdrbuf
= (unsigned char *)new_hdrbuf
;
2194 c
->hdrsize
= c
->msgused
* 2;
2197 /* If this is a multi-packet request, drop it. */
2198 if (c
->udp
&& (c
->msgused
> 1))
2200 fprintf(stderr
, "multi-packet request for UDP not supported.\n");
2205 for (i
= 0; i
< c
->msgused
; i
++)
2207 c
->msglist
[i
].msg_iov
[0].iov_base
= (void *)hdr
;
2208 c
->msglist
[i
].msg_iov
[0].iov_len
= UDP_HEADER_SIZE
;
2209 *hdr
++= (unsigned char)(c
->request_id
/ 256);
2210 *hdr
++= (unsigned char)(c
->request_id
% 256);
2211 *hdr
++= (unsigned char)(i
/ 256);
2212 *hdr
++= (unsigned char)(i
% 256);
2213 *hdr
++= (unsigned char)(c
->msgused
/ 256);
2214 *hdr
++= (unsigned char)(c
->msgused
% 256);
2215 *hdr
++= (unsigned char)1; /* support facebook memcached */
2216 *hdr
++= (unsigned char)0;
2218 ((unsigned char *)c
->msglist
[i
].msg_iov
[0].iov_base
2219 + UDP_HEADER_SIZE
));
2223 } /* ms_build_udp_headers */
2227 * Transmit the next chunk of data from our list of msgbuf structures.
2229 * @param c, pointer of the concurrency
2231 * @return TRANSMIT_COMPLETE All done writing.
2232 * TRANSMIT_INCOMPLETE More data remaining to write.
2233 * TRANSMIT_SOFT_ERROR Can't write any more right now.
2234 * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
2236 static int ms_transmit(ms_conn_t
*c
)
2240 if ((c
->msgcurr
< c
->msgused
)
2241 && (c
->msglist
[c
->msgcurr
].msg_iovlen
== 0))
2243 /* Finished writing the current msg; advance to the next. */
2247 if (c
->msgcurr
< c
->msgused
)
2250 struct msghdr
*m
= &c
->msglist
[c
->msgcurr
];
2252 res
= sendmsg(c
->sfd
, m
, 0);
2255 atomic_add_size(&ms_stats
.bytes_written
, res
);
2257 /* We've written some of the data. Remove the completed
2258 * iovec entries from the list of pending writes. */
2259 while (m
->msg_iovlen
> 0 && res
>= (ssize_t
)m
->msg_iov
->iov_len
)
2261 res
-= (ssize_t
)m
->msg_iov
->iov_len
;
2266 /* Might have written just part of the last iovec entry;
2267 * adjust it so the next write will do the rest. */
2270 m
->msg_iov
->iov_base
= (void *)((unsigned char *)m
->msg_iov
->iov_base
+ res
);
2271 m
->msg_iov
->iov_len
-= (size_t)res
;
2273 return TRANSMIT_INCOMPLETE
;
2275 if ((res
== -1) && ((errno
== EAGAIN
) || (errno
== EWOULDBLOCK
)))
2277 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2279 fprintf(stderr
, "Couldn't update event.\n");
2280 ms_conn_set_state(c
, conn_closing
);
2281 return TRANSMIT_HARD_ERROR
;
2283 return TRANSMIT_SOFT_ERROR
;
2286 /* if res==0 or res==-1 and error is not EAGAIN or EWOULDBLOCK,
2287 * we have a real error, on which we close the connection */
2288 fprintf(stderr
, "Failed to write, and not due to blocking.\n");
2290 ms_conn_set_state(c
, conn_closing
);
2291 return TRANSMIT_HARD_ERROR
;
2295 return TRANSMIT_COMPLETE
;
2301 * Shrinks a connection's buffers if they're too big. This prevents
2302 * periodic large "mget" response from server chewing lots of client
2305 * This should only be called in between requests since it can wipe output
2308 * @param c, pointer of the concurrency
2310 static void ms_conn_shrink(ms_conn_t
*c
)
2317 if ((c
->rsize
> READ_BUFFER_HIGHWAT
) && (c
->rbytes
< DATA_BUFFER_SIZE
))
2321 if (c
->rcurr
!= c
->rbuf
)
2322 memmove(c
->rbuf
, c
->rcurr
, (size_t)c
->rbytes
);
2324 newbuf
= (char *)realloc((void *)c
->rbuf
, DATA_BUFFER_SIZE
);
2329 c
->rsize
= DATA_BUFFER_SIZE
;
2334 if (c
->udp
&& (c
->rudpsize
> UDP_DATA_BUFFER_HIGHWAT
)
2335 && (c
->rudpbytes
+ UDP_MAX_PAYLOAD_SIZE
< UDP_DATA_BUFFER_SIZE
))
2337 char *new_rbuf
= (char *)realloc(c
->rudpbuf
, (size_t)c
->rudpsize
* 2);
2340 c
->rudpbuf
= new_rbuf
;
2341 c
->rudpsize
= UDP_DATA_BUFFER_SIZE
;
2343 /* TODO check error condition? */
2346 if (c
->msgsize
> MSG_LIST_HIGHWAT
)
2348 struct msghdr
*newbuf
= (struct msghdr
*)realloc(
2351 * sizeof(c
->msglist
[0]));
2355 c
->msgsize
= MSG_LIST_INITIAL
;
2357 /* TODO check error condition? */
2360 if (c
->iovsize
> IOV_LIST_HIGHWAT
)
2362 struct iovec
*newbuf
= (struct iovec
*)realloc((void *)c
->iov
,
2364 * sizeof(c
->iov
[0]));
2368 c
->iovsize
= IOV_LIST_INITIAL
;
2370 /* TODO check return value */
2372 } /* ms_conn_shrink */
2376 * Sets a connection's current state in the state machine. Any special
2377 * processing that needs to happen on certain state transitions can
2380 * @param c, pointer of the concurrency
2381 * @param state, connection state
2383 static void ms_conn_set_state(ms_conn_t
*c
, int state
)
2387 if (state
!= c
->state
)
2389 if (state
== conn_read
)
2395 } /* ms_conn_set_state */
2399 * update the event if socks change state. for example: when
2400 * change the listen scoket read event to sock write event, or
2401 * change socket handler, we could call this function.
2403 * @param c, pointer of the concurrency
2404 * @param new_flags, new event flags
2406 * @return bool, if success, return true, else return false
2408 static bool ms_update_event(ms_conn_t
*c
, const int new_flags
)
2412 struct event_base
*base
= c
->event
.ev_base
;
2413 if ((c
->ev_flags
== new_flags
) && (ms_setting
.rep_write_srv
== 0)
2414 && (! ms_setting
.facebook_test
|| (c
->total_sfds
== 1)))
2419 if (event_del(&c
->event
) == -1)
2421 /* try to delete the event again */
2422 if (event_del(&c
->event
) == -1)
2428 event_set(&c
->event
,
2433 event_base_set(base
, &c
->event
);
2434 c
->ev_flags
= (short)new_flags
;
2436 if (event_add(&c
->event
, NULL
) == -1)
2442 } /* ms_update_event */
2446 * If user want to get the expected throughput, we could limit
2447 * the performance of memslap. we could give up some work and
2448 * just wait a short time. The function is used to check this
2451 * @param c, pointer of the concurrency
2453 * @return bool, if success, return true, else return false
2455 static bool ms_need_yield(ms_conn_t
*c
)
2457 ms_thread_t
*ms_thread
= pthread_getspecific(ms_thread_key
);
2459 int64_t time_diff
= 0;
2460 struct timeval curr_time
;
2461 ms_task_t
*task
= &c
->curr_task
;
2463 if (ms_setting
.expected_tps
> 0)
2465 gettimeofday(&curr_time
, NULL
);
2466 time_diff
= ms_time_diff(&ms_thread
->startup_time
, &curr_time
);
2468 (int64_t)((task
->get_opt
2469 + task
->set_opt
) / ((uint64_t)time_diff
/ 1000000));
2471 /* current throughput is greater than expected throughput */
2472 if (tps
> ms_thread
->thread_ctx
->tps_perconn
)
2479 } /* ms_need_yield */
2483 * used to update the start time of each operation
2485 * @param c, pointer of the concurrency
2487 static void ms_update_start_time(ms_conn_t
*c
)
2489 ms_task_item_t
*item
= c
->curr_task
.item
;
2491 if ((ms_setting
.stat_freq
> 0) || c
->udp
2492 || ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0)))
2494 gettimeofday(&c
->start_time
, NULL
);
2495 if ((c
->currcmd
.cmd
== CMD_SET
) && (item
->exp_time
> 0))
2497 /* record the current time */
2498 item
->client_time
= c
->start_time
.tv_sec
;
2501 } /* ms_update_start_time */
2505 * run the state machine
2507 * @param c, pointer of the concurrency
2509 static void ms_drive_machine(ms_conn_t
*c
)
2522 if (c
->rbytes
>= c
->rvbytes
)
2524 ms_complete_nread(c
);
2530 if (ms_try_read_line(c
) != 0)
2536 if (ms_try_read_network(c
) != 0)
2541 /* doesn't read all the response data, wait event wake up */
2542 if (! c
->currcmd
.isfinish
)
2544 if (! ms_update_event(c
, EV_READ
| EV_PERSIST
))
2546 fprintf(stderr
, "Couldn't update event.\n");
2547 ms_conn_set_state(c
, conn_closing
);
2554 /* we have no command line and no data to read from network, next write */
2555 ms_conn_set_state(c
, conn_write
);
2556 memcpy(&c
->precmd
, &c
->currcmd
, sizeof(ms_cmdstat_t
)); /* replicate command state */
2561 if (! c
->ctnwrite
&& ms_need_yield(c
))
2565 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2567 fprintf(stderr
, "Couldn't update event.\n");
2568 ms_conn_set_state(c
, conn_closing
);
2575 if (! c
->ctnwrite
&& (ms_exec_task(c
) != 0))
2577 ms_conn_set_state(c
, conn_closing
);
2581 /* record the start time before starting to send data if necessary */
2582 if (! c
->ctnwrite
|| (c
->change_sfd
&& c
->ctnwrite
))
2586 c
->change_sfd
= false;
2588 ms_update_start_time(c
);
2591 /* change sfd if necessary */
2599 /* execute task until nothing need be written to network */
2600 if (! c
->ctnwrite
&& (c
->msgcurr
== c
->msgused
))
2602 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2604 fprintf(stderr
, "Couldn't update event.\n");
2605 ms_conn_set_state(c
, conn_closing
);
2612 switch (ms_transmit(c
))
2614 case TRANSMIT_COMPLETE
:
2615 /* we have no data to write to network, next wait repose */
2616 if (! ms_update_event(c
, EV_READ
| EV_PERSIST
))
2618 fprintf(stderr
, "Couldn't update event.\n");
2619 ms_conn_set_state(c
, conn_closing
);
2623 ms_conn_set_state(c
, conn_read
);
2628 case TRANSMIT_INCOMPLETE
:
2630 break; /* Continue in state machine. */
2632 case TRANSMIT_HARD_ERROR
:
2636 case TRANSMIT_SOFT_ERROR
:
2648 /* recovery mode, need reconnect if connection close */
2649 if (ms_setting
.reconnect
&& (! ms_global
.time_out
2650 || ((ms_setting
.run_time
== 0)
2651 && (c
->remain_exec_num
> 0))))
2653 if (ms_reconn(c
) != 0)
2660 ms_reset_conn(c
, false);
2662 if (c
->total_sfds
== 1)
2664 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2666 fprintf(stderr
, "Couldn't update event.\n");
2667 ms_conn_set_state(c
, conn_closing
);
2685 } /* ms_drive_machine */
2689 * the event handler of each thread
2691 * @param fd, the file descriptor of socket
2692 * @param which, event flag
2693 * @param arg, argument
2695 void ms_event_handler(const int fd
, const short which
, void *arg
)
2697 ms_conn_t
*c
= (ms_conn_t
*)arg
;
2707 "Catastrophic: event fd: %d doesn't match conn fd: %d\n",
2713 assert(fd
== c
->sfd
);
2715 ms_drive_machine(c
);
2717 /* wait for next event */
2718 } /* ms_event_handler */
2722 * get the next socket descriptor index to run for replication
2724 * @param c, pointer of the concurrency
2725 * @param cmd, command(get or set )
2727 * @return int, if success, return the index, else return 0
2729 static uint32_t ms_get_rep_sock_index(ms_conn_t
*c
, int cmd
)
2731 uint32_t sock_index
= 0;
2734 if (c
->total_sfds
== 1)
2739 if (ms_setting
.rep_write_srv
== 0)
2748 for (i
= 0; i
< ms_setting
.rep_write_srv
; i
++)
2750 if (c
->tcpsfd
[i
] > 0)
2756 if (i
== ms_setting
.rep_write_srv
)
2758 /* random get one replication server to read */
2759 sock_index
= (uint32_t)random() % c
->total_sfds
;
2763 /* random get one replication writing server to write */
2764 sock_index
= (uint32_t)random() % ms_setting
.rep_write_srv
;
2767 else if (cmd
== CMD_GET
)
2769 /* random get one replication server to read */
2770 sock_index
= (uint32_t)random() % c
->total_sfds
;
2773 while (c
->tcpsfd
[sock_index
] == 0);
2776 } /* ms_get_rep_sock_index */
2780 * get the next socket descriptor index to run
2782 * @param c, pointer of the concurrency
2784 * @return int, return the index
2786 static uint32_t ms_get_next_sock_index(ms_conn_t
*c
)
2788 uint32_t sock_index
= 0;
2792 sock_index
= (++c
->cur_idx
== c
->total_sfds
) ? 0 : c
->cur_idx
;
2794 while (c
->tcpsfd
[sock_index
] == 0);
2797 } /* ms_get_next_sock_index */
2801 * update socket event of the connections
2803 * @param c, pointer of the concurrency
2805 * @return int, if success, return 0, else return -1
2807 static int ms_update_conn_sock_event(ms_conn_t
*c
)
2811 switch (c
->currcmd
.cmd
)
2814 if (ms_setting
.facebook_test
&& c
->udp
)
2816 c
->sfd
= c
->tcpsfd
[0];
2818 c
->change_sfd
= true;
2823 if (ms_setting
.facebook_test
&& ! c
->udp
)
2827 c
->change_sfd
= true;
2835 if (! c
->udp
&& (c
->total_sfds
> 1))
2837 if (c
->cur_idx
!= c
->total_sfds
)
2839 if (ms_setting
.rep_write_srv
== 0)
2841 c
->cur_idx
= ms_get_next_sock_index(c
);
2845 c
->cur_idx
= ms_get_rep_sock_index(c
, c
->currcmd
.cmd
);
2850 /* must select the first sock of the connection at the beginning */
2854 c
->sfd
= c
->tcpsfd
[c
->cur_idx
];
2855 assert(c
->sfd
!= 0);
2856 c
->change_sfd
= true;
2861 if (! ms_update_event(c
, EV_WRITE
| EV_PERSIST
))
2863 fprintf(stderr
, "Couldn't update event.\n");
2864 ms_conn_set_state(c
, conn_closing
);
2870 } /* ms_update_conn_sock_event */
2874 * for ASCII protocol, this function build the set command
2875 * string and send the command.
2877 * @param c, pointer of the concurrency
2878 * @param item, pointer of task item which includes the object
2881 * @return int, if success, return 0, else return -1
2883 static int ms_build_ascii_write_buf_set(ms_conn_t
*c
, ms_task_item_t
*item
)
2887 char *buffer
= c
->wbuf
;
2889 write_len
= sprintf(buffer
,
2895 if (write_len
> c
->wsize
)
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)))
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 0, 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);
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 0, 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)))
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 0, 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);
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 0, 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)))
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 0, 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);
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 0, 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
;
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
);
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
.reserved
= 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 0, 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
);
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 0, 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
);
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 0, 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
);
3413 } /* ms_build_bin_write_buf_mlget */