/
ep_engine.cc
2349 lines (2049 loc) · 86.6 KB
/
ep_engine.cc
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 -*- */
/*
* Copyright 2010 NorthScale, Inc.
*
* 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.
*/
#include "config.h"
#include <limits>
#include <assert.h>
#include <fcntl.h>
#include <memcached/engine.h>
#include <memcached/protocol_binary.h>
#include "ep_engine.h"
static size_t percentOf(size_t val, double percent) {
return static_cast<size_t>(static_cast<double>(val) * percent);
}
Atomic<uint64_t> TapConnection::tapCounter(1);
/**
* Helper function to avoid typing in the long cast all over the place
* @param handle pointer to the engine
* @return the engine as a class
*/
static inline EventuallyPersistentEngine* getHandle(ENGINE_HANDLE* handle)
{
return reinterpret_cast<EventuallyPersistentEngine*>(handle);
}
void LookupCallback::callback(GetValue &value) {
if (value.getStatus() == ENGINE_SUCCESS) {
engine->addLookupResult(cookie, value.getValue());
} else {
engine->addLookupResult(cookie, NULL);
}
engine->getServerApi()->cookie->notify_io_complete(cookie, value.getStatus());
}
template <typename T>
static void validate(T v, T l, T h) {
if (v < l || v > h) {
throw std::runtime_error("value out of range.");
}
}
// The Engine API specifies C linkage for the functions..
extern "C" {
static const engine_info* EvpGetInfo(ENGINE_HANDLE* handle)
{
return getHandle(handle)->getInfo();
}
static ENGINE_ERROR_CODE EvpInitialize(ENGINE_HANDLE* handle,
const char* config_str)
{
return getHandle(handle)->initialize(config_str);
}
static void EvpDestroy(ENGINE_HANDLE* handle)
{
getHandle(handle)->destroy();
delete getHandle(handle);
}
static ENGINE_ERROR_CODE EvpItemAllocate(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)
{
return getHandle(handle)->itemAllocate(cookie, item, key,
nkey, nbytes, flags, exptime);
}
static ENGINE_ERROR_CODE EvpItemDelete(ENGINE_HANDLE* handle,
const void* cookie,
const void* key,
const size_t nkey,
uint64_t cas,
uint16_t vbucket)
{
return getHandle(handle)->itemDelete(cookie, key, nkey, cas, vbucket);
}
static void EvpItemRelease(ENGINE_HANDLE* handle,
const void *cookie,
item* item)
{
getHandle(handle)->itemRelease(cookie, item);
}
static ENGINE_ERROR_CODE EvpGet(ENGINE_HANDLE* handle,
const void* cookie,
item** item,
const void* key,
const int nkey,
uint16_t vbucket)
{
return getHandle(handle)->get(cookie, item, key, nkey, vbucket);
}
static ENGINE_ERROR_CODE EvpGetStats(ENGINE_HANDLE* handle,
const void* cookie,
const char* stat_key,
int nkey,
ADD_STAT add_stat)
{
return getHandle(handle)->getStats(cookie, stat_key, nkey, add_stat);
}
static ENGINE_ERROR_CODE EvpStore(ENGINE_HANDLE* handle,
const void *cookie,
item* item,
uint64_t *cas,
ENGINE_STORE_OPERATION operation,
uint16_t vbucket)
{
return getHandle(handle)->store(cookie, item, cas, operation, vbucket);
}
static ENGINE_ERROR_CODE EvpArithmetic(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)
{
return getHandle(handle)->arithmetic(cookie, key, nkey, increment,
create, delta, initial, exptime,
cas, result, vbucket);
}
static ENGINE_ERROR_CODE EvpFlush(ENGINE_HANDLE* handle,
const void* cookie, time_t when)
{
return getHandle(handle)->flush(cookie, when);
}
static void EvpResetStats(ENGINE_HANDLE* handle, const void *cookie)
{
(void)cookie;
return getHandle(handle)->resetStats();
}
static protocol_binary_response_status stopFlusher(EventuallyPersistentEngine *e,
const char **msg) {
return e->stopFlusher(msg);
}
static protocol_binary_response_status startFlusher(EventuallyPersistentEngine *e,
const char **msg) {
return e->startFlusher(msg);
}
static protocol_binary_response_status setTapParam(EventuallyPersistentEngine *e,
const char *keyz, const char *valz,
const char **msg) {
(void)e; (void)keyz; (void)valz;
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
*msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
return rv;
}
static protocol_binary_response_status setFlushParam(EventuallyPersistentEngine *e,
const char *keyz, const char *valz,
const char **msg) {
*msg = "Updated";
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
// Handle the actual mutation.
try {
int v = atoi(valz);
if (strcmp(keyz, "min_data_age") == 0) {
validate(v, 0, MAX_DATA_AGE_PARAM);
e->setMinDataAge(v);
} else if (strcmp(keyz, "queue_age_cap") == 0) {
validate(v, 0, MAX_DATA_AGE_PARAM);
e->setQueueAgeCap(v);
} else if (strcmp(keyz, "max_txn_size") == 0) {
validate(v, 1, MAX_TXN_SIZE);
e->setTxnSize(v);
} else if (strcmp(keyz, "bg_fetch_delay") == 0) {
validate(v, 0, MAX_BG_FETCH_DELAY);
e->setBGFetchDelay(static_cast<uint32_t>(v));
} else if (strcmp(keyz, "max_size") == 0) {
// Want more bits than int.
char *ptr = NULL;
// TODO: This parser isn't perfect.
uint64_t vsize = strtoull(valz, &ptr, 10);
validate(vsize, static_cast<uint64_t>(0),
std::numeric_limits<uint64_t>::max());
EPStats &stats = e->getEpStats();
stats.maxDataSize = vsize;
stats.mem_low_wat = percentOf(StoredValue::getMaxDataSize(stats), 0.6);
stats.mem_high_wat = percentOf(StoredValue::getMaxDataSize(stats), 0.75);
} else if (strcmp(keyz, "mem_low_wat") == 0) {
// Want more bits than int.
char *ptr = NULL;
// TODO: This parser isn't perfect.
uint64_t vsize = strtoull(valz, &ptr, 10);
validate(vsize, static_cast<uint64_t>(0),
std::numeric_limits<uint64_t>::max());
EPStats &stats = e->getEpStats();
stats.mem_low_wat = vsize;
} else if (strcmp(keyz, "mem_high_wat") == 0) {
// Want more bits than int.
char *ptr = NULL;
// TODO: This parser isn't perfect.
uint64_t vsize = strtoull(valz, &ptr, 10);
validate(vsize, static_cast<uint64_t>(0),
std::numeric_limits<uint64_t>::max());
EPStats &stats = e->getEpStats();
stats.mem_high_wat = vsize;
} else {
*msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
}
} catch(std::runtime_error ignored_exception) {
*msg = "Value out of range.";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
}
return rv;
}
static protocol_binary_response_status evictKey(EventuallyPersistentEngine *e,
protocol_binary_request_header *request,
const char **msg) {
protocol_binary_request_no_extras *req =
(protocol_binary_request_no_extras*)request;
char keyz[256];
// Read the key.
int keylen = ntohs(req->message.header.request.keylen);
if (keylen >= (int)sizeof(keyz)) {
*msg = "Key is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(keyz, ((char*)request) + sizeof(req->message.header), keylen);
keyz[keylen] = 0x00;
uint16_t vbucket = ntohs(request->request.vbucket);
std::string key(keyz, keylen);
getLogger()->log(EXTENSION_LOG_DEBUG, NULL,
"Manually evicting object with key %s\n",
keyz);
return e->evictKey(key, vbucket, msg);
}
static protocol_binary_response_status setParam(EventuallyPersistentEngine *e,
protocol_binary_request_header *request,
const char **msg) {
protocol_binary_request_no_extras *req =
(protocol_binary_request_no_extras*)request;
char keyz[32];
char valz[512];
// Read the key.
int keylen = ntohs(req->message.header.request.keylen);
if (keylen >= (int)sizeof(keyz)) {
*msg = "Key is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(keyz, ((char*)request) + sizeof(req->message.header), keylen);
keyz[keylen] = 0x00;
// Read the value.
size_t bodylen = ntohl(req->message.header.request.bodylen)
- ntohs(req->message.header.request.keylen);
if (bodylen >= sizeof(valz)) {
*msg = "Value is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(valz, (char*)request + sizeof(req->message.header)
+ keylen, bodylen);
valz[bodylen] = 0x00;
protocol_binary_response_status rv;
switch (request->request.opcode) {
case CMD_SET_FLUSH_PARAM:
rv = setFlushParam(e, keyz, valz, msg);
break;
case CMD_SET_TAP_PARAM:
rv = setTapParam(e, keyz, valz, msg);
break;
default:
rv = PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND;
}
return rv;
}
static protocol_binary_response_status getVbucket(EventuallyPersistentEngine *e,
protocol_binary_request_header *request,
const char **msg) {
protocol_binary_request_no_extras *req =
reinterpret_cast<protocol_binary_request_no_extras*>(request);
assert(req);
char keyz[8]; // stringy 2^16 int
// Read the key.
int keylen = ntohs(req->message.header.request.keylen);
if (keylen >= (int)sizeof(keyz)) {
*msg = "Key is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(keyz, ((char*)request) + sizeof(req->message.header), keylen);
keyz[keylen] = 0x00;
protocol_binary_response_status rv(PROTOCOL_BINARY_RESPONSE_SUCCESS);
uint16_t vbucket = 0;
if (!parseUint16(keyz, &vbucket)) {
*msg = "Value out of range.";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
} else {
RCPtr<VBucket> vb = e->getVBucket(vbucket);
if (!vb) {
*msg = "That's not my bucket.";
rv = PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET;
} else {
*msg = vb->getStateString();
assert(msg);
rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
}
}
return rv;
}
static protocol_binary_response_status setVbucket(EventuallyPersistentEngine *e,
protocol_binary_request_header *request,
const char **msg) {
protocol_binary_request_no_extras *req =
reinterpret_cast<protocol_binary_request_no_extras*>(request);
assert(req);
char keyz[32];
char valz[32];
// Read the key.
int keylen = ntohs(req->message.header.request.keylen);
if (keylen >= (int)sizeof(keyz)) {
*msg = "Key is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(keyz, ((char*)request) + sizeof(req->message.header), keylen);
keyz[keylen] = 0x00;
// Read the value.
size_t bodylen = ntohl(req->message.header.request.bodylen)
- ntohs(req->message.header.request.keylen);
if (bodylen >= sizeof(valz)) {
*msg = "Value is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(valz, (char*)request + sizeof(req->message.header)
+ keylen, bodylen);
valz[bodylen] = 0x00;
protocol_binary_response_status rv(PROTOCOL_BINARY_RESPONSE_SUCCESS);
*msg = "Configured";
vbucket_state_t state;
if (strcmp(valz, "active") == 0) {
state = active;
} else if(strcmp(valz, "replica") == 0) {
state = replica;
} else if(strcmp(valz, "pending") == 0) {
state = pending;
} else if(strcmp(valz, "dead") == 0) {
state = dead;
} else {
*msg = "Invalid state.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
uint16_t vbucket = 0;
if (!parseUint16(keyz, &vbucket)) {
*msg = "Value out of range.";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
} else {
e->setVBucketState(vbucket, state);
}
return rv;
}
static protocol_binary_response_status deleteVBucket(EventuallyPersistentEngine *e,
protocol_binary_request_header *request,
const char **msg) {
protocol_binary_request_no_extras *req =
reinterpret_cast<protocol_binary_request_no_extras*>(request);
assert(req);
char keyz[8]; // stringy 2^16 int
// Read the key.
int keylen = ntohs(req->message.header.request.keylen);
if (keylen >= (int)sizeof(keyz)) {
*msg = "Key is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(keyz, ((char*)request) + sizeof(req->message.header), keylen);
keyz[keylen] = 0x00;
protocol_binary_response_status rv(PROTOCOL_BINARY_RESPONSE_SUCCESS);
uint16_t vbucket = 0;
if (!parseUint16(keyz, &vbucket)) {
*msg = "Value out of range.";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
} else {
if (e->deleteVBucket(vbucket)) {
*msg = "Deleted.";
} else {
// If we fail to delete, try to figure out why.
RCPtr<VBucket> vb = e->getVBucket(vbucket);
if (!vb) {
*msg = "Failed to delete vbucket. Bucket not found.";
rv = PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET;
} else if(vb->getState() != dead) {
*msg = "Failed to delete vbucket. Must be in the dead state.";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
} else {
*msg = "Failed to delete vbucket. Unknown reason.";
rv = PROTOCOL_BINARY_RESPONSE_EINTERNAL;
}
}
}
assert(msg);
return rv;
}
static ENGINE_ERROR_CODE EvpUnknownCommand(ENGINE_HANDLE* handle,
const void* cookie,
protocol_binary_request_header *request,
ADD_RESPONSE response)
{
(void)handle;
(void)cookie;
(void)request;
protocol_binary_response_status res =
PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND;
const char *msg = NULL;
EventuallyPersistentEngine *h = getHandle(handle);
EPStats &stats = h->getEpStats();
switch (request->request.opcode) {
case CMD_STOP_PERSISTENCE:
res = stopFlusher(h, &msg);
break;
case CMD_START_PERSISTENCE:
res = startFlusher(h, &msg);
break;
case CMD_DEL_VBUCKET:
{
BlockTimer timer(&stats.delVbucketCmdHisto);
res = deleteVBucket(h, request, &msg);
}
break;
case CMD_SET_FLUSH_PARAM:
case CMD_SET_TAP_PARAM:
res = setParam(h, request, &msg);
break;
case CMD_GET_VBUCKET:
{
BlockTimer timer(&stats.getVbucketCmdHisto);
res = getVbucket(h, request, &msg);
}
break;
case CMD_SET_VBUCKET:
{
BlockTimer timer(&stats.setVbucketCmdHisto);
res = setVbucket(h, request, &msg);
}
break;
case CMD_EVICT_KEY:
res = evictKey(h, request, &msg);
break;
}
size_t msg_size = msg ? strlen(msg) : 0;
response(NULL, 0, NULL, 0,
msg, static_cast<uint16_t>(msg_size),
PROTOCOL_BINARY_RAW_BYTES,
static_cast<uint16_t>(res), 0, cookie);
return ENGINE_SUCCESS;
}
static void EvpItemSetCas(ENGINE_HANDLE* handle, const void *cookie,
item *item, uint64_t cas) {
(void)handle;
(void)cookie;
static_cast<Item*>(item)->setCas(cas);
}
static ENGINE_ERROR_CODE EvpTapNotify(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)
{
return getHandle(handle)->tapNotify(cookie, engine_specific, nengine,
ttl, tap_flags, tap_event,
tap_seqno, key, nkey, flags,
exptime, cas, data, ndata,
vbucket);
}
static tap_event_t EvpTapIterator(ENGINE_HANDLE* handle,
const void *cookie, item **itm,
void **es, uint16_t *nes, uint8_t *ttl,
uint16_t *flags, uint32_t *seqno,
uint16_t *vbucket) {
return getHandle(handle)->walkTapQueue(cookie, itm, es, nes, ttl,
flags, seqno, vbucket);
}
static TAP_ITERATOR EvpGetTapIterator(ENGINE_HANDLE* handle,
const void* cookie,
const void* client,
size_t nclient,
uint32_t flags,
const void* userdata,
size_t nuserdata) {
std::string c(static_cast<const char*>(client), nclient);
// Figure out what we want from the userdata before adding it to the API
// to the handle
getHandle(handle)->createTapQueue(cookie, c, flags,
userdata, nuserdata);
return EvpTapIterator;
}
static void EvpHandleDisconnect(const void *cookie,
ENGINE_EVENT_TYPE type,
const void *event_data,
const void *cb_data)
{
assert(type == ON_DISCONNECT);
assert(event_data == NULL);
void *c = const_cast<void*>(cb_data);
return getHandle(static_cast<ENGINE_HANDLE*>(c))->handleDisconnect(cookie);
}
/**
* The only public interface to the eventually persistance engine.
* Allocate a new instance and initialize it
* @param interface the highest interface the server supports (we only support
* interface 1)
* @param get_server_api callback function to get the server exported API
* functions
* @param handle Where to return the new instance
* @return ENGINE_SUCCESS on success
*/
ENGINE_ERROR_CODE create_instance(uint64_t interface,
GET_SERVER_API get_server_api,
ENGINE_HANDLE **handle)
{
SERVER_HANDLE_V1 *api = get_server_api();
if (interface != 1 || api == NULL) {
return ENGINE_ENOTSUP;
}
EventuallyPersistentEngine *engine;
engine = new struct EventuallyPersistentEngine(get_server_api);
if (engine == NULL) {
return ENGINE_ENOMEM;
}
ep_current_time = api->core->get_current_time;
ep_abs_time = api->core->abstime;
*handle = reinterpret_cast<ENGINE_HANDLE*> (engine);
return ENGINE_SUCCESS;
}
void *EvpNotifyTapIo(void*arg) {
static_cast<EventuallyPersistentEngine*>(arg)->notifyTapIoThread();
return NULL;
}
static bool EvpGetItemInfo(ENGINE_HANDLE *handle, const void *cookie,
const item* item, item_info *item_info)
{
(void)handle;
(void)cookie;
const Item *it = reinterpret_cast<const Item*>(item);
if (item_info->nvalue < 1) {
return false;
}
item_info->cas = it->getCas();
item_info->exptime = it->getExptime();
item_info->nbytes = it->getNBytes();
item_info->flags = it->getFlags();
item_info->clsid = 0;
item_info->nkey = static_cast<uint16_t>(it->getNKey());
item_info->nvalue = 1;
item_info->key = it->getKey().c_str();
item_info->value[0].iov_base = const_cast<char*>(it->getData());
item_info->value[0].iov_len = it->getNBytes();
return true;
}
} // C linkage
static SERVER_EXTENSION_API *extensionApi;
EXTENSION_LOGGER_DESCRIPTOR *getLogger(void) {
if (extensionApi != NULL) {
return (EXTENSION_LOGGER_DESCRIPTOR*)extensionApi->get_extension(EXTENSION_LOGGER);
}
return NULL;
}
EventuallyPersistentEngine::EventuallyPersistentEngine(GET_SERVER_API get_server_api) :
dbname("/tmp/test.db"), initFile(NULL), postInitFile(NULL),
warmup(true), wait_for_warmup(true), fail_on_partial_warmup(true),
startVb0(true), sqliteStrategy(NULL), sqliteDb(NULL), epstore(NULL),
databaseInitTime(0), tapIdleTimeout(DEFAULT_TAP_IDLE_TIMEOUT), nextTapNoop(0),
startedEngineThreads(false), shutdown(false),
getServerApiFunc(get_server_api), getlExtension(NULL),
tapEnabled(false), maxItemSize(20*1024*1024), tapBacklogLimit(5000),
memLowWat(std::numeric_limits<size_t>::max()),
memHighWat(std::numeric_limits<size_t>::max()),
minDataAge(DEFAULT_MIN_DATA_AGE),
queueAgeCap(DEFAULT_QUEUE_AGE_CAP),
itemExpiryWindow(3), expiryPagerSleeptime(3600), dbShards(4)
{
interface.interface = 1;
ENGINE_HANDLE_V1::get_info = EvpGetInfo;
ENGINE_HANDLE_V1::initialize = EvpInitialize;
ENGINE_HANDLE_V1::destroy = EvpDestroy;
ENGINE_HANDLE_V1::allocate = EvpItemAllocate;
ENGINE_HANDLE_V1::remove = EvpItemDelete;
ENGINE_HANDLE_V1::release = EvpItemRelease;
ENGINE_HANDLE_V1::get = EvpGet;
ENGINE_HANDLE_V1::get_stats = EvpGetStats;
ENGINE_HANDLE_V1::reset_stats = EvpResetStats;
ENGINE_HANDLE_V1::store = EvpStore;
ENGINE_HANDLE_V1::arithmetic = EvpArithmetic;
ENGINE_HANDLE_V1::flush = EvpFlush;
ENGINE_HANDLE_V1::unknown_command = EvpUnknownCommand;
ENGINE_HANDLE_V1::get_tap_iterator = EvpGetTapIterator;
ENGINE_HANDLE_V1::tap_notify = EvpTapNotify;
ENGINE_HANDLE_V1::item_set_cas = EvpItemSetCas;
ENGINE_HANDLE_V1::get_item_info = EvpGetItemInfo;
ENGINE_HANDLE_V1::get_stats_struct = NULL;
ENGINE_HANDLE_V1::errinfo = NULL;
ENGINE_HANDLE_V1::aggregate_stats = NULL;
serverApi = getServerApiFunc();
extensionApi = serverApi->extension;
memset(&info, 0, sizeof(info));
info.info.description = "EP engine v" VERSION;
info.info.features[info.info.num_features++].feature = ENGINE_FEATURE_CAS;
info.info.features[info.info.num_features++].feature = ENGINE_FEATURE_PERSISTENT_STORAGE;
info.info.features[info.info.num_features++].feature = ENGINE_FEATURE_LRU;
}
ENGINE_ERROR_CODE EventuallyPersistentEngine::initialize(const char* config) {
ENGINE_ERROR_CODE ret = ENGINE_SUCCESS;
resetStats();
if (config != NULL) {
char *dbn = NULL, *initf = NULL, *pinitf = NULL, *svaltype = NULL;
size_t htBuckets = 0;
size_t htLocks = 0;
size_t maxSize = 0;
const int max_items = 26;
struct config_item items[max_items];
int ii = 0;
memset(items, 0, sizeof(items));
items[ii].key = "dbname";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &dbn;
++ii;
items[ii].key = "initfile";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &initf;
++ii;
items[ii].key = "postInitfile";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &pinitf;
++ii;
items[ii].key = "warmup";
items[ii].datatype = DT_BOOL;
items[ii].value.dt_bool = &warmup;
++ii;
items[ii].key = "waitforwarmup";
items[ii].datatype = DT_BOOL;
items[ii].value.dt_bool = &wait_for_warmup;
++ii;
items[ii].key = "failpartialwarmup";
items[ii].datatype = DT_BOOL;
items[ii].value.dt_bool = &fail_on_partial_warmup;
++ii;
items[ii].key = "vb0";
items[ii].datatype = DT_BOOL;
items[ii].value.dt_bool = &startVb0;
++ii;
items[ii].key = "tap_keepalive";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &tapKeepAlive;
++ii;
items[ii].key = "ht_size";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &htBuckets;
++ii;
items[ii].key = "stored_val_type";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &svaltype;
++ii;
items[ii].key = "ht_locks";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &htLocks;
++ii;
items[ii].key = "max_size";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &maxSize;
++ii;
items[ii].key = "cache_size";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &maxSize;
++ii;
items[ii].key = "tap_idle_timeout";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &tapIdleTimeout;
++ii;
items[ii].key = "config_file";
items[ii].datatype = DT_CONFIGFILE;
++ii;
items[ii].key = "max_item_size";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &maxItemSize;
++ii;
items[ii].key = "min_data_age";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &minDataAge;
++ii;
items[ii].key = "mem_low_wat";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &memLowWat;
++ii;
items[ii].key = "mem_high_wat";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &memHighWat;
++ii;
items[ii].key = "queue_age_cap";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &queueAgeCap;
++ii;
items[ii].key = "tap_backlog_limit";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &tapBacklogLimit;
++ii;
items[ii].key = "expiry_window";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &itemExpiryWindow;
++ii;
items[ii].key = "exp_pager_stime";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &expiryPagerSleeptime;
++ii;
items[ii].key = "db_shards";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &dbShards;
++ii;
items[ii].key = NULL;
assert(ii < max_items);
if (serverApi->core->parse_config(config, items, stderr) != 0) {
ret = ENGINE_FAILED;
} else {
if (dbn != NULL) {
dbname = dbn;
}
if (initf != NULL) {
initFile = initf;
}
if (pinitf != NULL) {
postInitFile = pinitf;
}
HashTable::setDefaultNumBuckets(htBuckets);
HashTable::setDefaultNumLocks(htLocks);
StoredValue::setMaxDataSize(stats, maxSize);
if (svaltype && !HashTable::setDefaultStorageValueType(svaltype)) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Unhandled storage value type: %s",
svaltype);
}
}
}
if (tapIdleTimeout == 0) {
tapIdleTimeout = (size_t)-1;
}
if (ret == ENGINE_SUCCESS) {
time_t start = ep_real_time();
try {
sqliteStrategy = new MultiDBSqliteStrategy(*this, dbname,
initFile, postInitFile,
dbShards);
sqliteDb = new StrategicSqlite3(*this, sqliteStrategy);
} catch (std::exception& e) {
std::stringstream ss;
ss << "Failed to create database: " << e.what() << std::endl;
if (!dbAccess()) {
ss << "No access to \"" << dbname << "\"."
<< std::endl;
}
getLogger()->log(EXTENSION_LOG_WARNING, NULL, "%s",
ss.str().c_str());
return ENGINE_FAILED;
}
databaseInitTime = ep_real_time() - start;
epstore = new EventuallyPersistentStore(*this, sqliteDb, startVb0);
setMinDataAge(minDataAge);
setQueueAgeCap(queueAgeCap);
if (epstore == NULL) {
ret = ENGINE_ENOMEM;
} else {
if (!warmup) {
epstore->reset();
}
SERVER_CALLBACK_API *sapi;
sapi = getServerApi()->callback;
sapi->register_callback(reinterpret_cast<ENGINE_HANDLE*>(this),
ON_DISCONNECT, EvpHandleDisconnect, this);
}
if (memLowWat == std::numeric_limits<size_t>::max()) {
memLowWat = percentOf(StoredValue::getMaxDataSize(stats), 0.6);
}
if (memHighWat == std::numeric_limits<size_t>::max()) {
memHighWat = percentOf(StoredValue::getMaxDataSize(stats), 0.75);
}
stats.mem_low_wat = memLowWat;
stats.mem_high_wat = memHighWat;
startEngineThreads();
// If requested, don't complete the initialization until the
// flusher transitions out of the initializing state (i.e
// warmup is finished).
const Flusher *flusher = epstore->getFlusher();
if (wait_for_warmup && flusher) {
useconds_t sleepTime = 1;
useconds_t maxSleepTime = 500000;
while (flusher->state() == initializing) {
usleep(sleepTime);
sleepTime = std::min(sleepTime << 1, maxSleepTime);
}
if (fail_on_partial_warmup && stats.warmOOM > 0) {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Warmup failed to load %d records due to OOM, exiting.\n",
static_cast<unsigned int>(stats.warmOOM));
exit(1);
}
}
if (HashTable::getDefaultStorageValueType() != small) {
shared_ptr<DispatcherCallback> cb(new ItemPager(epstore, stats));
epstore->getDispatcher()->schedule(cb, NULL, Priority::ItemPagerPriority, 10);
shared_ptr<DispatcherCallback> exp_cb(new ExpiredItemPager(epstore, stats,
expiryPagerSleeptime));
epstore->getDispatcher()->schedule(exp_cb, NULL, Priority::ItemPagerPriority,
expiryPagerSleeptime);
}
}
if (ret == ENGINE_SUCCESS) {
getlExtension = new GetlExtension(epstore, getServerApiFunc);
getlExtension->initialize();
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Engine init complete.\n");
return ret;
}
void EventuallyPersistentEngine::destroy() {
stopEngineThreads();
}
ENGINE_ERROR_CODE EventuallyPersistentEngine::store(const void *cookie,
item* itm,
uint64_t *cas,
ENGINE_STORE_OPERATION operation,
uint16_t vbucket)
{
BlockTimer timer(&stats.storeCmdHisto);
ENGINE_ERROR_CODE ret;
Item *it = static_cast<Item*>(itm);
item *i = NULL;
it->setVBucketId(vbucket);
switch (operation) {
case OPERATION_CAS:
if (it->getCas() == 0) {
// Using a cas command with a cas wildcard doesn't make sense
ret = ENGINE_NOT_STORED;
break;
}
// FALLTHROUGH
case OPERATION_SET:
ret = epstore->set(*it, cookie);
if (ret == ENGINE_SUCCESS) {
*cas = it->getCas();
addMutationEvent(it, vbucket);
}