forked from memcached/memcached
-
Notifications
You must be signed in to change notification settings - Fork 1
/
zookeeper.c
437 lines (376 loc) · 12.6 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
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include "memcached.h"
/* zookeeper mgt */
static bool build_announcement_info(void);
static bool build_announcement_content(void);
static char *get_announce_ip(void);
static void node_completion(int, const struct String_vector *, const void *);
static void void_completion(int, const char *, const void *);
static void trigger_event(void);
static void zookeeper_event_handler(int, short, void *);
static const char* state2String(int);
static void process(zhandle_t *, int, int, const char *, void *);
static void close_zookeeper(void);
/**
* Called from the main memcached code to initialize zookeeper code.
*/
bool mc_zookeeper_init() {
//
// Initialize Zookeeper stuff
//
switch (settings.verbose) {
case 0:
zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
break;
case 1:
zoo_set_debug_level(ZOO_LOG_LEVEL_INFO);
break;
default:
zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);
break;
}
// enable deterministic order
zoo_deterministic_conn_order(1);
// Build the name of the announcement name and the path on the zookeeper service
bool result = true;
result &= build_announcement_info();
result &= build_announcement_content();
LOG_DEBUG(("Init called,%s starting zookeeper!", result ? "" : "not "));
return result;
}
/**
* Called from the main memcached code on shutdown to clean up the zookeeper connection.
*/
void mc_zookeeper_shutdown() {
close_zookeeper();
LOG_DEBUG(("Zookeeper shutdown complete"));
}
char *announce_name = NULL;
char *announce_path = NULL;
char *announce_id = NULL;
/**
* sets up the name, path and id for the service discovery announcement.
*/
static bool build_announcement_info() {
char *safe_service_type = settings.zookeeper_service_type ? settings.zookeeper_service_type : "";
uuid_t uuid;
uuid_generate(uuid);
// 36 char for UUID + \0
announce_id = malloc(37);
uuid_unparse(uuid, announce_id);
announce_id[36] = '\0';
// len of name + len of type if present + 36 for uuid + 2 for - + '\0'
int announce_name_len = strlen(settings.zookeeper_service_name) + strlen(safe_service_type) + 39;
announce_name = malloc(announce_name_len);
snprintf(announce_name, announce_name_len, "%s-%s-%s", settings.zookeeper_service_name, safe_service_type, announce_id);
// len of path + len of name + '/' + '\0'
int announce_path_len = strlen(settings.zookeeper_path) + strlen(announce_name) + 2;
announce_path = malloc(announce_path_len);
snprintf(announce_path, announce_path_len, "%s/%s", settings.zookeeper_path, announce_name);
LOG_DEBUG(("Announcement path is %s", announce_path));
return true;
}
const char *announce_data = NULL;
/**
* Creates service discovery announcement content.
*
* {
* "serviceType" : "user",
* "serviceName" : "memcached",
* "serviceId" : "eebf4159-c0d4-4d27-b002-43df95ef5824",
* "properties" : {
* "servicePort" : "21212",
* "serviceAddress" : "192.168.1.32",
* "serviceScheme" : "auto-negotiate"
* }
*/
static bool build_announcement_content() {
json_object * announce_object;
json_object * properties_object;
announce_object = json_object_new_object();
properties_object = json_object_new_object();
json_object_object_add(announce_object, SD_SERVICE_NAME, json_object_new_string(settings.zookeeper_service_name));
json_object_object_add(announce_object, SD_SERVICE_ID, json_object_new_string(announce_id));
if (settings.zookeeper_service_type) {
json_object_object_add(announce_object, SD_SERVICE_TYPE, json_object_new_string(settings.zookeeper_service_type));
}
json_object_object_add(properties_object, SD_PROP_SERVICE_SCHEME, json_object_new_string(prot_text(settings.binding_protocol)));
json_object_object_add(properties_object, SD_PROP_SERVICE_PORT, json_object_new_int(settings.port));
json_object_object_add(announce_object, SD_PROPERTIES, properties_object);
char *announce_ip = get_announce_ip();
if (!announce_ip) {
LOG_ERROR(("Could not determine announcement IP, vetoing announcement!"));
return false;
}
json_object_object_add(properties_object, SD_PROP_SERVICE_ADDRESS, json_object_new_string(announce_ip));
announce_data = json_object_get_string(announce_object);
LOG_DEBUG(("Announcement data is %s", announce_data));
return true;
}
/**
* Get the IP address that should be announced.
*/
static char *get_announce_ip()
{
struct addrinfo *ai;
struct addrinfo *next;
struct addrinfo hints = {
.ai_family = AF_INET,
.ai_socktype = SOCK_STREAM
};
char * result = NULL;
int error= getaddrinfo(settings.inter, NULL, &hints, &ai);
if (error != 0) {
if (error != EAI_SYSTEM) {
LOG_ERROR(("getaddrinfo(): %s", gai_strerror(error)));
}
else {
perror("getaddrinfo()");
}
}
else {
for (next= ai; next; next= next->ai_next) {
if (next->ai_family == AF_INET) {
struct sockaddr_in * foo = (struct sockaddr_in *) next->ai_addr;
if (foo->sin_addr.s_addr == htonl(INADDR_ANY)) {
continue;
}
else {
// 4*3 + dots + \0 = 16
result = malloc(16);
getnameinfo(next->ai_addr, next->ai_addrlen, result, 16, NULL, 0, NI_NUMERICHOST);
break; // for
}
}
}
freeaddrinfo(ai);
}
if (result) {
LOG_DEBUG(("Result is %s", result));
}
else {
LOG_DEBUG(("No address found!"));
}
return result;
}
bool connected = false;
unsigned long ticker = 0L;
// Current generation. Processing only happens if the generation
// changes (which implies a local state change). Start with 1 so that a
// full scan happens right after connection.
unsigned long generation = 1L;
unsigned long last_generation = 0;
zhandle_t *zh;
clientid_t myid;
/**
* periodically called by the main memcache loop. This will connect zookeeper if
* necessary. Also, if the generation has changed (because of a zookeeper even),
* it will then trigger data processing.
*/
void mc_zookeeper_tick() {
ticker++;
if (!zh) {
LOG_DEBUG(("Connecting zookeeper..."));
zh = zookeeper_init(settings.zookeeper_connect, process, 30000, &myid, 0, 0);
if (!zh) {
LOG_INFO(("Could not connect to zookeeper, error: %d", errno));
}
else {
LOG_DEBUG(("Zookeeper connection ok, status is %d", zoo_state(zh)));
}
trigger_event();
}
if (connected) {
long current_generation = generation;
if (last_generation < current_generation) {
LOG_DEBUG(("Tick (%d)", ticker));
int rc = zoo_aget_children(zh, settings.zookeeper_path, 1, node_completion, &ticker);
if (rc != 0) {
LOG_WARN(("Error %s while retrieving children!", zerror(rc)));
}
else {
last_generation = current_generation;
}
}
}
}
/**
* Callback with the list of children. If the local announcement is not present, create an ephemeral node on zk.
*/
static void node_completion(int rc, const struct String_vector *strings, const void *data) {
if (rc) {
LOG_WARN(("Error %s while retrieving children!", zerror(rc)));
return;
}
unsigned long tick = *((unsigned long *)data);
LOG_DEBUG(("Callback Tick (%d/%lx)", tick));
if (!strings) {
return;
}
for (int i = 0; i < strings->count; i++) {
if (!strcmp(strings->data[i], announce_name)) {
LOG_DEBUG(("Found local announcement %s", announce_name));
return;
}
}
// Need to add local announcement.
LOG_DEBUG(("Local announcement not found, creating %s", announce_path));
int rc2 = zoo_acreate(zh, announce_path, announce_data, strlen(announce_data), &ZOO_OPEN_ACL_UNSAFE, ZOO_EPHEMERAL, void_completion, NULL);
if (rc2) {
LOG_WARN(("Error %s while creating announcement!", zerror(rc)));
}
}
/**
* Callback for the node creation.
*/
static void void_completion(int rc, const char *name, const void *data) {
if (rc) {
LOG_WARN(("Error %s while creating announcement!", zerror(rc)));
}
else {
LOG_DEBUG(("Node creation complete, service now announced!"));
}
}
// Zookeeper File descriptor
int fd;
// libevent event;
struct event zk_event;
/**
* register zk with libevent for callbacks. This gets driven through the
* default timeout from zookeeper_interest (and subsequently whether there is
* need to read/write data.
*/
static void trigger_event()
{
int interest = 0;
struct timeval tv;
if (zh) {
int res = zookeeper_interest(zh, &fd, &interest, &tv);
if (res < 0) {
LOG_WARN(("Error while checking zookeeper: %d", res));
}
else {
// Always run with timeout.
short event_flags = EV_TIMEOUT;
if (fd != -1) {
if (interest & ZOOKEEPER_READ) {
LOG_DEBUG(("READ ->"));
event_flags |= EV_READ;
}
if (interest & ZOOKEEPER_WRITE) {
LOG_DEBUG(("WRITE ->"));
event_flags |= EV_WRITE;
}
}
else {
LOG_DEBUG(("Not interested in anything right now..."));
}
LOG_DEBUG(("Triggering event (%d/%d)", tv.tv_sec, tv.tv_usec));
event_set(&zk_event, fd, event_flags, zookeeper_event_handler, NULL);
event_add(&zk_event, &tv);
}
}
else {
LOG_DEBUG(("No zookeeper handle!"));
}
}
/**
* libevent handler for zookeeper events on the fd.
*/
static void zookeeper_event_handler(int fd, short event_type, void * arg)
{
int event_flags = 0;
if (event_type & EV_READ) {
LOG_DEBUG((" -> READ"));
event_flags |= ZOOKEEPER_READ;
}
if (event_type & EV_WRITE) {
LOG_DEBUG((" -> WRITE"));
event_flags |= ZOOKEEPER_WRITE;
}
if (event_flags) {
if (zh) {
zookeeper_process(zh, event_flags);
}
else {
LOG_INFO(("Event handler called with zh == null!"));
}
}
else {
LOG_DEBUG(("Called from timeout!"));
}
trigger_event();
}
/**
* Translate zookeeper status into string.
*/
static const char* state2String(int state){
if (state == 0)
return "CLOSED_STATE";
if (state == ZOO_CONNECTING_STATE)
return "CONNECTING_STATE";
if (state == ZOO_ASSOCIATING_STATE)
return "ASSOCIATING_STATE";
if (state == ZOO_CONNECTED_STATE)
return "CONNECTED_STATE";
if (state == ZOO_EXPIRED_SESSION_STATE)
return "EXPIRED_SESSION_STATE";
if (state == ZOO_AUTH_FAILED_STATE)
return "AUTH_FAILED_STATE";
return "INVALID_STATE";
}
/**
* Zookeeper callback when an event occurs.
*/
static void process(zhandle_t *zk_handle, int type, int state, const char *path, void *context)
{
LOG_DEBUG(("Watcher %d state = %s", type, state2String(state)));
if (type == ZOO_SESSION_EVENT) {
if (state == ZOO_AUTH_FAILED_STATE) {
// We don't do auth.
LOG_WARN(("Got an auth request from zookeeper. Server config is not compatible to this client!"));
}
else if (state == ZOO_CONNECTED_STATE) {
const clientid_t *id = zoo_client_id(zk_handle);
if (myid.client_id == 0 || myid.client_id != id->client_id) {
myid = *id;
LOG_DEBUG(("Got a new session id: 0x%llx",(long long int) myid.client_id));
}
connected = true;
generation++;
LOG_DEBUG(("Client now connected!"));
}
else if (state == ZOO_EXPIRED_SESSION_STATE) {
LOG_DEBUG(("Session expired, closing zookeeper"));
connected = false;
close_zookeeper();
}
else {
LOG_DEBUG(("Disconnecting"));
connected = false;
}
}
else {
generation++;
LOG_DEBUG(("Ignoring non-session event"));
}
}
static void close_zookeeper() {
if (zh) {
zookeeper_close(zh);
zh = NULL;
}
}