-
Notifications
You must be signed in to change notification settings - Fork 9
/
bucket_engine.c
2600 lines (2322 loc) · 91.9 KB
/
bucket_engine.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 -*- */
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <dlfcn.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/time.h>
#ifndef WIN32
#include <arpa/inet.h>
#else
#include <winsock.h>
#endif
#include <assert.h>
#include <stddef.h>
#include <stdarg.h>
#include <memcached/engine.h>
#include <ep-engine/command_ids.h>
#include "genhash.h"
#include "topkeys.h"
#include "bucket_engine.h"
#include "bucket_engine_internal.h"
static rel_time_t (*get_current_time)(void);
static EXTENSION_LOGGER_DESCRIPTOR *logger;
#if defined(HAVE_ATOMIC_H) && defined(__SUNPRO_C)
#include <atomic.h>
static inline int ATOMIC_ADD(volatile int *dest, int value) {
return atomic_add_int_nv((volatile unsigned int *)dest, value);
}
static inline int ATOMIC_INCR(volatile int *dest) {
return atomic_inc_32_nv((volatile unsigned int *)dest);
}
static inline int ATOMIC_DECR(volatile int *dest) {
return atomic_dec_32_nv((volatile unsigned int *)dest);
}
static inline int ATOMIC_CAS(volatile bucket_state_t *dest, int prev, int next) {
return (prev == atomic_cas_uint((volatile uint_t*)dest, (uint_t)prev,
(uint_t)next));
}
#else
#define ATOMIC_ADD(i, by) __sync_add_and_fetch(i, by)
#define ATOMIC_INCR(i) ATOMIC_ADD(i, 1)
#define ATOMIC_DECR(i) ATOMIC_ADD(i, -1)
#define ATOMIC_CAS(ptr, oldval, newval) \
__sync_bool_compare_and_swap(ptr, oldval, newval)
#endif
static ENGINE_ERROR_CODE (*upstream_reserve_cookie)(const void *cookie);
static ENGINE_ERROR_CODE (*upstream_release_cookie)(const void *cookie);
static ENGINE_ERROR_CODE bucket_engine_reserve_cookie(const void *cookie);
static ENGINE_ERROR_CODE bucket_engine_release_cookie(const void *cookie);
struct bucket_list {
char *name;
int namelen;
proxied_engine_handle_t *peh;
struct bucket_list *next;
};
MEMCACHED_PUBLIC_API
ENGINE_ERROR_CODE create_instance(uint64_t interface,
GET_SERVER_API gsapi,
ENGINE_HANDLE **handle);
static const engine_info* bucket_get_info(ENGINE_HANDLE* handle);
static ENGINE_ERROR_CODE bucket_initialize(ENGINE_HANDLE* handle,
const char* config_str);
static void bucket_destroy(ENGINE_HANDLE* handle,
const bool force);
static ENGINE_ERROR_CODE bucket_item_allocate(ENGINE_HANDLE* handle,
const void* cookie,
item **item,
const void* key,
const size_t nkey,
const size_t nbytes,
const int flags,
const rel_time_t exptime);
static ENGINE_ERROR_CODE bucket_item_delete(ENGINE_HANDLE* handle,
const void* cookie,
const void* key,
const size_t nkey,
uint64_t* cas,
uint16_t vbucket);
static void bucket_item_release(ENGINE_HANDLE* handle,
const void *cookie,
item* item);
static ENGINE_ERROR_CODE bucket_get(ENGINE_HANDLE* handle,
const void* cookie,
item** item,
const void* key,
const int nkey,
uint16_t vbucket);
static ENGINE_ERROR_CODE bucket_get_stats(ENGINE_HANDLE* handle,
const void *cookie,
const char *stat_key,
int nkey,
ADD_STAT add_stat);
static void *bucket_get_stats_struct(ENGINE_HANDLE* handle,
const void *cookie);
static ENGINE_ERROR_CODE bucket_aggregate_stats(ENGINE_HANDLE* handle,
const void* cookie,
void (*callback)(void*, void*),
void *stats);
static void bucket_reset_stats(ENGINE_HANDLE* handle, const void *cookie);
static ENGINE_ERROR_CODE bucket_store(ENGINE_HANDLE* handle,
const void *cookie,
item* item,
uint64_t *cas,
ENGINE_STORE_OPERATION operation,
uint16_t vbucket);
static ENGINE_ERROR_CODE bucket_arithmetic(ENGINE_HANDLE* handle,
const void* cookie,
const void* key,
const int nkey,
const bool increment,
const bool create,
const uint64_t delta,
const uint64_t initial,
const rel_time_t exptime,
uint64_t *cas,
uint64_t *result,
uint16_t vbucket);
static ENGINE_ERROR_CODE bucket_flush(ENGINE_HANDLE* handle,
const void* cookie, time_t when);
static ENGINE_ERROR_CODE initialize_configuration(struct bucket_engine *me,
const char *cfg_str);
static ENGINE_ERROR_CODE bucket_unknown_command(ENGINE_HANDLE* handle,
const void* cookie,
protocol_binary_request_header *request,
ADD_RESPONSE response);
static bool bucket_get_item_info(ENGINE_HANDLE *handle,
const void *cookie,
const item* item,
item_info *item_info);
static void bucket_item_set_cas(ENGINE_HANDLE *handle, const void *cookie,
item *item, uint64_t cas);
static ENGINE_ERROR_CODE bucket_tap_notify(ENGINE_HANDLE* handle,
const void *cookie,
void *engine_specific,
uint16_t nengine,
uint8_t ttl,
uint16_t tap_flags,
tap_event_t tap_event,
uint32_t tap_seqno,
const void *key,
size_t nkey,
uint32_t flags,
uint32_t exptime,
uint64_t cas,
const void *data,
size_t ndata,
uint16_t vbucket);
static TAP_ITERATOR bucket_get_tap_iterator(ENGINE_HANDLE* handle, const void* cookie,
const void* client, size_t nclient,
uint32_t flags,
const void* userdata, size_t nuserdata);
static size_t bucket_errinfo(ENGINE_HANDLE *handle, const void* cookie,
char *buffer, size_t buffsz);
static ENGINE_ERROR_CODE bucket_get_engine_vb_map(ENGINE_HANDLE* handle,
const void * cookie,
engine_get_vb_map_cb callback);
static ENGINE_HANDLE *load_engine(void **dlhandle, const char *soname);
static bool is_authorized(ENGINE_HANDLE* handle, const void* cookie);
static void free_engine_handle(proxied_engine_handle_t *);
static bool list_buckets(struct bucket_engine *e, struct bucket_list **blist);
static void bucket_list_free(struct bucket_list *blist);
static void maybe_start_engine_shutdown(proxied_engine_handle_t *e);
/**
* This is the one and only instance of the bucket engine.
*/
struct bucket_engine bucket_engine = {
.engine = {
.interface = {
.interface = 1
},
.get_info = bucket_get_info,
.initialize = bucket_initialize,
.destroy = bucket_destroy,
.allocate = bucket_item_allocate,
.remove = bucket_item_delete,
.release = bucket_item_release,
.get = bucket_get,
.store = bucket_store,
.arithmetic = bucket_arithmetic,
.flush = bucket_flush,
.get_stats = bucket_get_stats,
.reset_stats = bucket_reset_stats,
.get_stats_struct = bucket_get_stats_struct,
.aggregate_stats = bucket_aggregate_stats,
.unknown_command = bucket_unknown_command,
.tap_notify = bucket_tap_notify,
.get_tap_iterator = bucket_get_tap_iterator,
.item_set_cas = bucket_item_set_cas,
.get_item_info = bucket_get_item_info,
.errinfo = bucket_errinfo,
.get_engine_vb_map = bucket_get_engine_vb_map
},
.initialized = false,
.shutdown = {
.in_progress = false,
.bucket_counter = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.cond = PTHREAD_COND_INITIALIZER,
.refcount_cond = PTHREAD_COND_INITIALIZER
},
.info.engine_info = {
.description = "Bucket engine v0.2",
.num_features = 1,
.features = {
{.feature = ENGINE_FEATURE_MULTI_TENANCY,
.description = "Multi tenancy"}
}
},
};
/**
* To help us detect if we're using free'd memory, let's write a
* pattern to the memory before releasing it. That makes it more easy
* to identify in a core file if we're operating on a freed memory area
*/
static void release_memory(void *ptr, size_t size)
{
memset(ptr, 0xae, size);
free(ptr);
}
/* Internal utility functions */
/**
* pthread_mutex_lock should _never_ fail, and instead
* of clutter the code with a lot of tests this logic is moved
* here.
*/
void must_lock(pthread_mutex_t *mutex)
{
int rv = pthread_mutex_lock(mutex);
if (rv != 0) {
logger->log(EXTENSION_LOG_WARNING, NULL,
"FATAL: Failed to lock mutex: %d", rv);
abort();
}
}
/**
* pthread_mutex_unlock should _never_ fail, and instead
* of clutter the code with a lot of tests this logic is moved
* here.
*/
void must_unlock(pthread_mutex_t *mutex)
{
int rv = pthread_mutex_unlock(mutex);
if (rv != 0) {
logger->log(EXTENSION_LOG_WARNING, NULL,
"FATAL: Failed to release mutex: %d", rv);
abort();
}
}
/**
* Access to the global list of engines is protected by a single lock.
* To make the code more readable we're using a separate function
* to acquire the lock
*/
static void lock_engines(void)
{
must_lock(&bucket_engine.engines_mutex);
}
/**
* This is the corresponding function to release the lock for
* the list of engines.
*/
static void unlock_engines(void)
{
must_unlock(&bucket_engine.engines_mutex);
}
/**
* Convert a bucket state (enum) t a textual string
*/
static const char * bucket_state_name(bucket_state_t s) {
const char * rv = NULL;
switch(s) {
case STATE_NULL: rv = "NULL"; break;
case STATE_RUNNING: rv = "running"; break;
case STATE_STOPPING: rv = "stopping"; break;
case STATE_STOPPED: rv = "stopped"; break;
}
assert(rv);
return rv;
}
/**
* Helper function to get a pointer to the server API
*/
static SERVER_HANDLE_V1 *bucket_get_server_api(void) {
return &bucket_engine.server;
}
/**
* Helper structure used by find_bucket_by_engine
*/
struct bucket_find_by_handle_data {
/** The engine we're searching for */
ENGINE_HANDLE *needle;
/** The engine-handle for this engine */
proxied_engine_handle_t *peh;
};
/**
* A callback function used by genhash_iter to locate the engine handle
* object for a given engine.
*
* Runs with engines lock held.
*
* @param key not used
* @param nkey not used
* @param val the engine handle stored at this position in the hash
* @param nval not used
* @param args pointer to a bucket_find_by_handle_data structure
* used to pass the search cirtera into the function and
* return the object (if found).
*/
static void find_bucket_by_engine(const void* key, size_t nkey,
const void *val, size_t nval,
void *args) {
(void)key;
(void)nkey;
(void)nval;
struct bucket_find_by_handle_data *find_data = args;
assert(find_data);
assert(find_data->needle);
const proxied_engine_handle_t *peh = val;
if (find_data->needle == peh->pe.v0) {
find_data->peh = (proxied_engine_handle_t *)peh;
}
}
/**
* bucket_engine intercepts the calls from the underlying engine to
* register callbacks. During startup bucket engine registers a callback
* for ON_DISCONNECT in memcached, so we should always be notified
* whenever a client disconnects. The underlying engine may however also
* want this notification, so we intercept their attemt to register
* callbacks and forward the callback to the correct engine.
*
* This function will _always_ be called while we're holding the global
* lock for the hash table (during the call to "initialize" in the
* underlying engine. It is therefore safe to try to traverse the
* engines list.
*/
static void bucket_register_callback(ENGINE_HANDLE *eh,
ENGINE_EVENT_TYPE type,
EVENT_CALLBACK cb, const void *cb_data) {
/* For simplicity, we're not going to test every combination until
we need them. */
assert(type == ON_DISCONNECT);
/* Assume this always happens while holding the hash table lock. */
/* This is called from underlying engine 'initialize' handler
* which we invoke with engines_mutex held */
struct bucket_find_by_handle_data find_data = { .needle = eh,
.peh = NULL };
genhash_iter(bucket_engine.engines, find_bucket_by_engine, &find_data);
if (find_data.peh) {
find_data.peh->cb = cb;
find_data.peh->cb_data = cb_data;
find_data.peh->wants_disconnects = true;
} else if (bucket_engine.has_default && eh == bucket_engine.default_engine.pe.v0){
bucket_engine.default_engine.cb = cb;
bucket_engine.default_engine.cb_data = cb_data;
bucket_engine.default_engine.wants_disconnects = true;
}
}
/**
* The engine api allows the underlying engine to perform various callbacks
* This isn't implemented in bucket engine as of today.
*/
static void bucket_perform_callbacks(ENGINE_EVENT_TYPE type,
const void *data, const void *cookie) {
(void)type;
(void)data;
(void)cookie;
abort(); /* Not implemented */
}
/**
* Store engine-specific data in the engine-specific section of this
* cookie's data stored in the memcached core. The "upstream" cookie
* should have been registered during the "ON_CONNECT" callback, so it
* would be a bug if it isn't here anymore
*/
static void bucket_store_engine_specific(const void *cookie, void *engine_data) {
engine_specific_t *es;
es = bucket_engine.upstream_server->cookie->get_engine_specific(cookie);
assert(es);
es->engine_specific = engine_data;
}
/**
* Get the engine-specific data from the engine-specific section of
* this cookies data stored in the memcached core.
*/
static void* bucket_get_engine_specific(const void *cookie) {
engine_specific_t *es = bucket_engine.upstream_server->cookie->get_engine_specific(cookie);
assert(es);
return es->engine_specific;
}
/**
* We don't allow the underlying engines to register or remove extensions
*/
static bool bucket_register_extension(extension_type_t type,
void *extension) {
(void)type;
(void)extension;
logger->log(EXTENSION_LOG_WARNING, NULL,
"Extension support isn't implemented in this version "
"of bucket_engine");
return false;
}
/**
* Since you can't register an extension this function should _never_ be
* called...
*/
static void bucket_unregister_extension(extension_type_t type, void *extension) {
(void)type;
(void)extension;
logger->log(EXTENSION_LOG_WARNING, NULL,
"Extension support isn't implemented in this version "
"of bucket_engine");
abort(); /* No extensions registered, none can unregister */
}
/**
* Get a given extension type from the memcached core.
* @todo Why do we overload this when all we do is wrap it directly?
*/
static void* bucket_get_extension(extension_type_t type) {
return bucket_engine.upstream_server->extension->get_extension(type);
}
/* Engine API functions */
/**
* This is the public entry point for bucket_engine. It is called by
* the memcached core and is responsible for doing basic allocation and
* initialization of the one and only instance of the bucket_engine object.
*
* The "normal" initialization is performed in bucket_initialize which is
* called from the memcached core after a successful call to create_instance.
*/
ENGINE_ERROR_CODE create_instance(uint64_t interface,
GET_SERVER_API gsapi,
ENGINE_HANDLE **handle) {
if (interface != 1) {
return ENGINE_ENOTSUP;
}
*handle = (ENGINE_HANDLE*)&bucket_engine;
bucket_engine.upstream_server = gsapi();
bucket_engine.server = *bucket_engine.upstream_server;
bucket_engine.get_server_api = bucket_get_server_api;
/* Use our own callback API for inferior engines */
bucket_engine.callback_api.register_callback = bucket_register_callback;
bucket_engine.callback_api.perform_callbacks = bucket_perform_callbacks;
bucket_engine.server.callback = &bucket_engine.callback_api;
/* Same for extensions */
bucket_engine.extension_api.register_extension = bucket_register_extension;
bucket_engine.extension_api.unregister_extension = bucket_unregister_extension;
bucket_engine.extension_api.get_extension = bucket_get_extension;
bucket_engine.server.extension = &bucket_engine.extension_api;
/* Override engine specific */
bucket_engine.cookie_api = *bucket_engine.upstream_server->cookie;
bucket_engine.server.cookie = &bucket_engine.cookie_api;
bucket_engine.server.cookie->store_engine_specific = bucket_store_engine_specific;
bucket_engine.server.cookie->get_engine_specific = bucket_get_engine_specific;
upstream_reserve_cookie = bucket_engine.server.cookie->reserve;
upstream_release_cookie = bucket_engine.server.cookie->release;
bucket_engine.server.cookie->reserve = bucket_engine_reserve_cookie;
bucket_engine.server.cookie->release = bucket_engine_release_cookie;
logger = bucket_engine.server.extension->get_extension(EXTENSION_LOGGER);
return ENGINE_SUCCESS;
}
/**
* Grab the engine handle mutex and release the proxied engine handle.
* The function currently allows you to call it with a NULL pointer,
* but that should be replaced (we should have better control of if we
* have an engine handle or not....)
*/
static void release_handle(proxied_engine_handle_t *peh) {
if (!peh) {
return;
}
int count = ATOMIC_DECR(&peh->refcount);
assert(count >= 0);
if (count == 0) {
must_lock(&bucket_engine.shutdown.mutex);
pthread_cond_broadcast(&bucket_engine.shutdown.refcount_cond);
must_unlock(&bucket_engine.shutdown.mutex);
}
}
/**
* Helper function to search for a named bucket in the list of engines
* You must wrap this call with (un)lock_engines() in order for it to
* be mt-safe
*/
static proxied_engine_handle_t *find_bucket_inner(const char *name) {
return genhash_find(bucket_engine.engines, name, strlen(name));
}
/**
* If the bucket is in a runnable state, increment its reference counter
* and return its handle. Otherwise a NIL pointer is returned.
* The caller is responsible for releasing the handle
* with release_handle.
*/
static proxied_engine_handle_t* retain_handle(proxied_engine_handle_t *peh) {
proxied_engine_handle_t *rv = NULL;
if (peh) {
if (peh->state == STATE_RUNNING) {
int count = ATOMIC_INCR(&peh->refcount);
assert(count > 0);
rv = peh;
}
}
return rv;
}
/**
* Search the list of buckets for a named bucket. If the bucket
* exists and is in a runnable state, it's reference count is
* incremented and returned. The caller is responsible for
* releasing the handle with release_handle.
*/
static proxied_engine_handle_t *find_bucket(const char *name) {
lock_engines();
proxied_engine_handle_t *rv = retain_handle(find_bucket_inner(name));
unlock_engines();
return rv;
}
/**
* Validate that the bucket name only consists of legal characters
*/
static bool has_valid_bucket_name(const char *n) {
bool rv = n[0] != 0;
for (; *n; n++) {
rv &= isalpha(*n) || isdigit(*n) || *n == '.' || *n == '%' || *n == '_' || *n == '-';
}
return rv;
}
/**
* Initialize a proxied engine handle. (Assumes that it's zeroed already
*/
static ENGINE_ERROR_CODE init_engine_handle(proxied_engine_handle_t *peh, const char *name, const char *module) {
peh->stats = bucket_engine.upstream_server->stat->new_stats();
if (peh->stats == NULL) {
return ENGINE_ENOMEM;
}
if (bucket_engine.topkeys != 0) {
peh->topkeys = calloc(TK_SHARDS, sizeof(topkeys_t *));
for (int i = 0; i < TK_SHARDS; i++) {
peh->topkeys[i] = topkeys_init(bucket_engine.topkeys);
}
if (peh->topkeys == NULL) {
bucket_engine.upstream_server->stat->release_stats(peh->stats);
peh->stats = NULL;
return ENGINE_ENOMEM;
}
}
peh->refcount = 1;
peh->name = strdup(name);
if (peh->name == NULL) {
return ENGINE_ENOMEM;
}
peh->name_len = strlen(peh->name);
if (module && strstr(module, "default_engine") != 0) {
peh->tap_iterator_disabled = true;
}
peh->state = STATE_RUNNING;
return ENGINE_SUCCESS;
}
/**
* Release the allocated resources within a proxied engine handle.
* Use free_engine_handle if you like to release the memory for the
* proxied engine handle itself...
*/
static void uninit_engine_handle(proxied_engine_handle_t *peh) {
bucket_engine.upstream_server->stat->release_stats(peh->stats);
if (peh->topkeys != NULL) {
for (int i = 0; i < TK_SHARDS; i++) {
topkeys_free(peh->topkeys[i]);
}
free(peh->topkeys);
}
release_memory((void*)peh->name, peh->name_len);
/* Note: looks like current engine API allows engine to keep some
* connections reserved past destroy call return. This implies
* that doing dlclose is raceful and thus we should not do it.
*
* Currently we also have issue with tcmalloc integration on
* windows where apparently unloading ep.so is causing some
* troubles in tcmalloc. */
/*
* if (peh->dlhandle) {
* dlclose(peh->dlhandle);
* }
*/
}
/**
* Release all resources used by a proxied engine handle and
* invalidate the proxied engine handle itself.
*/
static void free_engine_handle(proxied_engine_handle_t *peh) {
uninit_engine_handle(peh);
release_memory(peh, sizeof(*peh));
}
/**
* Creates bucket and places it's handle into *e_out. NOTE: that
* caller is responsible for calling release_handle on that handle
*/
static ENGINE_ERROR_CODE create_bucket_UNLOCKED(struct bucket_engine *e,
const char *bucket_name,
const char *path,
const char *config,
proxied_engine_handle_t **e_out,
char *msg, size_t msglen) {
ENGINE_ERROR_CODE rv;
if (!has_valid_bucket_name(bucket_name)) {
return ENGINE_EINVAL;
}
proxied_engine_handle_t *peh = calloc(sizeof(proxied_engine_handle_t), 1);
if (peh == NULL) {
return ENGINE_ENOMEM;
}
rv = init_engine_handle(peh, bucket_name, path);
if (rv != ENGINE_SUCCESS) {
release_memory(peh, sizeof(*peh));
return rv;
}
rv = ENGINE_FAILED;
peh->pe.v0 = load_engine(&peh->dlhandle, path);
if (!peh->pe.v0) {
free_engine_handle(peh);
if (msg) {
snprintf(msg, msglen, "Failed to load engine.");
}
return rv;
}
proxied_engine_handle_t *tmppeh = find_bucket_inner(bucket_name);
if (tmppeh == NULL) {
genhash_update(e->engines, bucket_name, strlen(bucket_name), peh, 0);
// This was already verified, but we'll check it anyway
assert(peh->pe.v0->interface == 1);
rv = ENGINE_SUCCESS;
if (peh->pe.v1->initialize(peh->pe.v0, config) != ENGINE_SUCCESS) {
peh->pe.v1->destroy(peh->pe.v0, false);
genhash_delete_all(e->engines, bucket_name, strlen(bucket_name));
if (msg) {
snprintf(msg, msglen,
"Failed to initialize instance. Error code: %d\n", rv);
}
rv = ENGINE_FAILED;
}
} else {
if (msg) {
snprintf(msg, msglen,
"Bucket exists: %s", bucket_state_name(tmppeh->state));
}
peh->pe.v1->destroy(peh->pe.v0, true);
rv = ENGINE_KEY_EEXISTS;
}
if (rv == ENGINE_SUCCESS) {
if (e_out) {
*e_out = peh;
} else {
release_handle(peh);
}
} else {
free_engine_handle(peh);
}
return rv;
}
/**
* The client returned from the call inside the engine. If this was the
* last client inside the engine, and the engine is scheduled for removal
* it should be safe to nuke the engine :)
*
* @param engine the proxied engine
*/
static void release_engine_handle(proxied_engine_handle_t *engine) {
assert(engine->clients > 0);
int count = ATOMIC_DECR(&engine->clients);
assert(count >= 0);
if (count == 0 && engine->state == STATE_STOPPING) {
maybe_start_engine_shutdown(engine);
}
}
/**
* Returns engine handle for this connection.
* All access to underlying engine must go through this function, because
* we keep a counter of how many cookies that are currently calling into
* the engine..
*
* NOTE: this cannot ever return engine handle that's in STATE_STOPPED
* and if returns non-null it also prevents STATE_STOPPED to be
* reached until release_engine_handle is called that'll decrement
* clients counter. Here's why:
*
* Assume it returned non-null but engine's state is
* STATE_STOPPED. But that means state was changed after it was
* observed to be STATE_RUNNING in this function. And because we never
* change from running to stopped it changed twice. Because STATE_RUNNING was seen after incrementing clients count here's sequence of inter-dependendent events:
*
* - we bump clients count
*
* - we observe STATE_RUNNING (and that also implies didn't
have STATE_STOPPED & STATE_STOPPING in past because we don't
change from STOPPING/STOPPED back to RUNNING)
*
* - some other thread changes STATE_RUNNING to STATE_STOPPING
*
* - somebody sets STATE_STOPPED (see
maybe_start_engine_shutdown). But that implies that somebody
first observed STATE_STOPPING and _then_ observed clients ==
0. Which assuming nobody decrements it without first incrementing
it cannot happen because our bumped clients count prevents that.
*
* Q.E.D.
*/
static proxied_engine_handle_t *get_engine_handle(ENGINE_HANDLE *h,
const void *cookie) {
struct bucket_engine *e = (struct bucket_engine*)h;
engine_specific_t *es;
es = e->upstream_server->cookie->get_engine_specific(cookie);
assert(es);
proxied_engine_handle_t *peh = es->peh;
if (!peh) {
if (e->default_engine.pe.v0) {
peh = &e->default_engine;
} else {
return NULL;
}
}
int count = ATOMIC_INCR(&peh->clients);
assert(count > 0);
if (peh->state != STATE_RUNNING) {
release_engine_handle(peh);
peh = NULL;
}
return peh;
}
/**
* Returns engine handle for this connection.
* All access to underlying engine must go through this function, because
* we keep a counter of how many cookies that are currently calling into
* the engine..
*/
static proxied_engine_handle_t *try_get_engine_handle(ENGINE_HANDLE *h,
const void *cookie) {
struct bucket_engine *e = (struct bucket_engine*)h;
engine_specific_t *es;
es = e->upstream_server->cookie->get_engine_specific(cookie);
if (es == NULL || es->peh == NULL) {
return NULL;
}
proxied_engine_handle_t *peh = es->peh;
proxied_engine_handle_t *ret = peh;
int count = ATOMIC_INCR(&peh->clients);
assert(count > 0);
if (peh->state != STATE_RUNNING) {
release_engine_handle(peh);
ret = NULL;
}
return ret;
}
/**
* Create an engine specific section for the cookie
*/
static void create_engine_specific(struct bucket_engine *e,
const void *cookie) {
engine_specific_t *es;
es = e->upstream_server->cookie->get_engine_specific(cookie);
assert(es == NULL);
es = calloc(1, sizeof(engine_specific_t));
assert(es);
es->reserved = ES_CONNECTED_FLAG;
e->upstream_server->cookie->store_engine_specific(cookie, es);
}
/**
* Set the engine handle for a cookie (create if it doesn't exist)
*/
static proxied_engine_handle_t* set_engine_handle(ENGINE_HANDLE *h,
const void *cookie,
proxied_engine_handle_t *peh) {
(void)h;
engine_specific_t *es;
es = bucket_engine.upstream_server->cookie->get_engine_specific(cookie);
assert(es);
/* we cannot switch bucket for connection that's reserved. With
* current code at least. */
assert((es->reserved & ~ES_CONNECTED_FLAG) == 0);
proxied_engine_handle_t *old = es->peh;
// In with the new
es->peh = retain_handle(peh);
// out with the old (this may be NULL if we did't have an associated
// strucure...
release_handle(old);
return es->peh;
}
/**
* Helper function to convert an ENGINE_HANDLE* to a bucket engine pointer
* without a cast
*/
static inline struct bucket_engine* get_handle(ENGINE_HANDLE* handle) {
return (struct bucket_engine*)handle;
}
/**
* Implementation of the the get_info function in the engine interface
*/
static const engine_info* bucket_get_info(ENGINE_HANDLE* handle) {
return &(get_handle(handle)->info.engine_info);
}
/***********************************************************
** Implementation of functions used by genhash **
**********************************************************/
/**
* Function used by genhash to check if two keys differ
*/
static int my_hash_eq(const void *k1, size_t nkey1,
const void *k2, size_t nkey2) {
return nkey1 == nkey2 && memcmp(k1, k2, nkey1) == 0;
}
/**
* Function used by genhash to create a copy of a key
*/
static void* hash_strdup(const void *k, size_t nkey) {
void *rv = calloc(nkey, 1);
assert(rv);
memcpy(rv, k, nkey);
return rv;
}
/**
* Function used by genhash to create a copy of the value (this is
* the proxied engine handle). We don't copy that value, instead
* we increase the reference count.
*/
static void* refcount_dup(const void* ob, size_t vlen) {
(void)vlen;
proxied_engine_handle_t *peh = (proxied_engine_handle_t *)ob;
assert(peh);
int count = ATOMIC_INCR(&peh->refcount);
assert(count > 0);
return (void*)ob;
}
/**
* Function used by genhash to release an object.
*/
static void engine_hash_free(void* ob) {
proxied_engine_handle_t *peh = (proxied_engine_handle_t *)ob;
assert(peh);
release_handle(peh);
peh->state = STATE_NULL;
}
/**
* Try to load a shared object and create an engine.
*
* @param dlhandle The pointer to the loaded object (OUT). The caller is
* responsible for calling dlcose() to release the resources
* if the function succeeds.
* @param soname The name of the shared object to load
* @return A pointer to the created instance, or NULL if anything
* failed.
*/
static ENGINE_HANDLE *load_engine(void **dlhandle, const char *soname) {
ENGINE_HANDLE *engine = NULL;
/* Hack to remove the warning from C99 */
union my_hack {
CREATE_INSTANCE create;
void* voidptr;
} my_create = {.create = NULL };
void *handle = dlopen(soname, RTLD_NOW | RTLD_LOCAL);
if (handle == NULL) {
const char *msg = dlerror();
logger->log(EXTENSION_LOG_WARNING, NULL,
"Failed to open library \"%s\": %s\n",
soname ? soname : "self",
msg ? msg : "unknown error");
return NULL;
}
void *symbol = dlsym(handle, "create_instance");
if (symbol == NULL) {
logger->log(EXTENSION_LOG_WARNING, NULL,
"Could not find symbol \"create_instance\" in %s: %s\n",
soname ? soname : "self",
dlerror());
return NULL;
}
my_create.voidptr = symbol;
/* request a instance with protocol version 1 */
ENGINE_ERROR_CODE error = (*my_create.create)(1,
bucket_engine.get_server_api,
&engine);
if (error != ENGINE_SUCCESS || engine == NULL) {
logger->log(EXTENSION_LOG_WARNING, NULL,
"Failed to create instance. Error code: %d\n", error);
dlclose(handle);
return NULL;
}
*dlhandle = handle;
return engine;
}
/***********************************************************
** Implementation of callbacks from the memcached core **
**********************************************************/