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