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