-
Notifications
You must be signed in to change notification settings - Fork 33
/
cproxy.c
3123 lines (2570 loc) · 93.8 KB
/
cproxy.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
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <assert.h>
#include <fcntl.h>
#include <math.h>
#include "memcached.h"
#include "cproxy.h"
#include "work.h"
#include "log.h"
#ifndef MOXI_BLOCKING_CONNECT
#ifdef WIN32
#define MOXI_BLOCKING_CONNECT true
#else
#define MOXI_BLOCKING_CONNECT false
#endif
#endif
// Internal forward declarations.
//
downstream *downstream_list_remove(downstream *head, downstream *d);
downstream *downstream_list_waiting_remove(downstream *head,
downstream **tail,
downstream *d);
void downstream_timeout(const int fd,
const short which,
void *arg);
void wait_queue_timeout(const int fd,
const short which,
void *arg);
conn *conn_list_remove(conn *head, conn **tail,
conn *c, bool *found);
bool is_compatible_request(conn *existing, conn *candidate);
void propagate_error(downstream *d);
void downstream_reserved_time_sample(proxy_stats_td *ptds, uint64_t duration);
void downstream_connect_time_sample(proxy_stats_td *ptds, uint64_t duration);
bool downstream_connect_init(downstream *d, mcs_server_st *msst,
proxy_behavior *behavior, conn *c);
int init_mcs_st(mcs_st *mst, char *config);
bool cproxy_on_connect_downstream_conn(conn *c);
conn *zstored_acquire_downstream_conn(downstream *d,
LIBEVENT_THREAD *thread,
mcs_server_st *msst,
proxy_behavior *behavior,
bool *downstream_conn_max_reached);
void zstored_release_downstream_conn(conn *dc, bool closing);
void zstored_error_count(LIBEVENT_THREAD *thread,
const char *host_ident,
bool has_error);
bool zstored_downstream_waiting_add(downstream *d, LIBEVENT_THREAD *thread,
mcs_server_st *msst,
proxy_behavior *behavior);
void zstored_downstream_waiting_remove(downstream *d);
typedef struct {
conn *dc; // Linked-list of available downstream conns.
uint32_t dc_acquired; // Count of acquired (in-use) downstream conns.
char *host_ident;
uint32_t error_count;
rel_time_t error_time;
// Head & tail of singly linked-list/queue, using
// downstream->next_waiting pointers, where we've reached
// downstream_conn_max, so there are waiting downstreams.
//
downstream *downstream_waiting_head;
downstream *downstream_waiting_tail;
} zstored_downstream_conns;
zstored_downstream_conns *zstored_get_downstream_conns(LIBEVENT_THREAD *thread,
const char *host_ident);
void format_host_ident(char *buf, int buf_len,
mcs_server_st *msst,
enum protocol host_protocol);
bool cproxy_forward_or_error(downstream *d);
int delink_from_downstream_conns(conn *c);
// Function tables.
//
conn_funcs cproxy_listen_funcs = {
.conn_init = cproxy_init_upstream_conn,
.conn_close = NULL,
.conn_connect = NULL,
.conn_process_ascii_command = NULL,
.conn_process_binary_command = NULL,
.conn_complete_nread_ascii = NULL,
.conn_complete_nread_binary = NULL,
.conn_pause = NULL,
.conn_realtime = NULL,
.conn_state_change = NULL,
.conn_binary_command_magic = 0
};
conn_funcs cproxy_upstream_funcs = {
.conn_init = NULL,
.conn_close = cproxy_on_close_upstream_conn,
.conn_connect = NULL,
.conn_process_ascii_command = cproxy_process_upstream_ascii,
.conn_process_binary_command = cproxy_process_upstream_binary,
.conn_complete_nread_ascii = cproxy_process_upstream_ascii_nread,
.conn_complete_nread_binary = cproxy_process_upstream_binary_nread,
.conn_pause = NULL,
.conn_realtime = cproxy_realtime,
.conn_state_change = cproxy_upstream_state_change,
.conn_binary_command_magic = PROTOCOL_BINARY_REQ
};
conn_funcs cproxy_downstream_funcs = {
.conn_init = cproxy_init_downstream_conn,
.conn_close = cproxy_on_close_downstream_conn,
.conn_connect = cproxy_on_connect_downstream_conn,
.conn_process_ascii_command = cproxy_process_downstream_ascii,
.conn_process_binary_command = cproxy_process_downstream_binary,
.conn_complete_nread_ascii = cproxy_process_downstream_ascii_nread,
.conn_complete_nread_binary = cproxy_process_downstream_binary_nread,
.conn_pause = cproxy_on_pause_downstream_conn,
.conn_realtime = cproxy_realtime,
.conn_state_change = NULL,
.conn_binary_command_magic = PROTOCOL_BINARY_RES
};
/* Main function to create a proxy struct.
*/
proxy *cproxy_create(proxy_main *main,
char *name,
int port,
char *config,
uint32_t config_ver,
proxy_behavior_pool *behavior_pool,
int nthreads) {
assert(name != NULL);
assert(port > 0 || settings.socketpath != NULL);
assert(config != NULL);
assert(behavior_pool);
assert(nthreads > 1); // Main thread + at least one worker.
assert(nthreads == settings.num_threads);
if (settings.verbose > 1) {
moxi_log_write("cproxy_create on port %d, name %s, config %s\n",
port, name, config);
}
proxy *p = (proxy *) calloc(1, sizeof(proxy));
if (p != NULL) {
p->main = main;
p->name = trimstrdup(name);
p->port = port;
p->config = trimstrdup(config);
p->config_ver = config_ver;
p->behavior_pool.base = behavior_pool->base;
p->behavior_pool.num = behavior_pool->num;
p->behavior_pool.arr = cproxy_copy_behaviors(behavior_pool->num,
behavior_pool->arr);
p->listening = 0;
p->listening_failed = 0;
p->next = NULL;
pthread_mutex_init(&p->proxy_lock, NULL);
mcache_init(&p->front_cache, true, &mcache_item_funcs, true);
matcher_init(&p->front_cache_matcher, true);
matcher_init(&p->front_cache_unmatcher, true);
matcher_init(&p->optimize_set_matcher, true);
if (behavior_pool->base.front_cache_max > 0 &&
behavior_pool->base.front_cache_lifespan > 0) {
mcache_start(&p->front_cache,
behavior_pool->base.front_cache_max);
if (strlen(behavior_pool->base.front_cache_spec) > 0) {
matcher_start(&p->front_cache_matcher,
behavior_pool->base.front_cache_spec);
}
if (strlen(behavior_pool->base.front_cache_unspec) > 0) {
matcher_start(&p->front_cache_unmatcher,
behavior_pool->base.front_cache_unspec);
}
}
if (strlen(behavior_pool->base.optimize_set) > 0) {
matcher_start(&p->optimize_set_matcher,
behavior_pool->base.optimize_set);
}
p->thread_data_num = nthreads;
p->thread_data = (proxy_td *) calloc(p->thread_data_num,
sizeof(proxy_td));
if (p->thread_data != NULL &&
p->name != NULL &&
p->config != NULL &&
p->behavior_pool.arr != NULL) {
// We start at 1, because thread[0] is the main listen/accept
// thread, and not a true worker thread. Too lazy to save
// the wasted thread[0] slot memory.
//
for (int i = 1; i < p->thread_data_num; i++) {
proxy_td *ptd = &p->thread_data[i];
ptd->proxy = p;
ptd->config = strdup(p->config);
ptd->config_ver = p->config_ver;
ptd->behavior_pool.base = behavior_pool->base;
ptd->behavior_pool.num = behavior_pool->num;
ptd->behavior_pool.arr =
cproxy_copy_behaviors(behavior_pool->num,
behavior_pool->arr);
ptd->waiting_any_downstream_head = NULL;
ptd->waiting_any_downstream_tail = NULL;
ptd->downstream_reserved = NULL;
ptd->downstream_released = NULL;
ptd->downstream_tot = 0;
ptd->downstream_num = 0;
ptd->downstream_max = behavior_pool->base.downstream_max;
ptd->downstream_assigns = 0;
ptd->timeout_tv.tv_sec = 0;
ptd->timeout_tv.tv_usec = 0;
ptd->stats.stats.num_upstream = 0;
ptd->stats.stats.num_downstream_conn = 0;
cproxy_reset_stats_td(&ptd->stats);
mcache_init(&ptd->key_stats, true,
&mcache_key_stats_funcs, false);
matcher_init(&ptd->key_stats_matcher, false);
matcher_init(&ptd->key_stats_unmatcher, false);
if (behavior_pool->base.key_stats_max > 0 &&
behavior_pool->base.key_stats_lifespan > 0) {
mcache_start(&ptd->key_stats,
behavior_pool->base.key_stats_max);
if (strlen(behavior_pool->base.key_stats_spec) > 0) {
matcher_start(&ptd->key_stats_matcher,
behavior_pool->base.key_stats_spec);
}
if (strlen(behavior_pool->base.key_stats_unspec) > 0) {
matcher_start(&ptd->key_stats_unmatcher,
behavior_pool->base.key_stats_unspec);
}
}
}
return p;
}
free(p->name);
free(p->config);
free(p->behavior_pool.arr);
free(p->thread_data);
free(p);
}
return NULL;
}
/* Must be called on the main listener thread.
*/
int cproxy_listen(proxy *p) {
assert(p != NULL);
assert(is_listen_thread());
if (settings.verbose > 1) {
moxi_log_write("cproxy_listen on port %d, downstream %s\n",
p->port, p->config);
}
// Idempotent, remembers if it already created listening socket(s).
//
if (p->listening == 0) {
enum protocol listen_protocol = negotiating_proxy_prot;
if (IS_ASCII(settings.binding_protocol)) {
listen_protocol = proxy_upstream_ascii_prot;
}
if (IS_BINARY(settings.binding_protocol)) {
listen_protocol = proxy_upstream_binary_prot;
}
int listening = cproxy_listen_port(p->port, listen_protocol,
tcp_transport,
p,
&cproxy_listen_funcs);
if (listening > 0) {
p->listening += listening;
} else {
p->listening_failed++;
moxi_log_write("ERROR: could not listen on port %d. "
"Please use -Z port_listen=PORT_NUM "
"to specify a different port number.\n", p->port);
if (ml->log_mode != ERRORLOG_STDERR) {
fprintf(stderr, "ERROR: could not listen on port %d. "
"Please use -Z port_listen=PORT_NUM "
"to specify a different port number.\n", p->port);
}
exit(EXIT_FAILURE);
}
}
return p->listening;
}
int cproxy_listen_port(int port,
enum protocol protocol,
enum network_transport transport,
void *conn_extra,
conn_funcs *funcs) {
assert(port > 0 || settings.socketpath != NULL);
assert(conn_extra);
assert(funcs);
assert(is_listen_thread());
int listening = 0;
conn *listen_conn_orig = listen_conn;
conn *x = listen_conn_orig;
while (x != NULL) {
if (x->extra != NULL &&
x->funcs == funcs) {
struct in_addr in = {0};
struct sockaddr_in s_in = {.sin_family = 0};
socklen_t sin_len = sizeof(s_in);
if (getsockname(x->sfd, (struct sockaddr *) &s_in, &sin_len) == 0) {
in.s_addr = s_in.sin_addr.s_addr;
int x_port = ntohs(s_in.sin_port);
if (x_port == port) {
if (settings.verbose > 1) {
moxi_log_write(
"<%d cproxy listening reusing listener on port %d\n",
x->sfd, port);
}
listening++;
}
}
}
x = x->next;
}
if (listening > 0) {
// If we're already listening on the required port, then
// we don't need to start a new server_socket(). This happens
// in the multi-bucket case with binary protocol buckets.
// There will be multiple proxy struct's (one per bucket), but
// only one proxy struct will actually be pointed at by a
// listening conn->extra (usually 11211).
//
// TODO: Add a refcount to handle shutdown properly?
//
return listening;
}
#ifdef HAVE_SYS_UN_H
if (settings.socketpath ?
(server_socket_unix(settings.socketpath, settings.access) == 0) :
(server_socket(port, transport, NULL) == 0)) {
#else
if (server_socket(port, transport, NULL) == 0) {
#endif
assert(listen_conn != NULL);
// The listen_conn global list is changed by server_socket(),
// which adds a new listening conn on port for each bindable
// host address.
//
// For example, after the call to server_socket(), there
// might be two new listening conn's -- one for localhost,
// another for 127.0.0.1.
//
conn *c = listen_conn;
while (c != NULL &&
c != listen_conn_orig) {
if (settings.verbose > 1) {
moxi_log_write(
"<%d cproxy listening on port %d\n",
c->sfd, port);
}
listening++;
// TODO: Listening conn's never seem to close,
// but need to handle cleanup if they do,
// such as if we handle graceful shutdown one day.
//
c->extra = conn_extra;
c->funcs = funcs;
c->protocol = protocol;
c = c->next;
}
}
return listening;
}
/* Finds the proxy_td associated with a worker thread.
*/
proxy_td *cproxy_find_thread_data(proxy *p, pthread_t thread_id) {
if (p != NULL) {
int i = thread_index(thread_id);
// 0 is the main listen thread, not a worker thread.
assert(i > 0);
assert(i < p->thread_data_num);
if (i > 0 && i < p->thread_data_num) {
return &p->thread_data[i];
}
}
return NULL;
}
void cproxy_init_upstream_conn(conn *c) {
assert(c != NULL);
// We're called once per client/upstream conn early in its
// lifecycle, on the worker thread, so it's a good place
// to record the proxy_td into the conn->extra.
//
assert(!is_listen_thread());
proxy *p = c->extra;
assert(p != NULL);
proxy_td *ptd = cproxy_find_thread_data(p, pthread_self());
assert(ptd != NULL);
ptd->stats.stats.num_upstream++;
ptd->stats.stats.tot_upstream++;
c->extra = ptd;
c->funcs = &cproxy_upstream_funcs;
}
void cproxy_init_downstream_conn(conn *c) {
downstream *d = c->extra;
assert(d != NULL);
d->ptd->stats.stats.num_downstream_conn++;
d->ptd->stats.stats.tot_downstream_conn++;
}
void cproxy_on_close_upstream_conn(conn *c) {
assert(c != NULL);
if (settings.verbose > 2) {
moxi_log_write("<%d cproxy_on_close_upstream_conn\n", c->sfd);
}
proxy_td *ptd = c->extra;
assert(ptd != NULL);
c->extra = NULL;
if (ptd->stats.stats.num_upstream > 0) {
ptd->stats.stats.num_upstream--;
}
// Delink from any reserved downstream.
//
for (downstream *d = ptd->downstream_reserved; d != NULL; d = d->next) {
bool found = false;
d->upstream_conn = conn_list_remove(d->upstream_conn, NULL,
c, &found);
if (d->upstream_conn == NULL) {
d->upstream_suffix = NULL;
d->upstream_suffix_len = 0;
d->upstream_retry = 0;
// Don't need to do anything else, as we'll now just
// read and drop any remaining inflight downstream replies.
// Eventually, the downstream will be released.
}
// If the downstream was reserved for this upstream conn,
// also clear the upstream from any multiget de-duplication
// tracking structures.
//
if (found) {
if (d->multiget != NULL) {
genhash_iter(d->multiget, multiget_remove_upstream, c);
}
// The downstream conn's might have iov's that
// point to the upstream conn's buffers. Also, the
// downstream conn might be in all sorts of states
// (conn_read, write, mwrite, pause), and we want
// to be careful about the downstream channel being
// half written.
//
// The safest, but inefficient, thing to do then is
// to close any conn_mwrite downstream conns.
//
ptd->stats.stats.tot_downstream_close_on_upstream_close++;
int n = mcs_server_count(&d->mst);
for (int i = 0; i < n; i++) {
conn *downstream_conn = d->downstream_conns[i];
if (downstream_conn != NULL &&
downstream_conn != NULL_CONN &&
downstream_conn->state == conn_mwrite) {
downstream_conn->msgcurr = 0;
downstream_conn->msgused = 0;
downstream_conn->iovused = 0;
cproxy_close_conn(downstream_conn);
}
}
}
}
// Delink from wait queue.
//
ptd->waiting_any_downstream_head =
conn_list_remove(ptd->waiting_any_downstream_head,
&ptd->waiting_any_downstream_tail,
c, NULL);
}
int delink_from_downstream_conns(conn *c) {
downstream *d = c->extra;
if (d == NULL) {
return -1;
}
c->extra = NULL;
int n = mcs_server_count(&d->mst);
int k = -1; // Index of conn.
for (int i = 0; i < n; i++) {
if (d->downstream_conns[i] == c) {
d->downstream_conns[i] = NULL;
if (settings.verbose > 2) {
moxi_log_write(
"<%d cproxy_on_close_downstream_conn quit_server\n",
c->sfd);
}
d->ptd->stats.stats.tot_downstream_quit_server++;
mcs_server_st_quit(mcs_server_index(&d->mst, i), 1);
assert(mcs_server_st_fd(mcs_server_index(&d->mst, i)) == -1);
k = i;
}
}
return k;
}
void cproxy_on_close_downstream_conn(conn *c) {
assert(c != NULL);
assert(c->sfd >= 0);
assert(c->state == conn_closing);
if (settings.verbose > 2) {
moxi_log_write("<%d cproxy_on_close_downstream_conn\n", c->sfd);
}
downstream *d = c->extra;
// Might have been set to NULL during cproxy_free_downstream().
// Or, when a downstream conn is in the thread-based free pool, it
// is not associated with any particular downstream.
//
if (d == NULL) {
// TODO: See if we need to remove the downstream conn from the
// thread-based free pool. This shouldn't happen, but we
// should then figure out how to put an assert() here.
//
return;
}
int k = delink_from_downstream_conns(c);
proxy_td *ptd = d->ptd;
assert(ptd);
if (ptd->stats.stats.num_downstream_conn > 0) {
ptd->stats.stats.num_downstream_conn--;
}
conn *uc_retry = NULL;
if (d->upstream_conn != NULL &&
d->downstream_used == 1) {
// TODO: Revisit downstream close error handling.
// Should we propagate error when...
// - any downstream conn closes?
// - all downstream conns closes?
// - last downstream conn closes? Current behavior.
//
if (d->upstream_suffix == NULL) {
d->upstream_suffix = "SERVER_ERROR proxy downstream closed\r\n";
d->upstream_suffix_len = 0;
d->upstream_retry = 0;
}
// We sometimes see that drive_machine/transmit will not see
// a closed connection error during conn_mwrite, possibly
// due to non-blocking sockets. Because of this, drive_machine
// thinks it has a successful downstream request send and
// moves the state forward trying to read a response from
// the downstream conn (conn_new_cmd, conn_read, etc), and
// only then do we finally see the conn close situation,
// ending up here. That is, drive_machine only
// seems to move to conn_closing from conn_read.
//
// If we haven't received any reply yet, we retry based
// on our cmd_retries counter.
//
// TODO: Reconsider retry behavior, is it right in all situations?
//
if (c->rcurr != NULL &&
c->rbytes == 0 &&
d->downstream_used_start == d->downstream_used &&
d->downstream_used_start == 1 &&
d->upstream_conn->next == NULL &&
d->behaviors_arr != NULL) {
if (k >= 0 && k < d->behaviors_num) {
int retry_max = d->behaviors_arr[k].downstream_retry;
if (d->upstream_conn->cmd_retries < retry_max) {
d->upstream_conn->cmd_retries++;
uc_retry = d->upstream_conn;
d->upstream_suffix = NULL;
d->upstream_suffix_len = 0;
d->upstream_retry = 0;
}
}
}
}
// Are we over-decrementing here, and in handling conn_pause?
//
// Case 1: we're in conn_pause, and socket is closed concurrently.
// We unpause due to reserve, we move to conn_write/conn_mwrite,
// fail and move to conn_closing. So, no over-decrement.
//
// Case 2: we're waiting for a downstream response in conn_new_cmd,
// and socket is closed concurrently. State goes to conn_closing,
// so, no over-decrement.
//
// Case 3: we've finished processing downstream response (in
// conn_parse_cmd or conn_nread), and the downstream socket
// is closed concurrently. We then move to conn_pause,
// and same as Case 1.
//
cproxy_release_downstream_conn(d, c);
// Setup a retry after unwinding the call stack.
// We use the work_queue, because our caller, conn_close(),
// is likely to blow away our fd if we try to reconnect
// right now.
//
if (uc_retry != NULL) {
if (settings.verbose > 2) {
moxi_log_write("%d cproxy retrying\n", uc_retry->sfd);
}
ptd->stats.stats.tot_retry++;
assert(uc_retry->thread);
assert(uc_retry->thread->work_queue);
work_send(uc_retry->thread->work_queue,
upstream_retry, ptd, uc_retry);
}
}
void upstream_retry(void *data0, void *data1) {
proxy_td *ptd = data0;
assert(ptd);
conn *uc = data1;
assert(uc);
cproxy_pause_upstream_for_downstream(ptd, uc);
}
void cproxy_add_downstream(proxy_td *ptd) {
assert(ptd != NULL);
assert(ptd->proxy != NULL);
if (ptd->downstream_num < ptd->downstream_max) {
if (settings.verbose > 2) {
moxi_log_write("cproxy_add_downstream %d %d\n",
ptd->downstream_num,
ptd->downstream_max);
}
// The config/behaviors will be NULL if the
// proxy is shutting down.
//
if (ptd->config != NULL &&
ptd->behavior_pool.arr != NULL) {
downstream *d =
cproxy_create_downstream(ptd->config,
ptd->config_ver,
&ptd->behavior_pool);
if (d != NULL) {
d->ptd = ptd;
ptd->downstream_tot++;
ptd->downstream_num++;
cproxy_release_downstream(d, true);
} else {
ptd->stats.stats.tot_downstream_create_failed++;
}
}
} else {
ptd->stats.stats.tot_downstream_max_reached++;
}
}
downstream *cproxy_reserve_downstream(proxy_td *ptd) {
assert(ptd != NULL);
// Loop in case we need to clear out downstreams
// that have outdated configs.
//
while (true) {
downstream *d;
d = ptd->downstream_released;
if (d == NULL) {
cproxy_add_downstream(ptd);
}
d = ptd->downstream_released;
if (d == NULL) {
return NULL;
}
ptd->downstream_released = d->next;
assert(d->upstream_conn == NULL);
assert(d->upstream_suffix == NULL);
assert(d->upstream_suffix_len == 0);
assert(d->upstream_retry == 0);
assert(d->downstream_used == 0);
assert(d->downstream_used_start == 0);
assert(d->merger == NULL);
assert(d->timeout_tv.tv_sec == 0);
assert(d->timeout_tv.tv_usec == 0);
assert(d->next_waiting == NULL);
d->upstream_conn = NULL;
d->upstream_suffix = NULL;
d->upstream_suffix_len = 0;
d->upstream_retry = 0;
d->upstream_retries = 0;
d->usec_start = 0;
d->downstream_used = 0;
d->downstream_used_start = 0;
d->merger = NULL;
d->timeout_tv.tv_sec = 0;
d->timeout_tv.tv_usec = 0;
d->next_waiting = NULL;
if (cproxy_check_downstream_config(d)) {
ptd->downstream_reserved =
downstream_list_remove(ptd->downstream_reserved, d);
ptd->downstream_released =
downstream_list_remove(ptd->downstream_released, d);
zstored_downstream_waiting_remove(d);
d->next = ptd->downstream_reserved;
ptd->downstream_reserved = d;
ptd->stats.stats.tot_downstream_reserved++;
return d;
}
cproxy_free_downstream(d);
}
}
bool cproxy_release_downstream(downstream *d, bool force) {
assert(d != NULL);
assert(d->ptd != NULL);
if (settings.verbose > 2) {
moxi_log_write("%d: release_downstream\n",
d->upstream_conn != NULL ?
d->upstream_conn->sfd : -1);
}
// Always release the timeout_event, even if we're going to retry,
// to avoid pegging CPU with leaked timeout_events.
//
if (d->timeout_tv.tv_sec != 0 ||
d->timeout_tv.tv_usec != 0) {
evtimer_del(&d->timeout_event);
}
d->timeout_tv.tv_sec = 0;
d->timeout_tv.tv_usec = 0;
// If we need to retry the command, we do so here,
// keeping the same downstream that would otherwise
// be released.
//
if (!force &&
d->upstream_retry > 0) {
d->upstream_retry = 0;
d->upstream_retries++;
// But, we can stop retrying if we've tried each server twice.
//
int max_retries = cproxy_max_retries(d);
if (d->upstream_retries <= max_retries) {
if (settings.verbose > 2) {
moxi_log_write("%d: release_downstream,"
" instead retrying %d, %d <= %d, %d\n",
d->upstream_conn->sfd,
d->upstream_retry,
d->upstream_retries, max_retries,
d->ptd->stats.stats.tot_retry);
}
d->ptd->stats.stats.tot_retry++;
if (cproxy_forward(d) == true) {
return true;
} else {
d->ptd->stats.stats.tot_downstream_propagate_failed++;
propagate_error(d);
}
} else {
if (settings.verbose > 2) {
moxi_log_write("%d: release_downstream,"
" skipping retry %d, %d > %d\n",
d->upstream_conn->sfd,
d->upstream_retry,
d->upstream_retries, max_retries);
}
}
}
// Record reserved_time histogram timings.
//
if (d->usec_start > 0) {
uint64_t ux = usec_now() - d->usec_start;
d->ptd->stats.stats.tot_downstream_reserved_time += ux;
if (d->ptd->stats.stats.max_downstream_reserved_time < ux) {
d->ptd->stats.stats.max_downstream_reserved_time = ux;
}
if (d->upstream_retries > 0) {
d->ptd->stats.stats.tot_retry_time += ux;
if (d->ptd->stats.stats.max_retry_time < ux) {
d->ptd->stats.stats.max_retry_time = ux;
}
}
downstream_reserved_time_sample(&d->ptd->stats, ux);
}
d->ptd->stats.stats.tot_downstream_released++;
// Delink upstream conns.
//
while (d->upstream_conn != NULL) {
if (d->merger != NULL) {
// TODO: Allow merger callback to be func pointer.
//
genhash_iter(d->merger,
protocol_stats_foreach_write,
d->upstream_conn);
if (update_event(d->upstream_conn, EV_WRITE | EV_PERSIST)) {
conn_set_state(d->upstream_conn, conn_mwrite);
} else {
d->ptd->stats.stats.err_oom++;
cproxy_close_conn(d->upstream_conn);
}
}
if (d->upstream_suffix != NULL) {
// Do a last write on the upstream. For example,
// the upstream_suffix might be "END\r\n" or other
// way to mark the end of a scatter-gather or
// multiline response.
//
if (settings.verbose > 2) {
if (d->upstream_suffix_len > 0) {
moxi_log_write("%d: release_downstream"
" writing suffix binary: %d\n",
d->upstream_conn->sfd,
d->upstream_suffix_len);
cproxy_dump_header(d->upstream_conn->sfd,
d->upstream_suffix);
} else {
moxi_log_write("%d: release_downstream"
" writing suffix ascii: %s\n",
d->upstream_conn->sfd,
d->upstream_suffix);
}
}
int suffix_len = d->upstream_suffix_len;
if (suffix_len == 0) {
suffix_len = strlen(d->upstream_suffix);
}
if (add_iov(d->upstream_conn,
d->upstream_suffix,
suffix_len) == 0 &&
update_event(d->upstream_conn, EV_WRITE | EV_PERSIST)) {
conn_set_state(d->upstream_conn, conn_mwrite);
} else {
d->ptd->stats.stats.err_oom++;
cproxy_close_conn(d->upstream_conn);
}
}
conn *curr = d->upstream_conn;
d->upstream_conn = d->upstream_conn->next;
curr->next = NULL;
}
// Free extra hash tables.
//
if (d->multiget != NULL) {
genhash_iter(d->multiget, multiget_foreach_free, d);
genhash_free(d->multiget);
d->multiget = NULL;
}
if (d->merger != NULL) {
genhash_iter(d->merger, protocol_stats_foreach_free, NULL);
genhash_free(d->merger);
d->merger = NULL;
}
d->upstream_conn = NULL;
d->upstream_suffix = NULL; // No free(), expecting a static string.
d->upstream_suffix_len = 0;
d->upstream_retry = 0;
d->upstream_retries = 0;
d->usec_start = 0;
d->downstream_used = 0;
d->downstream_used_start = 0;
d->multiget = NULL;
d->merger = NULL;
int n = mcs_server_count(&d->mst);
for (int i = 0; i < n; i++) {
conn *dc = d->downstream_conns[i];
d->downstream_conns[i] = NULL;
if (dc != NULL) {
zstored_release_downstream_conn(dc, false);
}
}
// If this downstream still has the same configuration as our top-level
// proxy config, go back onto the available, released downstream list.
//