forked from empear-analytics/zookeeper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
zookeeper.c
4920 lines (4408 loc) · 151 KB
/
zookeeper.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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
#if !defined(DLL_EXPORT) && !defined(USE_STATIC_LIB)
# define USE_STATIC_LIB
#endif
#if defined(__CYGWIN__)
#define USE_IPV6
#endif
#include "config.h"
#include <zookeeper.h>
#include <zookeeper.jute.h>
#include <proto.h>
#include "zk_adaptor.h"
#include "zookeeper_log.h"
#include "zk_hashtable.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <assert.h>
#include <stdarg.h>
#include <limits.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_POLL
#include <poll.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h> // needed for _POSIX_MONOTONIC_CLOCK
#endif
#ifdef HAVE_SYS_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_GETPWUID_R
#include <pwd.h>
#endif
#ifdef __MACH__ // OS X
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#ifdef WIN32
#include <process.h> /* for getpid */
#include <direct.h> /* for getcwd */
#define EAI_ADDRFAMILY WSAEINVAL /* is this still needed? */
#define EHOSTDOWN EPIPE
#define ESTALE ENODEV
#endif
#define IF_DEBUG(x) if(logLevel==ZOO_LOG_LEVEL_DEBUG) {x;}
const int ZOOKEEPER_WRITE = 1 << 0;
const int ZOOKEEPER_READ = 1 << 1;
const int ZOO_EPHEMERAL = 1 << 0;
const int ZOO_SEQUENCE = 1 << 1;
const int ZOO_EXPIRED_SESSION_STATE = EXPIRED_SESSION_STATE_DEF;
const int ZOO_AUTH_FAILED_STATE = AUTH_FAILED_STATE_DEF;
const int ZOO_CONNECTING_STATE = CONNECTING_STATE_DEF;
const int ZOO_ASSOCIATING_STATE = ASSOCIATING_STATE_DEF;
const int ZOO_CONNECTED_STATE = CONNECTED_STATE_DEF;
const int ZOO_READONLY_STATE = READONLY_STATE_DEF;
const int ZOO_NOTCONNECTED_STATE = NOTCONNECTED_STATE_DEF;
static __attribute__ ((unused)) const char* state2String(int state){
switch(state){
case 0:
return "ZOO_CLOSED_STATE";
case CONNECTING_STATE_DEF:
return "ZOO_CONNECTING_STATE";
case ASSOCIATING_STATE_DEF:
return "ZOO_ASSOCIATING_STATE";
case CONNECTED_STATE_DEF:
return "ZOO_CONNECTED_STATE";
case READONLY_STATE_DEF:
return "ZOO_READONLY_STATE";
case EXPIRED_SESSION_STATE_DEF:
return "ZOO_EXPIRED_SESSION_STATE";
case AUTH_FAILED_STATE_DEF:
return "ZOO_AUTH_FAILED_STATE";
}
return "INVALID_STATE";
}
const int ZOO_CREATED_EVENT = CREATED_EVENT_DEF;
const int ZOO_DELETED_EVENT = DELETED_EVENT_DEF;
const int ZOO_CHANGED_EVENT = CHANGED_EVENT_DEF;
const int ZOO_CHILD_EVENT = CHILD_EVENT_DEF;
const int ZOO_SESSION_EVENT = SESSION_EVENT_DEF;
const int ZOO_NOTWATCHING_EVENT = NOTWATCHING_EVENT_DEF;
static __attribute__ ((unused)) const char* watcherEvent2String(int ev){
switch(ev){
case 0:
return "ZOO_ERROR_EVENT";
case CREATED_EVENT_DEF:
return "ZOO_CREATED_EVENT";
case DELETED_EVENT_DEF:
return "ZOO_DELETED_EVENT";
case CHANGED_EVENT_DEF:
return "ZOO_CHANGED_EVENT";
case CHILD_EVENT_DEF:
return "ZOO_CHILD_EVENT";
case SESSION_EVENT_DEF:
return "ZOO_SESSION_EVENT";
case NOTWATCHING_EVENT_DEF:
return "ZOO_NOTWATCHING_EVENT";
}
return "INVALID_EVENT";
}
const int ZOO_PERM_READ = 1 << 0;
const int ZOO_PERM_WRITE = 1 << 1;
const int ZOO_PERM_CREATE = 1 << 2;
const int ZOO_PERM_DELETE = 1 << 3;
const int ZOO_PERM_ADMIN = 1 << 4;
const int ZOO_PERM_ALL = 0x1f;
struct Id ZOO_ANYONE_ID_UNSAFE = {"world", "anyone"};
struct Id ZOO_AUTH_IDS = {"auth", ""};
static struct ACL _OPEN_ACL_UNSAFE_ACL[] = {{0x1f, {"world", "anyone"}}};
static struct ACL _READ_ACL_UNSAFE_ACL[] = {{0x01, {"world", "anyone"}}};
static struct ACL _CREATOR_ALL_ACL_ACL[] = {{0x1f, {"auth", ""}}};
struct ACL_vector ZOO_OPEN_ACL_UNSAFE = { 1, _OPEN_ACL_UNSAFE_ACL};
struct ACL_vector ZOO_READ_ACL_UNSAFE = { 1, _READ_ACL_UNSAFE_ACL};
struct ACL_vector ZOO_CREATOR_ALL_ACL = { 1, _CREATOR_ALL_ACL_ACL};
#define COMPLETION_WATCH -1
#define COMPLETION_VOID 0
#define COMPLETION_STAT 1
#define COMPLETION_DATA 2
#define COMPLETION_STRINGLIST 3
#define COMPLETION_STRINGLIST_STAT 4
#define COMPLETION_ACLLIST 5
#define COMPLETION_STRING 6
#define COMPLETION_MULTI 7
#define COMPLETION_STRING_STAT 8
typedef struct _auth_completion_list {
void_completion_t completion;
const char *auth_data;
struct _auth_completion_list *next;
} auth_completion_list_t;
typedef struct completion {
int type; /* one of COMPLETION_* values above */
union {
void_completion_t void_result;
stat_completion_t stat_result;
data_completion_t data_result;
strings_completion_t strings_result;
strings_stat_completion_t strings_stat_result;
acl_completion_t acl_result;
string_completion_t string_result;
string_stat_completion_t string_stat_result;
struct watcher_object_list *watcher_result;
};
completion_head_t clist; /* For multi-op */
} completion_t;
typedef struct _completion_list {
int xid;
completion_t c;
const void *data;
buffer_list_t *buffer;
struct _completion_list *next;
watcher_registration_t* watcher;
watcher_deregistration_t* watcher_deregistration;
} completion_list_t;
const char*err2string(int err);
static int queue_session_event(zhandle_t *zh, int state);
static const char* format_endpoint_info(const struct sockaddr_storage* ep);
/* deserialize forward declarations */
static void deserialize_response(zhandle_t *zh, int type, int xid, int failed, int rc, completion_list_t *cptr, struct iarchive *ia);
static int deserialize_multi(zhandle_t *zh, int xid, completion_list_t *cptr, struct iarchive *ia);
/* completion routine forward declarations */
static int add_completion(zhandle_t *zh, int xid, int completion_type,
const void *dc, const void *data, int add_to_front,
watcher_registration_t* wo, completion_head_t *clist);
static int add_completion_deregistration(zhandle_t *zh, int xid,
int completion_type, const void *dc, const void *data,
int add_to_front, watcher_deregistration_t* wo,
completion_head_t *clist);
static int do_add_completion(zhandle_t *zh, const void *dc, completion_list_t *c,
int add_to_front);
static completion_list_t* create_completion_entry(zhandle_t *zh, int xid, int completion_type,
const void *dc, const void *data, watcher_registration_t* wo,
completion_head_t *clist);
static completion_list_t* create_completion_entry_deregistration(zhandle_t *zh,
int xid, int completion_type, const void *dc, const void *data,
watcher_deregistration_t* wo, completion_head_t *clist);
static completion_list_t* do_create_completion_entry(zhandle_t *zh,
int xid, int completion_type, const void *dc, const void *data,
watcher_registration_t* wo, completion_head_t *clist,
watcher_deregistration_t* wdo);
static void destroy_completion_entry(completion_list_t* c);
static void queue_completion_nolock(completion_head_t *list, completion_list_t *c,
int add_to_front);
static void queue_completion(completion_head_t *list, completion_list_t *c,
int add_to_front);
static int handle_socket_error_msg(zhandle_t *zh, int line, int rc,
const char* format,...);
static void cleanup_bufs(zhandle_t *zh,int callCompletion,int rc);
static int disable_conn_permute=0; // permute enabled by default
static struct sockaddr_storage *addr_rw_server = 0;
static __attribute__((unused)) void print_completion_queue(zhandle_t *zh);
static void *SYNCHRONOUS_MARKER = (void*)&SYNCHRONOUS_MARKER;
static int isValidPath(const char* path, const int flags);
static int aremove_watches(
zhandle_t *zh, const char *path, ZooWatcherType wtype,
watcher_fn watcher, void *watcherCtx, int local,
void_completion_t *completion, const void *data, int all);
#ifdef THREADED
static void process_sync_completion(zhandle_t *zh,
completion_list_t *cptr,
struct sync_completion *sc,
struct iarchive *ia);
static int remove_watches(
zhandle_t *zh, const char *path, ZooWatcherType wtype,
watcher_fn watcher, void *watcherCtx, int local, int all);
#endif
#ifdef _WIN32
typedef SOCKET socket_t;
typedef int sendsize_t;
#define SEND_FLAGS 0
#else
#ifdef __APPLE__
#define SEND_FLAGS SO_NOSIGPIPE
#endif
#ifdef __linux__
#define SEND_FLAGS MSG_NOSIGNAL
#endif
#ifndef SEND_FLAGS
#define SEND_FLAGS 0
#endif
typedef int socket_t;
typedef ssize_t sendsize_t;
#endif
static void zookeeper_set_sock_nodelay(zhandle_t *, socket_t);
static void zookeeper_set_sock_noblock(zhandle_t *, socket_t);
static void zookeeper_set_sock_timeout(zhandle_t *, socket_t, int);
static socket_t zookeeper_connect(zhandle_t *, struct sockaddr_storage *, socket_t);
/*
* abort due to the use of a sync api in a singlethreaded environment
*/
static void abort_singlethreaded(zhandle_t *zh)
{
LOG_ERROR(LOGCALLBACK(zh), "Sync completion used without threads");
abort();
}
static sendsize_t zookeeper_send(socket_t s, const void* buf, size_t len)
{
return send(s, buf, len, SEND_FLAGS);
}
/**
* Get the system time.
*
* If the monotonic clock is available, we use that. The monotonic clock does
* not change when the wall-clock time is adjusted by NTP or the system
* administrator. The monotonic clock returns a value which is monotonically
* increasing.
*
* If POSIX monotonic clocks are not available, we fall back on the wall-clock.
*
* @param tv (out param) The time.
*/
void get_system_time(struct timeval *tv)
{
int ret;
#ifdef __MACH__ // OS X
clock_serv_t cclock;
mach_timespec_t mts;
ret = host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
if (!ret) {
ret += clock_get_time(cclock, &mts);
ret += mach_port_deallocate(mach_task_self(), cclock);
if (!ret) {
tv->tv_sec = mts.tv_sec;
tv->tv_usec = mts.tv_nsec / 1000;
}
}
if (ret) {
// Default to gettimeofday in case of failure.
ret = gettimeofday(tv, NULL);
}
#elif CLOCK_MONOTONIC_RAW
// On Linux, CLOCK_MONOTONIC is affected by ntp slew but CLOCK_MONOTONIC_RAW
// is not. We want the non-slewed (constant rate) CLOCK_MONOTONIC_RAW if it
// is available.
struct timespec ts = { 0 };
ret = clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / 1000;
#elif _POSIX_MONOTONIC_CLOCK
struct timespec ts = { 0 };
ret = clock_gettime(CLOCK_MONOTONIC, &ts);
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / 1000;
#elif _WIN32
LARGE_INTEGER counts, countsPerSecond, countsPerMicrosecond;
if (QueryPerformanceFrequency(&countsPerSecond) &&
QueryPerformanceCounter(&counts)) {
countsPerMicrosecond.QuadPart = countsPerSecond.QuadPart / 1000000;
tv->tv_sec = (long)(counts.QuadPart / countsPerSecond.QuadPart);
tv->tv_usec = (long)((counts.QuadPart % countsPerSecond.QuadPart) /
countsPerMicrosecond.QuadPart);
ret = 0;
} else {
ret = gettimeofday(tv, NULL);
}
#else
ret = gettimeofday(tv, NULL);
#endif
if (ret) {
abort();
}
}
const void *zoo_get_context(zhandle_t *zh)
{
return zh->context;
}
void zoo_set_context(zhandle_t *zh, void *context)
{
if (zh != NULL) {
zh->context = context;
}
}
int zoo_recv_timeout(zhandle_t *zh)
{
return zh->recv_timeout;
}
/** these functions are thread unsafe, so make sure that
zoo_lock_auth is called before you access them **/
static auth_info* get_last_auth(auth_list_head_t *auth_list) {
auth_info *element;
element = auth_list->auth;
if (element == NULL) {
return NULL;
}
while (element->next != NULL) {
element = element->next;
}
return element;
}
static void free_auth_completion(auth_completion_list_t *a_list) {
auth_completion_list_t *tmp, *ftmp;
if (a_list == NULL) {
return;
}
tmp = a_list->next;
while (tmp != NULL) {
ftmp = tmp;
tmp = tmp->next;
ftmp->completion = NULL;
ftmp->auth_data = NULL;
free(ftmp);
}
a_list->completion = NULL;
a_list->auth_data = NULL;
a_list->next = NULL;
return;
}
static void add_auth_completion(auth_completion_list_t* a_list, void_completion_t* completion,
const char *data) {
auth_completion_list_t *element;
auth_completion_list_t *n_element;
element = a_list;
if (a_list->completion == NULL) {
//this is the first element
a_list->completion = *completion;
a_list->next = NULL;
a_list->auth_data = data;
return;
}
while (element->next != NULL) {
element = element->next;
}
n_element = (auth_completion_list_t*) malloc(sizeof(auth_completion_list_t));
n_element->next = NULL;
n_element->completion = *completion;
n_element->auth_data = data;
element->next = n_element;
return;
}
static void get_auth_completions(auth_list_head_t *auth_list, auth_completion_list_t *a_list) {
auth_info *element;
element = auth_list->auth;
if (element == NULL) {
return;
}
while (element) {
if (element->completion) {
add_auth_completion(a_list, &element->completion, element->data);
}
element->completion = NULL;
element = element->next;
}
return;
}
static void add_last_auth(auth_list_head_t *auth_list, auth_info *add_el) {
auth_info *element;
element = auth_list->auth;
if (element == NULL) {
//first element in the list
auth_list->auth = add_el;
return;
}
while (element->next != NULL) {
element = element->next;
}
element->next = add_el;
return;
}
static void init_auth_info(auth_list_head_t *auth_list)
{
auth_list->auth = NULL;
}
static void mark_active_auth(zhandle_t *zh) {
auth_list_head_t auth_h = zh->auth_h;
auth_info *element;
if (auth_h.auth == NULL) {
return;
}
element = auth_h.auth;
while (element != NULL) {
element->state = 1;
element = element->next;
}
}
static void free_auth_info(auth_list_head_t *auth_list)
{
auth_info *auth = auth_list->auth;
while (auth != NULL) {
auth_info* old_auth = NULL;
if(auth->scheme!=NULL)
free(auth->scheme);
deallocate_Buffer(&auth->auth);
old_auth = auth;
auth = auth->next;
free(old_auth);
}
init_auth_info(auth_list);
}
int is_unrecoverable(zhandle_t *zh)
{
return (zh->state<0)? ZINVALIDSTATE: ZOK;
}
zk_hashtable *exists_result_checker(zhandle_t *zh, int rc)
{
if (rc == ZOK) {
return zh->active_node_watchers;
} else if (rc == ZNONODE) {
return zh->active_exist_watchers;
}
return 0;
}
zk_hashtable *data_result_checker(zhandle_t *zh, int rc)
{
return rc==ZOK ? zh->active_node_watchers : 0;
}
zk_hashtable *child_result_checker(zhandle_t *zh, int rc)
{
return rc==ZOK ? zh->active_child_watchers : 0;
}
/**
* Frees and closes everything associated with a handle,
* including the handle itself.
*/
static void destroy(zhandle_t *zh)
{
if (zh == NULL) {
return;
}
/* call any outstanding completions with a special error code */
cleanup_bufs(zh,1,ZCLOSING);
if (zh->hostname != 0) {
free(zh->hostname);
zh->hostname = NULL;
}
if (zh->fd != -1) {
close(zh->fd);
zh->fd = -1;
memset(&zh->addr_cur, 0, sizeof(zh->addr_cur));
zh->state = 0;
}
addrvec_free(&zh->addrs);
if (zh->chroot != NULL) {
free(zh->chroot);
zh->chroot = NULL;
}
free_auth_info(&zh->auth_h);
destroy_zk_hashtable(zh->active_node_watchers);
destroy_zk_hashtable(zh->active_exist_watchers);
destroy_zk_hashtable(zh->active_child_watchers);
addrvec_free(&zh->addrs_old);
addrvec_free(&zh->addrs_new);
}
static void setup_random()
{
#ifndef _WIN32 // TODO: better seed
int seed;
int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1) {
seed = getpid();
} else {
int seed_len = 0;
/* Enter a loop to fill in seed with random data from /dev/urandom.
* This is done in a loop so that we can safely handle short reads
* which can happen due to signal interruptions.
*/
while (seed_len < sizeof(seed)) {
/* Assert we either read something or we were interrupted due to a
* signal (errno == EINTR) in which case we need to retry.
*/
int rc = read(fd, &seed + seed_len, sizeof(seed) - seed_len);
assert(rc > 0 || errno == EINTR);
if (rc > 0) {
seed_len += rc;
}
}
close(fd);
}
srandom(seed);
srand48(seed);
#endif
}
#ifndef __CYGWIN__
/**
* get the errno from the return code
* of get addrinfo. Errno is not set
* with the call to getaddrinfo, so thats
* why we have to do this.
*/
static int getaddrinfo_errno(int rc) {
switch(rc) {
case EAI_NONAME:
// ZOOKEEPER-1323 EAI_NODATA and EAI_ADDRFAMILY are deprecated in FreeBSD.
#if defined EAI_NODATA && EAI_NODATA != EAI_NONAME
case EAI_NODATA:
#endif
return ENOENT;
case EAI_MEMORY:
return ENOMEM;
default:
return EINVAL;
}
}
#endif
/**
* Count the number of hosts in the connection host string. This assumes it's
* a well-formed connection string whereby each host is separated by a comma.
*/
static int count_hosts(char *hosts)
{
uint32_t count = 0;
char *loc = hosts;
if (!hosts || strlen(hosts) == 0) {
return 0;
}
while ((loc = strchr(loc, ','))) {
count++;
loc+=1;
}
return count+1;
}
/**
* Resolve hosts and populate provided address vector with shuffled results.
* The contents of the provided address vector will be initialized to an
* empty state.
*/
static int resolve_hosts(const zhandle_t *zh, const char *hosts_in, addrvec_t *avec)
{
int rc = ZOK;
char *host = NULL;
char *hosts = NULL;
int num_hosts = 0;
char *strtok_last = NULL;
if (zh == NULL || hosts_in == NULL || avec == NULL) {
return ZBADARGUMENTS;
}
// initialize address vector
addrvec_init(avec);
hosts = strdup(hosts_in);
if (hosts == NULL) {
LOG_ERROR(LOGCALLBACK(zh), "out of memory");
errno=ENOMEM;
rc=ZSYSTEMERROR;
goto fail;
}
num_hosts = count_hosts(hosts);
if (num_hosts == 0) {
free(hosts);
return ZOK;
}
// Allocate list inside avec
rc = addrvec_alloc_capacity(avec, num_hosts);
if (rc != 0) {
LOG_ERROR(LOGCALLBACK(zh), "out of memory");
errno=ENOMEM;
rc=ZSYSTEMERROR;
goto fail;
}
host = strtok_r(hosts, ",", &strtok_last);
while(host) {
char *port_spec = strrchr(host, ':');
char *end_port_spec;
int port;
if (!port_spec) {
LOG_ERROR(LOGCALLBACK(zh), "no port in %s", host);
errno=EINVAL;
rc=ZBADARGUMENTS;
goto fail;
}
*port_spec = '\0';
port_spec++;
port = strtol(port_spec, &end_port_spec, 0);
if (!*port_spec || *end_port_spec || port == 0) {
LOG_ERROR(LOGCALLBACK(zh), "invalid port in %s", host);
errno=EINVAL;
rc=ZBADARGUMENTS;
goto fail;
}
#if defined(__CYGWIN__)
// sadly CYGWIN doesn't have getaddrinfo
// but happily gethostbyname is threadsafe in windows
{
struct hostent *he;
char **ptr;
struct sockaddr_in *addr4;
he = gethostbyname(host);
if (!he) {
LOG_ERROR(LOGCALLBACK(zh), "could not resolve %s", host);
errno=ENOENT;
rc=ZBADARGUMENTS;
goto fail;
}
// Setup the address array
for(ptr = he->h_addr_list;*ptr != 0; ptr++) {
if (addrs->count == addrs->capacity) {
rc = addrvec_grow_default(addrs);
if (rc != 0) {
LOG_ERROR(LOGCALLBACK(zh), "out of memory");
errno=ENOMEM;
rc=ZSYSTEMERROR;
goto fail;
}
}
addr = &addrs->list[addrs->count];
addr4 = (struct sockaddr_in*)addr;
addr->ss_family = he->h_addrtype;
if (addr->ss_family == AF_INET) {
addr4->sin_port = htons(port);
memset(&addr4->sin_zero, 0, sizeof(addr4->sin_zero));
memcpy(&addr4->sin_addr, *ptr, he->h_length);
zh->addrs.count++;
}
#if defined(AF_INET6)
else if (addr->ss_family == AF_INET6) {
struct sockaddr_in6 *addr6;
addr6 = (struct sockaddr_in6*)addr;
addr6->sin6_port = htons(port);
addr6->sin6_scope_id = 0;
addr6->sin6_flowinfo = 0;
memcpy(&addr6->sin6_addr, *ptr, he->h_length);
zh->addrs.count++;
}
#endif
else {
LOG_WARN(LOGCALLBACK(zh), "skipping unknown address family %x for %s",
addr->ss_family, hosts_in);
}
}
host = strtok_r(0, ",", &strtok_last);
}
#else
{
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
#ifdef AI_ADDRCONFIG
hints.ai_flags = AI_ADDRCONFIG;
#else
hints.ai_flags = 0;
#endif
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
while(isspace(*host) && host != strtok_last)
host++;
if ((rc = getaddrinfo(host, port_spec, &hints, &res0)) != 0) {
//bug in getaddrinfo implementation when it returns
//EAI_BADFLAGS or EAI_ADDRFAMILY with AF_UNSPEC and
// ai_flags as AI_ADDRCONFIG
#ifdef AI_ADDRCONFIG
if ((hints.ai_flags == AI_ADDRCONFIG) &&
// ZOOKEEPER-1323 EAI_NODATA and EAI_ADDRFAMILY are deprecated in FreeBSD.
#ifdef EAI_ADDRFAMILY
((rc ==EAI_BADFLAGS) || (rc == EAI_ADDRFAMILY))) {
#else
(rc == EAI_BADFLAGS)) {
#endif
//reset ai_flags to null
hints.ai_flags = 0;
//retry getaddrinfo
rc = getaddrinfo(host, port_spec, &hints, &res0);
}
#endif
if (rc != 0) {
errno = getaddrinfo_errno(rc);
#ifdef _WIN32
LOG_ERROR(LOGCALLBACK(zh), "Win32 message: %s\n", gai_strerror(rc));
#elif __linux__ && __GNUC__
LOG_ERROR(LOGCALLBACK(zh), "getaddrinfo: %s\n", gai_strerror(rc));
#else
LOG_ERROR(LOGCALLBACK(zh), "getaddrinfo: %s\n", strerror(errno));
#endif
rc=ZSYSTEMERROR;
goto fail;
}
}
for (res = res0; res; res = res->ai_next) {
// Expand address list if needed
if (avec->count == avec->capacity) {
rc = addrvec_grow_default(avec);
if (rc != 0) {
LOG_ERROR(LOGCALLBACK(zh), "out of memory");
errno=ENOMEM;
rc=ZSYSTEMERROR;
goto fail;
}
}
// Copy addrinfo into address list
switch (res->ai_family) {
case AF_INET:
#if defined(AF_INET6)
case AF_INET6:
#endif
addrvec_append_addrinfo(avec, res);
break;
default:
LOG_WARN(LOGCALLBACK(zh), "skipping unknown address family %x for %s",
res->ai_family, hosts_in);
break;
}
}
freeaddrinfo(res0);
host = strtok_r(0, ",", &strtok_last);
}
#endif
}
free(hosts);
if(!disable_conn_permute){
setup_random();
addrvec_shuffle(avec);
}
return ZOK;
fail:
addrvec_free(avec);
if (hosts) {
free(hosts);
hosts = NULL;
}
return rc;
}
/**
* Updates the list of servers and determine if changing connections is necessary.
* Permutes server list for proper load balancing.
*
* Changing connections is necessary if one of the following holds:
* a) the server this client is currently connected is not in new address list.
* Otherwise (if currentHost is in the new list):
* b) the number of servers in the cluster is increasing - in this case the load
* on currentHost should decrease, which means that SOME of the clients
* connected to it will migrate to the new servers. The decision whether this
* client migrates or not is probabilistic so that the expected number of
* clients connected to each server is the same.
*
* If reconfig is set to true, the function sets pOld and pNew that correspond
* to the probability to migrate to ones of the new servers or one of the old
* servers (migrating to one of the old servers is done only if our client's
* currentHost is not in new list).
*
* See zoo_cycle_next_server for the selection logic.
*
* See {@link https://issues.apache.org/jira/browse/ZOOKEEPER-1355} for the
* protocol and its evaluation,
*/
int update_addrs(zhandle_t *zh)
{
int rc = ZOK;
char *hosts = NULL;
uint32_t num_old = 0;
uint32_t num_new = 0;
uint32_t i = 0;
int found_current = 0;
addrvec_t resolved = { 0 };
// Verify we have a valid handle
if (zh == NULL) {
return ZBADARGUMENTS;
}
// zh->hostname should always be set
if (zh->hostname == NULL)
{
return ZSYSTEMERROR;
}
// NOTE: guard access to {hostname, addr_cur, addrs, addrs_old, addrs_new}
lock_reconfig(zh);
// Copy zh->hostname for local use
hosts = strdup(zh->hostname);
if (hosts == NULL) {
rc = ZSYSTEMERROR;
goto fail;
}
rc = resolve_hosts(zh, hosts, &resolved);
if (rc != ZOK)
{
goto fail;
}
// If the addrvec list is identical to last time we ran don't do anything
if (addrvec_eq(&zh->addrs, &resolved))
{
goto fail;
}
// Is the server we're connected to in the new resolved list?
found_current = addrvec_contains(&resolved, &zh->addr_cur);
// Clear out old and new address lists
zh->reconfig = 1;
addrvec_free(&zh->addrs_old);
addrvec_free(&zh->addrs_new);
// Divide server list into addrs_old if in previous list and addrs_new if not
for (i = 0; i < resolved.count; i++)
{
struct sockaddr_storage *resolved_address = &resolved.data[i];
if (addrvec_contains(&zh->addrs, resolved_address))
{
rc = addrvec_append(&zh->addrs_old, resolved_address);
if (rc != ZOK)
{
goto fail;
}
}
else {
rc = addrvec_append(&zh->addrs_new, resolved_address);
if (rc != ZOK)
{
goto fail;
}
}
}
num_old = zh->addrs_old.count;
num_new = zh->addrs_new.count;
// Number of servers increased
if (num_old + num_new > zh->addrs.count)
{
if (found_current) {
// my server is in the new config, but load should be decreased.
// Need to decide if the client is moving to one of the new servers
if (drand48() <= (1 - ((double)zh->addrs.count) / (num_old + num_new))) {
zh->pNew = 1;
zh->pOld = 0;
} else {
// do nothing special -- stay with the current server
zh->reconfig = 0;
}
} else {
// my server is not in the new config, and load on old servers must
// be decreased, so connect to one of the new servers
zh->pNew = 1;
zh->pOld = 0;
}
}
// Number of servers stayed the same or decreased
else {
if (found_current) {
// my server is in the new config, and load should be increased, so
// stay with this server and do nothing special
zh->reconfig = 0;
} else {
zh->pOld = ((double) (num_old * (zh->addrs.count - (num_old + num_new)))) / ((num_old + num_new) * (zh->addrs.count - num_old));
zh->pNew = 1 - zh->pOld;
}