-
Notifications
You must be signed in to change notification settings - Fork 55
/
arcus_zk.c
2061 lines (1848 loc) · 69 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 2000 /* 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 # */
#define MAX_SERVICECODE_LENGTH 128
#define MAX_HOSTNAME_LENGTH 128
#ifdef ENABLE_ZK_RECONFIG
/* The maximum config data size per ZK server is 600.
* Therefore, config data of about 26 ZK servers can be stored.
*/
#define MAX_ZK_CONFIG_DATA_LENGTH (16 * 1024)
struct _zk_reconfig {
char data_buffer[MAX_ZK_CONFIG_DATA_LENGTH];
char host_buffer[MAX_ZK_CONFIG_DATA_LENGTH/2]; /* half space is enough */
int64_t version; /* current ZK config version */
bool enabled; /* dynamic reconfig is enabled in ZK ? */
bool needed; /* dynamic reconfig is needed by arcus ? */
} zk_reconfig;
#endif
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";
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
*/
static volatile sig_atomic_t arcus_zk_shutdown=0;
/* 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 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_config;
arcus_zk_config arcus_conf = {
.svc = NULL,
.mc_ipport = NULL,
.mc_hostnameport = NULL,
.hostip = NULL,
.zk_failstop = true,
.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;
/* static forward declaration */
static void arcus_zk_watcher(zhandle_t *wzh, int type, int state,
const char *path, void *cxt);
#ifdef ENABLE_ZK_RECONFIG
static int arcus_check_zk_reconfig_enabled(zhandle_t *zh);
static void arcus_zkconfig_watcher(zhandle_t *zh, int type, int state,
const char *path, void *ctx);
#endif
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);
/* 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 {
#ifdef ENABLE_ZK_RECONFIG
bool update_zkconfig;
#endif
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;
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 void clear_count(void)
{
pthread_mutex_lock(&azk_mtx);
azk_count = 0;
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\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;
}
// "recv" timeout is actually the session timeout
// ZK client ping period is recv_timeout / 3.
if (arcus_conf.zk_timeout != zoo_recv_timeout(zinfo->zh)) {
arcus_conf.zk_timeout = zoo_recv_timeout(zinfo->zh);
}
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"ZooKeeper client initialized. (ZK session timeout=%d sec)\n",
arcus_conf.zk_timeout/1000);
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;
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"ZOO_SESSION_EVENT Connected. server=%s, session_id=%#llx\n",
zoo_get_current_server(wzh),
(long long) id->client_id);
if (zinfo->myid.client_id == 0 || zinfo->myid.client_id != id->client_id) {
if (arcus_conf.verbose > 1)
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"A old session id: 0x%llx\n", (long long) zinfo->myid.client_id);
zinfo->myid = *id;
}
#ifdef ENABLE_ZK_RECONFIG
if (arcus_conf.init && zk_reconfig.needed && !zk_reconfig.enabled) {
/* check if ZK dynamic reconfig is enabled ? */
if (arcus_check_zk_reconfig_enabled(zinfo->zh) < 0) {
/* zoo_getconfig API failed.. (rarely)
* Instead of retry checking, set zk_reconfig to true to make it more safe.
*/
zk_reconfig.enabled = true;
}
if (zk_reconfig.enabled) {
/* Wake up the state machine thread and update zkconfig. */
sm_lock();
sm_info.request.update_zkconfig = true;
sm_wakeup(true);
sm_unlock();
}
}
#endif
// 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,
"ZOO_SESSION_EVENT Auth failed. 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,
"ZOO_SESSION_EVENT Expired. shutting down\n");
// send SMS here??
arcus_exit(wzh, EX_TEMPFAIL);
} else {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"ZOO_SESSION_EVENT Expired. 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_WARNING, NULL, "ZOO_SESSION_EVENT 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
}
}
#ifdef ENABLE_ZK_RECONFIG
/* config zk watcher */
static void
arcus_zkconfig_watcher(zhandle_t *zh, int type, int state, const char *path, void *ctx)
{
if (type == ZOO_CHANGED_EVENT) {
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"ZOO_CHANGED_EVENT from ZK config: state=%d, path=%s\n",
state, (path ? path : "null"));
} else if (type == ZOO_SESSION_EVENT) {
/* ZOO_SESSION_EVENT is handled by arcus_zk_watcher.
* Set the update flag when receiving a connected event.
*/
if (state != ZOO_CONNECTED_STATE) return;
} else {
/* Unexpected event(ZOO_DELETED_EVENT or ZOO_NOTWATCHING_EVENT) has 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"));
}
/* In ZK watcher context, don't do anything that may block or fail. */
/* Just wake up the sm thread and update the zk server list.
* This may be a false positive (session event or others).
* But it is harmless or must be treated like changed event.
*/
sm_lock();
sm_info.request.update_zkconfig = true;
sm_wakeup(true);
sm_unlock();
}
#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) {
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 if (type == ZOO_SESSION_EVENT) {
/* ZOO_SESSION_EVENT is handled by arcus_zk_watcher.
* Set the update flag when receiving a connected event.
*/
if (state != ZOO_CONNECTED_STATE) return;
} else {
/* Unexpected event(ZOO_DELETED_EVENT or ZOO_NOTWATCHING_EVENT) has 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"));
}
/* In ZK watcher context, don't do anything that may block or fail. */
/* 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 or must be treated like child event.
*/
sm_lock();
sm_info.request.update_cache_list = true;
sm_wakeup(true);
sm_unlock();
}
static bool
check_my_znode_existence(void)
{
if (cluster_config_get_self_id(arcus_conf.ch) == -1) {
return false;
}
return true;
}
#ifdef ENABLE_CLUSTER_AWARE
/* update cluster config, that is ketama hash ring. */
static int
update_cluster_config(struct String_vector *strv, int *num_added, int *num_removed)
{
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"update cluster config. (count=%d)\n", (int)strv->count);
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,
num_added, num_removed) < 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 > 1) {
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[128] = "";
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 > 1) {
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 > 1) {
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. error=%d(%s)\n", rc, 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 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[512];
// 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 > 1) {
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_WARNING, 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 > 1) {
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 > 1) {
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\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);
arcus_conf.logger->log(EXTENSION_LOG_DETAIL, NULL, "local IP: %s\n", myip);
if (getenv("ARCUS_CACHE_PUBLIC_IP") != NULL) {
free(arcus_conf.hostip);
arcus_conf.hostip = strdup(getenv("ARCUS_CACHE_PUBLIC_IP"));
arcus_conf.logger->log(EXTENSION_LOG_DETAIL, NULL, "local public IP: %s\n",
arcus_conf.hostip);
}
#ifdef PROXY_SUPPORT
if (arcus_conf.proxy) {
struct hostent *proxy_host;
char *proxy_ip, *proxy_port;
struct in_addr inaddr;
char buf[50];
proxy_ip = strtok(arcus_conf.proxy, sep2);
proxy_port = strtok(NULL, sep2);
if (inet_aton(proxy_ip, &inaddr)) {
if (arcus_conf.verbose > 1) {
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"Proxy IP: %s\n", proxy_ip);
}
} else {
// Must be hostname, not IP. Convert hostname to IP first
proxy_host = gethostbyname(proxy_ip);
if (!proxy_host) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Invalid proxy IP/hostname in arg: %s\n", proxy_ip);
return EX_UNAVAILABLE;
}
memcpy((char *)&inaddr,
proxy_host->h_addr_list[0], proxy_host->h_length);
inet_ntop(AF_INET, &inaddr, buf, sizeof(buf));
proxy_ip = buf;
}
proxy_host = gethostbyaddr((char*)&inaddr, sizeof(inaddr), AF_INET);
if (!proxy_host) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"cannot get hostname: %s\n", strerror(errno));
return EX_NOHOST;
}
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"proxy hostname: %s\n", proxy_host->h_name);
snprintf(rcbuf, sizeof(rcbuf), "%s:%s", proxy_ip, proxy_port);
arcus_conf.mc_ipport = strdup(rcbuf);
snprintf(rcbuf, sizeof(rcbuf), "%s:%s", proxy_host->h_name, proxy_port);
arcus_conf.mc_hostnameport = strdup(rcbuf);
snprintf(rcbuf, sizeof(rcbuf), "%s-%s", arcus_conf.mc_ipport, proxy_host->h_name);
arcus_conf.znode_name = strdup(rcbuf);
return 0; // EX_OK
}
#endif
if (!arcus_conf.znode_name) {
char *hostp=NULL;
char hostbuf[256];
// Also get local hostname.
// We want IP and hostname to better identify this cache
hp = gethostbyaddr((char*)&myaddr.sin_addr.s_addr,
sizeof(myaddr.sin_addr.s_addr), AF_INET);
if (hp) {
hostp = hp->h_name;
} else {
// if gethostbyaddr() doesn't work, try gethostname
if (gethostname((char *)&hostbuf, sizeof(hostbuf))) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"cannot get hostname: %s\n", strerror(errno));
return EX_NOHOST;
}
hostp = hostbuf;
}
if (strlen(hostp) > MAX_HOSTNAME_LENGTH) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Too long hostname. hostname=%s\n", hostp);
return EX_DATAERR;
}
arcus_conf.logger->log(EXTENSION_LOG_DEBUG, NULL,
"local hostname: %s\n", hostp);
// we need to keep ip:port-hostname tuple for later user (restart)
snprintf(rcbuf, sizeof(rcbuf), "%s:%d", arcus_conf.hostip, arcus_conf.port);
arcus_conf.mc_ipport = strdup(rcbuf);
snprintf(rcbuf, sizeof(rcbuf), "%s:%d", hostp, arcus_conf.port);
arcus_conf.mc_hostnameport = strdup(rcbuf);
snprintf(rcbuf, sizeof(rcbuf), "%s-%s", arcus_conf.mc_ipport, hostp);
arcus_conf.znode_name = strdup(rcbuf);
}
return 0; // EX_OK
}
static int arcus_parse_server_mapping(char *znode)
{
char *start[4], *end[4]; /* enough pointers for future extension */
int max_substrs = 4;
int i, count;
count = breakup_string(znode, start, end, max_substrs);
/* Null-terminate substrings */
for (i = 0; i < count; i++) {
*end[i] = '\0';
}
/* get service code */
arcus_conf.svc = strdup(start[0]);
if (strlen(arcus_conf.svc) > MAX_SERVICECODE_LENGTH) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Too long service code. service_code=%s\n", arcus_conf.svc);
return -1;
}
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Found the valid server mapping. service_code=%s\n",
arcus_conf.svc);
return 0;
}
#ifdef ENABLE_ZK_RECONFIG
static int arcus_check_zk_reconfig_enabled(zhandle_t *zh)
{
int len = 256;
char buf[256];
struct Stat zstat;
int rc = zoo_getconfig(zh, ZK_NOWATCH, buf, &len, &zstat);
if (rc == ZOK && len > 0) {
zk_reconfig.enabled = true;
zk_reconfig.version = -1;
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"Zookeeper dynamic reconfiguration is enabled.\n");
} else if (rc == ZNONODE) {
zk_reconfig.enabled = false;
arcus_conf.logger->log(EXTENSION_LOG_INFO, NULL,
"Zookeeper dynamic reconfiguration is disabled.\n");
} else {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"zoo_getconfig() failed. error=%d(%s).\n", rc, zerror(rc));
return -1;
}
return 0;
}
#endif
static int arcus_check_server_mapping(zhandle_t *zh, const char *root)
{
struct String_vector strv = {0, NULL};
char zpath[256];
int rc;
/* sync map path */
snprintf(zpath, sizeof(zpath), "%s/%s", root, zk_map_dir);
inc_count(1);
rc = zoo_async(zh, zpath, arcus_zk_sync_cb, NULL);
if (rc != ZOK) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"zoo_async() failed: error=%d(%s)\n", rc, zerror(rc));
return -1;
}
/* wait until above sync callback is called */
wait_count(0);
rc = last_rc;
if (rc != ZOK) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Failed to synchronize zpath=%s: error=%d(%s)\n",
zpath, rc, zerror(rc));
return -1;
}
/* check the cache_server_mapping info. */
do {
/* 1st check: get children of "/cache_server_mapping/ip:port" */
snprintf(zpath, sizeof(zpath), "%s/%s/%s",
root, zk_map_dir, arcus_conf.mc_ipport);
rc = zoo_get_children(zh, zpath, ZK_NOWATCH, &strv);
if (rc != ZNONODE) break;
/* 2nd check: get children of "/cache_server_mapping/hostname:port" */
snprintf(zpath, sizeof(zpath), "%s/%s/%s",
root, zk_map_dir, arcus_conf.mc_hostnameport);
rc = zoo_get_children(zh, zpath, ZK_NOWATCH, &strv);
if (rc != ZNONODE) break;
#ifdef PROXY_SUPPORT
if (arcus_conf.proxy) {
break; /* skip the below third checking */
}
#endif
/* 3rd check: get children of "/cache_server_mapping/ip" */
snprintf(zpath, sizeof(zpath), "%s/%s/%s",
root, zk_map_dir, arcus_conf.hostip);
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Recheck the server mapping without port number. zpath=%s\n",
zpath);
rc = zoo_get_children(zh, zpath, ZK_NOWATCH, &strv);
} while(0);
if (rc != ZOK) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Failed to read the server mapping. zpath=%s error=%d(%s)\n",
zpath, rc, zerror(rc));
return -1;
}
if (strv.count == 1) {
rc = arcus_parse_server_mapping(strv.data[0]);
if (rc < 0) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"Failed to parse server mapping znode.\n");
}
} else {
/* zoo_get_children returns ZOK even if no child exist */
/* We assume only one server mapping znode. We do not care that
* we have more than one (meaning one server participating in
* more than one service in the cluster: not likely though)
*/
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"The server mapping exists but has %d(!= 1) mapping znodes."
" zpath=%s\n", strv.count, zpath);
rc = -1;
}
deallocate_String_vector(&strv);
return rc;
}
static int arcus_create_ephemeral_znode(zhandle_t *zh)
{
int rc;
char zpath[512];
char value[200];
struct Stat zstat;
#ifdef PROXY_SUPPORT
if (arcus_conf.proxy) {
arcus_conf.znode_created = true;
return 0;
}
#endif
snprintf(zpath, sizeof(zpath), "%s/%s",
arcus_conf.cluster_path, arcus_conf.znode_name);
snprintf(value, sizeof(value), "%ldMB", (long)arcus_conf.maxbytes/1024/1024);
rc = zoo_create(zh, zpath, value, strlen(value), &ZOO_OPEN_ACL_UNSAFE,
ZOO_EPHEMERAL, NULL, 0);
if (rc) {
arcus_conf.logger->log(EXTENSION_LOG_WARNING, NULL,
"cannot create znode %s: error=%d(%s)\n", zpath, rc, zerror(rc));
if (rc == ZNODEEXISTS) {
arcus_conf.logger->log( EXTENSION_LOG_DETAIL, NULL,
"old session still exist. Wait a bit\n");
}
return -1;
}