-
Notifications
You must be signed in to change notification settings - Fork 11
/
omcache.c
1764 lines (1629 loc) · 57 KB
/
omcache.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
/*
* OMcache - a memcached client library
*
* Copyright (c) 2013-2014, Oskari Saarenmaa <[email protected]>
* All rights reserved.
*
* This file is under the Apache License, Version 2.0.
* See the file `LICENSE` for details.
*
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <poll.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/types.h>
#include <sys/uio.h>
#include "omcache_priv.h"
#ifdef WITH_ASYNCNS
#include <asyncns.h>
#endif // WITH_ASYNCNS
#define max(a,b) ({__typeof__(a) a_ = (a), b_ = (b); a_ > b_ ? a_ : b_; })
#define min(a,b) ({__typeof__(a) a_ = (a), b_ = (b); a_ < b_ ? a_ : b_; })
#define omc_log(pri,fmt,...) ({ \
if (mc->log_cb && (pri) <= mc->log_level) { \
char *log_msg_; \
if (asprintf(&log_msg_, "[%.03f] omcache/%s:%d: " fmt, \
(omc_msec() - mc->init_msec) / 1000.0, __func__, __LINE__, __VA_ARGS__) > 0) { \
mc->log_cb(mc->log_context, (pri), log_msg_); \
free(log_msg_); \
} \
} })
#define omc_srv_log(pri,srv,fmt,...) \
omc_log(pri, "[%s:%s] " fmt, (srv)->hostname, (srv)->port, __VA_ARGS__)
#ifndef NDEBUG
# define omc_debug(...) omc_log(LOG_DEBUG, __VA_ARGS__)
# define omc_srv_debug(...) omc_srv_log(LOG_DEBUG, __VA_ARGS__)
#else
# define omc_debug(...) do {} while(0)
# define omc_srv_debug(...) do {} while(0)
#endif
typedef struct omc_buf_s
{
unsigned char *base;
unsigned char *end;
unsigned char *r;
unsigned char *w;
} omc_buf_t;
typedef struct omc_srv_s
{
int list_index;
int sock;
char *hostname;
char *port;
struct addrinfo *addrs;
struct addrinfo *addrp;
#ifdef WITH_ASYNCNS
asyncns_query_t *nsq;
bool ans_addrs;
#endif // WITH_ASYNCNS
int64_t last_gai;
int64_t conn_timeout;
uint32_t last_req_recvd;
uint32_t last_req_sent;
uint32_t last_req_sent_nq;
uint32_t active_requests;
omc_buf_t send_buffer;
omc_buf_t recv_buffer;
uint32_t keep_recv_buffer_iteration;
bool disabled;
bool connected;
int64_t retry_at;
int64_t dead_timeout_start;
int64_t expected_noop;
} omc_srv_t;
typedef struct omc_ketama_point_s
{
uint32_t hash_value;
omc_srv_t *srv;
} omc_ketama_point_t;
typedef struct omc_ketama_s
{
uint32_t point_count;
omc_ketama_point_t points[];
} omc_ketama_t;
struct omcache_s
{
int64_t init_msec;
uint32_t req_id;
omc_srv_t **servers;
struct pollfd *server_polls;
ssize_t server_count;
omc_int_hash_table_t *fd_table;
#ifdef WITH_ASYNCNS
asyncns_t *ans;
int ans_fd;
#endif // WITH_ASYNCNS
// distribution
omc_ketama_t *ketama;
omcache_dist_t *dist_method;
// settings
omcache_log_callback_func *log_cb;
void *log_context;
int log_level;
omcache_response_callback_func *resp_cb;
void *resp_cb_context;
size_t recv_buffer_max;
size_t send_buffer_max;
uint32_t connect_timeout_msec;
uint32_t reconnect_timeout_msec;
uint32_t dead_timeout_msec;
bool buffer_writes;
struct
{
bool active;
uint32_t iteration;
uint32_t min_req;
uint32_t max_req;
uint32_t count;
uint32_t found;
omc_hash_table_t *table;
// values, values_size and values_returned are reset on each omcache_io call
omcache_value_t *values;
size_t values_size;
size_t values_returned;
} lookup;
};
static int omc_srv_free(omcache_t *mc, omc_srv_t *srv);
static int omc_srv_connect(omcache_t *mc, omc_srv_t *srv);
static int omc_srv_io(omcache_t *mc, omc_srv_t *srv);
static void omc_srv_reset(omcache_t *mc, omc_srv_t *srv, const char *log_msg);
static int omc_srv_send_noop(omcache_t *mc, omc_srv_t *srv);
static omc_ketama_t *omc_ketama_create(omcache_t *mc);
static uint32_t omc_lookup_discard_requests(omcache_t *mc, omc_srv_t *srv, uint32_t max_req);
static bool omc_is_request_quiet(uint8_t opcode);
static inline int64_t omc_msec();
static int g_iov_max = 0;
omcache_t *omcache_init(void)
{
if (g_iov_max == 0)
g_iov_max = sysconf(_SC_IOV_MAX);
omcache_t *mc = calloc(1, sizeof(*mc));
mc->init_msec = omc_msec();
mc->req_id = time(NULL);
mc->recv_buffer_max = 1024 * (1024 + 32);
mc->send_buffer_max = 1024 * (1024 * 10);
mc->connect_timeout_msec = 10 * 1000;
mc->reconnect_timeout_msec = 10 * 1000;
mc->dead_timeout_msec = 10 * 1000;
mc->dist_method = &omcache_dist_libmemcached_ketama;
#ifdef WITH_ASYNCNS
mc->ans = asyncns_new(1);
mc->ans_fd = asyncns_fd(mc->ans);
#endif // WITH_ASYNCNS
return mc;
}
int omcache_free(omcache_t *mc)
{
if (mc->servers)
{
for (off_t i=0; i<mc->server_count; i++)
{
if (mc->servers[i])
{
omc_srv_free(mc, mc->servers[i]);
mc->servers[i] = NULL;
}
}
memset(mc->servers, 'L', mc->server_count * sizeof(void *));
free(mc->servers);
}
free(mc->server_polls);
free(mc->ketama);
omc_int_hash_table_free(mc->fd_table);
omc_hash_table_free(mc->lookup.table);
#ifdef WITH_ASYNCNS
asyncns_free(mc->ans);
#endif // WITH_ASYNCNS
memset(mc, 'M', sizeof(*mc));
free(mc);
return OMCACHE_OK;
}
const char *omcache_strerror(int rc)
{
switch (rc)
{
case OMCACHE_OK: return "Success";
case OMCACHE_NOT_FOUND: return "Key not found from memcached";
case OMCACHE_KEY_EXISTS: return "Conflicting key exists in memcached";
case OMCACHE_TOO_LARGE_VALUE: return "Value size exceeds maximum";
case OMCACHE_NOT_STORED: return "Append or prepend value not stored";
case OMCACHE_DELTA_BAD_VALUE: return "Existing value can not be incremented or decremented";
case OMCACHE_FAIL: return "Command failed in memcached";
case OMCACHE_AGAIN: return "Call would block, try again";
case OMCACHE_INVALID: return "Invalid parameters";
case OMCACHE_BUFFERED: return "Data buffered in OMcache";
case OMCACHE_BUFFER_FULL: return "Buffer full, command dropped";
case OMCACHE_NO_SERVERS: return "No server available";
case OMCACHE_SERVER_FAILURE: return "Failure communicating to server";
default: return "Unknown";
}
}
static int omc_map_mc_status_to_ret_code(protocol_binary_response_status status)
{
switch (status)
{
case PROTOCOL_BINARY_RESPONSE_SUCCESS: return OMCACHE_OK;
case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: return OMCACHE_NOT_FOUND;
case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: return OMCACHE_KEY_EXISTS;
case PROTOCOL_BINARY_RESPONSE_E2BIG: return OMCACHE_TOO_LARGE_VALUE;
case PROTOCOL_BINARY_RESPONSE_NOT_STORED: return OMCACHE_NOT_STORED;
case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: return OMCACHE_DELTA_BAD_VALUE;
default:
return OMCACHE_FAIL;
}
}
void omcache_log_stderr(void *context,
int level,
const char *msg)
{
fprintf(stderr, "%s%s %s\n",
context ? (const char *) context : "",
level == LOG_ERR ? "ERROR" :
level == LOG_WARNING ? "WARNING" :
level == LOG_NOTICE ? "NOTICE" :
level == LOG_INFO ? "INFO" :
level == LOG_DEBUG ? "DEBUG" :
"?", msg);
}
static inline int64_t omc_msec()
{
struct timespec ts;
#ifdef CLOCK_MONOTONIC_COARSE
if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == -1)
#endif
#ifdef CLOCK_MONOTONIC
clock_gettime(CLOCK_MONOTONIC, &ts);
#else
clock_gettime(CLOCK_REALTIME, &ts);
#endif
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
static omc_srv_t *omc_srv_init(const char *hostname)
{
const char *p;
omc_srv_t *srv = calloc(1, sizeof(*srv));
srv->sock = -1;
srv->list_index = -1;
if (*hostname == '[' && (p = strchr(hostname, ']')) != NULL)
{
// handle [addr]:port form
srv->hostname = strndup(hostname + 1, p - (hostname + 1));
if (*(p + 1) == ':')
srv->port = strdup(p + 2);
else
srv->port = strdup(MC_PORT);
}
else if ((p = strchr(hostname, ':')) != NULL)
{
// handle hostname:port form
srv->hostname = strndup(hostname, p - hostname);
srv->port = strdup(p + 1);
}
else
{
// just use hostname as-is and default MC port
srv->hostname = strdup(hostname);
srv->port = strdup(MC_PORT);
}
return srv;
}
static void omc_srv_free_addrs(omcache_t *mc omc_attribute_unused, omc_srv_t *srv)
{
#ifdef WITH_ASYNCNS
if (srv->ans_addrs)
{
asyncns_freeaddrinfo(srv->addrs);
srv->ans_addrs = false;
srv->addrs = NULL;
srv->addrp = NULL;
}
if (srv->nsq)
{
asyncns_cancel(mc->ans, srv->nsq);
srv->nsq = NULL;
}
#endif // WITH_ASYNCNS
if (srv->addrs)
{
freeaddrinfo(srv->addrs);
srv->addrs = NULL;
srv->addrp = NULL;
}
}
static int omc_srv_free(omcache_t *mc, omc_srv_t *srv)
{
if (srv->sock >= 0)
{
shutdown(srv->sock, SHUT_RDWR);
close(srv->sock);
omc_int_hash_table_del(mc->fd_table, srv->sock);
srv->sock = -1;
}
omc_srv_free_addrs(mc, srv);
free(srv->send_buffer.base);
free(srv->recv_buffer.base);
free(srv->hostname);
free(srv->port);
memset(srv, 'S', sizeof(*srv));
free(srv);
return OMCACHE_OK;
}
static int omc_srv_cmp(const omc_srv_t *s1, const omc_srv_t *s2)
{
int res = strcmp(s1->hostname, s2->hostname);
if (res != 0)
return res;
return strcmp(s1->port, s2->port);
}
static int omc_srvp_cmp(const void *sp1, const void *sp2)
{
return omc_srv_cmp(*(omc_srv_t * const *) sp1, *(omc_srv_t * const *) sp2);
}
int omcache_set_servers(omcache_t *mc, const char *servers)
{
omc_srv_t **srv_new = NULL;
ssize_t srv_new_count = 0, srv_new_size = 0, srv_len;
char *srv_dup = strdup(servers), *srv, *p;
// parse and sort comma-delimited list of servers and strip whitespace
for (srv=srv_dup; srv; srv=p)
{
p = strchr(srv, ',');
if (p)
*p++ = 0;
while (*srv && isspace(*srv))
srv++;
srv_len = strlen(srv);
while (srv_len > 0 && isspace(srv[srv_len-1]))
srv[--srv_len] = 0;
if (srv_len == 0)
continue;
if (srv_new_count >= srv_new_size)
{
srv_new_size += 16;
srv_new = realloc(srv_new, sizeof(*srv_new) * srv_new_size);
}
srv_new[srv_new_count++] = omc_srv_init(srv);
}
free(srv_dup);
qsort(srv_new, srv_new_count, sizeof(*srv_new), omc_srvp_cmp);
// preallocated poll-structures for all servers
if (mc->server_count != srv_new_count)
mc->server_polls = realloc(mc->server_polls, srv_new_count * sizeof(*mc->server_polls));
// remove old servers that weren't on the new list and add the new ones
if (mc->server_count)
{
ssize_t i=0, j=0;
while (i < mc->server_count)
{
int res = (j >= srv_new_count) ? -1 : omc_srv_cmp(mc->servers[i], srv_new[j]);
if (res == 0)
{
// the same server is on both lists:
// move it to the new list
omc_srv_free(mc, srv_new[j]);
srv_new[j++] = mc->servers[i++];
}
else if (res < 0)
{
// server on old list is before the server on new list:
// it's not on the new list at all
omc_srv_free(mc, mc->servers[i++]);
}
else if (res > 0)
{
// server on old list is after the server on new list:
// it may be included on the new list as well
j++;
}
}
free(mc->servers);
}
mc->servers = srv_new;
mc->server_count = srv_new_count;
// reset list indices and fd_table
mc->fd_table = omc_int_hash_table_init(mc->fd_table, mc->server_count);
for (ssize_t i=0; i<mc->server_count; i++)
{
omc_srv_debug(mc->servers[i], "server #%zd", i);
mc->servers[i]->list_index = i;
if (mc->servers[i]->sock >= 0)
omc_int_hash_table_add(mc->fd_table, mc->servers[i]->sock, i);
}
// rerun distribution
free(mc->ketama);
mc->ketama = omc_ketama_create(mc);
return OMCACHE_OK;
}
int omcache_set_distribution_method(omcache_t *mc, omcache_dist_t *method)
{
mc->dist_method = method;
// rerun distribution
free(mc->ketama);
mc->ketama = omc_ketama_create(mc);
return OMCACHE_OK;
}
int omcache_set_log_callback(omcache_t *mc, int level, omcache_log_callback_func *func, void *context)
{
mc->log_cb = func;
mc->log_context = context;
mc->log_level = level ? level : LOG_DEBUG - 1;
return OMCACHE_OK;
}
int omcache_set_connect_timeout(omcache_t *mc, uint32_t msec)
{
mc->connect_timeout_msec = msec;
return OMCACHE_OK;
}
int omcache_set_reconnect_timeout(omcache_t *mc, uint32_t msec)
{
mc->reconnect_timeout_msec = msec;
return OMCACHE_OK;
}
int omcache_set_dead_timeout(omcache_t *mc, uint32_t msec)
{
mc->dead_timeout_msec = msec;
return OMCACHE_OK;
}
int omcache_set_recv_buffer_max_size(omcache_t *mc, size_t size)
{
mc->recv_buffer_max = size;
return OMCACHE_OK;
}
int omcache_set_send_buffer_max_size(omcache_t *mc, size_t size)
{
mc->send_buffer_max = size;
return OMCACHE_OK;
}
int omcache_set_response_callback(omcache_t *mc, omcache_response_callback_func *resp_cb, void *resp_cb_context)
{
mc->resp_cb = resp_cb;
mc->resp_cb_context = resp_cb_context;
return OMCACHE_OK;
}
struct pollfd *omcache_poll_fds(omcache_t *mc, int *nfds, int *poll_timeout)
{
int n, i;
#ifdef WITH_ASYNCNS
bool poll_ans = false;
#endif // WITH_ASYNCNS
int64_t now = omc_msec();
*poll_timeout = mc->dead_timeout_msec;
for (i=n=0; i<mc->server_count; i++)
{
omc_srv_t *srv = mc->servers[i];
mc->server_polls[n].events = 0;
if (srv->last_req_sent != srv->last_req_sent_nq)
{
omc_srv_send_noop(mc, srv);
}
if (srv->last_req_recvd < srv->last_req_sent_nq)
{
omc_srv_debug(srv, "polling %d for POLLIN", srv->sock);
mc->server_polls[n].events |= POLLIN;
}
if (srv->send_buffer.w != srv->send_buffer.r || srv->conn_timeout > 0)
{
omc_srv_debug(srv, "polling %d for POLLOUT", srv->sock);
mc->server_polls[n].events |= POLLOUT;
}
if (mc->server_polls[n].events != 0 || srv->conn_timeout > 0)
{
if (srv->sock < 0)
omc_srv_connect(mc, srv);
// make sure poll timeout is at connection timeout, and in
// case it has already expired, set connection timeout to a
// special value (1) so next time we get here we know we
// weren't able to establish a connection in time.
if (srv->conn_timeout > 0)
{
omc_srv_debug(srv, "polling %d for POLLIN (connect)", srv->sock);
mc->server_polls[n].events |= POLLIN;
if (srv->conn_timeout == 1)
{
errno = ETIME;
omc_srv_reset(mc, srv, "timeout waiting for connect");
}
else if (now >= srv->conn_timeout)
{
srv->conn_timeout = 1;
*poll_timeout = 1;
}
else
{
*poll_timeout = min(*poll_timeout, srv->conn_timeout - now);
}
}
if (srv->sock >= 0)
{
mc->server_polls[n].fd = srv->sock;
mc->server_polls[n].revents = 0;
n ++;
}
}
#ifdef WITH_ASYNCNS
if (srv->nsq && !poll_ans)
{
// NOTE: we don't allocate extra space in 'server_polls' for async
// ns polling because we can't poll for both the server and for
// async ns resuls for it.
omc_srv_debug(srv, "polling asyncns fd %d for POLLIN", mc->ans_fd);
poll_ans = true;
mc->server_polls[n].fd = mc->ans_fd;
mc->server_polls[n].events = POLLIN;
mc->server_polls[n++].revents = 0;
}
#endif // WITH_ASYNCNS
}
*nfds = n;
return mc->server_polls;
}
static int omc_ketama_point_cmp(const void *v1, const void *v2)
{
const omc_ketama_point_t *p1 = v1, *p2 = v2;
if (p1->hash_value == p2->hash_value)
return 0;
return p1->hash_value > p2->hash_value ? 1 : -1;
}
static omc_ketama_t *omc_ketama_create(omcache_t *mc)
{
uint32_t pps = mc->dist_method->points_per_server;
uint32_t eps = mc->dist_method->entries_per_point;
size_t cidx = 0, total_points = mc->server_count * pps * eps;
omc_ketama_t *ktm = (omc_ketama_t *) malloc(sizeof(omc_ketama_t) + total_points * sizeof(omc_ketama_point_t));
for (ssize_t i = 0; i < mc->server_count; i ++)
{
omc_srv_t *srv = mc->servers[i];
uint32_t hashes[eps];
for (size_t p = 0; p < pps; p ++)
{
uint32_t sp_count = mc->dist_method->point_hash_func(srv->hostname, srv->port, p, hashes);
for (uint32_t e = 0; e < sp_count; e ++)
ktm->points[cidx++] = (omc_ketama_point_t) { .srv = srv, .hash_value = hashes[e] };
}
}
ktm->point_count = cidx;
qsort(ktm->points, ktm->point_count, sizeof(omc_ketama_point_t), omc_ketama_point_cmp);
return ktm;
}
static int omc_ketama_lookup(omcache_t *mc, const unsigned char *key, size_t key_len)
{
uint32_t hash_value = mc->dist_method->key_hash_func(key, key_len);
const omc_ketama_point_t *first = mc->ketama->points, *last = mc->ketama->points + mc->ketama->point_count;
const omc_ketama_point_t *left = first, *right = last, *selected;
bool wrap = false;
int64_t now = 0;
while (left < right)
{
const omc_ketama_point_t *middle = left + (right - left) / 2;
if (middle->hash_value < hash_value)
left = middle + 1;
else
right = middle;
}
// skip disabled servers
size_t skipped = 0;
for (selected = (right == last) ? first : right;
selected == last || selected->srv->disabled;
selected++)
{
if (selected != last)
{
// try to bring disabled servers back online but don't select them
// yet as we need to (asynchronously) verify that they're usable
if (selected->srv->disabled)
{
if (now == 0)
now = omc_msec();
// only attempt io with servers once per millisecond
if (now > selected->srv->retry_at)
{
selected->srv->retry_at = now;
omc_srv_io(mc, selected->srv);
}
}
skipped ++;
continue;
}
if (wrap)
{
omc_log(LOG_ERR, "%s", "all servers are disabled");
return -1;
}
wrap = true;
selected = first;
}
if (skipped)
omc_log(LOG_INFO, "ketama skipped %zu disabled server points", skipped);
return selected->srv->list_index;
}
int omcache_server_index_for_key(omcache_t *mc, const unsigned char *key, size_t key_len)
{
if (mc->server_count > 1)
return omc_ketama_lookup(mc, key, key_len);
return 0;
}
static void omc_srv_disable(omcache_t *mc, omc_srv_t *srv)
{
// disable server until reconnect timeout
// log at higher level if it's not yet disabled
omc_srv_log(srv->disabled ? LOG_INFO : LOG_NOTICE, srv,
"disabling server for %u msec", mc->reconnect_timeout_msec);
srv->retry_at = omc_msec() + mc->reconnect_timeout_msec;
srv->disabled = true;
// clear addrinfo cache to force fresh addrs to be used on retry
omc_srv_free_addrs(mc, srv);
}
static void
omc_srv_reset(omcache_t *mc, omc_srv_t *srv, const char *log_msg)
{
omc_srv_log(LOG_NOTICE, srv, "reset: %s (%s)", log_msg, strerror(errno));
if (srv->sock != -1)
{
close(srv->sock);
omc_int_hash_table_del(mc->fd_table, srv->sock);
}
srv->connected = false;
srv->sock = -1;
srv->conn_timeout = 0;
srv->last_req_recvd = 0;
srv->last_req_sent = 0;
srv->last_req_sent_nq = 0;
srv->recv_buffer.r = srv->recv_buffer.base;
srv->recv_buffer.w = srv->recv_buffer.base;
srv->send_buffer.r = srv->send_buffer.base;
srv->send_buffer.w = srv->send_buffer.base;
if (srv->expected_noop)
{
omc_srv_disable(mc, srv);
}
omc_lookup_discard_requests(mc, srv, UINT32_MAX);
}
// make sure a connection is established to the server, if not, try to set it up
static int omc_srv_connect(omcache_t *mc, omc_srv_t *srv)
{
if (srv->connected)
{
return OMCACHE_OK; // all is good
}
int64_t now = omc_msec();
if (srv->disabled && now < srv->retry_at)
{
return OMCACHE_NO_SERVERS;
}
if (srv->sock == -1)
{
int err;
#ifdef WITH_ASYNCNS
if (srv->nsq)
{
err = asyncns_getaddrinfo_done(mc->ans, srv->nsq, &srv->addrs);
if (err != EAI_AGAIN)
srv->nsq = NULL;
if (err && (err != EAI_AGAIN || now - srv->last_gai >= mc->connect_timeout_msec))
{
omc_srv_log(LOG_WARNING, srv, "asyncns_getaddrinfo: %s", gai_strerror(err));
omc_srv_reset(mc, srv, "asyncns_getaddrinfo failed");
omc_srv_disable(mc, srv);
return OMCACHE_SERVER_FAILURE;
}
else if (err == EAI_AGAIN)
{
return OMCACHE_AGAIN;
}
srv->ans_addrs = true;
srv->addrp = srv->addrs;
srv->last_gai = now;
}
#endif // WITH_ASYNCNS
// clear addresses if we refreshed them more than a minute ago
if (now - srv->last_gai > 60000)
omc_srv_free_addrs(mc, srv);
// refresh the hosts addresses if needed
if (srv->addrs == NULL)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
// We'll first see if the address is numeric to avoid all the
// resolution overhead of a regular lookup which happens even if
// the caller supplied a numeric host and service and then fall
// back to AI_ADDRCONFIG lookup if that fails.
hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
err = getaddrinfo(srv->hostname, srv->port, &hints, &srv->addrs);
if (err == EAI_NONAME)
{
hints.ai_flags = AI_ADDRCONFIG;
#ifdef WITH_ASYNCNS
srv->nsq = asyncns_getaddrinfo(mc->ans, srv->hostname, srv->port, &hints);
srv->last_gai = now;
return OMCACHE_AGAIN;
#else // WITH_ASYNCNS
// NOTE: this can block
err = getaddrinfo(srv->hostname, srv->port, &hints, &srv->addrs);
#endif // WITH_ASYNCNS
}
if (err != 0)
{
omc_srv_log(LOG_WARNING, srv, "getaddrinfo: %s", gai_strerror(err));
omc_srv_reset(mc, srv, "getaddrinfo failed");
omc_srv_disable(mc, srv);
return OMCACHE_SERVER_FAILURE;
}
srv->addrp = srv->addrs;
srv->last_gai = now;
}
while (srv->addrp)
{
int sock = socket(srv->addrp->ai_family, srv->addrp->ai_socktype, srv->addrp->ai_protocol);
if (sock < 0)
{
omc_srv_reset(mc, srv, "socket creation failed");
}
else if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
{
omc_srv_reset(mc, srv, "fcntl(sock, F_SETFL, O_NONBLOCK)");
close(sock);
sock = -1;
}
else if (fcntl(sock, F_SETFD, FD_CLOEXEC) < 0)
{
omc_srv_reset(mc, srv, "fcntl(sock, F_SETFD, FD_CLOEXEC)");
close(sock);
sock = -1;
}
if (sock < 0)
{
omc_srv_disable(mc, srv);
return OMCACHE_SERVER_FAILURE;
}
omc_int_hash_table_add(mc->fd_table, sock, srv->list_index);
err = connect(sock, srv->addrp->ai_addr, srv->addrp->ai_addrlen);
srv->dead_timeout_start = now;
srv->addrp = srv->addrp->ai_next;
srv->sock = sock;
if (err == 0)
{
// connection established
break;
}
else if (errno == EINPROGRESS)
{
srv->conn_timeout = now + mc->connect_timeout_msec;
omc_srv_debug(srv, "%s", "connection in progress");
return OMCACHE_AGAIN;
}
else
{
omc_srv_reset(mc, srv, "connect failed");
}
}
if (srv->sock == -1)
{
omc_srv_reset(mc, srv, "no connection established");
// disable server if we've walked through the address list and
// weren't able to conncet to any address
if (srv->addrp == NULL)
omc_srv_disable(mc, srv);
return OMCACHE_SERVER_FAILURE;
}
}
else if (srv->conn_timeout > 0)
{
struct pollfd pfd = { .fd = srv->sock, .events = POLLOUT, .revents = 0, };
if (poll(&pfd, 1, 0) == 0)
{
if (omc_msec() >= srv->conn_timeout)
{
// timeout
errno = ETIME;
omc_srv_reset(mc, srv, "connection timeout");
}
return OMCACHE_AGAIN;
}
int err;
socklen_t err_len = sizeof(err);
if (getsockopt(srv->sock, SOL_SOCKET, SO_ERROR, &err, &err_len) == -1)
{
omc_srv_log(LOG_WARNING, srv, "getsockopt failed: %s", strerror(errno));
err = errno;
}
if (err)
{
errno = err;
omc_srv_reset(mc, srv, "async connect failed");
return OMCACHE_AGAIN;
}
}
srv->connected = true;
srv->conn_timeout = 0;
srv->dead_timeout_start = 0;
srv->addrp = srv->addrs;
omc_srv_log(LOG_INFO, srv, "%s", "connected");
omc_srv_send_noop(mc, srv);
srv->expected_noop = mc->req_id;
return OMCACHE_OK;
}
static bool omc_return_value(omcache_t *mc, omc_srv_t *srv, omcache_value_t *value,
uint32_t req_id, bool multi_req)
{
// pass value to response callback (if any)
if (mc->resp_cb)
mc->resp_cb(mc, value, mc->resp_cb_context);
// add it to response list if it matches lookup range
if (!mc->lookup.active)
return false;
bool final = (multi_req == false) || (mc->lookup.values_size <= mc->lookup.values_returned);
omcache_req_t *req = (final ? omc_hash_table_del : omc_hash_table_find)(mc->lookup.table, req_id);
if (req == NULL)
return false;
if (final)
{
mc->lookup.found ++;
srv->active_requests --;
}
omc_srv_debug(srv, "expected response %u (%u / %u): %s",
req_id, mc->lookup.found, mc->lookup.count,
omcache_strerror(value->status));
if (mc->lookup.values_size <= mc->lookup.values_returned)
{
if (mc->lookup.values_size)
omc_srv_log(LOG_WARNING, srv,
"no space to store response %u "
"in a buffer of %zu entries, dropping response",
req_id, mc->lookup.values_size);
return false;
}
mc->lookup.values[mc->lookup.values_returned++] = *value;
return true;
}
static uint32_t omc_lookup_discard_requests(omcache_t *mc, omc_srv_t *srv, uint32_t max_req)
{
if (!mc->lookup.active || srv->active_requests == 0)
return 0;
uint32_t discarded = 0;
for (uint32_t bucket = 0; bucket < mc->lookup.table->size; bucket ++)
for (omc_hash_node_t *node = mc->lookup.table->buckets[bucket], *next_node = NULL;
node != NULL; node = next_node)
{
omcache_req_t *req = (omcache_req_t *) node->val;
next_node = node->next;
if (req->server_index == srv->list_index && req->header.opaque < max_req)
{
// response "found" to never arrive
discarded ++;
if (max_req == UINT32_MAX || !omc_is_request_quiet(req->header.opcode))
{
// server failed (called from omc_srv_reset or request wasn't quiet)
omcache_value_t value = {
.status = OMCACHE_SERVER_FAILURE,
.key = req->key,
.key_len = be16toh(req->header.keylen),
.data = NULL,
};
omc_return_value(mc, srv, &value, req->header.opaque, false);
}
else
{
mc->lookup.found ++;
srv->active_requests --;
omc_hash_table_del(mc->lookup.table, node->key);
}
}
}
// log a differnet message if we're discarding everything and when we're
// discarding quiet messages when seeing a no-op
if (max_req == UINT32_MAX)
omc_log(LOG_NOTICE, "discarded %u requests", discarded);
else
omc_debug("discarded %u quiet requests", discarded);
return discarded;
}
static int omc_buffer_realloc(omc_buf_t *buf, size_t buf_max, uint32_t required)
{
size_t space = buf->end - buf->w, buffered = buf->w - buf->r;
if (space >= required)
return OMCACHE_OK;
// move the contents of the buffer to its beginning
if (buf->r != buf->base)
{
memmove(buf->base, buf->r, buffered);
space = buf->end - buf->base - buffered;
}
// allocate more space if required
if (space < required)
{
if ((size_t) (buf->end - buf->base) + required > buf_max)
return OMCACHE_BUFFER_FULL;
size_t new_size = min(buf_max, buffered + required + 30000);
buf->base = realloc(buf->base, new_size);
buf->end = buf->base + new_size;
}
buf->r = buf->base;
buf->w = buf->base + buffered;
return OMCACHE_OK;
}
static int omc_do_read(omcache_t *mc, omc_srv_t *srv, size_t msg_size)
{
// make sure we have room for at least the requested bytes, but read as much as possible
size_t space = srv->recv_buffer.end - srv->recv_buffer.w;
if (space < msg_size)
{
if (srv->keep_recv_buffer_iteration == mc->lookup.iteration)
return OMCACHE_BUFFER_FULL;