-
Notifications
You must be signed in to change notification settings - Fork 62
/
ewouldblock_engine.cc
2002 lines (1819 loc) · 76.5 KB
/
ewouldblock_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
/*
* Copyright 2015-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
/*
* "ewouldblock_engine"
*
* The "ewouldblock_engine" allows one to test how memcached responds when the
* engine returns EWOULDBLOCK instead of the correct response.
*
* Motivation:
*
* The EWOULDBLOCK response code can be returned from a number of engine
* functions, and is used to indicate that the request could not be immediately
* fulfilled, and it "would block" if it tried to. The correct way for
* memcached to handle this (in general) is to suspend that request until it
* is later notified by the engine (via notify_io_complete()).
*
* However, engines typically return the correct response to requests
* immediately, only rarely (and from memcached's POV non-deterministically)
* returning EWOULDBLOCK. This makes testing of the code-paths handling
* EWOULDBLOCK tricky.
*
*
* Operation:
* This engine, when loaded by memcached proxies requests to a "real" engine.
* Depending on how it is configured, it can simply pass the request on to the
* real engine, or artificially return EWOULDBLOCK back to memcached.
*
* See the 'Modes' enum below for the possible modes for a connection. The mode
* can be selected by sending a `request_ewouldblock_ctl` command
* (opcode cb::mcbp::ClientOpcode::EwouldblockCtl).
*/
#include "ewouldblock_engine.h"
#include "ewouldblock_engine_public.h"
#include <daemon/enginemap.h>
#include <fmt/format.h>
#include <folly/CancellationToken.h>
#include <gsl/gsl-lite.hpp>
#include <logger/logger.h>
#include <memcached/collections.h>
#include <memcached/config_parser.h>
#include <memcached/connection_iface.h>
#include <memcached/cookie_iface.h>
#include <memcached/dcp.h>
#include <memcached/durability_spec.h>
#include <memcached/engine.h>
#include <memcached/range_scan_optional_configuration.h>
#include <memcached/server_bucket_iface.h>
#include <platform/dirutils.h>
#include <platform/thread.h>
#include <atomic>
#include <chrono>
#include <iostream>
#include <memory>
#include <queue>
#include <random>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
static unique_engine_ptr createBucket(const std::string& module,
ServerApi* (*get_server_api)()) {
auto type = module_to_bucket_type(module);
if (type == BucketType::Unknown) {
return {};
}
try {
return new_engine_instance(type, get_server_api);
} catch (const std::exception&) {
return {};
}
}
/** ewouldblock_engine class */
class EWB_Engine : public EngineIface,
public DcpIface,
public DcpConnHandlerIface {
public:
explicit EWB_Engine(GET_SERVER_API gsa_);
~EWB_Engine() override;
/* Implementation of all the engine functions. ***************************/
void initiate_shutdown() override;
void disconnect(CookieIface& cookie) override;
cb::engine_errc initialize(std::string_view config_str,
const nlohmann::json& encryption) override;
void destroy(bool force) override;
cb::engine_errc set_traffic_control_mode(CookieIface& cookie,
TrafficControlMode mode) override;
cb::unique_item_ptr allocateItem(CookieIface& cookie,
const DocKeyView& key,
size_t nbytes,
size_t priv_nbytes,
uint32_t flags,
rel_time_t exptime,
uint8_t datatype,
Vbid vbucket) override;
cb::engine_errc remove(
CookieIface& cookie,
const DocKeyView& key,
uint64_t& cas,
Vbid vbucket,
const std::optional<cb::durability::Requirements>& durability,
mutation_descr_t& mut_info) override;
void release(ItemIface& item) override;
cb::EngineErrorItemPair get(CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
DocStateFilter documentStateFilter) override;
cb::EngineErrorItemPair get_random_document(CookieIface& cookie,
CollectionID cid) override;
cb::EngineErrorItemPair get_if(
CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
const std::function<bool(const item_info&)>& filter) override;
cb::EngineErrorItemPair get_and_touch(
CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
uint32_t exptime,
const std::optional<cb::durability::Requirements>& durability)
override;
cb::EngineErrorItemPair get_locked(
CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
std::chrono::seconds lock_timeout) override;
cb::engine_errc unlock(CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
uint64_t cas) override;
cb::EngineErrorMetadataPair get_meta(CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket) override;
cb::engine_errc evict_key(CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket) override;
cb::engine_errc observe(
CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
const std::function<void(uint8_t, uint64_t)>& key_handler,
uint64_t& persist_time_hint) override;
cb::engine_errc store(
CookieIface& cookie,
ItemIface& item,
uint64_t& cas,
StoreSemantics operation,
const std::optional<cb::durability::Requirements>& durability,
DocumentState document_state,
bool preserveTtl) override;
cb::EngineErrorCasPair store_if(
CookieIface& cookie,
ItemIface& item,
uint64_t cas,
StoreSemantics operation,
const cb::StoreIfPredicate& predicate,
const std::optional<cb::durability::Requirements>& durability,
DocumentState document_state,
bool preserveTtl) override;
cb::engine_errc flush(CookieIface& cookie) override;
cb::engine_errc get_stats(CookieIface& cookie,
std::string_view key,
std::string_view value,
const AddStatFn& add_stat,
const CheckYieldFn& check_yield) override;
void reset_stats(CookieIface& cookie) override;
cb::engine_errc unknown_command(CookieIface& cookie,
const cb::mcbp::Request& req,
const AddResponseFn& response) override;
bool get_item_info(const ItemIface& item, item_info& item_info) override;
cb::engine_errc set_collection_manifest(CookieIface& cookie,
std::string_view json) override;
cb::engine_errc get_collection_manifest(
CookieIface& cookie, const AddResponseFn& response) override;
cb::EngineErrorGetCollectionIDResult get_collection_id(
CookieIface& cookie, std::string_view path) override;
cb::EngineErrorGetScopeIDResult get_scope_id(
CookieIface& cookie, std::string_view path) override;
cb::EngineErrorGetCollectionMetaResult get_collection_meta(
CookieIface& cookie,
CollectionID cid,
std::optional<Vbid> vbid) const override;
cb::engine::FeatureSet getFeatures() override;
bool isXattrEnabled() override;
std::optional<cb::HlcTime> getVBucketHlcNow(Vbid vbucket) override;
BucketCompressionMode getCompressionMode() override;
size_t getMaxItemSize() override;
float getMinCompressionRatio() override;
cb::engine_errc setParameter(CookieIface& cookie,
EngineParamCategory category,
std::string_view key,
std::string_view value,
Vbid vbucket) override;
cb::engine_errc compactDatabase(
CookieIface& cookie,
Vbid vbid,
uint64_t purge_before_ts,
uint64_t purge_before_seq,
bool drop_deletes,
const std::vector<std::string>& obsolete_keys) override;
std::pair<cb::engine_errc, vbucket_state_t> getVBucket(CookieIface& cookie,
Vbid vbid) override;
cb::engine_errc setVBucket(CookieIface& cookie,
Vbid vbid,
uint64_t cas,
vbucket_state_t state,
nlohmann::json* meta) override;
cb::engine_errc deleteVBucket(CookieIface& cookie,
Vbid vbid,
bool sync) override;
std::pair<cb::engine_errc, cb::rangescan::Id> createRangeScan(
CookieIface& cookie,
const cb::rangescan::CreateParameters& params) override;
cb::engine_errc continueRangeScan(
CookieIface& cookie,
const cb::rangescan::ContinueParameters& params) override;
cb::engine_errc cancelRangeScan(CookieIface& cookie,
Vbid vbid,
cb::rangescan::Id uuid) override;
std::pair<cb::engine_errc, nlohmann::json> getFusionStorageSnapshot(
Vbid vbid,
std::string_view snapshotUuid,
std::time_t validity) override;
cb::engine_errc releaseFusionStorageSnapshot(
Vbid vbid, std::string_view snapshotUuid) override;
std::pair<cb::engine_errc, std::vector<std::string>> mountVBucket(
Vbid vbid, const std::vector<std::string>& paths) override;
cb::engine_errc pause(folly::CancellationToken cancellationToken) override;
cb::engine_errc resume() override;
cb::engine_errc start_persistence(CookieIface& cookie) override;
cb::engine_errc stop_persistence(CookieIface& cookie) override;
cb::engine_errc wait_for_seqno_persistence(CookieIface& cookie,
uint64_t seqno,
Vbid vbid) override;
cb::engine_errc prepare_snapshot(
CookieIface& cookie,
Vbid vbid,
const std::function<void(const nlohmann::json&)>& callback)
override;
cb::engine_errc download_snapshot(CookieIface& cookie,
Vbid vbid,
std::string_view metadata) override;
cb::engine_errc get_snapshot_file_info(
CookieIface& cookie,
std::string_view uuid,
std::size_t file_id,
const std::function<void(const nlohmann::json&)>& callback)
override;
cb::engine_errc release_snapshot(
CookieIface& cookie, std::variant<Vbid, std::string_view>) override;
///////////////////////////////////////////////////////////////////////////
// All of the methods used in the DCP interface //
// //
// We don't support mocking with the DCP interface yet, so all access to //
// the DCP interface will be proxied down to the underlying engine. //
///////////////////////////////////////////////////////////////////////////
cb::engine_errc step(CookieIface& cookie,
bool throttled,
DcpMessageProducersIface& producers) override;
cb::engine_errc open(CookieIface& cookie,
uint32_t opaque,
uint32_t seqno,
cb::mcbp::DcpOpenFlag flags,
std::string_view name,
std::string_view value) override;
cb::engine_errc add_stream(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpAddStreamFlag flags) override;
cb::engine_errc close_stream(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamId sid) override;
cb::engine_errc stream_req(CookieIface& cookie,
cb::mcbp::DcpAddStreamFlag flags,
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
uint64_t vbucket_uuid,
uint64_t snap_start_seqno,
uint64_t snap_end_seqno,
uint64_t* rollback_seqno,
dcp_add_failover_log callback,
std::optional<std::string_view> json) override;
cb::engine_errc get_failover_log(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
dcp_add_failover_log callback) override;
cb::engine_errc stream_end(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
cb::mcbp::DcpStreamEndStatus status) override;
cb::engine_errc snapshot_marker(
CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
uint64_t start_seqno,
uint64_t end_seqno,
cb::mcbp::request::DcpSnapshotMarkerFlag flags,
std::optional<uint64_t> high_completed_seqno,
std::optional<uint64_t> max_visible_seqno,
std::optional<uint64_t> purge_seqno) override;
cb::engine_errc mutation(CookieIface& cookie,
uint32_t opaque,
const DocKeyView& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t expiration,
uint32_t lock_time,
cb::const_byte_buffer meta,
uint8_t nru) override;
cb::engine_errc deletion(CookieIface& cookie,
uint32_t opaque,
const DocKeyView& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
cb::const_byte_buffer meta) override;
cb::engine_errc deletion_v2(CookieIface& cookie,
uint32_t opaque,
const DocKeyView& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t delete_time) override;
cb::engine_errc expiration(CookieIface& cookie,
uint32_t opaque,
const DocKeyView& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t deleteTime) override;
cb::engine_errc set_vbucket_state(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
vbucket_state_t state) override;
cb::engine_errc noop(CookieIface& cookie, uint32_t opaque) override;
cb::engine_errc buffer_acknowledgement(CookieIface& cookie,
uint32_t opaque,
uint32_t buffer_bytes) override;
cb::engine_errc control(CookieIface& cookie,
uint32_t opaque,
std::string_view key,
std::string_view value) override;
cb::engine_errc response_handler(
CookieIface& cookie, const cb::mcbp::Response& response) override;
cb::engine_errc system_event(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
mcbp::systemevent::id event,
uint64_t bySeqno,
mcbp::systemevent::version version,
cb::const_byte_buffer key,
cb::const_byte_buffer eventData) override;
cb::engine_errc prepare(CookieIface& cookie,
uint32_t opaque,
const DocKeyView& key,
cb::const_byte_buffer value,
uint8_t datatype,
uint64_t cas,
Vbid vbucket,
uint32_t flags,
uint64_t by_seqno,
uint64_t rev_seqno,
uint32_t expiration,
uint32_t lock_time,
uint8_t nru,
DocumentState document_state,
cb::durability::Level level) override;
cb::engine_errc seqno_acknowledged(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
uint64_t prepared_seqno) override;
cb::engine_errc commit(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
const DocKeyView& key,
uint64_t prepared_seqno,
uint64_t commit_seqno) override;
cb::engine_errc abort(CookieIface& cookie,
uint32_t opaque,
Vbid vbucket,
const DocKeyView& key,
uint64_t prepared_seqno,
uint64_t abort_seqno) override;
protected:
GET_SERVER_API gsa;
ServerApi* real_api;
// Actual engine we are proxying requests to.
unique_engine_ptr real_engine;
// Pointer to DcpIface for the underlying engine we are proxying; or
// nullptr if it doesn't implement DcpIface;
DcpIface* real_engine_dcp = nullptr;
/**
* Handle the control message for block monitor file
*
* @param cookie The cookie executing the operation
* @param id The identifier used to represent the cookie
* @param file The file to monitor
* @param response callback used to send a response to the client
* @return The standard engine error codes
*/
cb::engine_errc handleBlockMonitorFile(CookieIface* cookie,
uint32_t id,
const std::string& file,
const AddResponseFn& response);
/**
* Handle the control message for suspend
*
* @param cookie The cookie executing the operation
* @param id The identifier used to represent the cookie to resume
* (the use of a different id is to allow resume to
* be sent on a different connection)
* @param response callback used to send a response to the client
* @return The standard engine error codes
*/
cb::engine_errc handleSuspend(CookieIface* cookie,
uint32_t id,
const AddResponseFn& response);
/**
* Handle the control message for resume
*
* @param cookie The cookie executing the operation
* @param id The identifier representing the connection to resume
* @param response callback used to send a response to the client
* @return The standard engine error codes
*/
cb::engine_errc handleResume(CookieIface* cookie,
uint32_t id,
const AddResponseFn& response);
/**
* @param cookie the cookie executing the operation
* @param key ID of the item whose CAS should be changed
* @param cas The new CAS
* @param response Response callback used to send a response to the client
* @return Standard engine error codes
*/
cb::engine_errc setItemCas(CookieIface* cookie,
const std::string& key,
uint32_t cas,
const AddResponseFn& response);
cb::engine_errc checkLogLevels(CookieIface* cookie,
uint32_t value,
const AddResponseFn& response);
private:
enum class Cmd {
NONE,
GET_INFO,
ALLOCATE,
REMOVE,
GET,
STORE,
CAS,
ARITHMETIC,
LOCK,
UNLOCK,
FLUSH,
GET_STATS,
GET_META,
UNKNOWN_COMMAND
};
const char* to_string(Cmd cmd);
/**
* Returns true if the next command should have a fake error code injected.
* @param func Address of the command function (get, store, etc).
* @param cookie The cookie for the user's request.
* @param[out] Error code to return.
*/
bool should_inject_error(Cmd cmd,
CookieIface* cookie,
cb::engine_errc& err);
// Base class for all fault injection modes.
struct FaultInjectMode {
virtual ~FaultInjectMode() = default;
explicit FaultInjectMode(cb::engine_errc injected_error_)
: injected_error(injected_error_) {
}
// In the event of injecting an EWOULDBLOCK error, should the connection
// be added to the pending_io_ops (and subsequently notified)?
// @returns empty if shouldn't be added, otherwise contains the
// status code to notify with.
virtual std::optional<cb::engine_errc> add_to_pending_io_ops() {
return cb::engine_errc::success;
}
virtual bool should_inject_error(Cmd cmd, cb::engine_errc& err) = 0;
virtual std::string to_string() const = 0;
protected:
cb::engine_errc injected_error;
};
// Subclasses for each fault inject mode: /////////////////////////////////
class ErrOnFirst : public FaultInjectMode {
public:
explicit ErrOnFirst(cb::engine_errc injected_error_)
: FaultInjectMode(injected_error_) {
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
// Block unless the previous command from this cookie
// was the same - i.e. all of a connections' commands
// will EWOULDBLOCK the first time they are called.
bool inject = (prev_cmd != cmd);
prev_cmd = cmd;
if (inject) {
err = injected_error;
}
return inject;
}
std::string to_string() const override {
return "ErrOnFirst inject_error=" + cb::to_string(injected_error);
}
private:
// Last command issued by this cookie.
Cmd prev_cmd = Cmd::NONE;
};
class ErrOnNextN : public FaultInjectMode {
public:
ErrOnNextN(cb::engine_errc injected_error_, uint32_t count_)
: FaultInjectMode(injected_error_), count(count_) {
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
if (count > 0) {
--count;
err = injected_error;
return true;
}
return false;
}
std::string to_string() const override {
return std::string("ErrOnNextN") +
" inject_error=" + cb::to_string(injected_error) +
" count=" + std::to_string(count);
}
private:
// The count of commands issued that should return error.
uint32_t count;
};
class ErrRandom : public FaultInjectMode {
public:
ErrRandom(cb::engine_errc injected_error_, uint32_t percentage_)
: FaultInjectMode(injected_error_), percentage_to_err(percentage_) {
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<uint32_t> dis(1, 100);
if (dis(gen) < percentage_to_err) {
err = injected_error;
return true;
}
return false;
}
std::string to_string() const override {
return std::string("ErrRandom") +
" inject_error=" + cb::to_string(injected_error) +
" percentage=" + std::to_string(percentage_to_err);
}
private:
// Percentage chance that the specified error should be injected.
uint32_t percentage_to_err;
};
/**
* Injects a sequence of error codes for each call to should_inject_error().
* If the end of the given sequence is reached, then throws
* std::logic_error.
*
* cb::mcbp::Status::ReservedUserStart can be used to specify that the
* no error is injected (the original status code is returned unchanged).
*/
class ErrSequence : public FaultInjectMode {
public:
/**
* Construct with a sequence of the specified error, or the 'normal'
* status code.
*/
ErrSequence(cb::engine_errc injected_error_, uint32_t sequence_)
: FaultInjectMode(injected_error_) {
for (int ii = 0; ii < 32; ii++) {
if ((sequence_ & (1 << ii)) != 0) {
sequence.push_back(injected_error_);
} else {
sequence.push_back(cb::engine_errc(-1));
}
}
pos = sequence.begin();
}
/**
* Construct with a specific sequence of (potentially different) status
* codes encoded as vector of cb::engine_errc elements in the
* request value.
*/
explicit ErrSequence(std::vector<cb::engine_errc> sequence_)
: FaultInjectMode(cb::engine_errc::success),
sequence(std::move(sequence_)),
pos(sequence.begin()) {
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
if (pos == sequence.end()) {
throw std::logic_error(
"ErrSequence::should_inject_error() Reached end of "
"sequence");
}
bool inject = false;
if (*pos != cb::engine_errc(-1)) {
inject = true;
err = *pos;
}
pos++;
return inject;
}
std::optional<cb::engine_errc> add_to_pending_io_ops() override {
// If this function has been called, should_inject_error() must
// have returned true. Return the next status code in the sequnce
// as the result of the pending IO.
if (pos == sequence.end()) {
throw std::logic_error(
"ErrSequence::add_to_pending_io_ops() Reached end of "
"sequence");
}
return *pos++;
}
std::string to_string() const override {
std::stringstream ss;
ss << "ErrSequence sequence=[";
for (const auto& err : sequence) {
if (err == cb::engine_errc(-1)) {
ss << "'<passthrough>',";
} else {
ss << "'" << err << "',";
}
}
ss << "] pos=" << pos - sequence.begin();
return ss.str();
}
private:
std::vector<cb::engine_errc> sequence;
std::vector<cb::engine_errc>::const_iterator pos;
};
class ErrOnNoNotify : public FaultInjectMode {
public:
explicit ErrOnNoNotify(cb::engine_errc injected_error_)
: FaultInjectMode(injected_error_) {
}
std::optional<cb::engine_errc> add_to_pending_io_ops() override {
return {};
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
if (!issued_return_error) {
issued_return_error = true;
err = injected_error;
return true;
}
return false;
}
std::string to_string() const override {
return std::string("ErrOnNoNotify") +
" inject_error=" + cb::to_string(injected_error) +
" issued_return_error=" +
std::to_string(issued_return_error);
}
private:
// Record of whether have yet issued return error.
bool issued_return_error = false;
};
class CASMismatch : public FaultInjectMode {
public:
explicit CASMismatch(uint32_t count_)
: FaultInjectMode(cb::engine_errc::key_already_exists),
count(count_) {
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
if (cmd == Cmd::CAS && (count > 0)) {
--count;
err = injected_error;
return true;
}
return false;
}
std::string to_string() const override {
return std::string("CASMismatch") +
" count=" + std::to_string(count);
}
protected:
uint32_t count;
};
class SlowCasMismatch : public CASMismatch {
public:
explicit SlowCasMismatch(uint32_t count_)
: CASMismatch(count_ & 0xffff),
sleep_time((count_ & 0xffff0000) >> 16) {
if (sleep_time.count() == 0) {
sleep_time = std::chrono::milliseconds{1};
}
}
bool should_inject_error(Cmd cmd, cb::engine_errc& err) override {
if (CASMismatch::should_inject_error(cmd, err)) {
std::this_thread::sleep_for(sleep_time);
return true;
}
return false;
}
std::string to_string() const override {
return fmt::format("SlowCasMismatch count={} sleep_time={}ms",
count,
sleep_time.count());
}
protected:
std::chrono::milliseconds sleep_time;
};
// Map of connections (aka cookies) to their current mode.
folly::Synchronized<
std::unordered_map<
uint64_t,
std::pair<CookieIface*, std::shared_ptr<FaultInjectMode>>>,
std::mutex>
connection_map;
/// A map from connection id to cookies which are suspended
folly::Synchronized<std::unordered_map<uint32_t, CookieIface*>, std::mutex>
suspended_map;
bool suspendConn(CookieIface* cookie, uint32_t id) {
return suspended_map.withLock([id, cookie](auto& map) {
auto [iter, inserted] = map.insert({id, cookie});
return inserted;
});
}
bool resumeConn(uint32_t id) {
CookieIface* cookie = nullptr;
if (suspended_map.withLock([id, &cookie](auto& map) {
auto iter = map.find(id);
if (iter == map.cend()) {
return false;
}
cookie = iter->second;
map.erase(iter);
return true;
})) {
schedule_notification(cookie, cb::engine_errc::success);
return true;
}
return false;
}
bool is_connection_suspended(CookieIface* cookie) {
return suspended_map.withLock([cookie, this](const auto& map) {
for (const auto& [id, c] : map) {
if (c == cookie) {
return true;
}
}
return false;
});
}
void schedule_notification(CookieIface* cookie, cb::engine_errc status) {
cookie->notifyIoComplete(status);
}
// Vector to keep track of the threads we've started to ensure
// we don't leak memory ;-)
folly::Synchronized<std::vector<std::unique_ptr<Couchbase::Thread>>,
std::mutex>
threads;
};
EWB_Engine::EWB_Engine(GET_SERVER_API gsa_) : gsa(gsa_), real_api(gsa()) {
}
EWB_Engine::~EWB_Engine() {
threads.lock()->clear();
}
void EWB_Engine::disconnect(CookieIface& cookie) {
connection_map.lock()->erase(uint64_t(&cookie.getConnectionIface()));
if (real_engine) {
real_engine->disconnect(cookie);
}
}
/* Returns true if the next command should have a fake error code injected.
* @param func Address of the command function (get, store, etc).
* @param cookie The cookie for the user's request.
* @param[out] Error code to return.
*/
bool EWB_Engine::should_inject_error(Cmd cmd,
CookieIface* cookie,
cb::engine_errc& err) {
if (is_connection_suspended(cookie)) {
err = cb::engine_errc::would_block;
return true;
}
return connection_map.withLock([&err, cmd, cookie, this](auto& map) {
auto iter = map.find(uint64_t(&cookie->getConnectionIface()));
if (iter == map.end()) {
return false;
}
if (iter->second.first != cookie) {
// The cookie is different so it represents a different command
map.erase(iter);
return false;
}
const bool inject = iter->second.second->should_inject_error(cmd, err);
if (inject) {
if (err == cb::engine_errc::would_block) {
const auto add_to_pending_io_ops =
iter->second.second->add_to_pending_io_ops();
if (add_to_pending_io_ops) {
// The server expects that if EWOULDBLOCK is returned
// then the server should be notified in the future when
// the operation is ready - so add this op to the
// pending IO queue.
schedule_notification(iter->second.first,
*add_to_pending_io_ops);
}
}
}
return inject;
});
}
cb::engine_errc EWB_Engine::initialize(std::string_view config_str,
const nlohmann::json& encryption) {
std::string real_engine_name;
auto engine_config = cb::config::filter(
config_str, [&real_engine_name](auto k, auto v) -> bool {
if (k == "ewb_real_engine") {
real_engine_name = v;
return false;
}
return true;
});
real_engine = createBucket(real_engine_name, gsa);
if (!real_engine) {
LOG_CRITICAL(
"ERROR: EWB_Engine::initialize(): Failed create "
"engine instance '{}'",
real_engine_name);
std::abort();
}
real_engine_dcp = dynamic_cast<DcpIface*>(real_engine.get());
return real_engine->initialize(engine_config, encryption);
}
void EWB_Engine::destroy(bool force) {
real_engine->destroy(force);
(void)real_engine.release();
delete this;
}
cb::engine_errc EWB_Engine::set_traffic_control_mode(CookieIface& cookie,
TrafficControlMode mode) {
return real_engine->set_traffic_control_mode(cookie, mode);
}
cb::unique_item_ptr EWB_Engine::allocateItem(CookieIface& cookie,
const DocKeyView& key,
size_t nbytes,
size_t priv_nbytes,
uint32_t flags,
rel_time_t exptime,
uint8_t datatype,
Vbid vbucket) {
cb::engine_errc err = cb::engine_errc::success;
if (should_inject_error(Cmd::ALLOCATE, &cookie, err)) {
throw cb::engine_error(err, "ewb: injecting error");
}
return real_engine->allocateItem(cookie,
key,
nbytes,
priv_nbytes,
flags,
exptime,
datatype,
vbucket);
}
cb::engine_errc EWB_Engine::remove(
CookieIface& cookie,
const DocKeyView& key,
uint64_t& cas,
Vbid vbucket,
const std::optional<cb::durability::Requirements>& durability,
mutation_descr_t& mut_info) {
cb::engine_errc err = cb::engine_errc::success;
if (should_inject_error(Cmd::REMOVE, &cookie, err)) {
return err;
}
return real_engine->remove(cookie, key, cas, vbucket, durability, mut_info);
}
void EWB_Engine::release(ItemIface& item) {
return real_engine->release(item);
}
cb::EngineErrorItemPair EWB_Engine::get(CookieIface& cookie,
const DocKeyView& key,
Vbid vbucket,
DocStateFilter documentStateFilter) {
cb::engine_errc err = cb::engine_errc::success;
if (should_inject_error(Cmd::GET, &cookie, err)) {
return std::make_pair(
err, cb::unique_item_ptr{nullptr, cb::ItemDeleter{this}});
}
return real_engine->get(cookie, key, vbucket, documentStateFilter);
}
cb::EngineErrorItemPair EWB_Engine::get_random_document(CookieIface& cookie,
CollectionID cid) {
cb::engine_errc err;
if (should_inject_error(Cmd::GET, &cookie, err)) {
return std::make_pair(