/
ep_engine.cc
6378 lines (5720 loc) · 250 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 2017 Couchbase, 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 "ep_engine.h"
#include "backfill.h"
#include "common.h"
#include "connmap.h"
#include "dcp/consumer.h"
#include "dcp/dcpconnmap.h"
#include "dcp/flow-control-manager.h"
#include "dcp/producer.h"
#include "ep_bucket.h"
#include "ep_vb.h"
#include "ephemeral_bucket.h"
#include "failover-table.h"
#include "flusher.h"
#include "htresizer.h"
#include "logger.h"
#include "memory_tracker.h"
#include "replicationthrottle.h"
#include "stats-info.h"
#define STATWRITER_NAMESPACE core_engine
#include "statwriter.h"
#undef STATWRITER_NAMESPACE
#include "string_utils.h"
#include "tapconnmap.h"
#include "vb_count_visitor.h"
#include "warmup.h"
#include <JSON_checker.h>
#include <cJSON_utils.h>
#include <memcached/engine.h>
#include <memcached/extension.h>
#include <memcached/protocol_binary.h>
#include <memcached/server_api.h>
#include <memcached/util.h>
#include <platform/cb_malloc.h>
#include <platform/checked_snprintf.h>
#include <platform/make_unique.h>
#include <platform/platform.h>
#include <platform/processclock.h>
#include <xattr/utils.h>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <limits>
#include <mutex>
#include <stdarg.h>
#include <string>
#include <vector>
static size_t percentOf(size_t val, double percent) {
return static_cast<size_t>(static_cast<double>(val) * percent);
}
struct EPHandleReleaser {
void operator()(EventuallyPersistentEngine*) {
ObjectRegistry::onSwitchThread(nullptr);
}
};
using EPHandle = std::unique_ptr<EventuallyPersistentEngine, EPHandleReleaser>;
/**
* Helper function to acquire a handle to the engine which allows access to
* the engine while the handle is in scope.
* @param handle pointer to the engine
* @return EPHandle which is a unique_ptr to an EventuallyPersistentEngine
* with a custom deleter (EPHandleReleaser) which performs the required
* ObjectRegistry release.
*/
static inline EPHandle acquireEngine(ENGINE_HANDLE* handle) {
auto ret = reinterpret_cast<EventuallyPersistentEngine*>(handle);
ObjectRegistry::onSwitchThread(ret);
return EPHandle(ret);
}
/**
* Call the response callback and return the appropriate value so that
* the core knows what to do..
*/
static ENGINE_ERROR_CODE sendResponse(ADD_RESPONSE response, const void *key,
uint16_t keylen,
const void *ext, uint8_t extlen,
const void *body, uint32_t bodylen,
uint8_t datatype, uint16_t status,
uint64_t cas, const void *cookie)
{
ENGINE_ERROR_CODE rv = ENGINE_FAILED;
EventuallyPersistentEngine *e = ObjectRegistry::onSwitchThread(NULL, true);
if (response(key, keylen, ext, extlen, body, bodylen, datatype,
status, cas, cookie)) {
rv = ENGINE_SUCCESS;
}
ObjectRegistry::onSwitchThread(e);
return rv;
}
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.");
}
}
static void checkNumeric(const char* str) {
int i = 0;
if (str[0] == '-') {
i++;
}
for (; str[i]; i++) {
using namespace std;
if (!isdigit(str[i])) {
throw std::runtime_error("Value is not numeric");
}
}
}
static const engine_info* EvpGetInfo(ENGINE_HANDLE* handle) {
return acquireEngine(handle)->getInfo();
}
static ENGINE_ERROR_CODE EvpInitialize(ENGINE_HANDLE* handle,
const char* config_str) {
return acquireEngine(handle)->initialize(config_str);
}
static void EvpDestroy(ENGINE_HANDLE* handle, const bool force) {
auto eng = acquireEngine(handle);
eng->destroy(force);
delete eng.get();
}
static ENGINE_ERROR_CODE EvpItemAllocate(ENGINE_HANDLE* handle,
const void* cookie,
item** itm,
const DocKey& key,
const size_t nbytes,
const int flags,
const rel_time_t exptime,
uint8_t datatype,
uint16_t vbucket) {
if (!mcbp::datatype::is_valid(datatype)) {
LOG(EXTENSION_LOG_WARNING, "Invalid value for datatype "
" (ItemAllocate)");
return ENGINE_EINVAL;
}
return acquireEngine(handle)->itemAllocate(itm,
key,
nbytes,
0, // No privileged bytes
flags,
exptime,
datatype,
vbucket);
}
static bool EvpGetItemInfo(ENGINE_HANDLE *handle, const void *,
const item* itm, item_info *itm_info);
static void EvpItemRelease(ENGINE_HANDLE* handle, const void *cookie,
item* itm);
static std::pair<cb::unique_item_ptr, item_info> EvpItemAllocateEx(ENGINE_HANDLE* handle,
const void* cookie,
const DocKey& key,
const size_t nbytes,
const size_t priv_nbytes,
const int flags,
const rel_time_t exptime,
uint8_t datatype,
uint16_t vbucket) {
item* it = nullptr;
auto err = acquireEngine(handle)->itemAllocate(
&it, key, nbytes, priv_nbytes, flags, exptime, datatype, vbucket);
if (err != ENGINE_SUCCESS) {
throw cb::engine_error(cb::engine_errc(err),
"EvpItemAllocateEx: failed to allocate memory");
}
item_info info;
if (!EvpGetItemInfo(handle, cookie, it, &info)) {
EvpItemRelease(handle, cookie, it);
throw cb::engine_error(cb::engine_errc::failed,
"EvpItemAllocateEx: EvpGetItemInfo failed");
}
return std::make_pair(cb::unique_item_ptr{it, cb::ItemDeleter{handle}},
info);
}
static ENGINE_ERROR_CODE EvpItemDelete(ENGINE_HANDLE* handle,
const void* cookie,
const DocKey& key,
uint64_t* cas,
uint16_t vbucket,
mutation_descr_t* mut_info) {
if (!cas) {
LOG(EXTENSION_LOG_WARNING,
"EvpItemDelete(): cas ptr passed is null for vb: %" PRIu16,
vbucket);
return ENGINE_EINVAL;
}
return acquireEngine(handle)->itemDelete(
cookie, key, *cas, vbucket, nullptr, mut_info);
}
static void EvpItemRelease(ENGINE_HANDLE* handle,
const void* cookie,
item* itm) {
acquireEngine(handle)->itemRelease(cookie, itm);
}
static ENGINE_ERROR_CODE EvpGet(ENGINE_HANDLE* handle,
const void* cookie,
item** itm,
const DocKey& key,
uint16_t vbucket,
DocStateFilter documentStateFilter) {
get_options_t options = static_cast<get_options_t>(QUEUE_BG_FETCH |
HONOR_STATES |
TRACK_REFERENCE |
DELETE_TEMP |
HIDE_LOCKED_CAS |
TRACK_STATISTICS);
switch (documentStateFilter) {
case DocStateFilter::Alive:
break;
case DocStateFilter::Deleted:
// MB-23640 was caused by this bug as the frontend asked for
// Alive and Deleted documents. The internals don't have a
// way of requesting just deleted documents, and luckily for
// us no part of our code is using this yet. Return an error
// if anyone start using it
return ENGINE_ENOTSUP;
case DocStateFilter::AliveOrDeleted:
options = static_cast<get_options_t>(options | GET_DELETED_VALUE);
break;
}
return acquireEngine(handle)->get(cookie, itm, key, vbucket, options);
}
static cb::EngineErrorItemPair EvpGetIf(ENGINE_HANDLE* handle,
const void* cookie,
const DocKey& key,
uint16_t vbucket,
std::function<bool(
const item_info&)> filter) {
return acquireEngine(handle)->get_if(cookie, key, vbucket, filter);
}
static cb::EngineErrorItemPair EvpGetAndTouch(ENGINE_HANDLE* handle,
const void* cookie,
const DocKey& key,
uint16_t vbucket,
uint32_t expiry_time) {
return acquireEngine(handle)->get_and_touch(cookie, key, vbucket,
expiry_time);
}
static ENGINE_ERROR_CODE EvpGetLocked(ENGINE_HANDLE* handle,
const void* cookie,
item** itm,
const DocKey& key,
uint16_t vbucket,
uint32_t lock_timeout) {
return acquireEngine(handle)->get_locked(
cookie, itm, key, vbucket, lock_timeout);
}
static ENGINE_ERROR_CODE EvpUnlock(ENGINE_HANDLE* handle,
const void* cookie,
const DocKey& key,
uint16_t vbucket,
uint64_t cas) {
return acquireEngine(handle)->unlock(cookie, key, vbucket, cas);
}
static ENGINE_ERROR_CODE EvpGetStats(ENGINE_HANDLE* handle,
const void* cookie,
const char* stat_key,
int nkey,
ADD_STAT add_stat) {
return acquireEngine(handle)->getStats(cookie, stat_key, nkey, add_stat);
}
static ENGINE_ERROR_CODE EvpStore(ENGINE_HANDLE* handle,
const void* cookie,
item* itm,
uint64_t* cas,
ENGINE_STORE_OPERATION operation,
DocumentState document_state) {
auto engine = acquireEngine(handle);
if (document_state == DocumentState::Deleted) {
Item* item = static_cast<Item*>(itm);
item->setDeleted();
}
return engine->store(cookie, itm, cas, operation);
}
static ENGINE_ERROR_CODE EvpFlush(ENGINE_HANDLE* handle,
const void* cookie) {
return acquireEngine(handle)->flush(cookie);
}
static void EvpResetStats(ENGINE_HANDLE* handle, const void*) {
acquireEngine(handle)->resetStats();
}
protocol_binary_response_status EventuallyPersistentEngine::setTapParam(
const char* keyz, const char* valz, std::string& msg) {
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
try {
if (strcmp(keyz, "tap_keepalive") == 0) {
int v = std::stoi(valz);
validate(v, 0, MAX_TAP_KEEP_ALIVE);
getConfiguration().requirementsMetOrThrow("tap_keepalive");
setTapKeepAlive(static_cast<uint32_t>(v));
} else if (strcmp(keyz, "replication_throttle_threshold") == 0) {
getConfiguration().setReplicationThrottleThreshold(
std::stoull(valz));
} else if (strcmp(keyz, "replication_throttle_queue_cap") == 0) {
getConfiguration().setReplicationThrottleQueueCap(std::stoll(valz));
} else if (strcmp(keyz, "replication_throttle_cap_pcnt") == 0) {
getConfiguration().setReplicationThrottleCapPcnt(std::stoull(valz));
} else {
msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
}
// Handles exceptions thrown by the standard
// library stoi/stoul style functions when not numeric
} catch (std::invalid_argument&) {
msg = "Argument was not numeric";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles exceptions thrown by the standard library stoi/stoul
// style functions when the conversion does not fit in the datatype
} catch (std::out_of_range&) {
msg = "Argument was out of range";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles any miscellaenous exceptions in addition to the range_error
// exceptions thrown by the configuration::set<param>() methods
} catch (std::exception& error) {
msg = error.what();
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
}
return rv;
}
protocol_binary_response_status EventuallyPersistentEngine::setCheckpointParam(
const char* keyz, const char* valz, std::string& msg) {
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
try {
if (strcmp(keyz, "chk_max_items") == 0) {
size_t v = std::stoull(valz);
validate(v, size_t(MIN_CHECKPOINT_ITEMS),
size_t(MAX_CHECKPOINT_ITEMS));
getConfiguration().setChkMaxItems(v);
} else if (strcmp(keyz, "chk_period") == 0) {
size_t v = std::stoull(valz);
validate(v, size_t(MIN_CHECKPOINT_PERIOD),
size_t(MAX_CHECKPOINT_PERIOD));
getConfiguration().setChkPeriod(v);
} else if (strcmp(keyz, "max_checkpoints") == 0) {
size_t v = std::stoull(valz);
validate(v, size_t(DEFAULT_MAX_CHECKPOINTS),
size_t(MAX_CHECKPOINTS_UPPER_BOUND));
getConfiguration().setMaxCheckpoints(v);
} else if (strcmp(keyz, "item_num_based_new_chk") == 0) {
getConfiguration().setItemNumBasedNewChk(cb_stob(valz));
} else if (strcmp(keyz, "keep_closed_chks") == 0) {
getConfiguration().setKeepClosedChks(cb_stob(valz));
} else if (strcmp(keyz, "enable_chk_merge") == 0) {
getConfiguration().setEnableChkMerge(cb_stob(valz));
} else {
msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
}
// Handles exceptions thrown by the cb_stob function
} catch (invalid_argument_bool& error) {
msg = error.what();
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles exceptions thrown by the standard
// library stoi/stoul style functions when not numeric
} catch (std::invalid_argument&) {
msg = "Argument was not numeric";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles exceptions thrown by the standard library stoi/stoul
// style functions when the conversion does not fit in the datatype
} catch (std::out_of_range&) {
msg = "Argument was out of range";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles any miscellaenous exceptions in addition to the range_error
// exceptions thrown by the configuration::set<param>() methods
} catch (std::exception& error) {
msg = error.what();
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
}
return rv;
}
protocol_binary_response_status EventuallyPersistentEngine::setFlushParam(
const char* keyz, const char* valz, std::string& msg) {
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
// Handle the actual mutation.
try {
if (strcmp(keyz, "bg_fetch_delay") == 0) {
getConfiguration().setBgFetchDelay(std::stoull(valz));
} else if (strcmp(keyz, "flushall_enabled") == 0) {
getConfiguration().setFlushallEnabled(cb_stob(valz));
} else if (strcmp(keyz, "max_size") == 0) {
size_t vsize = std::stoull(valz);
getConfiguration().setMaxSize(vsize);
EPStats& st = getEpStats();
getConfiguration().setMemLowWat(
percentOf(vsize, st.mem_low_wat_percent));
getConfiguration().setMemHighWat(
percentOf(vsize, st.mem_high_wat_percent));
} else if (strcmp(keyz, "mem_low_wat") == 0) {
getConfiguration().setMemLowWat(std::stoull(valz));
} else if (strcmp(keyz, "mem_high_wat") == 0) {
getConfiguration().setMemHighWat(std::stoull(valz));
} else if (strcmp(keyz, "backfill_mem_threshold") == 0) {
getConfiguration().setBackfillMemThreshold(std::stoull(valz));
} else if (strcmp(keyz, "compaction_exp_mem_threshold") == 0) {
getConfiguration().setCompactionExpMemThreshold(std::stoull(valz));
} else if (strcmp(keyz, "mutation_mem_threshold") == 0) {
getConfiguration().setMutationMemThreshold(std::stoull(valz));
} else if (strcmp(keyz, "timing_log") == 0) {
EPStats& stats = getEpStats();
std::ostream* old = stats.timingLog;
stats.timingLog = NULL;
delete old;
if (strcmp(valz, "off") == 0) {
LOG(EXTENSION_LOG_INFO, "Disabled timing log.");
} else {
std::ofstream* tmp(new std::ofstream(valz));
if (tmp->good()) {
LOG(EXTENSION_LOG_INFO,
"Logging detailed timings to ``%s''.", valz);
stats.timingLog = tmp;
} else {
LOG(EXTENSION_LOG_WARNING,
"Error setting detailed timing log to ``%s'': %s",
valz, strerror(errno));
delete tmp;
}
}
} else if (strcmp(keyz, "exp_pager_enabled") == 0) {
getConfiguration().setExpPagerEnabled(cb_stob(valz));
} else if (strcmp(keyz, "exp_pager_stime") == 0) {
getConfiguration().setExpPagerStime(std::stoull(valz));
} else if (strcmp(keyz, "exp_pager_initial_run_time") == 0) {
getConfiguration().setExpPagerInitialRunTime(std::stoll(valz));
} else if (strcmp(keyz, "access_scanner_enabled") == 0) {
getConfiguration().requirementsMetOrThrow("access_scanner_enabled");
getConfiguration().setAccessScannerEnabled(cb_stob(valz));
} else if (strcmp(keyz, "alog_sleep_time") == 0) {
getConfiguration().requirementsMetOrThrow("alog_sleep_time");
getConfiguration().setAlogSleepTime(std::stoull(valz));
} else if (strcmp(keyz, "alog_task_time") == 0) {
getConfiguration().requirementsMetOrThrow("alog_task_time");
getConfiguration().setAlogTaskTime(std::stoull(valz));
} else if (strcmp(keyz, "pager_active_vb_pcnt") == 0) {
getConfiguration().setPagerActiveVbPcnt(std::stoull(valz));
} else if (strcmp(keyz, "warmup_min_memory_threshold") == 0) {
getConfiguration().setWarmupMinMemoryThreshold(std::stoull(valz));
} else if (strcmp(keyz, "warmup_min_items_threshold") == 0) {
getConfiguration().setWarmupMinItemsThreshold(std::stoull(valz));
} else if (strcmp(keyz, "max_num_readers") == 0 ||
strcmp(keyz, "num_reader_threads") == 0) {
size_t value = std::stoull(valz);
getConfiguration().setNumReaderThreads(value);
ExecutorPool::get()->setNumReaders(value);
} else if (strcmp(keyz, "max_num_writers") == 0 ||
strcmp(keyz, "num_writer_threads") == 0) {
size_t value = std::stoull(valz);
getConfiguration().setNumWriterThreads(value);
ExecutorPool::get()->setNumWriters(value);
} else if (strcmp(keyz, "max_num_auxio") == 0 ||
strcmp(keyz, "num_auxio_threads") == 0) {
size_t value = std::stoull(valz);
getConfiguration().setNumAuxioThreads(value);
ExecutorPool::get()->setNumAuxIO(value);
} else if (strcmp(keyz, "max_num_nonio") == 0 ||
strcmp(keyz, "num_nonio_threads") == 0) {
size_t value = std::stoull(valz);
getConfiguration().setNumNonioThreads(value);
ExecutorPool::get()->setNumNonIO(value);
} else if (strcmp(keyz, "bfilter_enabled") == 0) {
getConfiguration().setBfilterEnabled(cb_stob(valz));
} else if (strcmp(keyz, "bfilter_residency_threshold") == 0) {
getConfiguration().setBfilterResidencyThreshold(std::stof(valz));
} else if (strcmp(keyz, "defragmenter_enabled") == 0) {
getConfiguration().setDefragmenterEnabled(cb_stob(valz));
} else if (strcmp(keyz, "defragmenter_interval") == 0) {
size_t v = std::stoull(valz);
// Adding separate validation as external limit is minimum 1
// to prevent setting defragmenter to constantly run
validate(v, size_t(1), std::numeric_limits<size_t>::max());
getConfiguration().setDefragmenterInterval(v);
} else if (strcmp(keyz, "defragmenter_age_threshold") == 0) {
getConfiguration().setDefragmenterAgeThreshold(std::stoull(valz));
} else if (strcmp(keyz, "defragmenter_chunk_duration") == 0) {
getConfiguration().setDefragmenterChunkDuration(std::stoull(valz));
} else if (strcmp(keyz, "defragmenter_run") == 0) {
runDefragmenterTask();
} else if (strcmp(keyz, "compaction_write_queue_cap") == 0) {
getConfiguration().setCompactionWriteQueueCap(std::stoull(valz));
} else if (strcmp(keyz, "dcp_min_compression_ratio") == 0) {
getConfiguration().setDcpMinCompressionRatio(std::stof(valz));
} else if (strcmp(keyz, "access_scanner_run") == 0) {
if (!(runAccessScannerTask())) {
rv = PROTOCOL_BINARY_RESPONSE_ETMPFAIL;
}
} else if (strcmp(keyz, "vb_state_persist_run") == 0) {
runVbStatePersistTask(std::stoi(valz));
} else if (strcmp(keyz, "ephemeral_full_policy") == 0) {
getConfiguration().requirementsMetOrThrow("ephemeral_full_policy");
getConfiguration().setEphemeralFullPolicy(valz);
} else if (strcmp(keyz, "ephemeral_metadata_purge_age") == 0) {
getConfiguration().requirementsMetOrThrow(
"ephemeral_metadata_purge_age");
getConfiguration().setEphemeralMetadataPurgeAge(std::stoull(valz));
} else if (strcmp(keyz, "ephemeral_metadata_purge_interval") == 0) {
getConfiguration().requirementsMetOrThrow("ephemeral_metadata_purge_interval");
getConfiguration().setEphemeralMetadataPurgeInterval(
std::stoull(valz));
} else if (strcmp(keyz, "mem_merge_count_threshold") == 0) {
getConfiguration().setMemMergeCountThreshold(std::stoul(valz));
} else if (strcmp(keyz, "mem_merge_bytes_threshold") == 0) {
getConfiguration().setMemMergeBytesThreshold(std::stoul(valz));
} else {
msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
}
// Handles exceptions thrown by the cb_stob function
} catch (invalid_argument_bool& error) {
msg = error.what();
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles exceptions thrown by the standard
// library stoi/stoul style functions when not numeric
} catch (std::invalid_argument&) {
msg = "Argument was not numeric";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles exceptions thrown by the standard library stoi/stoul
// style functions when the conversion does not fit in the datatype
} catch (std::out_of_range&) {
msg = "Argument was out of range";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
// Handles any miscellaneous exceptions in addition to the range_error
// exceptions thrown by the configuration::set<param>() methods
} catch (std::exception& error) {
msg = error.what();
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
}
return rv;
}
protocol_binary_response_status EventuallyPersistentEngine::setDcpParam(
const char* keyz, const char* valz, std::string& msg) {
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
try {
if (strcmp(keyz,
"dcp_consumer_process_buffered_messages_yield_limit") == 0) {
size_t v = atoi(valz);
checkNumeric(valz);
validate(v, size_t(1), std::numeric_limits<size_t>::max());
getConfiguration().setDcpConsumerProcessBufferedMessagesYieldLimit(
v);
} else if (
strcmp(keyz, "dcp_consumer_process_buffered_messages_batch_size") ==
0) {
size_t v = atoi(valz);
checkNumeric(valz);
validate(v, size_t(1), std::numeric_limits<size_t>::max());
getConfiguration().setDcpConsumerProcessBufferedMessagesBatchSize(
v);
} else {
msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
}
} catch (std::runtime_error& ex) {
msg = "Value out of range.";
rv = PROTOCOL_BINARY_RESPONSE_EINVAL;
}
return rv;
}
protocol_binary_response_status EventuallyPersistentEngine::setVbucketParam(
uint16_t vbucket,
const char* keyz,
const char* valz,
std::string& msg) {
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
try {
if (strcmp(keyz, "hlc_drift_ahead_threshold_us") == 0) {
uint64_t v = std::strtoull(valz, nullptr, 10);
checkNumeric(valz);
getConfiguration().setHlcDriftAheadThresholdUs(v);
} else if (strcmp(keyz, "hlc_drift_behind_threshold_us") == 0) {
uint64_t v = std::strtoull(valz, nullptr, 10);
checkNumeric(valz);
getConfiguration().setHlcDriftBehindThresholdUs(v);
} else if (strcmp(keyz, "max_cas") == 0) {
uint64_t v = std::strtoull(valz, nullptr, 10);
checkNumeric(valz);
LOG(EXTENSION_LOG_WARNING, "setVbucketParam: max_cas:%" PRIu64 " "
"vb:%" PRIu16 "\n", v, vbucket);
if (getKVBucket()->forceMaxCas(vbucket, v) != ENGINE_SUCCESS) {
rv = PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET;
msg = "Not my vbucket";
}
} else {
msg = "Unknown config param";
rv = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
}
} catch (std::runtime_error& ex) {
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,
size_t* msg_size,
DocNamespace docNamespace) {
protocol_binary_request_no_extras* req =
(protocol_binary_request_no_extras*)request;
const uint8_t* keyPtr = reinterpret_cast<const uint8_t*>(request) +
sizeof(*request);
size_t keylen = ntohs(req->message.header.request.keylen);
uint16_t vbucket = ntohs(request->request.vbucket);
LOG(EXTENSION_LOG_DEBUG, "Manually evicting object with key{%.*s}\n",
int(keylen), keyPtr);
msg_size = 0;
auto rv = e->evictKey(DocKey(keyPtr, keylen, docNamespace), vbucket, msg);
if (rv == PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET ||
rv == PROTOCOL_BINARY_RESPONSE_KEY_ENOENT) {
if (e->isDegradedMode()) {
return PROTOCOL_BINARY_RESPONSE_ETMPFAIL;
}
}
return rv;
}
protocol_binary_response_status EventuallyPersistentEngine::setParam(
protocol_binary_request_set_param* req, std::string& msg) {
size_t keylen = ntohs(req->message.header.request.keylen);
uint8_t extlen = req->message.header.request.extlen;
size_t vallen = ntohl(req->message.header.request.bodylen);
uint16_t vbucket = ntohs(req->message.header.request.vbucket);
protocol_binary_engine_param_t paramtype =
static_cast<protocol_binary_engine_param_t>(ntohl(
req->message.body.param_type));
if (keylen == 0 || (vallen - keylen - extlen) == 0) {
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
const char* keyp = reinterpret_cast<const char*>(req->bytes)
+ sizeof(req->bytes);
const char* valuep = keyp + keylen;
vallen -= (keylen + extlen);
char keyz[128];
char valz[512];
// Read the key.
if (keylen >= sizeof(keyz)) {
msg = "Key is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(keyz, keyp, keylen);
keyz[keylen] = 0x00;
// Read the value.
if (vallen >= sizeof(valz)) {
msg = "Value is too large.";
return PROTOCOL_BINARY_RESPONSE_EINVAL;
}
memcpy(valz, valuep, vallen);
valz[vallen] = 0x00;
protocol_binary_response_status rv;
switch (paramtype) {
case protocol_binary_engine_param_flush:
rv = setFlushParam(keyz, valz, msg);
break;
case protocol_binary_engine_param_tap:
rv = setTapParam(keyz, valz, msg);
break;
case protocol_binary_engine_param_checkpoint:
rv = setCheckpointParam(keyz, valz, msg);
break;
case protocol_binary_engine_param_dcp:
rv = setDcpParam(keyz, valz, msg);
break;
case protocol_binary_engine_param_vbucket:
rv = setVbucketParam(vbucket, keyz, valz, msg);
break;
default:
rv = PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND;
}
return rv;
}
static ENGINE_ERROR_CODE getVBucket(EventuallyPersistentEngine* e,
const void* cookie,
protocol_binary_request_header* request,
ADD_RESPONSE response) {
protocol_binary_request_get_vbucket* req =
reinterpret_cast<protocol_binary_request_get_vbucket*>(request);
if (req == nullptr) {
throw std::invalid_argument("getVBucket: Unable to convert req"
" to protocol_binary_request_get_vbucket");
}
uint16_t vbucket = ntohs(req->message.header.request.vbucket);
VBucketPtr vb = e->getVBucket(vbucket);
if (!vb) {
return e->sendNotMyVBucketResponse(response, cookie, 0);
} else {
vbucket_state_t state = (vbucket_state_t)ntohl(vb->getState());
return sendResponse(response, NULL, 0, NULL, 0, &state,
sizeof(state),
PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_SUCCESS, 0, cookie);
}
}
static ENGINE_ERROR_CODE setVBucket(EventuallyPersistentEngine* e,
const void* cookie,
protocol_binary_request_header* request,
ADD_RESPONSE response) {
protocol_binary_request_set_vbucket* req =
reinterpret_cast<protocol_binary_request_set_vbucket*>(request);
uint64_t cas = ntohll(req->message.header.request.cas);
size_t bodylen = ntohl(req->message.header.request.bodylen)
- ntohs(req->message.header.request.keylen);
if (bodylen != sizeof(vbucket_state_t)) {
const std::string msg("Incorrect packet format");
return sendResponse(response, NULL, 0, NULL, 0, msg.c_str(),
msg.length(), PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_EINVAL,
cas, cookie);
}
vbucket_state_t state;
memcpy(&state, &req->message.body.state, sizeof(state));
state = static_cast<vbucket_state_t>(ntohl(state));
if (!is_valid_vbucket_state_t(state)) {
const std::string msg("Invalid vbucket state");
return sendResponse(response, NULL, 0, NULL, 0, msg.c_str(),
msg.length(), PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_EINVAL,
cas, cookie);
}
uint16_t vb = ntohs(req->message.header.request.vbucket);
if (e->setVBucketState(vb, state, false) == ENGINE_ERANGE) {
const std::string msg("VBucket number too big");
return sendResponse(response, NULL, 0, NULL, 0, msg.c_str(),
msg.length(), PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_ERANGE,
cas, cookie);
}
return sendResponse(response, NULL, 0, NULL, 0, NULL, 0,
PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_SUCCESS,
cas, cookie);
}
static ENGINE_ERROR_CODE delVBucket(EventuallyPersistentEngine* e,
const void* cookie,
protocol_binary_request_header* req,
ADD_RESPONSE response) {
uint64_t cas = ntohll(req->request.cas);
protocol_binary_response_status res = PROTOCOL_BINARY_RESPONSE_SUCCESS;
uint16_t vbucket = ntohs(req->request.vbucket);
std::string msg = "";
if (ntohs(req->request.keylen) > 0 || req->request.extlen > 0) {
msg = "Incorrect packet format.";
return sendResponse(response, NULL, 0, NULL, 0, msg.c_str(),
msg.length(),
PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_EINVAL, cas, cookie);
}
bool sync = false;
uint32_t bodylen = ntohl(req->request.bodylen);
if (bodylen > 0) {
const char* ptr = reinterpret_cast<const char*>(req->bytes) +
sizeof(req->bytes);
if (bodylen == 7 && strncmp(ptr, "async=0", bodylen) == 0) {
sync = true;
}
}
ENGINE_ERROR_CODE err;
void* es = e->getEngineSpecific(cookie);
if (sync) {
if (es == NULL) {
err = e->deleteVBucket(vbucket, cookie);
e->storeEngineSpecific(cookie, e);
} else {
e->storeEngineSpecific(cookie, NULL);
LOG(EXTENSION_LOG_INFO,
"Completed sync deletion of vbucket %u",
(unsigned)vbucket);
err = ENGINE_SUCCESS;
}
} else {
err = e->deleteVBucket(vbucket);
}
switch (err) {
case ENGINE_SUCCESS:
LOG(EXTENSION_LOG_NOTICE,
"Deletion of vbucket %d was completed.", vbucket);
break;
case ENGINE_NOT_MY_VBUCKET:
LOG(EXTENSION_LOG_WARNING, "Deletion of vbucket %d failed "
"because the vbucket doesn't exist!!!", vbucket);
res = PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET;
break;
case ENGINE_EINVAL:
LOG(EXTENSION_LOG_WARNING, "Deletion of vbucket %d failed "
"because the vbucket is not in a dead state\n", vbucket);
msg = "Failed to delete vbucket. Must be in the dead state.";
res = PROTOCOL_BINARY_RESPONSE_EINVAL;
break;
case ENGINE_EWOULDBLOCK:
LOG(EXTENSION_LOG_NOTICE, "Request for vbucket %d deletion is in"
" EWOULDBLOCK until the database file is removed from disk",
vbucket);
e->storeEngineSpecific(cookie, req);
return ENGINE_EWOULDBLOCK;
default:
LOG(EXTENSION_LOG_WARNING, "Deletion of vbucket %d failed "
"because of unknown reasons\n", vbucket);
msg = "Failed to delete vbucket. Unknown reason.";
res = PROTOCOL_BINARY_RESPONSE_EINTERNAL;
}
if (err != ENGINE_NOT_MY_VBUCKET) {
return sendResponse(response, NULL, 0, NULL, 0, msg.c_str(),
msg.length(), PROTOCOL_BINARY_RAW_BYTES,
res, cas, cookie);
} else {
return e->sendNotMyVBucketResponse(response, cookie, cas);
}
}
static ENGINE_ERROR_CODE getReplicaCmd(EventuallyPersistentEngine* e,
protocol_binary_request_header* request,
const void* cookie,
Item** it,
const char** msg,
protocol_binary_response_status* res,
DocNamespace docNamespace) {
KVBucketIface* kvb = e->getKVBucket();
protocol_binary_request_no_extras* req =
(protocol_binary_request_no_extras*)request;
int keylen = ntohs(req->message.header.request.keylen);
uint16_t vbucket = ntohs(req->message.header.request.vbucket);
ENGINE_ERROR_CODE error_code;
DocKey key(reinterpret_cast<const uint8_t*>(request) + sizeof(*request),
keylen, docNamespace);
GetValue rv(kvb->getReplica(key, vbucket, cookie));
if ((error_code = rv.getStatus()) != ENGINE_SUCCESS) {
if (error_code == ENGINE_NOT_MY_VBUCKET) {
*res = PROTOCOL_BINARY_RESPONSE_NOT_MY_VBUCKET;
return error_code;
} else if (error_code == ENGINE_TMPFAIL) {
*msg = "NOT_FOUND";
*res = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT;
} else {
return error_code;
}
} else {
*it = rv.getValue();
*res = PROTOCOL_BINARY_RESPONSE_SUCCESS;
}
++(e->getEpStats().numOpsGet);
return ENGINE_SUCCESS;
}
static ENGINE_ERROR_CODE compactDB(EventuallyPersistentEngine* e,
const void* cookie,
protocol_binary_request_compact_db* req,
ADD_RESPONSE response) {
std::string msg = "";
protocol_binary_response_status res = PROTOCOL_BINARY_RESPONSE_SUCCESS;
compaction_ctx compactreq;
uint64_t cas = ntohll(req->message.header.request.cas);
if (ntohs(req->message.header.request.keylen) > 0 ||
req->message.header.request.extlen != 24) {
LOG(EXTENSION_LOG_WARNING,
"Compaction received bad ext/key len %d/%d.",
req->message.header.request.extlen,
ntohs(req->message.header.request.keylen));
msg = "Incorrect packet format.";
return sendResponse(response, NULL, 0, NULL, 0, msg.c_str(),
msg.length(),
PROTOCOL_BINARY_RAW_BYTES,
PROTOCOL_BINARY_RESPONSE_EINVAL, cas, cookie);
}
EPStats& stats = e->getEpStats();
compactreq.purge_before_ts = ntohll(req->message.body.purge_before_ts);
compactreq.purge_before_seq =
ntohll(req->message.body.purge_before_seq);
compactreq.drop_deletes = req->message.body.drop_deletes;
compactreq.db_file_id = e->getKVBucket()->getDBFileId(*req);
uint16_t vbid = ntohs(req->message.header.request.vbucket);
ENGINE_ERROR_CODE err;
void* es = e->getEngineSpecific(cookie);
if (es == NULL) {
++stats.pendingCompactions;
e->storeEngineSpecific(cookie, e);
err = e->compactDB(vbid, compactreq, cookie);
} else {
e->storeEngineSpecific(cookie, NULL);
err = ENGINE_SUCCESS;
}
switch (err) {
case ENGINE_SUCCESS:
LOG(EXTENSION_LOG_NOTICE,
"Compaction of db file id: %d completed.", compactreq.db_file_id);
break;
case ENGINE_NOT_MY_VBUCKET:
--stats.pendingCompactions;
LOG(EXTENSION_LOG_WARNING, "Compaction of db file id: %d failed "