-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagent.c
2343 lines (1999 loc) · 53 KB
/
magent.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2008, 2010 QUE Hongyu
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/* Changelog:
* 2008-08-20, coding started
* 2008-09-04, v0.1 finished
* 2008-09-07, v0.2 finished, code cleanup, drive_get_server function
* 2008-09-09, support get/gets' multi keys(can > 7 keys)
* 2008-09-10, ketama allocation
* 2008-09-12, backup server added
* 2008-09-12, try backup server for get/gets command
* 2008-09-16, v0.3 finished
* 2008-09-20, support unix domain socket
* 2008-09-23, write "END\r\n" with the last packet of GET/GETS response
* 2008-09-23, combine drive_get_server with drive_server functions -> drive_memcached_server function
* 2008-10-05, fix header file include under BSD systems
*/
#define _GNU_SOURCE
#include <sys/types.h>
#if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__) )
#include <sys/uio.h>
#include <limits.h>
#else
#include <getopt.h>
#endif
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <event.h>
#include "ketama.h"
#define VERSION "0.6"
#define OUTOFCONN "SERVER_ERROR OUT OF CONNECTION"
#define BUFFERLEN 2048
#define MAX_TOKENS 8
#define COMMAND_TOKEN 0
#define KEY_TOKEN 1
#define BYTES_TOKEN 4
#define KEY_MAX_LENGTH 250
#define BUFFER_PIECE_SIZE 16
#define UNUSED(x) ( (void)(x) )
#define STEP 5
/* structure definitions */
typedef struct conn conn;
typedef struct matrix matrix;
typedef struct list list;
typedef struct buffer buffer;
typedef struct server server;
typedef enum
{
CLIENT_COMMAND,
CLIENT_NREAD, /* MORE CLIENT DATA */
CLIENT_TRANSCATION
} client_state_t;
typedef enum
{
SERVER_INIT,
SERVER_CONNECTING,
SERVER_CONNECTED,
SERVER_ERROR
} server_state_t;
struct buffer
{
char *ptr;
size_t used;
size_t size;
size_t len; /* ptr length */
struct buffer *next;
};
/* list to buffers */
struct list
{
buffer *first;
buffer *last;
};
/* connection to memcached server */
struct server
{
int sfd;
server_state_t state;
struct event ev;
int ev_flags;
matrix *owner;
/* first response line
* NOT_FOUND\r\n
* STORED\r\n
*/
char line[BUFFERLEN];
int pos;
/* get/gets key ....
* VALUE <key> <flags> <bytes> [<cas unique>]\r\n
*/
int valuebytes;
int has_response_header:1;
int remove_trail:1;
/* input buffer */
list *request;
/* output buffer */
list *response;
int pool_idx;
};
struct conn
{
/* client part */
int cfd;
client_state_t state;
struct event ev;
int ev_flags;
/* command buffer */
char line[BUFFERLEN+1];
int pos;
int storebytes; /* bytes stored by CAS/SET/ADD/... command */
struct flag {
unsigned int is_get_cmd:1;
unsigned int is_gets_cmd:1;
unsigned int is_set_cmd:1;
unsigned int is_incr_decr_cmd:1;
unsigned int no_reply:1;
unsigned int is_update_cmd:1;
unsigned int is_backup:1;
unsigned int is_last_key:1;
} flag;
int keycount; /* GET/GETS multi keys */
int keyidx;
char **keys;
/* input buffer */
list *request;
/* output buffer */
list *response;
struct server *srv;
};
/* memcached server structure */
struct matrix
{
char *ip;
int port;
struct sockaddr_in dstaddr;
int size;
int used;
struct server **pool;
};
typedef struct token_s
{
char *value;
size_t length;
} token_t;
/* static variables */
static int port = 11211, maxconns = 4096, curconns = 0, sockfd = -1, verbose_mode = 0, use_ketama = 0;
static struct event ev_master;
static struct matrix *matrixs = NULL; /* memcached server list */
static int matrixcnt = 0;
static struct ketama *ketama = NULL;
static struct matrix *backups= NULL; /* backup memcached server list */
static int backupcnt = 0;
static struct ketama *backupkt = NULL;
static char *socketpath = NULL;
static int unixfd = -1;
static struct event ev_unix;
static int maxidle = 20; /* max keep alive connections for one memcached server */
static struct event ev_timer;
time_t cur_ts;
char cur_ts_str[128];
static void drive_client(const int, const short, void *);
static void drive_backup_server(const int, const short, void *);
static void drive_memcached_server(const int, const short, void *);
static void finish_transcation(conn *);
static void do_transcation(conn *);
static void start_magent_transcation(conn *);
static void out_string(conn *, const char *);
static void process_update_response(conn *);
static void process_get_response(conn *, int);
static void append_buffer_to_list(list *, buffer *);
static void try_backup_server(conn *);
static const char resivion[] __attribute__((used)) = { "$Id$" };
static void
show_help(void)
{
char *b = "memcached agent v" VERSION " Build-Date: " __DATE__ " " __TIME__ "\n"
"Usage:\n -h this message\n"
" -u uid\n"
" -g gid\n"
" -p port, default is 11211. (0 to disable tcp support)\n"
" -s ip:port, set memcached server ip and port\n"
" -b ip:port, set backup memcached server ip and port\n"
" -l ip, local bind ip address, default is 0.0.0.0\n"
" -n number, set max connections, default is 4096\n"
" -D don't go to background\n"
" -k use ketama key allocation algorithm\n"
" -f file, unix socket path to listen on. default is off\n"
" -i number, set max keep alive connections for one memcached server, default is 20\n"
" -v verbose\n"
"\n";
fprintf(stderr, b, strlen(b));
}
/* the famous DJB hash function for strings from stat_cache.c*/
static int
hashme(char *str)
{
unsigned int hash = 5381;
const char *s;
if (str == NULL) return 0;
for (s = str; *s; s++) {
hash = ((hash << 5) + hash) + *s;
}
hash &= 0x7FFFFFFF; /* strip the highest bit */
return hash;
}
static buffer *
buffer_init_size(int size)
{
buffer *b;
if (size <= 0) return NULL;
b = (struct buffer *) calloc(sizeof(struct buffer), 1);
if (b == NULL) return NULL;
size += BUFFER_PIECE_SIZE - (size % BUFFER_PIECE_SIZE);
b->ptr = (char *) calloc(1, size);
if (b->ptr == NULL) {
free(b);
return NULL;
}
b->len = size;
return b;
}
static void
set_nonblock(int fd)
{
int flags = 1;
struct linger ling = {0, 0};
if (fd > 0) {
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)|O_NONBLOCK);
setsockopt(fd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling));
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags));
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags));
}
}
static void
buffer_free(buffer *b)
{
if (!b) return;
free(b->ptr);
free(b);
}
static list *
list_init(void)
{
list *l;
l = (struct list *) calloc(sizeof(struct list), 1);
return l;
}
static void
list_free(list *l, int keep_list)
{
buffer *b, *n;
if (l == NULL) return;
b = l->first;
while(b) {
n = b->next;
buffer_free(b);
b = n;
}
if (keep_list)
l->first = l->last = NULL;
else
free(l);
}
static void
remove_finished_buffers(list *l)
{
buffer *n, *b;
if (l == NULL) return;
b = l->first;
while(b) {
if (b->used < b->size) /* incompleted buffer */
break;
n = b->next;
buffer_free(b);
b = n;
}
if (b == NULL) {
l->first = l->last = NULL;
} else {
l->first = b;
}
}
static void
copy_list(list *src, list *dst)
{
buffer *b, *r;
int size = 0;
if (src == NULL || dst == NULL || src->first == NULL) return;
b = src->first;
while(b) {
size += b->size;
b = b->next;
}
if (size == 0) return;
r = buffer_init_size(size+1);
if (r == NULL) return;
b = src->first;
while(b) {
if (b->size > 0 ) {
memcpy(r->ptr + r->size, b->ptr, b->size);
r->size += b->size;
}
b = b->next;
}
append_buffer_to_list(dst, r);
}
static void
move_list(list *src, list *dst)
{
if (src == NULL || dst == NULL || src->first == NULL) return;
if (dst->first == NULL)
dst->first = src->first;
else
dst->last->next = src->first;
dst->last = src->last;
src->last = src->first = NULL;
}
static void
append_buffer_to_list(list *l, buffer *b)
{
if (l == NULL || b == NULL)
return;
if (l->first == NULL) {
l->first = l->last = b;
} else {
l->last->next = b;
l->last = b;
}
}
/* return -1 if not found
* return pos if found
*/
static int
memstr(char *s, char *find, int srclen, int findlen)
{
char *bp, *sp;
int len = 0, success = 0;
if (findlen == 0 || srclen < findlen) return -1;
for (len = 0; len <= (srclen-findlen); len ++) {
if (s[len] == find[0]) {
bp = s + len;
sp = find;
do {
if (!*sp) {
success = 1;
break;
}
} while (*bp++ == *sp++);
if (success) break;
}
}
if (success) return len;
else return -1;
}
static size_t
tokenize_command(char *command, token_t *tokens, const size_t max_tokens)
{
char *s, *e;
size_t ntokens = 0;
if (command == NULL || tokens == NULL || max_tokens < 1) return 0;
for (s = e = command; ntokens < max_tokens - 1; ++e) {
if (*e == ' ') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
*e = '\0';
}
s = e + 1;
}
else if (*e == '\0') {
if (s != e) {
tokens[ntokens].value = s;
tokens[ntokens].length = e - s;
ntokens++;
}
break; /* string end */
}
}
/*
* If we scanned the whole string, the terminal value pointer is null,
* otherwise it is the first unprocessed character.
*/
tokens[ntokens].value = *e == '\0' ? NULL : e;
tokens[ntokens].length = 0;
ntokens++;
return ntokens;
}
static void
server_free(struct server *s)
{
if (s == NULL) return;
if (s->sfd > 0) {
event_del(&(s->ev));
close(s->sfd);
}
list_free(s->request, 0);
list_free(s->response, 0);
free(s);
}
static void
pool_server_handler(const int fd, const short which, void *arg)
{
struct server *s;
struct matrix *m;
char buf[128];
int toread = 0, toexit = 0, i;
if (arg == NULL) return;
s = (struct server *)arg;
if (!(which & EV_READ)) return;
/* get the byte counts of read */
if (ioctl(s->sfd, FIONREAD, &toread) || toread == 0) {
toexit = 1;
} else {
if (toread > 128) toread = 128;
if (0 == read(s->sfd, buf, toread)) toexit = 1;
}
if (toexit) {
if (verbose_mode)
fprintf(stderr, "%s: (%s.%d) CLOSE POOL SERVER FD %d\n", cur_ts_str, __FILE__, __LINE__, s->sfd);
event_del(&(s->ev));
close(s->sfd);
list_free(s->request, 0);
list_free(s->response, 0);
m = s->owner;
if (m) {
if (s->pool_idx <= 0) {
fprintf(stderr, "%s: (%s.%d) POOL SERVER FD %d, IDX %d <= 0\n",
cur_ts_str, __FILE__, __LINE__, s->sfd, s->pool_idx);
} else {
/* remove from list */
for (i = s->pool_idx; i < m->used; i ++) {
m->pool[i-1] = m->pool[i];
m->pool[i-1]->pool_idx = i;
}
-- m->used;
}
}
free(s);
}
}
/* put server connection into keep alive pool */
static void
put_server_into_pool(struct server *s)
{
struct matrix *m;
struct server **p;
if (s == NULL) return;
if (s->owner == NULL || s->state != SERVER_CONNECTED || s->sfd <= 0) {
server_free(s);
return;
}
list_free(s->request, 1);
list_free(s->response, 1);
s->pos = s->has_response_header = s->remove_trail = 0;
m = s->owner;
if (m->size == 0) {
m->pool = (struct server **) calloc(sizeof(struct server *), STEP);
if (m->pool == NULL) {
fprintf(stderr, "%s: (%s.%d) out of memory for pool allocation\n", cur_ts_str, __FILE__, __LINE__);
m = NULL;
} else {
m->size = STEP;
m->used = 0;
}
} else if (m->used == m->size) {
if (m->size < maxidle) {
p = (struct server **)realloc(m->pool, sizeof(struct server *)*(m->size + STEP));
if (p == NULL) {
fprintf(stderr, "%s: (%s.%d) out of memory for pool reallocation\n", cur_ts_str, __FILE__, __LINE__);
m = NULL;
} else {
m->pool = p;
m->size += STEP;
}
} else {
m = NULL;
}
}
if (m != NULL) {
if (verbose_mode)
fprintf(stderr, "%s: (%s.%d) PUT SERVER FD %d -> POOL\n", cur_ts_str, __FILE__, __LINE__, s->sfd);
m->pool[m->used ++] = s;
s->pool_idx = m->used;
event_del(&(s->ev));
event_set(&(s->ev), s->sfd, EV_READ|EV_PERSIST, pool_server_handler, (void *) s);
event_add(&(s->ev), 0);
} else {
server_free(s);
}
}
static void
server_error(conn *c, const char *s)
{
int i;
if (c == NULL) return;
if (c->srv) {
server_free(c->srv);
c->srv = NULL;
}
if (c->keys) {
for (i = 0; i < c->keycount; i ++)
free(c->keys[i]);
free(c->keys);
c->keys = NULL;
}
c->pos = c->keycount = c->keyidx = 0;
list_free(c->request, 1);
list_free(c->response, 1);
out_string(c, s);
}
/* return 0 if ok, return 1 if failed */
static int
socket_connect(struct server *s)
{
socklen_t servlen;
if (s == NULL || s->sfd <= 0 || s->state != SERVER_INIT) return 1;
servlen = sizeof(s->owner->dstaddr);
if (-1 == connect(s->sfd, (struct sockaddr *) &(s->owner->dstaddr), servlen)) {
if (errno != EINPROGRESS && errno != EALREADY)
return 1;
s->state = SERVER_CONNECTING;
} else {
s->state = SERVER_CONNECTED;
}
return 0;
}
static void
conn_close(conn *c)
{
int i;
if (c == NULL) return;
/* check client connection */
if (c->cfd > 0) {
if (verbose_mode)
fprintf(stderr, "%s: (%s.%d) CLOSE CLIENT CONNECTION FD %d\n", cur_ts_str, __FILE__, __LINE__, c->cfd);
event_del(&(c->ev));
close(c->cfd);
curconns --;
c->cfd = 0;
}
server_free(c->srv);
if (c->keys) {
for (i = 0; i < c->keycount; i ++)
free(c->keys[i]);
free(c->keys);
c->keys = NULL;
}
list_free(c->request, 0);
list_free(c->response, 0);
free(c);
}
/* ------------- from lighttpd's network_writev.c ------------ */
#ifndef UIO_MAXIOV
# if defined(__FreeBSD__) || defined(__APPLE__) || defined(__NetBSD__)
/* FreeBSD 4.7 defines it in sys/uio.h only if _KERNEL is specified */
# define UIO_MAXIOV 1024
# elif defined(__sgi)
/* IRIX 6.5 has sysconf(_SC_IOV_MAX) which might return 512 or bigger */
# define UIO_MAXIOV 512
# elif defined(__sun)
/* Solaris (and SunOS?) defines IOV_MAX instead */
# ifndef IOV_MAX
# define UIO_MAXIOV 16
# else
# define UIO_MAXIOV IOV_MAX
# endif
# elif defined(IOV_MAX)
# define UIO_MAXIOV IOV_MAX
# else
# error UIO_MAXIOV nor IOV_MAX are defined
# endif
#endif
/* return 0 if success */
static int
writev_list(int fd, list *l)
{
size_t num_chunks, i, num_bytes = 0, toSend, r, r2;
struct iovec chunks[UIO_MAXIOV];
buffer *b;
if (l == NULL || l->first == NULL || fd <= 0) return 0;
for (num_chunks = 0, b = l->first; b && num_chunks < UIO_MAXIOV; num_chunks ++, b = b->next) ;
for (i = 0, b = l->first; i < num_chunks; b = b->next, i ++) {
if (b->size == 0) {
num_chunks --;
i --;
} else {
chunks[i].iov_base = b->ptr + b->used;
toSend = b->size - b->used;
/* protect the return value of writev() */
if (toSend > SSIZE_MAX ||
(num_bytes + toSend) > SSIZE_MAX) {
chunks[i].iov_len = SSIZE_MAX - num_bytes;
num_chunks = i + 1;
break;
} else {
chunks[i].iov_len = toSend;
}
num_bytes += toSend;
}
}
if ((r = writev(fd, chunks, num_chunks)) < 0) {
switch (errno) {
case EAGAIN:
case EINTR:
return 0; /* try again */
break;
case EPIPE:
case ECONNRESET:
return -2; /* connection closed */
break;
default:
return -1; /* error */
break;
}
}
r2 = r;
for (i = 0, b = l->first; i < num_chunks; b = b->next, i ++) {
if (r >= (ssize_t)chunks[i].iov_len) {
r -= chunks[i].iov_len;
b->used += chunks[i].iov_len;
} else {
/* partially written */
b->used += r;
break;
}
}
remove_finished_buffers(l);
return r2;
}
/* --------- end here ----------- */
static void
out_string(conn *c, const char *str)
{
/* append str to c->wbuf */
int len = 0;
buffer *b;
if (c == NULL || str == NULL || str[0] == '\0') return;
len = strlen(str);
b = buffer_init_size(len + 3);
if (b == NULL) return;
memcpy(b->ptr, str, len);
memcpy(b->ptr + len, "\r\n", 2);
b->size = len + 2;
b->ptr[b->size] = '\0';
append_buffer_to_list(c->response, b);
if (writev_list(c->cfd, c->response) >= 0) {
if (c->response->first && (c->ev_flags != EV_WRITE)) {
/* update event handler */
event_del(&(c->ev));
event_set(&(c->ev), c->cfd, EV_WRITE|EV_PERSIST, drive_client, (void *) c);
event_add(&(c->ev), 0);
c->ev_flags = EV_WRITE;
}
} else {
/* client reset/close connection*/
conn_close(c);
}
}
/* finish proxy transcation */
static void
finish_transcation(conn *c)
{
int i;
if (c == NULL) return;
if (c->keys) {
for (i = 0; i < c->keycount; i ++)
free(c->keys[i]);
free(c->keys);
c->keys = NULL;
c->keycount = c->keyidx = 0;
}
c->state = CLIENT_COMMAND;
list_free(c->request, 1);
}
static void
start_update_backupserver(conn *c)
{
int size = 0, idx;
buffer *b, *r;
matrix *m;
server *s;
if (c == NULL) return;
if (c->flag.is_update_cmd == 0 || backupcnt == 0 || c->keycount != 1) return;
/* start backup set server now */
b = c->request->first;
while(b) {
size += b->size;
b = b->next;
}
if (size == 0) return;
r = buffer_init_size(size+1);
if (r == NULL) return;
b = c->request->first;
while(b) {
if (b->size > 0 ) {
memcpy(r->ptr + r->size, b->ptr, b->size);
r->size += b->size;
}
b = b->next;
}
if (use_ketama && backupkt) {
idx = get_server(backupkt, c->keys[0]);
if (idx < 0) {
/* fall back to round selection */
idx = hashme(c->keys[0])%backupcnt;
}
} else {
/* just round selection */
idx = hashme(c->keys[0])%backupcnt;
}
m = backups + idx;
if (m->pool && (m->used > 0)) {
s = m->pool[--m->used];
s->pool_idx = 0;
if (verbose_mode)
fprintf(stderr, "%s: (%s.%d) GET SERVER FD %d <- POOL\n", cur_ts_str, __FILE__, __LINE__, s->sfd);
} else {
s = (struct server *) calloc(sizeof(struct server), 1);
if (s == NULL) {
buffer_free(r);
return;
}
s->request = list_init();
s->response = list_init();
s->state = SERVER_INIT;
}
s->owner = m;
if (verbose_mode)
fprintf(stderr, "%s: (%s.%d) BACKUP KEY \"%s\" -> %s:%d\n", cur_ts_str, __FILE__, __LINE__, c->keys[0], m->ip, m->port);
if (s->sfd <= 0) {
s->sfd = socket(AF_INET, SOCK_STREAM, 0);
if (s->sfd < 0) {
fprintf(stderr, "%s: (%s.%d) CAN'T CREATE TCP SOCKET TO MEMCACHED\n", cur_ts_str, __FILE__, __LINE__);
free(s);
buffer_free(r);
return;
}
set_nonblock(s->sfd);
}
append_buffer_to_list(s->request, r);
if (s->state == SERVER_INIT && socket_connect(s)) {
/* server error */
server_free(s);
return;
}
/* server event handler */
memset(&(s->ev), 0, sizeof(struct event));
event_set(&(s->ev), s->sfd, EV_PERSIST|EV_WRITE, drive_backup_server, (void *)s);
event_add(&(s->ev), 0);
}
/* start whole memcache agent transcation */
static void
start_magent_transcation(conn *c)
{
if (c == NULL) return;
if (c->flag.is_update_cmd && backupcnt > 0 && c->keycount == 1)
start_update_backupserver(c);
/* start first transaction to normal server */
do_transcation(c);
}
/* start/repeat memcached proxy transcations */
static void
do_transcation(conn *c)
{
int idx;
struct matrix *m;
struct server *s;
char *key = NULL;
buffer *b;
if (c == NULL) return;
c->flag.is_backup = 0;
if (c->flag.is_get_cmd) {
if (c->keyidx >= c->keycount) {
/* end of get transcation */
finish_transcation(c);
return;
}
key = c->keys[c->keyidx++];
if (c->keyidx == c->keycount) c->flag.is_last_key = 1;
} else {
key = c->keys[0];
}
if (use_ketama && ketama) {
idx = get_server(ketama, key);
if (idx < 0) {
/* fall back to round selection */
idx = hashme(key)%matrixcnt;
}
} else {
/* just round selection */
idx = hashme(key)%matrixcnt;
}
m = matrixs + idx;
if (m->pool && (m->used > 0)) {