1.Fix bug that memslap can't start up(ms_thread=NULL). 2.ignore signal SIGPIPE. 3...
[m6w6/libmemcached] / clients / ms_conn.c
1 /*
2 * File: ms_conn.c
3 * Author: Mingqiang Zhuang
4 *
5 * Created on February 10, 2009
6 *
7 * (c) Copyright 2009, Schooner Information Technology, Inc.
8 * http://www.schoonerinfotech.com/
9 *
10 */
11
12 #include "config.h"
13
14 #include <stdio.h>
15 #include <inttypes.h>
16 #include <limits.h>
17 #include <sys/uio.h>
18 #include <event.h>
19 #include <fcntl.h>
20 #include <netinet/tcp.h>
21 #include <arpa/inet.h>
22 #if TIME_WITH_SYS_TIME
23 # include <sys/time.h>
24 # include <time.h>
25 #else
26 # if HAVE_SYS_TIME_H
27 # include <sys/time.h>
28 # else
29 # include <time.h>
30 # endif
31 #endif
32 #include "ms_setting.h"
33 #include "ms_thread.h"
34 #include "ms_atomic.h"
35
36 #ifdef linux
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 ..
41 */
42 #undef ntohs
43 #undef ntohl
44 #undef htons
45 #undef htonl
46 #endif
47
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
53
54 /* for generating key */
55 #define KEY_PREFIX_BASE 0x1010101010101010 /* not include ' ' '\r' '\n' '\0' */
56 #define KEY_PREFIX_MASK 0x1010101010101010
57
58 /* For parse the value length return by server */
59 #define KEY_TOKEN 1
60 #define VALUELEN_TOKEN 3
61
62 /* global increasing counter, to ensure the key prefix unique */
63 static uint64_t key_prefix_seq= KEY_PREFIX_BASE;
64
65 /* global increasing counter, generating request id for UDP */
66 static volatile uint32_t udp_request_id= 0;
67
68 extern pthread_key_t ms_thread_key;
69
70 /* generate upd request id */
71 static uint32_t ms_get_udp_request_id(void);
72
73
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,
80 const int init_state,
81 const int read_buffer_size,
82 const bool is_udp);
83 static void ms_warmup_num_init(ms_conn_t *c);
84 static int ms_item_win_init(ms_conn_t *c);
85
86
87 /* connection close */
88 void ms_conn_free(ms_conn_t *c);
89 static void ms_conn_close(ms_conn_t *c);
90
91
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,
96 char *srv_host_name,
97 const int srv_port,
98 const bool is_udp,
99 int *ret_sfd);
100 static int ms_reconn(ms_conn_t *c);
101
102
103 /* read and parse */
104 static int ms_tokenize_command(char *command,
105 token_t *tokens,
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,
114 char *value,
115 int vlen);
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);
119
120
121 /* send functions */
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);
127
128
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 int ms_get_rep_sock_index(ms_conn_t *c, int cmd);
134 static int 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);
138
139
140 /* main loop */
141 static void ms_drive_machine(ms_conn_t *c);
142 void ms_event_handler(const int fd, const short which, void *arg);
143
144
145 /* ascii protocol */
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);
149
150
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,
154 uint8_t opcode,
155 uint8_t hdr_len,
156 uint16_t key_len,
157 uint32_t body_len);
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);
162
163
164 /**
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'.
170 *
171 * @return uint64_t
172 */
173 uint64_t ms_get_key_prefix(void)
174 {
175 uint64_t key_prefix;
176
177 pthread_mutex_lock(&ms_global.seq_mutex);
178 key_prefix_seq|= KEY_PREFIX_MASK;
179 key_prefix= key_prefix_seq;
180 key_prefix_seq++;
181 pthread_mutex_unlock(&ms_global.seq_mutex);
182
183 return key_prefix;
184 } /* ms_get_key_prefix */
185
186
187 /**
188 * get an unique udp request id
189 *
190 * @return an unique UDP request id
191 */
192 static uint32_t ms_get_udp_request_id(void)
193 {
194 return atomic_add_32_nv(&udp_request_id, 1);
195 }
196
197
198 /**
199 * initialize current task structure
200 *
201 * @param c, pointer of the concurrency
202 */
203 static void ms_task_init(ms_conn_t *c)
204 {
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;
210
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;
217 } /* ms_task_init */
218
219
220 /**
221 * initialize udp for the connection structure
222 *
223 * @param c, pointer of the concurrency
224 * @param is_udp, whether it's udp
225 *
226 * @return int, if success, return 0, else return -1
227 */
228 static int ms_conn_udp_init(ms_conn_t *c, const bool is_udp)
229 {
230 c->hdrbuf= 0;
231 c->rudpbuf= 0;
232 c->udppkt= 0;
233
234 c->rudpsize= UDP_DATA_BUFFER_SIZE;
235 c->hdrsize= 0;
236
237 c->rudpbytes= 0;
238 c->packets= 0;
239 c->recvpkt= 0;
240 c->pktcurr= 0;
241 c->ordcurr= 0;
242
243 c->udp= is_udp;
244
245 if (c->udp || (! c->udp && ms_setting.facebook_test))
246 {
247 c->rudpbuf= (char *)malloc((size_t)c->rudpsize);
248 c->udppkt= (ms_udppkt_t *)malloc(MAX_UDP_PACKET * sizeof(ms_udppkt_t));
249
250 if ((c->rudpbuf == NULL) || (c->udppkt == NULL))
251 {
252 if (c->rudpbuf != NULL)
253 free(c->rudpbuf);
254 if (c->udppkt != NULL)
255 free(c->udppkt);
256 fprintf(stderr, "malloc()\n");
257 return -1;
258 }
259 memset(c->udppkt, 0, MAX_UDP_PACKET * sizeof(ms_udppkt_t));
260 }
261
262 return 0;
263 } /* ms_conn_udp_init */
264
265
266 /**
267 * initialize the connection structure
268 *
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
273 *
274 * @return int, if success, return 0, else return -1
275 */
276 static int ms_conn_init(ms_conn_t *c,
277 const int init_state,
278 const int read_buffer_size,
279 const bool is_udp)
280 {
281 assert(c != NULL);
282
283 c->rbuf= c->wbuf= 0;
284 c->iov= 0;
285 c->msglist= 0;
286
287 c->rsize= read_buffer_size;
288 c->wsize= WRITE_BUFFER_SIZE;
289 c->iovsize= IOV_LIST_INITIAL;
290 c->msgsize= MSG_LIST_INITIAL;
291
292 /* for replication, each connection need connect all the server */
293 if (ms_setting.rep_write_srv > 0)
294 {
295 c->total_sfds= ms_setting.srv_cnt * ms_setting.sock_per_conn;
296 }
297 else
298 {
299 c->total_sfds= ms_setting.sock_per_conn;
300 }
301 c->alive_sfds= 0;
302
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)
309 {
310 c->mlget_task.mlget_item= (ms_mlget_task_item_t *)
311 malloc(
312 sizeof(ms_mlget_task_item_t) * (size_t)ms_setting.mult_key_num);
313 }
314 c->tcpsfd= (int *)malloc((size_t)c->total_sfds * sizeof(int));
315
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)))
320 {
321 if (c->rbuf != NULL)
322 free(c->rbuf);
323 if (c->wbuf != NULL)
324 free(c->wbuf);
325 if (c->iov != NULL)
326 free(c->iov);
327 if (c->msglist != NULL)
328 free(c->msglist);
329 if (c->mlget_task.mlget_item != NULL)
330 free(c->mlget_task.mlget_item);
331 if (c->tcpsfd != NULL)
332 free(c->tcpsfd);
333 fprintf(stderr, "malloc()\n");
334 return -1;
335 }
336
337 c->state= init_state;
338 c->rvbytes= 0;
339 c->rbytes= 0;
340 c->rcurr= c->rbuf;
341 c->wcurr= c->wbuf;
342 c->iovused= 0;
343 c->msgcurr= 0;
344 c->msgused= 0;
345 c->cur_idx= c->total_sfds; /* default index is a invalid value */
346
347 c->ctnwrite= false;
348 c->readval= false;
349 c->change_sfd= false;
350
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;
356
357 c->mlget_task.mlget_num= 0;
358 c->mlget_task.value_index= -1; /* default invalid value */
359
360 if (ms_setting.binary_prot)
361 {
362 c->protocol= binary_prot;
363 }
364 else
365 {
366 c->protocol= ascii_prot;
367 }
368
369 /* initialize udp */
370 if (ms_conn_udp_init(c, is_udp) != 0)
371 {
372 return -1;
373 }
374
375 /* initialize task */
376 ms_task_init(c);
377
378 if (! (ms_setting.facebook_test && is_udp))
379 {
380 atomic_add_32(&ms_stats.active_conns, 1);
381 }
382
383 return 0;
384 } /* ms_conn_init */
385
386
387 /**
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.
391 *
392 * @param c, pointer of the concurrency
393 */
394 static void ms_warmup_num_init(ms_conn_t *c)
395 {
396 /* no set operation, preset all the items in the window */
397 if (ms_setting.cmd_distr[CMD_SET].cmd_prop < PROP_ERROR)
398 {
399 c->warmup_num= c->win_size;
400 c->remain_warmup_num= c->warmup_num;
401 }
402 else
403 {
404 c->warmup_num= 0;
405 c->remain_warmup_num= c->warmup_num;
406 }
407 } /* ms_warmup_num_init */
408
409
410 /**
411 * each connection has an item window, this function initialize
412 * the window. The window is used to generate task.
413 *
414 * @param c, pointer of the concurrency
415 *
416 * @return int, if success, return 0, else return -1
417 */
418 static int ms_item_win_init(ms_conn_t *c)
419 {
420 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
421 int exp_cnt= 0;
422
423 c->win_size= (int)ms_setting.win_size;
424 c->set_cursor= 0;
425 c->exec_num= ms_thread->thread_ctx->exec_num_perconn;
426 c->remain_exec_num= c->exec_num;
427
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)
431 {
432 fprintf(stderr, "Can't allocate task item array for conn.\n");
433 return -1;
434 }
435 memset(c->item_win, 0, sizeof(ms_task_item_t) * (size_t)c->win_size);
436
437 for (int i= 0; i < c->win_size; i++)
438 {
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;
445
446 /* set expire time base on the proportion */
447 if (exp_cnt < ms_setting.exp_ver_per * i)
448 {
449 c->item_win[i].exp_time= FIXED_EXPIRE_TIME;
450 exp_cnt++;
451 }
452 else
453 {
454 c->item_win[i].exp_time= 0;
455 }
456 }
457
458 ms_warmup_num_init(c);
459
460 return 0;
461 } /* ms_item_win_init */
462
463
464 /**
465 * each connection structure can include one or more sock
466 * handlers. this function create these socks and connect the
467 * server(s).
468 *
469 * @param c, pointer of the concurrency
470 *
471 * @return int, if success, return 0, else return -1
472 */
473 static int ms_conn_sock_init(ms_conn_t *c)
474 {
475 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
476 int i;
477 int ret_sfd;
478 int srv_idx= 0;
479
480 assert(c != NULL);
481 assert(c->tcpsfd != NULL);
482
483 for (i= 0; i < c->total_sfds; i++)
484 {
485 ret_sfd= 0;
486 if (ms_setting.rep_write_srv > 0)
487 {
488 /* for replication, each connection need connect all the server */
489 srv_idx= i % ms_setting.srv_cnt;
490 }
491 else
492 {
493 /* all the connections in a thread connects the same server */
494 srv_idx= ms_thread->thread_ctx->srv_idx;
495 }
496
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)
500 {
501 break;
502 }
503
504 if (i == 0)
505 {
506 c->sfd= ret_sfd;
507 }
508
509 if (! ms_setting.udp)
510 {
511 c->tcpsfd[i]= ret_sfd;
512 }
513
514 c->alive_sfds++;
515 }
516
517 /* initialize udp sock handler if necessary */
518 if (ms_setting.facebook_test)
519 {
520 ret_sfd= 0;
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)
524 {
525 c->udpsfd= 0;
526 }
527 else
528 {
529 c->udpsfd= ret_sfd;
530 }
531 }
532
533 if ((i != c->total_sfds) || (ms_setting.facebook_test && (c->udpsfd == 0)))
534 {
535 if (ms_setting.udp)
536 {
537 close(c->sfd);
538 }
539 else
540 {
541 for (int j= 0; j < i; j++)
542 {
543 close(c->tcpsfd[j]);
544 }
545 }
546
547 if (c->udpsfd != 0)
548 {
549 close(c->udpsfd);
550 }
551
552 return -1;
553 }
554
555 return 0;
556 } /* ms_conn_sock_init */
557
558
559 /**
560 * each connection is managed by libevent, this function
561 * initialize the event of the connection structure.
562 *
563 * @param c, pointer of the concurrency
564 *
565 * @return int, if success, return 0, else return -1
566 */
567 static int ms_conn_event_init(ms_conn_t *c)
568 {
569 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
570 short event_flags= EV_WRITE | EV_PERSIST;
571
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;
575
576 if (event_add(&c->event, NULL) == -1)
577 {
578 return -1;
579 }
580
581 return 0;
582 } /* ms_conn_event_init */
583
584
585 /**
586 * setup a connection, each connection structure of each
587 * thread must call this function to initialize.
588 *
589 * @param c, pointer of the concurrency
590 *
591 * @return int, if success, return 0, else return -1
592 */
593 int ms_setup_conn(ms_conn_t *c)
594 {
595 if (ms_item_win_init(c) != 0)
596 {
597 return -1;
598 }
599
600 if (ms_conn_init(c, conn_write, DATA_BUFFER_SIZE, ms_setting.udp) != 0)
601 {
602 return -1;
603 }
604
605 if (ms_conn_sock_init(c) != 0)
606 {
607 return -1;
608 }
609
610 if (ms_conn_event_init(c) != 0)
611 {
612 return -1;
613 }
614
615 return 0;
616 } /* ms_setup_conn */
617
618
619 /**
620 * Frees a connection.
621 *
622 * @param c, pointer of the concurrency
623 */
624 void ms_conn_free(ms_conn_t *c)
625 {
626 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
627 if (c != NULL)
628 {
629 if (c->hdrbuf != NULL)
630 free(c->hdrbuf);
631 if (c->msglist != NULL)
632 free(c->msglist);
633 if (c->rbuf != NULL)
634 free(c->rbuf);
635 if (c->wbuf != NULL)
636 free(c->wbuf);
637 if (c->iov != NULL)
638 free(c->iov);
639 if (c->mlget_task.mlget_item != NULL)
640 free(c->mlget_task.mlget_item);
641 if (c->rudpbuf != NULL)
642 free(c->rudpbuf);
643 if (c->udppkt != NULL)
644 free(c->udppkt);
645 if (c->item_win != NULL)
646 free(c->item_win);
647 if (c->tcpsfd != NULL)
648 free(c->tcpsfd);
649
650 if (--ms_thread->nactive_conn == 0)
651 {
652 free(ms_thread->conn);
653 }
654 }
655 } /* ms_conn_free */
656
657
658 /**
659 * close a connection
660 *
661 * @param c, pointer of the concurrency
662 */
663 static void ms_conn_close(ms_conn_t *c)
664 {
665 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
666 assert(c != NULL);
667
668 /* delete the event, the socket and the connection */
669 event_del(&c->event);
670
671 for (int i= 0; i < c->total_sfds; i++)
672 {
673 if (c->tcpsfd[i] > 0)
674 {
675 close(c->tcpsfd[i]);
676 }
677 }
678 c->sfd= 0;
679
680 if (ms_setting.facebook_test)
681 {
682 close(c->udpsfd);
683 }
684
685 atomic_dec_32(&ms_stats.active_conns);
686
687 ms_conn_free(c);
688
689 if (ms_setting.run_time == 0)
690 {
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);
695 }
696
697 if (ms_thread->nactive_conn == 0)
698 {
699 pthread_exit(NULL);
700 }
701 } /* ms_conn_close */
702
703
704 /**
705 * create a new sock
706 *
707 * @param ai, server address information
708 *
709 * @return int, if success, return 0, else return -1
710 */
711 static int ms_new_socket(struct addrinfo *ai)
712 {
713 int sfd;
714
715 if ((sfd= socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1)
716 {
717 fprintf(stderr, "socket() error: %s.\n", strerror(errno));
718 return -1;
719 }
720
721 return sfd;
722 } /* ms_new_socket */
723
724
725 /**
726 * Sets a socket's send buffer size to the maximum allowed by the system.
727 *
728 * @param sfd, file descriptor of socket
729 */
730 static void ms_maximize_sndbuf(const int sfd)
731 {
732 socklen_t intsize= sizeof(int);
733 unsigned int last_good= 0;
734 unsigned int min, max, avg;
735 unsigned int old_size;
736
737 /* Start with the default size. */
738 if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0)
739 {
740 fprintf(stderr, "getsockopt(SO_SNDBUF)\n");
741 return;
742 }
743
744 /* Binary-search for the real maximum. */
745 min= old_size;
746 max= MAX_SENDBUF_SIZE;
747
748 while (min <= max)
749 {
750 avg= ((unsigned int)(min + max)) / 2;
751 if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0)
752 {
753 last_good= avg;
754 min= avg + 1;
755 }
756 else
757 {
758 max= avg - 1;
759 }
760 }
761 } /* ms_maximize_sndbuf */
762
763
764 /**
765 * socket connects the server
766 *
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
772 *
773 * @return int, if success, return 0, else return -1
774 */
775 static int ms_network_connect(ms_conn_t *c,
776 char *srv_host_name,
777 const int srv_port,
778 const bool is_udp,
779 int *ret_sfd)
780 {
781 int sfd;
782 struct linger ling=
783 {
784 0, 0
785 };
786 struct addrinfo *ai;
787 struct addrinfo *next;
788 struct addrinfo hints;
789 char port_buf[NI_MAXSERV];
790 int error;
791 int success= 0;
792
793 int flags= 1;
794
795 /*
796 * the memset call clears nonstandard fields in some impementations
797 * that otherwise mess things up.
798 */
799 memset(&hints, 0, sizeof(hints));
800 hints.ai_flags= AI_PASSIVE | AI_ADDRCONFIG;
801 if (is_udp)
802 {
803 hints.ai_protocol= IPPROTO_UDP;
804 hints.ai_socktype= SOCK_DGRAM;
805 hints.ai_family= AF_INET; /* This left here because of issues with OSX 10.5 */
806 }
807 else
808 {
809 hints.ai_family= AF_UNSPEC;
810 hints.ai_protocol= IPPROTO_TCP;
811 hints.ai_socktype= SOCK_STREAM;
812 }
813
814 snprintf(port_buf, NI_MAXSERV, "%d", srv_port);
815 error= getaddrinfo(srv_host_name, port_buf, &hints, &ai);
816 if (error != 0)
817 {
818 if (error != EAI_SYSTEM)
819 fprintf(stderr, "getaddrinfo(): %s.\n", gai_strerror(error));
820 else
821 perror("getaddrinfo()\n");
822
823 return -1;
824 }
825
826 for (next= ai; next; next= next->ai_next)
827 {
828 if ((sfd= ms_new_socket(next)) == -1)
829 {
830 freeaddrinfo(ai);
831 return -1;
832 }
833
834 setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
835 if (is_udp)
836 {
837 ms_maximize_sndbuf(sfd);
838 }
839 else
840 {
841 setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags,
842 sizeof(flags));
843 setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
844 setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags,
845 sizeof(flags));
846 }
847
848 if (is_udp)
849 {
850 c->srv_recv_addr_size= sizeof(struct sockaddr);
851 memcpy(&c->srv_recv_addr, next->ai_addr, c->srv_recv_addr_size);
852 }
853 else
854 {
855 if (connect(sfd, next->ai_addr, next->ai_addrlen) == -1)
856 {
857 close(sfd);
858 freeaddrinfo(ai);
859 return -1;
860 }
861 }
862
863 if (((flags= fcntl(sfd, F_GETFL, 0)) < 0)
864 || (fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0))
865 {
866 fprintf(stderr, "setting O_NONBLOCK\n");
867 close(sfd);
868 freeaddrinfo(ai);
869 return -1;
870 }
871
872 if (ret_sfd != NULL)
873 {
874 *ret_sfd= sfd;
875 }
876
877 success++;
878 }
879
880 freeaddrinfo(ai);
881
882 /* Return zero if we detected no errors in starting up connections */
883 return success == 0;
884 } /* ms_network_connect */
885
886
887 /**
888 * reconnect a disconnected sock
889 *
890 * @param c, pointer of the concurrency
891 *
892 * @return int, if success, return 0, else return -1
893 */
894 static int ms_reconn(ms_conn_t *c)
895 {
896 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
897 int srv_idx= 0;
898 int32_t srv_conn_cnt= 0;
899
900 if (ms_setting.rep_write_srv > 0)
901 {
902 srv_idx= c->cur_idx % ms_setting.srv_cnt;
903 srv_conn_cnt= (int)(ms_setting.sock_per_conn * ms_setting.nconns);
904 }
905 else
906 {
907 srv_idx= ms_thread->thread_ctx->srv_idx;
908 srv_conn_cnt= (int32_t)((int)ms_setting.nconns / ms_setting.srv_cnt);
909 }
910
911 /* close the old socket handler */
912 close(c->sfd);
913 c->tcpsfd[c->cur_idx]= 0;
914
915 if (atomic_add_32_nv(&ms_setting.servers[srv_idx].disconn_cnt, 1)
916 % (uint32_t)srv_conn_cnt == 0)
917 {
918 gettimeofday(&ms_setting.servers[srv_idx].disconn_time, NULL);
919 fprintf(stderr, "Server %s:%d disconnect\n",
920 ms_setting.servers[srv_idx].srv_host_name,
921 ms_setting.servers[srv_idx].srv_port);
922 }
923
924 if (ms_setting.rep_write_srv > 0)
925 {
926 int i= 0;
927 for (i= 0; i < c->total_sfds; i++)
928 {
929 if (c->tcpsfd[i] != 0)
930 {
931 break;
932 }
933 }
934
935 /* all socks disconnect */
936 if (i == c->total_sfds)
937 {
938 return -1;
939 }
940 }
941 else
942 {
943 do
944 {
945 /* reconnect success, break the loop */
946 if (ms_network_connect(c, ms_setting.servers[srv_idx].srv_host_name,
947 ms_setting.servers[srv_idx].srv_port,
948 ms_setting.udp, &c->sfd) == 0)
949 {
950 c->tcpsfd[c->cur_idx]= c->sfd;
951 if (atomic_add_32_nv(&ms_setting.servers[srv_idx].reconn_cnt, 1)
952 % (uint32_t)srv_conn_cnt == 0)
953 {
954 gettimeofday(&ms_setting.servers[srv_idx].reconn_time, NULL);
955 int reconn_time=
956 (int)(ms_setting.servers[srv_idx].reconn_time.tv_sec
957 - ms_setting.servers[srv_idx].disconn_time
958 .tv_sec);
959 fprintf(stderr, "Server %s:%d reconnect after %ds\n",
960 ms_setting.servers[srv_idx].srv_host_name,
961 ms_setting.servers[srv_idx].srv_port, reconn_time);
962 }
963 break;
964 }
965
966 if (ms_setting.rep_write_srv == 0 && c->total_sfds > 0)
967 {
968 /* wait a second and reconnect */
969 sleep(1);
970 }
971 }
972 while (ms_setting.rep_write_srv == 0 && c->total_sfds > 0);
973 }
974
975 if ((c->total_sfds > 1) && (c->tcpsfd[c->cur_idx] == 0))
976 {
977 c->sfd= 0;
978 c->alive_sfds--;
979 }
980
981 return 0;
982 } /* ms_reconn */
983
984
985 /**
986 * reconnect several disconnected socks in the connection
987 * structure, the ever-1-second timer of the thread will check
988 * whether some socks in the connections disconnect. if
989 * disconnect, reconnect the sock.
990 *
991 * @param c, pointer of the concurrency
992 *
993 * @return int, if success, return 0, else return -1
994 */
995 int ms_reconn_socks(ms_conn_t *c)
996 {
997 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
998 int srv_idx= 0;
999 int ret_sfd= 0;
1000 int srv_conn_cnt= 0;
1001 struct timeval cur_time;
1002
1003 assert(c != NULL);
1004
1005 if ((c->total_sfds == 1) || (c->total_sfds == c->alive_sfds))
1006 {
1007 return 0;
1008 }
1009
1010 for (int i= 0; i < c->total_sfds; i++)
1011 {
1012 if (c->tcpsfd[i] == 0)
1013 {
1014 gettimeofday(&cur_time, NULL);
1015
1016 /**
1017 * For failover test of replication, reconnect the socks after
1018 * it disconnects more than 5 seconds, Otherwise memslap will
1019 * block at connect() function and the work threads can't work
1020 * in this interval.
1021 */
1022 if (cur_time.tv_sec
1023 - ms_setting.servers[srv_idx].disconn_time.tv_sec < 5)
1024 {
1025 break;
1026 }
1027
1028 if (ms_setting.rep_write_srv > 0)
1029 {
1030 srv_idx= i % ms_setting.srv_cnt;
1031 srv_conn_cnt= (int)(ms_setting.sock_per_conn * ms_setting.nconns);
1032 }
1033 else
1034 {
1035 srv_idx= ms_thread->thread_ctx->srv_idx;
1036 srv_conn_cnt= (int)ms_setting.nconns / ms_setting.srv_cnt;
1037 }
1038
1039 if (ms_network_connect(c, ms_setting.servers[srv_idx].srv_host_name,
1040 ms_setting.servers[srv_idx].srv_port,
1041 ms_setting.udp, &ret_sfd) == 0)
1042 {
1043 c->tcpsfd[i]= ret_sfd;
1044 c->alive_sfds++;
1045
1046 if (atomic_add_32_nv(&ms_setting.servers[srv_idx].reconn_cnt, 1)
1047 % (uint32_t)srv_conn_cnt == 0)
1048 {
1049 gettimeofday(&ms_setting.servers[srv_idx].reconn_time, NULL);
1050 int reconn_time=
1051 (int)(ms_setting.servers[srv_idx].reconn_time.tv_sec
1052 - ms_setting.servers[srv_idx].disconn_time
1053 .tv_sec);
1054 fprintf(stderr, "Server %s:%d reconnect after %ds\n",
1055 ms_setting.servers[srv_idx].srv_host_name,
1056 ms_setting.servers[srv_idx].srv_port, reconn_time);
1057 }
1058 }
1059 }
1060 }
1061
1062 return 0;
1063 } /* ms_reconn_socks */
1064
1065
1066 /**
1067 * Tokenize the command string by replacing whitespace with '\0' and update
1068 * the token array tokens with pointer to start of each token and length.
1069 * Returns total number of tokens. The last valid token is the terminal
1070 * token (value points to the first unprocessed character of the string and
1071 * length zero).
1072 *
1073 * Usage example:
1074 *
1075 * while(ms_tokenize_command(command, ncommand, tokens, max_tokens) > 0) {
1076 * for(int ix = 0; tokens[ix].length != 0; ix++) {
1077 * ...
1078 * }
1079 * ncommand = tokens[ix].value - command;
1080 * command = tokens[ix].value;
1081 * }
1082 *
1083 * @param command, the command string to token
1084 * @param tokens, array to store tokens
1085 * @param max_tokens, maximum tokens number
1086 *
1087 * @return int, the number of tokens
1088 */
1089 static int ms_tokenize_command(char *command,
1090 token_t *tokens,
1091 const int max_tokens)
1092 {
1093 char *s, *e;
1094 int ntokens= 0;
1095
1096 assert(command != NULL && tokens != NULL && max_tokens > 1);
1097
1098 for (s= e= command; ntokens < max_tokens - 1; ++e)
1099 {
1100 if (*e == ' ')
1101 {
1102 if (s != e)
1103 {
1104 tokens[ntokens].value= s;
1105 tokens[ntokens].length= (size_t)(e - s);
1106 ntokens++;
1107 *e= '\0';
1108 }
1109 s= e + 1;
1110 }
1111 else if (*e == '\0')
1112 {
1113 if (s != e)
1114 {
1115 tokens[ntokens].value= s;
1116 tokens[ntokens].length= (size_t)(e - s);
1117 ntokens++;
1118 }
1119
1120 break; /* string end */
1121 }
1122 }
1123
1124 return ntokens;
1125 } /* ms_tokenize_command */
1126
1127
1128 /**
1129 * parse the response of server.
1130 *
1131 * @param c, pointer of the concurrency
1132 * @param command, the string responded by server
1133 *
1134 * @return int, if the command completed return 0, else return
1135 * -1
1136 */
1137 static int ms_ascii_process_line(ms_conn_t *c, char *command)
1138 {
1139 int ret= 0;
1140 int64_t value_len;
1141 char *buffer= command;
1142
1143 assert(c != NULL);
1144
1145 /**
1146 * for command get, we store the returned value into local buffer
1147 * then continue in ms_complete_nread().
1148 */
1149
1150 switch (buffer[0])
1151 {
1152 case 'V': /* VALUE || VERSION */
1153 if (buffer[1] == 'A') /* VALUE */
1154 {
1155 token_t tokens[MAX_TOKENS];
1156 ms_tokenize_command(command, tokens, MAX_TOKENS);
1157 value_len= strtol(tokens[VALUELEN_TOKEN].value, NULL, 10);
1158 c->currcmd.key_prefix= *(uint64_t *)tokens[KEY_TOKEN].value;
1159
1160 /*
1161 * We read the \r\n into the string since not doing so is more
1162 * cycles then the waster of memory to do so.
1163 *
1164 * We are null terminating through, which will most likely make
1165 * some people lazy about using the return length.
1166 */
1167 c->rvbytes= (int)(value_len + 2);
1168 c->readval= true;
1169 ret= -1;
1170 }
1171
1172 break;
1173
1174 case 'O': /* OK */
1175 c->currcmd.retstat= MCD_SUCCESS;
1176
1177 case 'S': /* STORED STATS SERVER_ERROR */
1178 if (buffer[2] == 'A') /* STORED STATS */
1179 { /* STATS*/
1180 c->currcmd.retstat= MCD_STAT;
1181 }
1182 else if (buffer[1] == 'E')
1183 {
1184 /* SERVER_ERROR */
1185 printf("<%d %s\n", c->sfd, buffer);
1186
1187 c->currcmd.retstat= MCD_SERVER_ERROR;
1188 }
1189 else if (buffer[1] == 'T')
1190 {
1191 /* STORED */
1192 c->currcmd.retstat= MCD_STORED;
1193 }
1194 else
1195 {
1196 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
1197 }
1198 break;
1199
1200 case 'D': /* DELETED DATA */
1201 if (buffer[1] == 'E')
1202 {
1203 c->currcmd.retstat= MCD_DELETED;
1204 }
1205 else
1206 {
1207 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
1208 }
1209
1210 break;
1211
1212 case 'N': /* NOT_FOUND NOT_STORED*/
1213 if (buffer[4] == 'F')
1214 {
1215 c->currcmd.retstat= MCD_NOTFOUND;
1216 }
1217 else if (buffer[4] == 'S')
1218 {
1219 printf("<%d %s\n", c->sfd, buffer);
1220 c->currcmd.retstat= MCD_NOTSTORED;
1221 }
1222 else
1223 {
1224 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
1225 }
1226 break;
1227
1228 case 'E': /* PROTOCOL ERROR or END */
1229 if (buffer[1] == 'N')
1230 {
1231 /* END */
1232 c->currcmd.retstat= MCD_END;
1233 }
1234 else if (buffer[1] == 'R')
1235 {
1236 printf("<%d ERROR\n", c->sfd);
1237 c->currcmd.retstat= MCD_PROTOCOL_ERROR;
1238 }
1239 else if (buffer[1] == 'X')
1240 {
1241 c->currcmd.retstat= MCD_DATA_EXISTS;
1242 printf("<%d %s\n", c->sfd, buffer);
1243 }
1244 else
1245 {
1246 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
1247 }
1248 break;
1249
1250 case 'C': /* CLIENT ERROR */
1251 printf("<%d %s\n", c->sfd, buffer);
1252 c->currcmd.retstat= MCD_CLIENT_ERROR;
1253 break;
1254
1255 default:
1256 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
1257 break;
1258 } /* switch */
1259
1260 return ret;
1261 } /* ms_ascii_process_line */
1262
1263
1264 /**
1265 * after one operation completes, reset the concurrency
1266 *
1267 * @param c, pointer of the concurrency
1268 * @param timeout, whether it's timeout
1269 */
1270 void ms_reset_conn(ms_conn_t *c, bool timeout)
1271 {
1272 assert(c != NULL);
1273
1274 if (c->udp)
1275 {
1276 if ((c->packets > 0) && (c->packets < MAX_UDP_PACKET))
1277 {
1278 memset(c->udppkt, 0, sizeof(ms_udppkt_t) * (size_t)c->packets);
1279 }
1280
1281 c->packets= 0;
1282 c->recvpkt= 0;
1283 c->pktcurr= 0;
1284 c->ordcurr= 0;
1285 c->rudpbytes= 0;
1286 }
1287 c->currcmd.isfinish= true;
1288 c->ctnwrite= false;
1289 c->rbytes= 0;
1290 c->rcurr= c->rbuf;
1291 c->msgcurr = 0;
1292 c->msgused = 0;
1293 c->iovused = 0;
1294 ms_conn_set_state(c, conn_write);
1295 memcpy(&c->precmd, &c->currcmd, sizeof(ms_cmdstat_t)); /* replicate command state */
1296
1297 if (timeout)
1298 {
1299 ms_drive_machine(c);
1300 }
1301 } /* ms_reset_conn */
1302
1303
1304 /**
1305 * if we have a complete line in the buffer, process it.
1306 *
1307 * @param c, pointer of the concurrency
1308 *
1309 * @return int, if success, return 0, else return -1
1310 */
1311 static int ms_try_read_line(ms_conn_t *c)
1312 {
1313 if (c->protocol == binary_prot)
1314 {
1315 /* Do we have the complete packet header? */
1316 if ((uint64_t)c->rbytes < sizeof(c->binary_header))
1317 {
1318 /* need more data! */
1319 return 0;
1320 }
1321 else
1322 {
1323 #ifdef NEED_ALIGN
1324 if (((long)(c->rcurr)) % 8 != 0)
1325 {
1326 /* must realign input buffer */
1327 memmove(c->rbuf, c->rcurr, c->rbytes);
1328 c->rcurr= c->rbuf;
1329 if (settings.verbose)
1330 {
1331 fprintf(stderr, "%d: Realign input buffer.\n", c->sfd);
1332 }
1333 }
1334 #endif
1335 protocol_binary_response_header *rsp;
1336 rsp= (protocol_binary_response_header *)c->rcurr;
1337
1338 c->binary_header= *rsp;
1339 c->binary_header.response.extlen= rsp->response.extlen;
1340 c->binary_header.response.keylen= ntohs(rsp->response.keylen);
1341 c->binary_header.response.bodylen= ntohl(rsp->response.bodylen);
1342 c->binary_header.response.status= ntohs(rsp->response.status);
1343
1344 if (c->binary_header.response.magic != PROTOCOL_BINARY_RES)
1345 {
1346 fprintf(stderr, "Invalid magic: %x\n",
1347 c->binary_header.response.magic);
1348 ms_conn_set_state(c, conn_closing);
1349 return 0;
1350 }
1351
1352 /* process this complete response */
1353 if (ms_bin_process_response(c) == 0)
1354 {
1355 /* current operation completed */
1356 ms_reset_conn(c, false);
1357 return -1;
1358 }
1359 else
1360 {
1361 c->rbytes-= (int32_t)sizeof(c->binary_header);
1362 c->rcurr+= sizeof(c->binary_header);
1363 }
1364 }
1365 }
1366 else
1367 {
1368 char *el, *cont;
1369
1370 assert(c != NULL);
1371 assert(c->rcurr <= (c->rbuf + c->rsize));
1372
1373 if (c->rbytes == 0)
1374 return 0;
1375
1376 el= memchr(c->rcurr, '\n', (size_t)c->rbytes);
1377 if (! el)
1378 return 0;
1379
1380 cont= el + 1;
1381 if (((el - c->rcurr) > 1) && (*(el - 1) == '\r'))
1382 {
1383 el--;
1384 }
1385 *el= '\0';
1386
1387 assert(cont <= (c->rcurr + c->rbytes));
1388
1389 /* process this complete line */
1390 if (ms_ascii_process_line(c, c->rcurr) == 0)
1391 {
1392 /* current operation completed */
1393 ms_reset_conn(c, false);
1394 return -1;
1395 }
1396 else
1397 {
1398 /* current operation didn't complete */
1399 c->rbytes-= (int32_t)(cont - c->rcurr);
1400 c->rcurr= cont;
1401 }
1402
1403 assert(c->rcurr <= (c->rbuf + c->rsize));
1404 }
1405
1406 return -1;
1407 } /* ms_try_read_line */
1408
1409
1410 /**
1411 * because the packet of UDP can't ensure the order, the
1412 * function is used to sort the received udp packet.
1413 *
1414 * @param c, pointer of the concurrency
1415 * @param buf, the buffer to store the ordered packages data
1416 * @param rbytes, the maximum capacity of the buffer
1417 *
1418 * @return int, if success, return the copy bytes, else return
1419 * -1
1420 */
1421 static int ms_sort_udp_packet(ms_conn_t *c, char *buf, int rbytes)
1422 {
1423 int len= 0;
1424 int wbytes= 0;
1425 uint16_t req_id= 0;
1426 uint16_t seq_num= 0;
1427 uint16_t packets= 0;
1428 unsigned char *header= NULL;
1429
1430 /* no enough data */
1431 assert(c != NULL);
1432 assert(buf != NULL);
1433 assert(c->rudpbytes >= UDP_HEADER_SIZE);
1434
1435 /* calculate received packets count */
1436 if (c->rudpbytes % UDP_MAX_PAYLOAD_SIZE >= UDP_HEADER_SIZE)
1437 {
1438 /* the last packet has some data */
1439 c->recvpkt= c->rudpbytes / UDP_MAX_PAYLOAD_SIZE + 1;
1440 }
1441 else
1442 {
1443 c->recvpkt= c->rudpbytes / UDP_MAX_PAYLOAD_SIZE;
1444 }
1445
1446 /* get the total packets count if necessary */
1447 if (c->packets == 0)
1448 {
1449 c->packets= HEADER_TO_PACKETS((unsigned char *)c->rudpbuf);
1450 }
1451
1452 /* build the ordered packet array */
1453 for (int i= c->pktcurr; i < c->recvpkt; i++)
1454 {
1455 header= (unsigned char *)c->rudpbuf + i * UDP_MAX_PAYLOAD_SIZE;
1456 req_id= (uint16_t)HEADER_TO_REQID(header);
1457 assert(req_id == c->request_id % (1 << 16));
1458
1459 packets= (uint16_t)HEADER_TO_PACKETS(header);
1460 assert(c->packets == HEADER_TO_PACKETS(header));
1461
1462 seq_num= (uint16_t)HEADER_TO_SEQNUM(header);
1463 c->udppkt[seq_num].header= header;
1464 c->udppkt[seq_num].data= (char *)header + UDP_HEADER_SIZE;
1465
1466 if (i == c->recvpkt - 1)
1467 {
1468 /* last received packet */
1469 if (c->rudpbytes % UDP_MAX_PAYLOAD_SIZE == 0)
1470 {
1471 c->udppkt[seq_num].rbytes= UDP_MAX_PAYLOAD_SIZE - UDP_HEADER_SIZE;
1472 c->pktcurr++;
1473 }
1474 else
1475 {
1476 c->udppkt[seq_num].rbytes= c->rudpbytes % UDP_MAX_PAYLOAD_SIZE
1477 - UDP_HEADER_SIZE;
1478 }
1479 }
1480 else
1481 {
1482 c->udppkt[seq_num].rbytes= UDP_MAX_PAYLOAD_SIZE - UDP_HEADER_SIZE;
1483 c->pktcurr++;
1484 }
1485 }
1486
1487 for (int i= c->ordcurr; i < c->recvpkt; i++)
1488 {
1489 /* there is some data to copy */
1490 if ((c->udppkt[i].data != NULL)
1491 && (c->udppkt[i].copybytes < c->udppkt[i].rbytes))
1492 {
1493 header= c->udppkt[i].header;
1494 len= c->udppkt[i].rbytes - c->udppkt[i].copybytes;
1495 if (len > rbytes - wbytes)
1496 {
1497 len= rbytes - wbytes;
1498 }
1499
1500 assert(len <= rbytes - wbytes);
1501 assert(i == HEADER_TO_SEQNUM(header));
1502
1503 memcpy(buf + wbytes, c->udppkt[i].data + c->udppkt[i].copybytes,
1504 (size_t)len);
1505 wbytes+= len;
1506 c->udppkt[i].copybytes+= len;
1507
1508 if ((c->udppkt[i].copybytes == c->udppkt[i].rbytes)
1509 && (c->udppkt[i].rbytes == UDP_MAX_PAYLOAD_SIZE - UDP_HEADER_SIZE))
1510 {
1511 /* finish copying all the data of this packet, next */
1512 c->ordcurr++;
1513 }
1514
1515 /* last received packet, and finish copying all the data */
1516 if ((c->recvpkt == c->packets) && (i == c->recvpkt - 1)
1517 && (c->udppkt[i].copybytes == c->udppkt[i].rbytes))
1518 {
1519 break;
1520 }
1521
1522 /* no space to copy data */
1523 if (wbytes >= rbytes)
1524 {
1525 break;
1526 }
1527
1528 /* it doesn't finish reading all the data of the packet from network */
1529 if ((i != c->recvpkt - 1)
1530 && (c->udppkt[i].rbytes < UDP_MAX_PAYLOAD_SIZE - UDP_HEADER_SIZE))
1531 {
1532 break;
1533 }
1534 }
1535 else
1536 {
1537 /* no data to copy */
1538 break;
1539 }
1540 }
1541
1542 return wbytes == 0 ? -1 : wbytes;
1543 } /* ms_sort_udp_packet */
1544
1545
1546 /**
1547 * encapsulate upd read like tcp read
1548 *
1549 * @param c, pointer of the concurrency
1550 * @param buf, read buffer
1551 * @param len, length to read
1552 *
1553 * @return int, if success, return the read bytes, else return
1554 * -1
1555 */
1556 static int ms_udp_read(ms_conn_t *c, char *buf, int len)
1557 {
1558 int res= 0;
1559 int avail= 0;
1560 int rbytes= 0;
1561 int copybytes= 0;
1562
1563 assert(c->udp);
1564
1565 while (1)
1566 {
1567 if (c->rudpbytes + UDP_MAX_PAYLOAD_SIZE > c->rudpsize)
1568 {
1569 char *new_rbuf= realloc(c->rudpbuf, (size_t)c->rudpsize * 2);
1570 if (! new_rbuf)
1571 {
1572 fprintf(stderr, "Couldn't realloc input buffer.\n");
1573 c->rudpbytes= 0; /* ignore what we read */
1574 return -1;
1575 }
1576 c->rudpbuf= new_rbuf;
1577 c->rudpsize*= 2;
1578 }
1579
1580 avail= c->rudpsize - c->rudpbytes;
1581 /* UDP each time read a packet, 1400 bytes */
1582 res= (int)read(c->sfd, c->rudpbuf + c->rudpbytes, (size_t)avail);
1583
1584 if (res > 0)
1585 {
1586 atomic_add_size(&ms_stats.bytes_read, res);
1587 c->rudpbytes+= res;
1588 rbytes+= res;
1589 if (res == avail)
1590 {
1591 continue;
1592 }
1593 else
1594 {
1595 break;
1596 }
1597 }
1598
1599 if (res == 0)
1600 {
1601 /* "connection" closed */
1602 return res;
1603 }
1604
1605 if (res == -1)
1606 {
1607 /* no data to read */
1608 return res;
1609 }
1610 }
1611
1612 /* copy data to read buffer */
1613 if (rbytes > 0)
1614 {
1615 copybytes= ms_sort_udp_packet(c, buf, len);
1616 }
1617
1618 if (copybytes == -1)
1619 {
1620 atomic_add_size(&ms_stats.pkt_disorder, 1);
1621 }
1622
1623 return copybytes;
1624 } /* ms_udp_read */
1625
1626
1627 /*
1628 * read from network as much as we can, handle buffer overflow and connection
1629 * close.
1630 * before reading, move the remaining incomplete fragment of a command
1631 * (if any) to the beginning of the buffer.
1632 * return 0 if there's nothing to read on the first read.
1633 */
1634
1635 /**
1636 * read from network as much as we can, handle buffer overflow and connection
1637 * close. before reading, move the remaining incomplete fragment of a command
1638 * (if any) to the beginning of the buffer.
1639 *
1640 * @param c, pointer of the concurrency
1641 *
1642 * @return int,
1643 * return 0 if there's nothing to read on the first read.
1644 * return 1 if get data
1645 * return -1 if error happens
1646 */
1647 static int ms_try_read_network(ms_conn_t *c)
1648 {
1649 int gotdata= 0;
1650 int res;
1651 int64_t avail;
1652
1653 assert(c != NULL);
1654
1655 if ((c->rcurr != c->rbuf)
1656 && (! c->readval || (c->rvbytes > c->rsize - (c->rcurr - c->rbuf))
1657 || (c->readval && (c->rcurr - c->rbuf > c->rbytes))))
1658 {
1659 if (c->rbytes != 0) /* otherwise there's nothing to copy */
1660 memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
1661 c->rcurr= c->rbuf;
1662 }
1663
1664 while (1)
1665 {
1666 if (c->rbytes >= c->rsize)
1667 {
1668 char *new_rbuf= realloc(c->rbuf, (size_t)c->rsize * 2);
1669 if (! new_rbuf)
1670 {
1671 fprintf(stderr, "Couldn't realloc input buffer.\n");
1672 c->rbytes= 0; /* ignore what we read */
1673 return -1;
1674 }
1675 c->rcurr= c->rbuf= new_rbuf;
1676 c->rsize*= 2;
1677 }
1678
1679 avail= c->rsize - c->rbytes - (c->rcurr - c->rbuf);
1680 if (avail == 0)
1681 {
1682 break;
1683 }
1684
1685 if (c->udp)
1686 {
1687 res= (int32_t)ms_udp_read(c, c->rcurr + c->rbytes, (int32_t)avail);
1688 }
1689 else
1690 {
1691 res= (int)read(c->sfd, c->rcurr + c->rbytes, (size_t)avail);
1692 }
1693
1694 if (res > 0)
1695 {
1696 if (! c->udp)
1697 {
1698 atomic_add_size(&ms_stats.bytes_read, res);
1699 }
1700 gotdata= 1;
1701 c->rbytes+= res;
1702 if (res == avail)
1703 {
1704 continue;
1705 }
1706 else
1707 {
1708 break;
1709 }
1710 }
1711 if (res == 0)
1712 {
1713 /* connection closed */
1714 ms_conn_set_state(c, conn_closing);
1715 return -1;
1716 }
1717 if (res == -1)
1718 {
1719 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
1720 break;
1721 /* Should close on unhandled errors. */
1722 ms_conn_set_state(c, conn_closing);
1723 return -1;
1724 }
1725 }
1726
1727 return gotdata;
1728 } /* ms_try_read_network */
1729
1730
1731 /**
1732 * after get the object from server, verify the value if
1733 * necessary.
1734 *
1735 * @param c, pointer of the concurrency
1736 * @param mlget_item, pointer of mulit-get task item structure
1737 * @param value, received value string
1738 * @param vlen, received value string length
1739 */
1740 static void ms_verify_value(ms_conn_t *c,
1741 ms_mlget_task_item_t *mlget_item,
1742 char *value,
1743 int vlen)
1744 {
1745 if (c->curr_task.verify)
1746 {
1747 assert(c->curr_task.item->value_offset != INVALID_OFFSET);
1748 char *orignval= &ms_setting.char_block[c->curr_task.item->value_offset];
1749 char *orignkey=
1750 &ms_setting.char_block[c->curr_task.item->key_suffix_offset];
1751
1752 /* verify expire time if necessary */
1753 if (c->curr_task.item->exp_time > 0)
1754 {
1755 struct timeval curr_time;
1756 gettimeofday(&curr_time, NULL);
1757
1758 /* object expired but get it now */
1759 if (curr_time.tv_sec - c->curr_task.item->client_time
1760 > c->curr_task.item->exp_time + EXPIRE_TIME_ERROR)
1761 {
1762 atomic_add_size(&ms_stats.exp_get, 1);
1763
1764 if (ms_setting.verbose)
1765 {
1766 char set_time[64];
1767 char cur_time[64];
1768 strftime(set_time, 64, "%Y-%m-%d %H:%M:%S",
1769 localtime(&c->curr_task.item->client_time));
1770 strftime(cur_time, 64, "%Y-%m-%d %H:%M:%S",
1771 localtime(&curr_time.tv_sec));
1772 fprintf(stderr,
1773 "\n<%d expire time verification failed, "
1774 "object expired but get it now\n"
1775 "\tkey len: %d\n"
1776 "\tkey: %" PRIx64 " %.*s\n"
1777 "\tset time: %s current time: %s "
1778 "diff time: %d expire time: %d\n"
1779 "\texpected data: \n"
1780 "\treceived data len: %d\n"
1781 "\treceived data: %.*s\n",
1782 c->sfd,
1783 c->curr_task.item->key_size,
1784 c->curr_task.item->key_prefix,
1785 c->curr_task.item->key_size - (int)KEY_PREFIX_SIZE,
1786 orignkey,
1787 set_time,
1788 cur_time,
1789 (int)(curr_time.tv_sec - c->curr_task.item->client_time),
1790 c->curr_task.item->exp_time,
1791 vlen,
1792 vlen,
1793 value);
1794 fflush(stderr);
1795 }
1796 }
1797 }
1798 else
1799 {
1800 if ((c->curr_task.item->value_size != vlen)
1801 || (memcmp(orignval, value, (size_t)vlen) != 0))
1802 {
1803 atomic_add_size(&ms_stats.vef_failed, 1);
1804
1805 if (ms_setting.verbose)
1806 {
1807 fprintf(stderr,
1808 "\n<%d data verification failed\n"
1809 "\tkey len: %d\n"
1810 "\tkey: %" PRIx64" %.*s\n"
1811 "\texpected data len: %d\n"
1812 "\texpected data: %.*s\n"
1813 "\treceived data len: %d\n"
1814 "\treceived data: %.*s\n",
1815 c->sfd,
1816 c->curr_task.item->key_size,
1817 c->curr_task.item->key_prefix,
1818 c->curr_task.item->key_size - (int)KEY_PREFIX_SIZE,
1819 orignkey,
1820 c->curr_task.item->value_size,
1821 c->curr_task.item->value_size,
1822 orignval,
1823 vlen,
1824 vlen,
1825 value);
1826 fflush(stderr);
1827 }
1828 }
1829 }
1830
1831 c->curr_task.finish_verify= true;
1832
1833 if (mlget_item != NULL)
1834 {
1835 mlget_item->finish_verify= true;
1836 }
1837 }
1838 } /* ms_verify_value */
1839
1840
1841 /**
1842 * For ASCII protocol, after store the data into the local
1843 * buffer, run this function to handle the data.
1844 *
1845 * @param c, pointer of the concurrency
1846 */
1847 static void ms_ascii_complete_nread(ms_conn_t *c)
1848 {
1849 assert(c != NULL);
1850 assert(c->rbytes >= c->rvbytes);
1851 assert(c->protocol == ascii_prot);
1852 if (c->rvbytes > 2)
1853 {
1854 assert(
1855 c->rcurr[c->rvbytes - 1] == '\n' && c->rcurr[c->rvbytes - 2] == '\r');
1856 }
1857
1858 /* multi-get */
1859 ms_mlget_task_item_t *mlget_item= NULL;
1860 if (((ms_setting.mult_key_num > 1)
1861 && (c->mlget_task.mlget_num >= ms_setting.mult_key_num))
1862 || ((c->remain_exec_num == 0) && (c->mlget_task.mlget_num > 0)))
1863 {
1864 c->mlget_task.value_index++;
1865 mlget_item= &c->mlget_task.mlget_item[c->mlget_task.value_index];
1866
1867 if (mlget_item->item->key_prefix == c->currcmd.key_prefix)
1868 {
1869 c->curr_task.item= mlget_item->item;
1870 c->curr_task.verify= mlget_item->verify;
1871 c->curr_task.finish_verify= mlget_item->finish_verify;
1872 mlget_item->get_miss= false;
1873 }
1874 else
1875 {
1876 /* Try to find the task item in multi-get task array */
1877 for (int i= 0; i < c->mlget_task.mlget_num; i++)
1878 {
1879 mlget_item= &c->mlget_task.mlget_item[i];
1880 if (mlget_item->item->key_prefix == c->currcmd.key_prefix)
1881 {
1882 c->curr_task.item= mlget_item->item;
1883 c->curr_task.verify= mlget_item->verify;
1884 c->curr_task.finish_verify= mlget_item->finish_verify;
1885 mlget_item->get_miss= false;
1886
1887 break;
1888 }
1889 }
1890 }
1891 }
1892
1893 ms_verify_value(c, mlget_item, c->rcurr, c->rvbytes - 2);
1894
1895 c->curr_task.get_miss= false;
1896 c->rbytes-= c->rvbytes;
1897 c->rcurr= c->rcurr + c->rvbytes;
1898 assert(c->rcurr <= (c->rbuf + c->rsize));
1899 c->readval= false;
1900 c->rvbytes= 0;
1901 } /* ms_ascii_complete_nread */
1902
1903
1904 /**
1905 * For binary protocol, after store the data into the local
1906 * buffer, run this function to handle the data.
1907 *
1908 * @param c, pointer of the concurrency
1909 */
1910 static void ms_bin_complete_nread(ms_conn_t *c)
1911 {
1912 assert(c != NULL);
1913 assert(c->rbytes >= c->rvbytes);
1914 assert(c->protocol == binary_prot);
1915
1916 int extlen= c->binary_header.response.extlen;
1917 int keylen= c->binary_header.response.keylen;
1918 uint8_t opcode= c->binary_header.response.opcode;
1919
1920 /* not get command or not include value, just return */
1921 if (((opcode != PROTOCOL_BINARY_CMD_GET)
1922 && (opcode != PROTOCOL_BINARY_CMD_GETQ))
1923 || (c->rvbytes <= extlen + keylen))
1924 {
1925 /* get miss */
1926 if (c->binary_header.response.opcode == PROTOCOL_BINARY_CMD_GET)
1927 {
1928 c->currcmd.retstat= MCD_END;
1929 c->curr_task.get_miss= true;
1930 }
1931
1932 c->readval= false;
1933 c->rvbytes= 0;
1934 ms_reset_conn(c, false);
1935 return;
1936 }
1937
1938 /* multi-get */
1939 ms_mlget_task_item_t *mlget_item= NULL;
1940 if (((ms_setting.mult_key_num > 1)
1941 && (c->mlget_task.mlget_num >= ms_setting.mult_key_num))
1942 || ((c->remain_exec_num == 0) && (c->mlget_task.mlget_num > 0)))
1943 {
1944 c->mlget_task.value_index++;
1945 mlget_item= &c->mlget_task.mlget_item[c->mlget_task.value_index];
1946
1947 c->curr_task.item= mlget_item->item;
1948 c->curr_task.verify= mlget_item->verify;
1949 c->curr_task.finish_verify= mlget_item->finish_verify;
1950 mlget_item->get_miss= false;
1951 }
1952
1953 ms_verify_value(c,
1954 mlget_item,
1955 c->rcurr + extlen + keylen,
1956 c->rvbytes - extlen - keylen);
1957
1958 c->currcmd.retstat= MCD_END;
1959 c->curr_task.get_miss= false;
1960 c->rbytes-= c->rvbytes;
1961 c->rcurr= c->rcurr + c->rvbytes;
1962 assert(c->rcurr <= (c->rbuf + c->rsize));
1963 c->readval= false;
1964 c->rvbytes= 0;
1965
1966 if (ms_setting.mult_key_num > 1)
1967 {
1968 /* multi-get have check all the item */
1969 if (c->mlget_task.value_index == c->mlget_task.mlget_num - 1)
1970 {
1971 ms_reset_conn(c, false);
1972 }
1973 }
1974 else
1975 {
1976 /* single get */
1977 ms_reset_conn(c, false);
1978 }
1979 } /* ms_bin_complete_nread */
1980
1981
1982 /**
1983 * we get here after reading the value of get commands.
1984 *
1985 * @param c, pointer of the concurrency
1986 */
1987 static void ms_complete_nread(ms_conn_t *c)
1988 {
1989 assert(c != NULL);
1990 assert(c->rbytes >= c->rvbytes);
1991 assert(c->protocol == ascii_prot
1992 || c->protocol == binary_prot);
1993
1994 if (c->protocol == binary_prot)
1995 {
1996 ms_bin_complete_nread(c);
1997 }
1998 else
1999 {
2000 ms_ascii_complete_nread(c);
2001 }
2002 } /* ms_complete_nread */
2003
2004
2005 /**
2006 * Adds a message header to a connection.
2007 *
2008 * @param c, pointer of the concurrency
2009 *
2010 * @return int, if success, return 0, else return -1
2011 */
2012 static int ms_add_msghdr(ms_conn_t *c)
2013 {
2014 struct msghdr *msg;
2015
2016 assert(c != NULL);
2017
2018 if (c->msgsize == c->msgused)
2019 {
2020 msg=
2021 realloc(c->msglist, (size_t)c->msgsize * 2 * sizeof(struct msghdr));
2022 if (! msg)
2023 return -1;
2024
2025 c->msglist= msg;
2026 c->msgsize*= 2;
2027 }
2028
2029 msg= c->msglist + c->msgused;
2030
2031 /**
2032 * this wipes msg_iovlen, msg_control, msg_controllen, and
2033 * msg_flags, the last 3 of which aren't defined on solaris:
2034 */
2035 memset(msg, 0, sizeof(struct msghdr));
2036
2037 msg->msg_iov= &c->iov[c->iovused];
2038
2039 if (c->udp && (c->srv_recv_addr_size > 0))
2040 {
2041 msg->msg_name= &c->srv_recv_addr;
2042 msg->msg_namelen= c->srv_recv_addr_size;
2043 }
2044
2045 c->msgbytes= 0;
2046 c->msgused++;
2047
2048 if (c->udp)
2049 {
2050 /* Leave room for the UDP header, which we'll fill in later. */
2051 return ms_add_iov(c, NULL, UDP_HEADER_SIZE);
2052 }
2053
2054 return 0;
2055 } /* ms_add_msghdr */
2056
2057
2058 /**
2059 * Ensures that there is room for another structure iovec in a connection's
2060 * iov list.
2061 *
2062 * @param c, pointer of the concurrency
2063 *
2064 * @return int, if success, return 0, else return -1
2065 */
2066 static int ms_ensure_iov_space(ms_conn_t *c)
2067 {
2068 assert(c != NULL);
2069
2070 if (c->iovused >= c->iovsize)
2071 {
2072 int i, iovnum;
2073 struct iovec *new_iov= (struct iovec *)realloc(c->iov,
2074 ((size_t)c->iovsize
2075 * 2)
2076 * sizeof(struct iovec));
2077 if (! new_iov)
2078 return -1;
2079
2080 c->iov= new_iov;
2081 c->iovsize*= 2;
2082
2083 /* Point all the msghdr structures at the new list. */
2084 for (i= 0, iovnum= 0; i < c->msgused; i++)
2085 {
2086 c->msglist[i].msg_iov= &c->iov[iovnum];
2087 iovnum+= (int)c->msglist[i].msg_iovlen;
2088 }
2089 }
2090
2091 return 0;
2092 } /* ms_ensure_iov_space */
2093
2094
2095 /**
2096 * Adds data to the list of pending data that will be written out to a
2097 * connection.
2098 *
2099 * @param c, pointer of the concurrency
2100 * @param buf, the buffer includes data to send
2101 * @param len, the data length in the buffer
2102 *
2103 * @return int, if success, return 0, else return -1
2104 */
2105 static int ms_add_iov(ms_conn_t *c, const void *buf, int len)
2106 {
2107 struct msghdr *m;
2108 int leftover;
2109 bool limit_to_mtu;
2110
2111 assert(c != NULL);
2112
2113 do
2114 {
2115 m= &c->msglist[c->msgused - 1];
2116
2117 /*
2118 * Limit UDP packets, to UDP_MAX_PAYLOAD_SIZE bytes.
2119 */
2120 limit_to_mtu= c->udp;
2121
2122 /* We may need to start a new msghdr if this one is full. */
2123 if ((m->msg_iovlen == IOV_MAX)
2124 || (limit_to_mtu && (c->msgbytes >= UDP_MAX_SEND_PAYLOAD_SIZE)))
2125 {
2126 ms_add_msghdr(c);
2127 m= &c->msglist[c->msgused - 1];
2128 }
2129
2130 if (ms_ensure_iov_space(c) != 0)
2131 return -1;
2132
2133 /* If the fragment is too big to fit in the datagram, split it up */
2134 if (limit_to_mtu && (len + c->msgbytes > UDP_MAX_SEND_PAYLOAD_SIZE))
2135 {
2136 leftover= len + c->msgbytes - UDP_MAX_SEND_PAYLOAD_SIZE;
2137 len-= leftover;
2138 }
2139 else
2140 {
2141 leftover= 0;
2142 }
2143
2144 m= &c->msglist[c->msgused - 1];
2145 m->msg_iov[m->msg_iovlen].iov_base= (void *)buf;
2146 m->msg_iov[m->msg_iovlen].iov_len= (size_t)len;
2147
2148 c->msgbytes+= len;
2149 c->iovused++;
2150 m->msg_iovlen++;
2151
2152 buf= ((char *)buf) + len;
2153 len= leftover;
2154 }
2155 while (leftover > 0);
2156
2157 return 0;
2158 } /* ms_add_iov */
2159
2160
2161 /**
2162 * Constructs a set of UDP headers and attaches them to the outgoing messages.
2163 *
2164 * @param c, pointer of the concurrency
2165 *
2166 * @return int, if success, return 0, else return -1
2167 */
2168 static int ms_build_udp_headers(ms_conn_t *c)
2169 {
2170 int i;
2171 unsigned char *hdr;
2172
2173 assert(c != NULL);
2174
2175 c->request_id= ms_get_udp_request_id();
2176
2177 if (c->msgused > c->hdrsize)
2178 {
2179 void *new_hdrbuf;
2180 if (c->hdrbuf)
2181 new_hdrbuf= realloc(c->hdrbuf,
2182 (size_t)c->msgused * 2 * UDP_HEADER_SIZE);
2183 else
2184 new_hdrbuf= malloc((size_t)c->msgused * 2 * UDP_HEADER_SIZE);
2185 if (! new_hdrbuf)
2186 return -1;
2187
2188 c->hdrbuf= (unsigned char *)new_hdrbuf;
2189 c->hdrsize= c->msgused * 2;
2190 }
2191
2192 /* If this is a multi-packet request, drop it. */
2193 if (c->udp && (c->msgused > 1))
2194 {
2195 fprintf(stderr, "multi-packet request for UDP not supported.\n");
2196 return -1;
2197 }
2198
2199 hdr= c->hdrbuf;
2200 for (i= 0; i < c->msgused; i++)
2201 {
2202 c->msglist[i].msg_iov[0].iov_base= (void *)hdr;
2203 c->msglist[i].msg_iov[0].iov_len= UDP_HEADER_SIZE;
2204 *hdr++= (unsigned char)(c->request_id / 256);
2205 *hdr++= (unsigned char)(c->request_id % 256);
2206 *hdr++= (unsigned char)(i / 256);
2207 *hdr++= (unsigned char)(i % 256);
2208 *hdr++= (unsigned char)(c->msgused / 256);
2209 *hdr++= (unsigned char)(c->msgused % 256);
2210 *hdr++= (unsigned char)1; /* support facebook memcached */
2211 *hdr++= (unsigned char)0;
2212 assert(hdr ==
2213 ((unsigned char *)c->msglist[i].msg_iov[0].iov_base
2214 + UDP_HEADER_SIZE));
2215 }
2216
2217 return 0;
2218 } /* ms_build_udp_headers */
2219
2220
2221 /**
2222 * Transmit the next chunk of data from our list of msgbuf structures.
2223 *
2224 * @param c, pointer of the concurrency
2225 *
2226 * @return TRANSMIT_COMPLETE All done writing.
2227 * TRANSMIT_INCOMPLETE More data remaining to write.
2228 * TRANSMIT_SOFT_ERROR Can't write any more right now.
2229 * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing)
2230 */
2231 static int ms_transmit(ms_conn_t *c)
2232 {
2233 assert(c != NULL);
2234
2235 if ((c->msgcurr < c->msgused)
2236 && (c->msglist[c->msgcurr].msg_iovlen == 0))
2237 {
2238 /* Finished writing the current msg; advance to the next. */
2239 c->msgcurr++;
2240 }
2241
2242 if (c->msgcurr < c->msgused)
2243 {
2244 ssize_t res;
2245 struct msghdr *m= &c->msglist[c->msgcurr];
2246
2247 res= sendmsg(c->sfd, m, 0);
2248 if (res > 0)
2249 {
2250 atomic_add_size(&ms_stats.bytes_written, res);
2251
2252 /* We've written some of the data. Remove the completed
2253 * iovec entries from the list of pending writes. */
2254 while (m->msg_iovlen > 0 && res >= (ssize_t)m->msg_iov->iov_len)
2255 {
2256 res-= (ssize_t)m->msg_iov->iov_len;
2257 m->msg_iovlen--;
2258 m->msg_iov++;
2259 }
2260
2261 /* Might have written just part of the last iovec entry;
2262 * adjust it so the next write will do the rest. */
2263 if (res > 0)
2264 {
2265 m->msg_iov->iov_base= (void *)((unsigned char *)m->msg_iov->iov_base + res);
2266 m->msg_iov->iov_len-= (size_t)res;
2267 }
2268 return TRANSMIT_INCOMPLETE;
2269 }
2270 if ((res == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
2271 {
2272 if (! ms_update_event(c, EV_WRITE | EV_PERSIST))
2273 {
2274 fprintf(stderr, "Couldn't update event.\n");
2275 ms_conn_set_state(c, conn_closing);
2276 return TRANSMIT_HARD_ERROR;
2277 }
2278 return TRANSMIT_SOFT_ERROR;
2279 }
2280
2281 /* if res==0 or res==-1 and error is not EAGAIN or EWOULDBLOCK,
2282 * we have a real error, on which we close the connection */
2283 fprintf(stderr, "Failed to write, and not due to blocking.\n");
2284
2285 ms_conn_set_state(c, conn_closing);
2286 return TRANSMIT_HARD_ERROR;
2287 }
2288 else
2289 {
2290 return TRANSMIT_COMPLETE;
2291 }
2292 } /* ms_transmit */
2293
2294
2295 /**
2296 * Shrinks a connection's buffers if they're too big. This prevents
2297 * periodic large "mget" response from server chewing lots of client
2298 * memory.
2299 *
2300 * This should only be called in between requests since it can wipe output
2301 * buffers!
2302 *
2303 * @param c, pointer of the concurrency
2304 */
2305 static void ms_conn_shrink(ms_conn_t *c)
2306 {
2307 assert(c != NULL);
2308
2309 if (c->udp)
2310 return;
2311
2312 if ((c->rsize > READ_BUFFER_HIGHWAT) && (c->rbytes < DATA_BUFFER_SIZE))
2313 {
2314 char *newbuf;
2315
2316 if (c->rcurr != c->rbuf)
2317 memmove(c->rbuf, c->rcurr, (size_t)c->rbytes);
2318
2319 newbuf= (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE);
2320
2321 if (newbuf)
2322 {
2323 c->rbuf= newbuf;
2324 c->rsize= DATA_BUFFER_SIZE;
2325 }
2326 c->rcurr= c->rbuf;
2327 }
2328
2329 if (c->udp && (c->rudpsize > UDP_DATA_BUFFER_HIGHWAT)
2330 && (c->rudpbytes + UDP_MAX_PAYLOAD_SIZE < UDP_DATA_BUFFER_SIZE))
2331 {
2332 char *new_rbuf= (char *)realloc(c->rudpbuf, (size_t)c->rudpsize * 2);
2333 if (! new_rbuf)
2334 {
2335 c->rudpbuf= new_rbuf;
2336 c->rudpsize= UDP_DATA_BUFFER_SIZE;
2337 }
2338 /* TODO check error condition? */
2339 }
2340
2341 if (c->msgsize > MSG_LIST_HIGHWAT)
2342 {
2343 struct msghdr *newbuf= (struct msghdr *)realloc(
2344 (void *)c->msglist,
2345 MSG_LIST_INITIAL
2346 * sizeof(c->msglist[0]));
2347 if (newbuf)
2348 {
2349 c->msglist= newbuf;
2350 c->msgsize= MSG_LIST_INITIAL;
2351 }
2352 /* TODO check error condition? */
2353 }
2354
2355 if (c->iovsize > IOV_LIST_HIGHWAT)
2356 {
2357 struct iovec *newbuf= (struct iovec *)realloc((void *)c->iov,
2358 IOV_LIST_INITIAL
2359 * sizeof(c->iov[0]));
2360 if (newbuf)
2361 {
2362 c->iov= newbuf;
2363 c->iovsize= IOV_LIST_INITIAL;
2364 }
2365 /* TODO check return value */
2366 }
2367 } /* ms_conn_shrink */
2368
2369
2370 /**
2371 * Sets a connection's current state in the state machine. Any special
2372 * processing that needs to happen on certain state transitions can
2373 * happen here.
2374 *
2375 * @param c, pointer of the concurrency
2376 * @param state, connection state
2377 */
2378 static void ms_conn_set_state(ms_conn_t *c, int state)
2379 {
2380 assert(c != NULL);
2381
2382 if (state != c->state)
2383 {
2384 if (state == conn_read)
2385 {
2386 ms_conn_shrink(c);
2387 }
2388 c->state= state;
2389 }
2390 } /* ms_conn_set_state */
2391
2392
2393 /**
2394 * update the event if socks change state. for example: when
2395 * change the listen scoket read event to sock write event, or
2396 * change socket handler, we could call this function.
2397 *
2398 * @param c, pointer of the concurrency
2399 * @param new_flags, new event flags
2400 *
2401 * @return bool, if success, return true, else return false
2402 */
2403 static bool ms_update_event(ms_conn_t *c, const int new_flags)
2404 {
2405 assert(c != NULL);
2406
2407 struct event_base *base= c->event.ev_base;
2408 if ((c->ev_flags == new_flags) && (ms_setting.rep_write_srv == 0)
2409 && (! ms_setting.facebook_test || (c->total_sfds == 1)))
2410 {
2411 return true;
2412 }
2413
2414 if (event_del(&c->event) == -1)
2415 {
2416 /* try to delete the event again */
2417 if (event_del(&c->event) == -1)
2418 {
2419 return false;
2420 }
2421 }
2422
2423 event_set(&c->event,
2424 c->sfd,
2425 (short)new_flags,
2426 ms_event_handler,
2427 (void *)c);
2428 event_base_set(base, &c->event);
2429 c->ev_flags= (short)new_flags;
2430
2431 if (event_add(&c->event, NULL) == -1)
2432 {
2433 return false;
2434 }
2435
2436 return true;
2437 } /* ms_update_event */
2438
2439
2440 /**
2441 * If user want to get the expected throughput, we could limit
2442 * the performance of memslap. we could give up some work and
2443 * just wait a short time. The function is used to check this
2444 * case.
2445 *
2446 * @param c, pointer of the concurrency
2447 *
2448 * @return bool, if success, return true, else return false
2449 */
2450 static bool ms_need_yield(ms_conn_t *c)
2451 {
2452 ms_thread_t *ms_thread= pthread_getspecific(ms_thread_key);
2453 int64_t tps= 0;
2454 int64_t time_diff= 0;
2455 struct timeval curr_time;
2456 ms_task_t *task= &c->curr_task;
2457
2458 if (ms_setting.expected_tps > 0)
2459 {
2460 gettimeofday(&curr_time, NULL);
2461 time_diff= ms_time_diff(&ms_thread->startup_time, &curr_time);
2462 tps=
2463 (int64_t)((task->get_opt
2464 + task->set_opt) / ((uint64_t)time_diff / 1000000));
2465
2466 /* current throughput is greater than expected throughput */
2467 if (tps > ms_thread->thread_ctx->tps_perconn)
2468 {
2469 return true;
2470 }
2471 }
2472
2473 return false;
2474 } /* ms_need_yield */
2475
2476
2477 /**
2478 * used to update the start time of each operation
2479 *
2480 * @param c, pointer of the concurrency
2481 */
2482 static void ms_update_start_time(ms_conn_t *c)
2483 {
2484 ms_task_item_t *item= c->curr_task.item;
2485
2486 if ((ms_setting.stat_freq > 0) || c->udp
2487 || ((c->currcmd.cmd == CMD_SET) && (item->exp_time > 0)))
2488 {
2489 gettimeofday(&c->start_time, NULL);
2490 if ((c->currcmd.cmd == CMD_SET) && (item->exp_time > 0))
2491 {
2492 /* record the current time */
2493 item->client_time= c->start_time.tv_sec;
2494 }
2495 }
2496 } /* ms_update_start_time */
2497
2498
2499 /**
2500 * run the state machine
2501 *
2502 * @param c, pointer of the concurrency
2503 */
2504 static void ms_drive_machine(ms_conn_t *c)
2505 {
2506 bool stop= false;
2507
2508 assert(c != NULL);
2509
2510 while (! stop)
2511 {
2512 switch (c->state)
2513 {
2514 case conn_read:
2515 if (c->readval)
2516 {
2517 if (c->rbytes >= c->rvbytes)
2518 {
2519 ms_complete_nread(c);
2520 break;
2521 }
2522 }
2523 else
2524 {
2525 if (ms_try_read_line(c) != 0)
2526 {
2527 break;
2528 }
2529 }
2530
2531 if (ms_try_read_network(c) != 0)
2532 {
2533 break;
2534 }
2535
2536 /* doesn't read all the response data, wait event wake up */
2537 if (! c->currcmd.isfinish)
2538 {
2539 if (! ms_update_event(c, EV_READ | EV_PERSIST))
2540 {
2541 fprintf(stderr, "Couldn't update event.\n");
2542 ms_conn_set_state(c, conn_closing);
2543 break;
2544 }
2545 stop= true;
2546 break;
2547 }
2548
2549 /* we have no command line and no data to read from network, next write */
2550 ms_conn_set_state(c, conn_write);
2551 memcpy(&c->precmd, &c->currcmd, sizeof(ms_cmdstat_t)); /* replicate command state */
2552
2553 break;
2554
2555 case conn_write:
2556 if (! c->ctnwrite && ms_need_yield(c))
2557 {
2558 usleep(10);
2559
2560 if (! ms_update_event(c, EV_WRITE | EV_PERSIST))
2561 {
2562 fprintf(stderr, "Couldn't update event.\n");
2563 ms_conn_set_state(c, conn_closing);
2564 break;
2565 }
2566 stop= true;
2567 break;
2568 }
2569
2570 if (! c->ctnwrite && (ms_exec_task(c) != 0))
2571 {
2572 ms_conn_set_state(c, conn_closing);
2573 break;
2574 }
2575
2576 /* record the start time before starting to send data if necessary */
2577 if (! c->ctnwrite || (c->change_sfd && c->ctnwrite))
2578 {
2579 if (c->change_sfd)
2580 {
2581 c->change_sfd= false;
2582 }
2583 ms_update_start_time(c);
2584 }
2585
2586 /* change sfd if necessary */
2587 if (c->change_sfd)
2588 {
2589 c->ctnwrite= true;
2590 stop= true;
2591 break;
2592 }
2593
2594 /* execute task until nothing need be written to network */
2595 if (! c->ctnwrite && (c->msgcurr == c->msgused))
2596 {
2597 if (! ms_update_event(c, EV_WRITE | EV_PERSIST))
2598 {
2599 fprintf(stderr, "Couldn't update event.\n");
2600 ms_conn_set_state(c, conn_closing);
2601 break;
2602 }
2603 stop= true;
2604 break;
2605 }
2606
2607 switch (ms_transmit(c))
2608 {
2609 case TRANSMIT_COMPLETE:
2610 /* we have no data to write to network, next wait repose */
2611 if (! ms_update_event(c, EV_READ | EV_PERSIST))
2612 {
2613 fprintf(stderr, "Couldn't update event.\n");
2614 ms_conn_set_state(c, conn_closing);
2615 c->ctnwrite= false;
2616 break;
2617 }
2618 ms_conn_set_state(c, conn_read);
2619 c->ctnwrite= false;
2620 stop= true;
2621 break;
2622
2623 case TRANSMIT_INCOMPLETE:
2624 c->ctnwrite= true;
2625 break; /* Continue in state machine. */
2626
2627 case TRANSMIT_HARD_ERROR:
2628 c->ctnwrite= false;
2629 break;
2630
2631 case TRANSMIT_SOFT_ERROR:
2632 c->ctnwrite= true;
2633 stop= true;
2634 break;
2635
2636 default:
2637 break;
2638 } /* switch */
2639
2640 break;
2641
2642 case conn_closing:
2643 /* recovery mode, need reconnect if connection close */
2644 if (ms_setting.reconnect && (! ms_global.time_out
2645 || ((ms_setting.run_time == 0)
2646 && (c->remain_exec_num > 0))))
2647 {
2648 if (ms_reconn(c) != 0)
2649 {
2650 ms_conn_close(c);
2651 stop= true;
2652 break;
2653 }
2654
2655 ms_reset_conn(c, false);
2656
2657 if (c->total_sfds == 1)
2658 {
2659 if (! ms_update_event(c, EV_WRITE | EV_PERSIST))
2660 {
2661 fprintf(stderr, "Couldn't update event.\n");
2662 ms_conn_set_state(c, conn_closing);
2663 break;
2664 }
2665 }
2666
2667 break;
2668 }
2669 else
2670 {
2671 ms_conn_close(c);
2672 stop= true;
2673 break;
2674 }
2675
2676 default:
2677 assert(0);
2678 } /* switch */
2679 }
2680 } /* ms_drive_machine */
2681
2682
2683 /**
2684 * the event handler of each thread
2685 *
2686 * @param fd, the file descriptor of socket
2687 * @param which, event flag
2688 * @param arg, argument
2689 */
2690 void ms_event_handler(const int fd, const short which, void *arg)
2691 {
2692 ms_conn_t *c= (ms_conn_t *)arg;
2693
2694 assert(c != NULL);
2695
2696 c->which= which;
2697
2698 /* sanity */
2699 if (fd != c->sfd)
2700 {
2701 fprintf(stderr,
2702 "Catastrophic: event fd: %d doesn't match conn fd: %d\n",
2703 fd,
2704 c->sfd);
2705 ms_conn_close(c);
2706 exit(1);
2707 }
2708 assert(fd == c->sfd);
2709
2710 ms_drive_machine(c);
2711
2712 /* wait for next event */
2713 } /* ms_event_handler */
2714
2715
2716 /**
2717 * get the next socket descriptor index to run for replication
2718 *
2719 * @param c, pointer of the concurrency
2720 * @param cmd, command(get or set )
2721 *
2722 * @return int, if success, return the index, else return 0
2723 */
2724 static int ms_get_rep_sock_index(ms_conn_t *c, int cmd)
2725 {
2726 int sock_index= -1;
2727 int i= 0;
2728
2729 if (c->total_sfds == 1)
2730 {
2731 return 0;
2732 }
2733
2734 if (ms_setting.rep_write_srv == 0)
2735 {
2736 return sock_index;
2737 }
2738
2739 do
2740 {
2741 if (cmd == CMD_SET)
2742 {
2743 for (i= 0; i < ms_setting.rep_write_srv; i++)
2744 {
2745 if (c->tcpsfd[i] > 0)
2746 {
2747 break;
2748 }
2749 }
2750
2751 if (i == ms_setting.rep_write_srv)
2752 {
2753 /* random get one replication server to read */
2754 sock_index= (int)(random() % c->total_sfds);
2755 }
2756 else
2757 {
2758 /* random get one replication writing server to write */
2759 sock_index= (int)(random() % ms_setting.rep_write_srv);
2760 }
2761 }
2762 else if (cmd == CMD_GET)
2763 {
2764 /* random get one replication server to read */
2765 sock_index= (int)(random() % c->total_sfds);
2766 }
2767 }
2768 while (c->tcpsfd[sock_index] == 0);
2769
2770 return sock_index;
2771 } /* ms_get_rep_sock_index */
2772
2773
2774 /**
2775 * get the next socket descriptor index to run
2776 *
2777 * @param c, pointer of the concurrency
2778 *
2779 * @return int, return the index
2780 */
2781 static int ms_get_next_sock_index(ms_conn_t *c)
2782 {
2783 int sock_index= 0;
2784
2785 do
2786 {
2787 sock_index= (++c->cur_idx == c->total_sfds) ? 0 : c->cur_idx;
2788 }
2789 while (c->tcpsfd[sock_index] == 0);
2790
2791 return sock_index;
2792 } /* ms_get_next_sock_index */
2793
2794
2795 /**
2796 * update socket event of the connections
2797 *
2798 * @param c, pointer of the concurrency
2799 *
2800 * @return int, if success, return 0, else return -1
2801 */
2802 static int ms_update_conn_sock_event(ms_conn_t *c)
2803 {
2804 assert(c != NULL);
2805
2806 switch (c->currcmd.cmd)
2807 {
2808 case CMD_SET:
2809 if (ms_setting.facebook_test && c->udp)
2810 {
2811 c->sfd= c->tcpsfd[0];
2812 c->udp= false;
2813 c->change_sfd= true;
2814 }
2815 break;
2816
2817 case CMD_GET:
2818 if (ms_setting.facebook_test && ! c->udp)
2819 {
2820 c->sfd= c->udpsfd;
2821 c->udp= true;
2822 c->change_sfd= true;
2823 }
2824 break;
2825
2826 default:
2827 break;
2828 } /* switch */
2829
2830 if (! c->udp && (c->total_sfds > 1))
2831 {
2832 if (c->cur_idx != c->total_sfds)
2833 {
2834 if (ms_setting.rep_write_srv == 0)
2835 {
2836 c->cur_idx= ms_get_next_sock_index(c);
2837 }
2838 else
2839 {
2840 c->cur_idx= ms_get_rep_sock_index(c, c->currcmd.cmd);
2841 }
2842 }
2843 else
2844 {
2845 /* must select the first sock of the connection at the beginning */
2846 c->cur_idx= 0;
2847 }
2848
2849 c->sfd= c->tcpsfd[c->cur_idx];
2850 assert(c->sfd != 0);
2851 c->change_sfd= true;
2852 }
2853
2854 if (c->change_sfd)
2855 {
2856 if (! ms_update_event(c, EV_WRITE | EV_PERSIST))
2857 {
2858 fprintf(stderr, "Couldn't update event.\n");
2859 ms_conn_set_state(c, conn_closing);
2860 return -1;
2861 }
2862 }
2863
2864 return 0;
2865 } /* ms_update_conn_sock_event */
2866
2867
2868 /**
2869 * for ASCII protocol, this function build the set command
2870 * string and send the command.
2871 *
2872 * @param c, pointer of the concurrency
2873 * @param item, pointer of task item which includes the object
2874 * information
2875 *
2876 * @return int, if success, return 0, else return -1
2877 */
2878 static int ms_build_ascii_write_buf_set(ms_conn_t *c, ms_task_item_t *item)
2879 {
2880 int value_offset;
2881 int write_len;
2882 char *buffer= c->wbuf;
2883
2884 write_len= sprintf(buffer,
2885 " %u %d %d\r\n",
2886 0,
2887 item->exp_time,
2888 item->value_size);
2889
2890 if (write_len > c->wsize)
2891 {
2892 /* ought to be always enough. just fail for simplicity */
2893 fprintf(stderr, "output command line too long.\n");
2894 return -1;
2895 }
2896
2897 if (item->value_offset == INVALID_OFFSET)
2898 {
2899 value_offset= item->key_suffix_offset;
2900 }
2901 else
2902 {
2903 value_offset= item->value_offset;
2904 }
2905
2906 if ((ms_add_iov(c, "set ", 4) != 0)
2907 || (ms_add_iov(c, (char *)&item->key_prefix,
2908 (int)KEY_PREFIX_SIZE) != 0)
2909 || (ms_add_iov(c, &ms_setting.char_block[item->key_suffix_offset],
2910 item->key_size - (int)KEY_PREFIX_SIZE) != 0)
2911 || (ms_add_iov(c, buffer, write_len) != 0)
2912 || (ms_add_iov(c, &ms_setting.char_block[value_offset],
2913 item->value_size) != 0)
2914 || (ms_add_iov(c, "\r\n", 2) != 0)
2915 || (c->udp && (ms_build_udp_headers(c) != 0)))
2916 {
2917 return -1;
2918 }
2919
2920 return 0;
2921 } /* ms_build_ascii_write_buf_set */
2922
2923
2924 /**
2925 * used to send set command to server
2926 *
2927 * @param c, pointer of the concurrency
2928 * @param item, pointer of task item which includes the object
2929 * information
2930 *
2931 * @return int, if success, return 0, else return -1
2932 */
2933 int ms_mcd_set(ms_conn_t *c, ms_task_item_t *item)
2934 {
2935 assert(c != NULL);
2936
2937 c->currcmd.cmd= CMD_SET;
2938 c->currcmd.isfinish= false;
2939 c->currcmd.retstat= MCD_FAILURE;
2940
2941 if (ms_update_conn_sock_event(c) != 0)
2942 {
2943 return -1;
2944 }
2945
2946 c->msgcurr= 0;
2947 c->msgused= 0;
2948 c->iovused= 0;
2949 if (ms_add_msghdr(c) != 0)
2950 {
2951 fprintf(stderr, "Out of memory preparing request.");
2952 return -1;
2953 }
2954
2955 /* binary protocol */
2956 if (c->protocol == binary_prot)
2957 {
2958 if (ms_build_bin_write_buf_set(c, item) != 0)
2959 {
2960 return -1;
2961 }
2962 }
2963 else
2964 {
2965 if (ms_build_ascii_write_buf_set(c, item) != 0)
2966 {
2967 return -1;
2968 }
2969 }
2970
2971 atomic_add_size(&ms_stats.obj_bytes,
2972 item->key_size + item->value_size);
2973 atomic_add_size(&ms_stats.cmd_set, 1);
2974
2975 return 0;
2976 } /* ms_mcd_set */
2977
2978
2979 /**
2980 * for ASCII protocol, this function build the get command
2981 * string and send the command.
2982 *
2983 * @param c, pointer of the concurrency
2984 * @param item, pointer of task item which includes the object
2985 * information
2986 *
2987 * @return int, if success, return 0, else return -1
2988 */
2989 static int ms_build_ascii_write_buf_get(ms_conn_t *c, ms_task_item_t *item)
2990 {
2991 if ((ms_add_iov(c, "get ", 4) != 0)
2992 || (ms_add_iov(c, (char *)&item->key_prefix,
2993 (int)KEY_PREFIX_SIZE) != 0)
2994 || (ms_add_iov(c, &ms_setting.char_block[item->key_suffix_offset],
2995 item->key_size - (int)KEY_PREFIX_SIZE) != 0)
2996 || (ms_add_iov(c, "\r\n", 2) != 0)
2997 || (c->udp && (ms_build_udp_headers(c) != 0)))
2998 {
2999 return -1;
3000 }
3001
3002 return 0;
3003 } /* ms_build_ascii_write_buf_get */
3004
3005
3006 /**
3007 * used to send the get command to server
3008 *
3009 * @param c, pointer of the concurrency
3010 * @param item, pointer of task item which includes the object
3011 * information
3012 *
3013 * @return int, if success, return 0, else return -1
3014 */
3015 int ms_mcd_get(ms_conn_t *c, ms_task_item_t *item)
3016 {
3017 assert(c != NULL);
3018
3019 c->currcmd.cmd= CMD_GET;
3020 c->currcmd.isfinish= false;
3021 c->currcmd.retstat= MCD_FAILURE;
3022
3023 if (ms_update_conn_sock_event(c) != 0)
3024 {
3025 return -1;
3026 }
3027
3028 c->msgcurr= 0;
3029 c->msgused= 0;
3030 c->iovused= 0;
3031 if (ms_add_msghdr(c) != 0)
3032 {
3033 fprintf(stderr, "Out of memory preparing request.");
3034 return -1;
3035 }
3036
3037 /* binary protocol */
3038 if (c->protocol == binary_prot)
3039 {
3040 if (ms_build_bin_write_buf_get(c, item) != 0)
3041 {
3042 return -1;
3043 }
3044 }
3045 else
3046 {
3047 if (ms_build_ascii_write_buf_get(c, item) != 0)
3048 {
3049 return -1;
3050 }
3051 }
3052
3053 atomic_add_size(&ms_stats.cmd_get, 1);
3054
3055 return 0;
3056 } /* ms_mcd_get */
3057
3058
3059 /**
3060 * for ASCII protocol, this function build the multi-get command
3061 * string and send the command.
3062 *
3063 * @param c, pointer of the concurrency
3064 *
3065 * @return int, if success, return 0, else return -1
3066 */
3067 static int ms_build_ascii_write_buf_mlget(ms_conn_t *c)
3068 {
3069 ms_task_item_t *item;
3070
3071 if (ms_add_iov(c, "get", 3) != 0)
3072 {
3073 return -1;
3074 }
3075
3076 for (int i= 0; i < c->mlget_task.mlget_num; i++)
3077 {
3078 item= c->mlget_task.mlget_item[i].item;
3079 assert(item != NULL);
3080 if ((ms_add_iov(c, " ", 1) != 0)
3081 || (ms_add_iov(c, (char *)&item->key_prefix,
3082 (int)KEY_PREFIX_SIZE) != 0)
3083 || (ms_add_iov(c, &ms_setting.char_block[item->key_suffix_offset],
3084 item->key_size - (int)KEY_PREFIX_SIZE) != 0))
3085 {
3086 return -1;
3087 }
3088 }
3089
3090 if ((ms_add_iov(c, "\r\n", 2) != 0)
3091 || (c->udp && (ms_build_udp_headers(c) != 0)))
3092 {
3093 return -1;
3094 }
3095
3096 return 0;
3097 } /* ms_build_ascii_write_buf_mlget */
3098
3099
3100 /**
3101 * used to send the multi-get command to server
3102 *
3103 * @param c, pointer of the concurrency
3104 *
3105 * @return int, if success, return 0, else return -1
3106 */
3107 int ms_mcd_mlget(ms_conn_t *c)
3108 {
3109 ms_task_item_t *item;
3110
3111 assert(c != NULL);
3112 assert(c->mlget_task.mlget_num >= 1);
3113
3114 c->currcmd.cmd= CMD_GET;
3115 c->currcmd.isfinish= false;
3116 c->currcmd.retstat= MCD_FAILURE;
3117
3118 if (ms_update_conn_sock_event(c) != 0)
3119 {
3120 return -1;
3121 }
3122
3123 c->msgcurr= 0;
3124 c->msgused= 0;
3125 c->iovused= 0;
3126 if (ms_add_msghdr(c) != 0)
3127 {
3128 fprintf(stderr, "Out of memory preparing request.");
3129 return -1;
3130 }
3131
3132 /* binary protocol */
3133 if (c->protocol == binary_prot)
3134 {
3135 if (ms_build_bin_write_buf_mlget(c) != 0)
3136 {
3137 return -1;
3138 }
3139 }
3140 else
3141 {
3142 if (ms_build_ascii_write_buf_mlget(c) != 0)
3143 {
3144 return -1;
3145 }
3146 }
3147
3148 /* decrease operation time of each item */
3149 for (int i= 0; i < c->mlget_task.mlget_num; i++)
3150 {
3151 item= c->mlget_task.mlget_item[i].item;
3152 atomic_add_size(&ms_stats.cmd_get, 1);
3153 }
3154
3155 return 0;
3156 } /* ms_mcd_mlget */
3157
3158
3159 /**
3160 * binary protocol support
3161 */
3162
3163 /**
3164 * for binary protocol, parse the response of server
3165 *
3166 * @param c, pointer of the concurrency
3167 *
3168 * @return int, if success, return 0, else return -1
3169 */
3170 static int ms_bin_process_response(ms_conn_t *c)
3171 {
3172 const char *errstr= NULL;
3173
3174 assert(c != NULL);
3175
3176 uint32_t bodylen= c->binary_header.response.bodylen;
3177 uint8_t opcode= c->binary_header.response.opcode;
3178 uint16_t status= c->binary_header.response.status;
3179
3180 if (bodylen > 0)
3181 {
3182 c->rvbytes= (int32_t)bodylen;
3183 c->readval= true;
3184 return 1;
3185 }
3186 else
3187 {
3188 switch (status)
3189 {
3190 case PROTOCOL_BINARY_RESPONSE_SUCCESS:
3191 if (opcode == PROTOCOL_BINARY_CMD_SET)
3192 {
3193 c->currcmd.retstat= MCD_STORED;
3194 }
3195 else if (opcode == PROTOCOL_BINARY_CMD_DELETE)
3196 {
3197 c->currcmd.retstat= MCD_DELETED;
3198 }
3199 else if (opcode == PROTOCOL_BINARY_CMD_GET)
3200 {
3201 c->currcmd.retstat= MCD_END;
3202 }
3203 break;
3204
3205 case PROTOCOL_BINARY_RESPONSE_ENOMEM:
3206 errstr= "Out of memory";
3207 c->currcmd.retstat= MCD_SERVER_ERROR;
3208 break;
3209
3210 case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND:
3211 errstr= "Unknown command";
3212 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
3213 break;
3214
3215 case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT:
3216 errstr= "Not found";
3217 c->currcmd.retstat= MCD_NOTFOUND;
3218 break;
3219
3220 case PROTOCOL_BINARY_RESPONSE_EINVAL:
3221 errstr= "Invalid arguments";
3222 c->currcmd.retstat= MCD_PROTOCOL_ERROR;
3223 break;
3224
3225 case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS:
3226 errstr= "Data exists for key.";
3227 break;
3228
3229 case PROTOCOL_BINARY_RESPONSE_E2BIG:
3230 errstr= "Too large.";
3231 c->currcmd.retstat= MCD_SERVER_ERROR;
3232 break;
3233
3234 case PROTOCOL_BINARY_RESPONSE_NOT_STORED:
3235 errstr= "Not stored.";
3236 c->currcmd.retstat= MCD_NOTSTORED;
3237 break;
3238
3239 default:
3240 errstr= "Unknown error";
3241 c->currcmd.retstat= MCD_UNKNOWN_READ_FAILURE;
3242 break;
3243 } /* switch */
3244
3245 if (errstr != NULL)
3246 {
3247 fprintf(stderr, "%s\n", errstr);
3248 }
3249 }
3250
3251 return 0;
3252 } /* ms_bin_process_response */
3253
3254
3255 /* build binary header and add the header to the buffer to send */
3256
3257 /**
3258 * build binary header and add the header to the buffer to send
3259 *
3260 * @param c, pointer of the concurrency
3261 * @param opcode, operation code
3262 * @param hdr_len, length of header
3263 * @param key_len, length of key
3264 * @param body_len. length of body
3265 */
3266 static void ms_add_bin_header(ms_conn_t *c,
3267 uint8_t opcode,
3268 uint8_t hdr_len,
3269 uint16_t key_len,
3270 uint32_t body_len)
3271 {
3272 protocol_binary_request_header *header;
3273
3274 assert(c != NULL);
3275
3276 header= (protocol_binary_request_header *)c->wcurr;
3277
3278 header->request.magic= (uint8_t)PROTOCOL_BINARY_REQ;
3279 header->request.opcode= (uint8_t)opcode;
3280 header->request.keylen= htons(key_len);
3281
3282 header->request.extlen= (uint8_t)hdr_len;
3283 header->request.datatype= (uint8_t)PROTOCOL_BINARY_RAW_BYTES;
3284 header->request.reserved= 0;
3285
3286 header->request.bodylen= htonl(body_len);
3287 header->request.opaque= 0;
3288 header->request.cas= 0;
3289
3290 ms_add_iov(c, c->wcurr, sizeof(header->request));
3291 } /* ms_add_bin_header */
3292
3293
3294 /**
3295 * add the key to the socket write buffer array
3296 *
3297 * @param c, pointer of the concurrency
3298 * @param item, pointer of task item which includes the object
3299 * information
3300 */
3301 static void ms_add_key_to_iov(ms_conn_t *c, ms_task_item_t *item)
3302 {
3303 ms_add_iov(c, (char *)&item->key_prefix, (int)KEY_PREFIX_SIZE);
3304 ms_add_iov(c, &ms_setting.char_block[item->key_suffix_offset],
3305 item->key_size - (int)KEY_PREFIX_SIZE);
3306 }
3307
3308
3309 /**
3310 * for binary protocol, this function build the set command
3311 * and add the command to send buffer array.
3312 *
3313 * @param c, pointer of the concurrency
3314 * @param item, pointer of task item which includes the object
3315 * information
3316 *
3317 * @return int, if success, return 0, else return -1
3318 */
3319 static int ms_build_bin_write_buf_set(ms_conn_t *c, ms_task_item_t *item)
3320 {
3321 assert(c->wbuf == c->wcurr);
3322
3323 int value_offset;
3324 protocol_binary_request_set *rep= (protocol_binary_request_set *)c->wcurr;
3325 uint16_t keylen= (uint16_t)item->key_size;
3326 uint32_t bodylen= (uint32_t)sizeof(rep->message.body)
3327 + (uint32_t)keylen + (uint32_t)item->value_size;
3328
3329 ms_add_bin_header(c,
3330 PROTOCOL_BINARY_CMD_SET,
3331 sizeof(rep->message.body),
3332 keylen,
3333 bodylen);
3334 rep->message.body.flags= 0;
3335 rep->message.body.expiration= htonl((uint32_t)item->exp_time);
3336 ms_add_iov(c, &rep->message.body, sizeof(rep->message.body));
3337 ms_add_key_to_iov(c, item);
3338
3339 if (item->value_offset == INVALID_OFFSET)
3340 {
3341 value_offset= item->key_suffix_offset;
3342 }
3343 else
3344 {
3345 value_offset= item->value_offset;
3346 }
3347 ms_add_iov(c, &ms_setting.char_block[value_offset], item->value_size);
3348
3349 return 0;
3350 } /* ms_build_bin_write_buf_set */
3351
3352
3353 /**
3354 * for binary protocol, this function build the get command and
3355 * add the command to send buffer array.
3356 *
3357 * @param c, pointer of the concurrency
3358 * @param item, pointer of task item which includes the object
3359 * information
3360 *
3361 * @return int, if success, return 0, else return -1
3362 */
3363 static int ms_build_bin_write_buf_get(ms_conn_t *c, ms_task_item_t *item)
3364 {
3365 assert(c->wbuf == c->wcurr);
3366
3367 ms_add_bin_header(c, PROTOCOL_BINARY_CMD_GET, 0, (uint16_t)item->key_size,
3368 (uint32_t)item->key_size);
3369 ms_add_key_to_iov(c, item);
3370
3371 return 0;
3372 } /* ms_build_bin_write_buf_get */
3373
3374
3375 /**
3376 * for binary protocol, this function build the multi-get
3377 * command and add the command to send buffer array.
3378 *
3379 * @param c, pointer of the concurrency
3380 * @param item, pointer of task item which includes the object
3381 * information
3382 *
3383 * @return int, if success, return 0, else return -1
3384 */
3385 static int ms_build_bin_write_buf_mlget(ms_conn_t *c)
3386 {
3387 ms_task_item_t *item;
3388
3389 assert(c->wbuf == c->wcurr);
3390
3391 for (int i= 0; i < c->mlget_task.mlget_num; i++)
3392 {
3393 item= c->mlget_task.mlget_item[i].item;
3394 assert(item != NULL);
3395
3396 ms_add_bin_header(c,
3397 PROTOCOL_BINARY_CMD_GET,
3398 0,
3399 (uint16_t)item->key_size,
3400 (uint32_t)item->key_size);
3401 ms_add_key_to_iov(c, item);
3402 c->wcurr+= sizeof(protocol_binary_request_get);
3403 }
3404
3405 c->wcurr= c->wbuf;
3406
3407 return 0;
3408 } /* ms_build_bin_write_buf_mlget */