forked from naver/arcus-memcached
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arcus_zk.c
2093 lines (1863 loc) · 71.6 KB
/
arcus_zk.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 -*- */
/*
* arcus-memcached - Arcus memory cache server
* Copyright 2010-2014 NAVER Corp.
* Copyright 2015 JaM2in Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Arcus incorporates memcached instance as a ephemeral entity
Here's how memcached participates in Arcus cluster
1. get local IP address
2. connect to Zookeeper ensemble
3. sync "/arcus/cache_server_mapping"
for latest provisioned cache server
4. get child of "/arcus/cache_server_mapping/{ip}:{port}" znode
to get service code
this service code is a string that indicates which service this
cache server belongs to
ie. /arcus/cache_server_mapping/10.0.0.1:11211/{svc}
5. create an ephemeral "/arcus/cache_list/{svc}/{ip}:{port}-{hostname}" znode
to indicate that this server is participating in Arcus {svc} cluster
{port} is the memcached listen port
hostname is a redudant information to easily identify the server
the memcached memory capacity is stored in the znode's data
6. create "/arcus/cache_server_log/{date}/{ip}:{port}-{hostname}-" sequential znode
this is to log join and leave activity for later debugging or post-mortem
In global watcher callback routine, we chose not to restart/reconnect to
Zookeeper ensemble (when session expires), because this may create stale cache
entry access. We need to restart the whole memcached process to flush its content
before rejoin the Arcus cluster. We need to force restart of memcached (/etc/inittab)
*/
#include <config.h>
#ifdef ENABLE_ZK_INTEGRATION
#include <assert.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <zookeeper.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdbool.h>
#include <sysexits.h>
#include <limits.h>
#include "arcus_zk.h"
#ifdef ENABLE_CLUSTER_AWARE
#include "cluster_config.h"
#endif
/* zookeeper.h unfortunately includes a lot of other headers. One of
* them (recordio.h) unconditionally defines htonll. memcached.h also
* includes so many headers. util.h defines htonll, which conflicts
* with the one in zookeeper.h. As a workaround, define HAVE_HTONLL
* here to prevent util.h from defining htonll again.
*
* All we need from memcached.h is ADMIN_CLIENT_IP...
*/
#define HAVE_HTONLL 1
#include "memcached.h"
/* Kill server if disconnected from zookeeper for too long */
//#define ENABLE_SUICIDE_UPON_DISCONNECT 1
// Recv. timeout governs ZK heartbeat period, reconnect timeout
// as well as ZK session timeout
//
// Below sets 30 sec. session timeout, 20 sec Zookeeper ensemble timeout,
// and 10 second heartbeat period
#define DEFAULT_ZK_TO 30000 // ZK session timeout in msec (server tick time is 2 sec, min is 4 sec)
#define MAX_ZK_TO 300 // Max allowable session timeout in sec
#define MIN_ZK_TO 10 // Min 10 seconds, in line with the current heartbeat timeout
#define ZK_WATCH 1
#define ZK_NOWATCH 0
#define SYSLOGD_PORT 514 // UDP syslog port #
/* One heartbeat every 3 seconds. */
#define HEART_BEAT_PERIOD 3 /* sec */
/* If consecutive heartbeats fail, consider memcached dead and commit
* suicide. If the accumulated latency of consecutive heartbeats is
* over the following HEART_BEAT_FAILSTOP value, it does fail-stop.
*/
#define HEART_BEAT_MIN_FAILSTOP 3000 /* msec */
#define HEART_BEAT_DFT_FAILSTOP 60000 /* msec */
#define HEART_BEAT_MAX_FAILSTOP 300000 /* msec */
/* If hearbeat takes more than timeout msec, consider it failed. */
#define HEART_BEAT_MIN_TIMEOUT 50 /* msec */
#define HEART_BEAT_DFT_TIMEOUT 10000 /* msec */
#define HEART_BEAT_MAX_TIMEOUT HEART_BEAT_MAX_FAILSTOP /* msec */
#define MAX_SERVICECODE_LENGTH 128
#define MAX_HOSTNAME_LENGTH 128
static const char *zk_root = NULL;
static const char *zk_map_dir = "cache_server_mapping";
static const char *zk_log_dir = "cache_server_log";
static const char *zk_cache_dir = "cache_list";
static const char *mc_hb_command = "set arcus:zk-ping 1 0 1\r\n1\r\n";
typedef struct {
char *ensemble_list; /* ZK ensemble IP:port list */
zhandle_t *zh; /* ZK handle */
clientid_t myid;
} zk_info_t;
static zk_info_t zk_info;
static zk_info_t *main_zk=NULL;
static int last_rc=ZOK;
#ifdef ENABLE_SUICIDE_UPON_DISCONNECT
static bool zk_connected = false;
#endif
/* this is to indicate if we get shutdown signal during ZK initialization
* ZK shutdown is done at the end of arcus_zk_init() to simplify synchronization
*/
volatile sig_atomic_t arcus_zk_shutdown=0;
/* This flag is now used to indicate graceful shutdown. See hb_thread for
* more comment.
*/
/* placeholder for zookeeper and memcached settings */
typedef struct {
char *svc; // Service code name
char *mc_ipport; // this memcached ip:port string
char *mc_hostnameport; // this memcached hostname:port string
char *hostip; // localhost server IP
int port; // memcached port number
bool zk_failstop; // memcached automatic failstop on/off
int hb_failstop; // memcached heartbeat failstop
int hb_timeout; // memcached heartbeat timeout
int zk_timeout; // Zookeeper session timeout
bool auto_scrub; // automactic scrub_stale
char *znode_name; // Ephemeral ZK node name for this mc identification
int znode_ver; // Ephemeral ZK node version
bool znode_created; // Ephemeral ZK node is created ?
int verbose; // verbose output
size_t maxbytes; // mc -M option
EXTENSION_LOGGER_DESCRIPTOR *logger; // mc logger
union {
ENGINE_HANDLE *v0;
ENGINE_HANDLE_V1 *v1;
} engine; // mc engine
char *cluster_path; // cluster path for this memcached
#ifdef PROXY_SUPPORT
char *proxy; // proxy server ip:port
#endif
#ifdef ENABLE_CLUSTER_AWARE
struct cluster_config *ch; // cluster configuration handle
#endif
pthread_mutex_t lock;
bool init; // is this structure initialized?
} arcus_zk_conf;
arcus_zk_conf arcus_conf = {
.svc = NULL,
.mc_ipport = NULL,
.mc_hostnameport = NULL,
.hostip = NULL,
.zk_failstop = true,
.hb_failstop = HEART_BEAT_DFT_FAILSTOP,
.hb_timeout = HEART_BEAT_DFT_TIMEOUT,
.zk_timeout = DEFAULT_ZK_TO,
.auto_scrub = true,
.znode_name = NULL,
.znode_ver = -1,
.znode_created = false,
.verbose = -1,
.port = -1,
.maxbytes = -1,
.logger = NULL,
.cluster_path = NULL,
#ifdef PROXY_SUPPORT
.proxy = NULL,
#endif
#ifdef ENABLE_CLUSTER_AWARE
.ch = NULL,
#endif
.lock = PTHREAD_MUTEX_INITIALIZER,
.init = false
};
/* Arcus ZK stats */
arcus_zk_stats azk_stat;
// context struct to pass to app_ping
typedef struct {
struct sockaddr_in addr; // cache this for use in L7 ping routine
struct timeval to; // mc_hb may block for up to this long (give or take)
} app_ping_t;
static app_ping_t mc_ping_context;
// static declaration
static void arcus_zk_watcher(zhandle_t *wzh, int type, int state,
const char *path, void *cxt);
static void arcus_cache_list_watcher(zhandle_t *zh, int type, int state,
const char *path, void *ctx);
static void arcus_zk_sync_cb(int rc, const char *name, const void *data);
static void arcus_zk_log(zhandle_t *zh, const char *);
static void arcus_exit(zhandle_t *zh, int err);
int mc_hb(void *context); // memcached self-heartbeat
/* State machine thread.
* It performs all blocking ZK operations including cluster_config.
* We don't do blocking operations in the context of watcher callback
* any more.
*/
/* sm request structure */
struct sm_request {
bool update_cache_list;
};
/* sm structure */
struct sm {
/* sm requests by other threads */
struct sm_request request;
/* Cache of the latest version we pulled from ZK */
struct String_vector sv_cache_list; /* from /cache_list/{svc} */
/* Current # of nodes in cluster */
int cluster_node_count;
/* the time a new node was added to the cluster */
volatile uint64_t node_added_time;
volatile bool mc_pause;
/* Used to wake up the thread */
pthread_mutex_t lock;
pthread_cond_t cond;
bool notification;
volatile bool state_running;
#ifdef ENABLE_SUICIDE_UPON_DISCONNECT
volatile bool timer_running;
#endif
pthread_t state_tid;
#ifdef ENABLE_SUICIDE_UPON_DISCONNECT
/* A timer thread to fail-stop the server
* when it is disconnected from the ZK ensemble.
*/
pthread_t timer_tid;
#endif
} sm_info;
/* sm functions */
static int sm_init(void);
static void sm_lock(void);
static void sm_unlock(void);
static void sm_wakeup(bool locked);
/* async routine synchronization */
static pthread_cond_t azk_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t azk_mtx = PTHREAD_MUTEX_INITIALIZER;
static int azk_count;
/* zookeeper close synchronization */
static pthread_mutex_t zk_lock = PTHREAD_MUTEX_INITIALIZER;
/* memcached heartheat thread */
static volatile bool hb_thread_running = false;
static bool hb_thread_sleep = false;
static pthread_mutex_t hb_thread_lock;
static pthread_cond_t hb_thread_cond;
static void *hb_thread(void *arg);
static int start_hb_thread(app_ping_t *data);
static int
arcus_memcached_scrub_stale(void)
{
ENGINE_ERROR_CODE ret;
ret = arcus_conf.engine.v1->scrub_stale(arcus_conf.engine.v0);
return ret == ENGINE_SUCCESS ? 0 : -1;
}
/* Some znode names use '^' as a delimiter.
* Return pointers to the starting and ending ('^') characters.
*/
static int
breakup_string(char *str, char *start[], char *end[], int vec_len)
{
char *c = str;
int i = 0;
while (i < vec_len) {
start[i] = c;
while (*c != '\0') {
if (*c == '^')
break;
c++;
}
if (*c == '\0') {
end[i] = c;
i++;
break;
}
if (start[i] == c)
break; /* empty */
end[i] = c++;
i++;
}
if (*c != '\0') {
/* There are leftover characters. Ignore them. */
}
return i; /* i <= vec_len */
}
/* mutex for async operations */
static void inc_count(int delta)
{
pthread_mutex_lock(&azk_mtx);
azk_count += delta;
pthread_cond_broadcast(&azk_cond);
pthread_mutex_unlock(&azk_mtx);
}
static int wait_count(int timeout)
{
struct timeval tv;
struct timespec ts;
int rc = 0;
pthread_mutex_lock(&azk_mtx);
while (azk_count > 0 && rc == 0) {
if (timeout == 0) {
rc = pthread_cond_wait(&azk_cond, &azk_mtx);
} else {
gettimeofday(&tv, NULL);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec*1000;
//clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += timeout/1000; /* timeout: msec */
rc = pthread_cond_timedwait(&azk_cond, &azk_mtx, &ts);
}
}
pthread_mutex_unlock(&azk_mtx);
return rc;
}
static int
arcus_zk_client_init(zk_info_t *zinfo)
{
inc_count(1);
zinfo->zh = zookeeper_init(zinfo->ensemble_list, arcus_zk_watcher,
arcus_conf.zk_timeout, &zinfo->myid, zinfo, 0);
if (!zinfo->zh) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"zookeeper_init() failed (%s error)\n", strerror(errno));
return EX_PROTOCOL;
}
/* wait until above init callback is called
* We need to wait until ZOO_CONNECTED_STATE
*/
if (wait_count(arcus_conf.zk_timeout) != 0) {
/* zoo_state(zh) != ZOO_CONNECTED_STATE */
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"cannot to be ZOO_CONNECTED_STATE\n");
zookeeper_close(zinfo->zh);
zinfo->zh = NULL;
inc_count(-1);
return EX_PROTOCOL;
}
return 0;
}
// Arcus zookeeper global watch callback routine
static void
arcus_zk_watcher(zhandle_t *wzh, int type, int state, const char *path, void *cxt)
{
if (type != ZOO_SESSION_EVENT) {
return;
}
if (state == ZOO_CONNECTED_STATE) {
const clientid_t *id = zoo_client_id(wzh);
zk_info_t *zinfo = cxt;
if (arcus_conf.verbose > 2) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"ZK ensemble connected. session id: 0x%llx\n",
(long long) zinfo->myid.client_id);
}
if (zinfo->myid.client_id == 0 || zinfo->myid.client_id != id->client_id) {
if (arcus_conf.verbose > 2)
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"A old session id: 0x%llx\n", (long long) zinfo->myid.client_id);
zinfo->myid = *id;
}
// finally connected to one of ZK ensemble. signal go.
inc_count(-1);
#ifdef ENABLE_SUICIDE_UPON_DISCONNECT
zk_connected = true;
#endif
}
else if (state == ZOO_AUTH_FAILED_STATE) {
// authorization failure
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL, "Auth failure. shutting down\n");
arcus_exit(wzh, EX_NOPERM);
}
else if (state == ZOO_EXPIRED_SESSION_STATE) {
if (arcus_conf.zk_failstop) {
// very likely that memcached process exited and restarted within
// session timeout
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL, "Expired state. shutting down\n");
// send SMS here??
arcus_exit(wzh, EX_TEMPFAIL);
} else {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL, "Expired state. pausing memcached (zk_failstop: off)\n");
sm_lock();
sm_info.mc_pause = true;
sm_wakeup(true);
sm_unlock();
}
}
else if (state == ZOO_ASSOCIATING_STATE || state == ZOO_CONNECTING_STATE) {
/* we get these when connection to Ensemble is dropped and retrying
* this happens emsemble failover as well
* since this is not memcached operation issue, we will allow reconnecting
* but it is possible that app_ping fails and zk server may have disconnected
* and if that's the case, we let heartbeat timeout algorithm decide
* what to do.
*/
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL, "CONNECTING.... \n");
#ifdef ENABLE_SUICIDE_UPON_DISCONNECT
/* The server is disconnected from ZK. But we do not know how much
* time has elapsed from the last successful ZK ping. A connection
* timeout (session timeout * 2/3) might have occurred. Or, the
* TCP connection might have reset/closed (immediate).
* See sm_timer_thread. For now, it is being conservative and dies
* in session timeout * 1/3. Perhaps we should do our own ping, not
* rely on ZK session notifications. FIXME
*/
zk_connected = false;
#endif
}
}
/* cache_list zk watcher */
static void
arcus_cache_list_watcher(zhandle_t *zh, int type, int state, const char *path, void *ctx)
{
if (type == ZOO_CHILD_EVENT) {
/* The ZK library has two threads of its own. The completion thread
* calls watcher functions.
*
* Do not do operations that may block or fail in the watcher context.
*/
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"ZOO_CHILD_EVENT from ZK cache list: state=%d, path=%s\n",
state, (path ? path : "null"));
} else {
/* an unexpected event has been occurred */
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Unexpected event(%d) gotten by cache_list_watcher: state=%d path=%s\n",
type, state, (path ? path : "null"));
}
/* Just wake up the sm thread and update the hash ring.
* This may be a false positive (session event or others).
* But it is harmless.
*
* Should we do this only in ZOO_CHILD_EVENT ? FIXME.
*/
sm_lock();
sm_info.request.update_cache_list = true;
sm_wakeup(true);
sm_unlock();
}
static int
arcus_read_ZK_children(zhandle_t *zh, const char *zpath, watcher_fn watcher,
struct String_vector *strv)
{
int rc = zoo_wget_children(zh, zpath, watcher, NULL, strv);
if (rc != ZOK) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Failed to read children(znode list) of zpath=%s: "
"error=%d(%s)\n", zpath, rc, zerror(rc));
return (rc == ZNONODE ? 0 : -1);
}
return 1; /* The caller must free strv */
}
static bool
check_znode_existence(struct String_vector *strv, char *znode_name)
{
for (int i = 0; i < strv->count; i++) {
if (strcmp(strv->data[i], znode_name) == 0)
return true;
}
return false;
}
#ifdef ENABLE_CLUSTER_AWARE
/* update cluster config, that is ketama hash ring. */
static int
update_cluster_config(struct String_vector *strv)
{
if (strv->count == 0) { /* cache_list can be empty. */
sm_info.cluster_node_count = 0;
return 0;
}
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL, "update cluster config...\n");
if (arcus_conf.verbose > 0) {
for (int i = 0; i < strv->count; i++) {
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL, "server[%d] = %s\n",
i, strv->data[i]);
}
}
/* reconfigure arcus-memcached cluster */
if (cluster_config_reconfigure(arcus_conf.ch, strv->data, strv->count) < 0) {
return -1;
}
sm_info.cluster_node_count = strv->count;
return 0;
}
#endif
/* callback for sync command */
static void
arcus_zk_sync_cb(int rc, const char *name, const void *data)
{
if (arcus_conf.verbose > 2) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL, "arcus_zk_sync cb\n");
}
// signal cond var
inc_count(-1);
last_rc = rc;
}
/* Log memcached join/leave acvitivity for debugging purpose
* We cannot log in case of memcached crash
*/
static void
arcus_zk_log(zhandle_t *zh, const char *action)
{
int rc;
char zpath[200] = "";
char rcbuf[200] = "";
char sbuf[200] = "";
struct timeval now;
struct tm *ltm;
struct Stat zstat;
if (!zh || zoo_state(zh) != ZOO_CONNECTED_STATE || !arcus_conf.init)
return;
gettimeofday(&now, 0);
ltm = localtime (&now.tv_sec);
strftime(sbuf, sizeof(sbuf), "%Y-%m-%d", ltm);
snprintf(zpath, sizeof(zpath), "%s/%s/%s", zk_root, zk_log_dir, sbuf);
rc = zoo_exists(zh, zpath, ZK_NOWATCH, &zstat);
if (rc == ZNONODE) {
// if this "date" directory does not exist, create one
rc = zoo_create(zh, zpath, NULL, 0, &ZOO_OPEN_ACL_UNSAFE,
0, rcbuf, sizeof(rcbuf));
if (rc == ZOK && arcus_conf.verbose > 2) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"znode %s does not exist. created\n", rcbuf);
}
}
if (rc == ZOK || rc == ZNODEEXISTS) {
// if this znode already exist or the creation was successful
snprintf(zpath, sizeof(zpath), "%s/%s/%s/%s-",
zk_root, zk_log_dir, sbuf, arcus_conf.znode_name);
snprintf(sbuf, sizeof(sbuf), "%s", action);
rc = zoo_create(zh, zpath, sbuf, strlen(sbuf), &ZOO_OPEN_ACL_UNSAFE,
ZOO_SEQUENCE, rcbuf, sizeof(rcbuf));
if (arcus_conf.verbose > 2)
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL, "znode \"%s\" created\n", rcbuf);
}
if (rc) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"cannot log this acvitiy (%s error)\n", zerror(rc));
}
}
static void
arcus_exit(zhandle_t *zh, int err)
{
if (zh)
zookeeper_close(zh);
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL, "shutting down\n");
exit(err);
}
static void arcus_adjust_ping_timeout(app_ping_t *ping_data, int timeout)
{
/* +50 msec so that the caller can detect the timeout */
uint64_t usec = timeout * 1000 + 50000;
ping_data->to.tv_sec = usec / 1000000;
ping_data->to.tv_usec = usec % 1000000;
}
static void arcus_prepare_ping_context(app_ping_t *ping_data, int port)
{
/* prepare app_ping context data:
* sockaddr for memcached connection in app ping
*/
memset(ping_data, 0, sizeof(app_ping_t));
ping_data->addr.sin_family = AF_INET;
ping_data->addr.sin_port = htons(port);
/* Use the admin ip (currently localhost) to avoid competing with
* regular clients for connections.
*/
ping_data->addr.sin_addr.s_addr = inet_addr(ADMIN_CLIENT_IP);
arcus_adjust_ping_timeout(ping_data, arcus_conf.hb_timeout);
}
/* This is L7 application ping callback
* only one app ping per ZK ping period if successful
* In this case, we make a TCP connection to self memcached port, and
* try to set a key.
*
* Make sure that successful app heartbeat completes in 2/3 of recv timeout,
* otherwise it is very possible have expired state in the end.
* This retries 2 twice at every 1/3 of ZK recv timeout
*/
int mc_hb(void *context)
{
app_ping_t *data = (app_ping_t *) context;
struct linger linger;
struct timeval tv_timeo;
char buf[32];
int flags;
int sock;
int err=0;
/* make a tcp connection to this memcached itself,
* and try "set arcus:zk-ping".
*/
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
if (sock == -1) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"mc_hb: cannot create a socket (error=%s)\n", strerror(errno));
return 0; /* Allow ZK ping by returning 0 even if socket() fails. */
}
flags = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)); /* fast port recycle */
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags));
/* send()/recv() could be blocked forever when all memcached worker threads are deadlocked
* while the acceptor thread is still alive.
* Blocked in L7 health check, ZK ping fails, then ZK ensemble gives up the connection.
* However, as the blocked ZK ping runs on ZK client's I/O thread
* the client cannot receive the events from ZK ensemble. So memcached fails to fail-stop.
* To prevent this situation we set timeouts to send()/recv().
*/
tv_timeo = data->to;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv_timeo, sizeof(tv_timeo));
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv_timeo, sizeof(tv_timeo));
linger.l_onoff = 1;
linger.l_linger = 0; /* flush buffers upon close() and send TCP RST */
setsockopt(sock, SOL_SOCKET, SO_LINGER, &linger, sizeof(linger));
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"mc_hb: connecting to memcached at %s:%d...\n",
inet_ntoa(data->addr.sin_addr), arcus_conf.port);
err = connect(sock, (struct sockaddr *) &data->addr, sizeof(struct sockaddr));
if (err) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"mc_hb: cannot connect to local memcached (error=%s)\n", strerror(errno));
close(sock);
return 0; /* Allow ZK ping by returning 0 even if socket() fails. */
}
/* Try to set a key "arcus:zk-ping"
* we need to be careful here. Since we can make a connection, basic
* memcached event loop works and system resources are enough. if we can an
* error during send()/recv(), it may not be a memcached failure at all.
* We may get slab memory shortage for slab class 0 for above key.
* For now, we simply return here without ping error or intentional delay
*/
err = send(sock, mc_hb_command, 28, 0);
if (err > 0) {
// expects "STORED\r\n"
err = recv(sock, buf, 8, 0);
if (err < 0) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"mc_hb: recv failed (error=%s)\n", strerror(errno));
}
} else {
if (err < 0) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"mc_hb: send failed (error=%s)\n", strerror(errno));
}
}
close(sock);
return 0;
}
static void hb_wakeup(void)
{
pthread_mutex_lock(&hb_thread_lock);
if (hb_thread_sleep == true)
pthread_cond_signal(&hb_thread_cond);
pthread_mutex_unlock(&hb_thread_lock);
}
static void *hb_thread(void *arg)
{
app_ping_t *ping_data = arg;
int cur_hb_failstop = arcus_conf.hb_failstop;
int cur_hb_timeout = arcus_conf.hb_timeout;
int acc_hb_latency = 0;
bool shutdown_by_me = false;
struct timeval tv;
struct timespec ts;
struct timeval start_time;
struct timeval end_time;
uint64_t elapsed_msec, start_msec, end_msec;
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Heartbeat thread is running.\n");
/* We consider 3 types of shutdowns.
*
* 1. control-c
* The user wants a graceful shutdown. The main thread wakes up all
* the worker threads and wait for them to terminate. It also calls
* the engine destroy function. In this case, heartbeat should just stop.
* arcus_zk_shutdown = 1 indicates this case. So, we check that flag
* in this function.
*
* 2. kill -KILL
* Something is very wrong, and the user wants to kill the process right
* away. For example, control-c/graceful shutdown might hang due to bugs.
* And, the user wants to forcefully kill the process. There is nothing
* we can do here.
*
* 3. Heartbeat failure
* memcached is not working properly. We attempt to close the ZK session
* and then forcefully terminate. This is NOT a graceful shutdown. We
* do not wait for worker threads to terminate. We do not call the engine
* destroy function.
*/
hb_thread_running = true;
while (!arcus_zk_shutdown) {
/* If the last hearbeat timed out, do not wait and try another
* right away.
*/
if (acc_hb_latency == 0) {
/* sleep HEART_BEAT_PERIOD seconds */
gettimeofday(&tv, NULL);
ts.tv_sec = tv.tv_sec + HEART_BEAT_PERIOD;
ts.tv_nsec = tv.tv_usec*1000;
/* sleep with spurious wakeups checking */
while (tv.tv_sec < ts.tv_sec && !arcus_zk_shutdown) {
pthread_mutex_lock(&hb_thread_lock);
hb_thread_sleep = true;
pthread_cond_timedwait(&hb_thread_cond, &hb_thread_lock, &ts);
hb_thread_sleep = false;
pthread_mutex_unlock(&hb_thread_lock);
gettimeofday(&tv, NULL);
}
}
/* Graceful shutdown was requested while sleeping. */
if (arcus_zk_shutdown)
break;
/* check if hb_failstop is changed */
if (cur_hb_failstop != arcus_conf.hb_failstop) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Heartbeat failstop has changed. old(%d) => new(%d)\n",
cur_hb_failstop, arcus_conf.hb_failstop);
cur_hb_failstop = arcus_conf.hb_failstop;
acc_hb_latency = 0; /* reset accumulated hb latency */
}
/* check if hb_timeout is changed */
if (cur_hb_timeout != arcus_conf.hb_timeout) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Heartbeat timeout has changed. old(%d) => new(%d)\n",
cur_hb_timeout, arcus_conf.hb_timeout);
cur_hb_timeout = arcus_conf.hb_timeout;
acc_hb_latency = 0; /* reset accumulated hb latency */
/* adjust ping timeout */
arcus_adjust_ping_timeout(ping_data, cur_hb_timeout);
}
/* Do one ping and measure how long it takes. */
gettimeofday(&start_time, NULL);
mc_hb((void *)ping_data);
gettimeofday(&end_time, NULL);
/* Graceful shutdown was requested while doing heartbeat.
* When worker threads die, there is no one to process heartbeat
* request, and we would see a timeout. Ignore the false alarm.
*/
if (arcus_zk_shutdown)
break;
/* Paranoid. Check if the clock had gone backwards. */
start_msec = start_time.tv_sec * 1000 + start_time.tv_usec / 1000;
end_msec = end_time.tv_sec * 1000 + end_time.tv_usec / 1000;
if (start_msec <= end_msec) {
elapsed_msec = end_msec - start_msec;
azk_stat.hb_count += 1;
azk_stat.hb_latency += elapsed_msec;
} else {
elapsed_msec = 0; /* Ignore this heartbeat */
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"hb_thread: Clock has gone backwards? start_msec=%"PRIu64
" end_msec=%"PRIu64"\n", start_msec, end_msec);
}
if (elapsed_msec > cur_hb_timeout) {
if (cur_hb_failstop > 0) {
acc_hb_latency += elapsed_msec;
} else {
/* Reset the acc_hb_latency */
acc_hb_latency = 0;
}
/* Print a message for every failure to help debugging, postmortem
* analysis, etc.
*/
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Heartbeat failure. hb_timeout=%d hb_latency=%"PRIu64
" accumulated_hb_latency=%d\n", cur_hb_timeout,
elapsed_msec, acc_hb_latency);
if (acc_hb_latency > cur_hb_failstop) {
/* Do not bother calling memcached.c:shutdown_server.
* Call arcus_zk_final directly. shutdown_server just sets
* memcached_shutdown = arcus_zk_shutdown = 1 and calls
* arcus_zk_final. These flags are used for graceful shutdown.
* We do not need them here. Besides, arcus_zk_final kills
* the process right away, assuming the zookeeper library
* still functions.
*/
/*
SERVER_HANDLE_V1 *api = arcus_conf.get_server_api();
api->core->shutdown();
*/
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"consecutive heartbeat failures. Shutting down...\n");
shutdown_by_me = true;
break;
}
} else {
/* Reset the acc_hb_latency */
acc_hb_latency = 0;
}
}
hb_thread_running = false;
if (shutdown_by_me) {
arcus_zk_shutdown = 1;
arcus_zk_final("Heartbeat failure");
arcus_zk_destroy();
exit(0);
}
return NULL;
}
static int start_hb_thread(app_ping_t *data)
{
pthread_t tid;
pthread_attr_t attr;
int ret;
pthread_attr_init(&attr);
pthread_mutex_init(&hb_thread_lock, NULL);
pthread_cond_init(&hb_thread_cond, NULL);
if ((ret = pthread_create(&tid, &attr, hb_thread, (void *)data)) != 0) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Cannot create hb thread: %s\n", strerror(ret));
}
return ret;
}
static int arcus_build_znode_name(char *ensemble_list)
{
int sock, rc;
socklen_t socklen=16;
struct in_addr inaddr;
struct sockaddr_in saddr, myaddr;
struct hostent *zkhost, *hp;
char *zip, *hlist;
char *sep1=",";
char *sep2=":";
char myip[50];
char rcbuf[200];
// Need to figure out local IP. first create a dummy udp socket
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"socket() failed: %s\n", strerror(errno));
return EX_OSERR;
}
saddr.sin_family = AF_INET;
saddr.sin_port = htons(SYSLOGD_PORT); // what if this is not open? XXX
// loop through all ensemble IP in case ensemble failure
zip = strtok_r(ensemble_list, sep1, &hlist); // separate IP:PORT tuple
while (zip)
{
zip = strtok(zip, sep2); // extract the first IP
// try to convert IP -> network IP format
if (inet_aton(zip, &inaddr)) {
// just use the IP
saddr.sin_addr = inaddr;
if (arcus_conf.verbose > 2) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"Trying ensemble IP: %s\n", zip);
}
} else {
// Must be hostname, not IP. Convert hostname to IP first
zkhost = gethostbyname(zip);
if (!zkhost) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"Invalid IP/hostname in arg: %s\n", zip);
// get next token: separate IP:PORT tuple
zip = strtok_r(NULL, sep1, &hlist);
continue;
}
memcpy((char *)&saddr.sin_addr,
zkhost->h_addr_list[0], zkhost->h_length);
inet_ntop(AF_INET, &saddr.sin_addr, rcbuf, sizeof(rcbuf));
if (arcus_conf.verbose > 2) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"Trying converted IP of hostname(%s): %s\n", zip, rcbuf);
}
}
// try to connect to ensemble' arcus_conf.logger->logd UDP port
// this is dummy code that simply is used to get local IP address
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
rc = connect(sock, (struct sockaddr*) &saddr, sizeof(struct sockaddr_in));
fcntl(sock, F_SETFL, flags);
if (rc == 0) { // connect immediately
if (arcus_conf.verbose > 2) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"connected to ensemble \"%s\" syslogd UDP port\n", zip);
}
break;
}
// if cannot connect immediately, try other ensemble
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Cannot connect to ensemble %s (%s error)\n", zip, strerror(errno));
zip = strtok_r(NULL, sep1, &hlist); // get next token: separate IP:PORT tuple
}
if (!zip) { // failed to connect to all ensemble host. fail
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"not able to connect any Ensemble server\n");
close(sock); sock = -1;
return EX_UNAVAILABLE;
}
// finally, what's my local IP?
if (getsockname(sock, (struct sockaddr *) &myaddr, &socklen)) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"getsockname failed: %s\n", strerror(errno));
close(sock); sock = -1;
return EX_NOHOST;
}
close(sock); sock = -1;
// Finally local IP
inet_ntop(AF_INET, &myaddr.sin_addr, myip, sizeof(myip));
arcus_conf.hostip = strdup(myip);