/
ep_engine.h
1719 lines (1498 loc) · 56 KB
/
ep_engine.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "locks.hh"
#include "ep.hh"
#include "flusher.hh"
#include "sqlite-kvstore.hh"
#include "ep_extension.h"
#include <memcached/util.h>
#include <cstdio>
#include <map>
#include <list>
#include <errno.h>
#define NUMBER_OF_SHARDS 4
#define CONNECTION_TIMEOUT 15000
#define MAX_RECONNECT_INTERVAL 30
#define MIN_RECONNECT_INTERVAL 5
#define MAX_RECONNECT_ATTEMPTS 300
extern "C" {
EXPORT_FUNCTION
ENGINE_ERROR_CODE create_instance(uint64_t interface,
GET_SERVER_API get_server_api,
ENGINE_HANDLE **handle);
void EvpHandleDisconnect(const void *cookie,
ENGINE_EVENT_TYPE type,
const void *event_data,
const void *cb_data);
void *EvpNotifyTapIo(void*arg);
void EvpHandleTapCallback(const void *cookie,
ENGINE_EVENT_TYPE type,
const void *event_data,
const void *cb_data);
void EvpClockHandler(const void *cookie,
ENGINE_EVENT_TYPE type,
const void *event_data,
const void *cb_data);
}
#ifdef linux
/* /usr/include/netinet/in.h defines macros from ntohs() to _bswap_nn to
* optimize the conversion functions, but the prototypes generate warnings
* from gcc. The conversion methods isn't the bottleneck for my app, so
* just remove the warnings by undef'ing the optimization ..
*/
#undef ntohs
#undef ntohl
#undef htons
#undef htonl
#endif
#define CMD_STOP_PERSISTENCE 0x80
#define CMD_START_PERSISTENCE 0x81
#define CMD_SET_FLUSH_PARAM 0x82
#define CMD_START_REPLICATION 0x90
#define CMD_STOP_REPLICATION 0x91
#define CMD_SET_TAP_PARAM 0x92
class BoolCallback : public Callback<bool>
{
public:
virtual void callback(bool &theValue) {
value = theValue;
}
bool getValue() {
return value;
}
private:
bool value;
};
class EventuallyPersistentEngine;
class LookupCallback : public Callback<GetValue> {
public:
LookupCallback(EventuallyPersistentEngine *e, const void* c) :
engine(e), cookie(c) {}
virtual void callback(GetValue &value);
private:
EventuallyPersistentEngine *engine;
const void *cookie;
};
/**
* Class used by the EventuallyPersistentEngine to keep track of all
* information needed per Tap connection.
*/
class TapConnection {
friend class EventuallyPersistentEngine;
friend class BackFillVisitor;
private:
/**
* Add a new item to the tap queue.
* @return true if the the queue was empty
*/
bool addEvent(Item *it) {
return addEvent(it->getKey());
}
/**
* Add a key to the tap queue.
* @return true if the the queue was empty
*/
bool addEvent(const std::string &key) {
bool wasEmpty = queue->empty();
std::pair<std::set<std::string>::iterator, bool> ret;
ret = queue_set->insert(key);
if (ret.second) {
queue->push_back(key);
}
return wasEmpty;
}
std::string next() {
assert(!empty());
std::string key = queue->front();
queue->pop_front();
queue_set->erase(key);
++recordsFetched;
return key;
}
bool empty() {
return queue->empty();
}
void flush() {
pendingFlush = true;
/* No point of keeping the rep queue when someone wants to flush it */
queue->clear();
queue_set->clear();
}
bool shouldFlush() {
bool ret = pendingFlush;
pendingFlush = false;
return ret;
}
void replaceQueues(std::list<std::string> *q,
std::set<std::string> *qs) {
delete queue_set;
queue_set = qs;
std::list<std::string> *old = queue;
queue = q;
while (!old->empty()) {
addEvent(old->front());
old->pop_front();
}
// replaceQueues is called when the backfill is complete.
pendingBackfill = false;
}
bool complete(void) {
return dumpQueue && empty() && !pendingBackfill;
}
TapConnection(const std::string &n, uint32_t f):
client(n), queue(NULL), queue_set(NULL), flags(f),
recordsFetched(0), pendingFlush(false), expiry_time((rel_time_t)-1),
reconnects(0), connected(true), paused(false), backfillAge(0),
doRunBackfill(false), pendingBackfill(true)
{
queue = new std::list<std::string>;
queue_set = new std::set<std::string>;
}
~TapConnection() {
delete queue;
delete queue_set;
}
/**
* String used to identify the client.
* @todo design the connect packet and fill inn som info here
*/
std::string client;
/**
* The queue of keys that needs to be sent (this is the "live stream")
*/
std::list<std::string> *queue;
/**
* Set to prevent duplicate queue entries.
*
* Note that stl::set is O(log n) for ops we care about, so we'll
* want to look out for this.
*/
std::set<std::string> *queue_set;
/**
* Flags passed by the client
*/
uint32_t flags;
/**
* Counter of the number of records fetched from this stream since the
* beginning
*/
size_t recordsFetched;
/**
* Do we have a pending flush command?
*/
bool pendingFlush;
/**
* when this tap conneciton expires.
*/
rel_time_t expiry_time;
/**
* Number of times this client reconnected
*/
uint32_t reconnects;
/**
* Is connected?
*/
bool connected;
/**
* is his paused
*/
bool paused;
/**
* Backfill age for the connection
*/
uint64_t backfillAge;
/**
* Dump and disconnect?
*/
bool dumpQueue;
/**
* We don't want to do the backfill in the thread used by the client,
* because that would block all clients bound to the same thread.
* Instead we run the backfill the first time we try to walk the
* stream (that would be in the TAP thread). This would cause the other
* tap streams to block, but allows all clients to use the cache.
*/
bool doRunBackfill;
// True until a backfill has dumped all the content.
bool pendingBackfill;
DISALLOW_COPY_AND_ASSIGN(TapConnection);
};
/**
* Tap client connection
*/
class TapClientConnection {
friend class EventuallyPersistentEngine;
private:
TapClientConnection(const std::string &n, uint32_t f) : peer(n), flags(f),
connected(false), reconnects(0), failed(false), retry_interval(0), last_retry(0)
{ }
void setFailed() {
failed = true;
connected = false;
retry_interval = last_retry += MIN_RECONNECT_INTERVAL;
if (retry_interval > MAX_RECONNECT_INTERVAL) {
retry_interval = last_retry = MIN_RECONNECT_INTERVAL;
}
}
bool shouldRetry() {
if (reconnects++ > MAX_RECONNECT_ATTEMPTS) {
return false;
}
return failed;
}
/**
* String used to identify the peer.
*/
std::string peer;
/**
* Flags passed to the peer
*/
uint32_t flags;
/**
* Is connected?
*/
bool connected;
/**
* Number of reconnect attempts
*/
int reconnects;
/**
* connection attempt failed
*/
bool failed;
/**
* Next retry in seconds
*/
int retry_interval;
/**
* retry interval in seconds
*/
int last_retry;
DISALLOW_COPY_AND_ASSIGN(TapClientConnection);
};
/**
*
*/
class EventuallyPersistentEngine : public ENGINE_HANDLE_V1 {
friend class LookupCallback;
public:
ENGINE_ERROR_CODE initialize(const char* config)
{
ENGINE_ERROR_CODE ret = ENGINE_SUCCESS;
char *master = NULL;
if (config != NULL) {
char *dbn = NULL, *initf = NULL;
size_t htBuckets = 0;
size_t htLocks = 0;
const int max_items = 10;
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 = "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 = "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 = "ht_locks";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &htLocks;
++ii;
items[ii].key = "tap_peer";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &master;
++ii;
items[ii].key = "config_file";
items[ii].datatype = DT_CONFIGFILE;
++ii;
items[ii].key = NULL;
if (serverApi->core->parse_config(config, items, stderr) != 0) {
ret = ENGINE_FAILED;
} else {
if (dbn != NULL) {
dbname = dbn;
}
if (initf != NULL) {
initFile = initf;
}
HashTable::setDefaultNumBuckets(htBuckets);
HashTable::setDefaultNumLocks(htLocks);
}
}
if (ret == ENGINE_SUCCESS) {
time_t start = time(NULL);
try {
MultiDBSqliteStrategy *strategy =
new MultiDBSqliteStrategy(dbname,
initFile,
NUMBER_OF_SHARDS);
sqliteDb = new StrategicSqlite3(strategy);
} 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 = time(NULL) - start;
backend = epstore = new EventuallyPersistentStore(sqliteDb);
if (backend == NULL) {
ret = ENGINE_ENOMEM;
} else {
if (!warmup) {
backend->reset();
}
SERVER_CALLBACK_API *sapi;
sapi = getServerApi()->callback;
sapi->register_callback(ON_DISCONNECT, EvpHandleDisconnect, this);
sapi->register_callback(ON_TAP_CONNECT, EvpHandleTapCallback, this);
sapi->register_callback(ON_TAP_TIMEOUT, EvpHandleTapCallback, this);
sapi->register_callback(ON_TIMER, EvpClockHandler, this);
}
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) {
while (flusher->state() == initializing) {
sleep(1);
}
}
if (master != NULL) {
tapEnabled = true;
tapPeer.assign((const char *)master);
free(master);
tapConnect(tapPeer);
}
}
if (ret == ENGINE_SUCCESS) {
getlExtension = new GetlExtension(backend, getServerApi);
getlExtension->initialize();
}
getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Engine init complete.\n");
return ret;
}
void destroy()
{
stopEngineThreads();
}
ENGINE_ERROR_CODE itemAllocate(const void* cookie,
item** item,
const void* key,
const size_t nkey,
const size_t nbytes,
const int flags,
const rel_time_t exptime)
{
(void)cookie;
*item = new Item(key, nkey, nbytes, flags, exptime);
if (*item == NULL) {
return ENGINE_ENOMEM;
} else {
return ENGINE_SUCCESS;
}
}
ENGINE_ERROR_CODE itemDelete(const void* cookie,
const void* key,
const size_t nkey,
uint64_t cas,
uint16_t vbucket)
{
(void)cas;
(void)vbucket;
std::string k(static_cast<const char*>(key), nkey);
return itemDelete(cookie, k);
}
ENGINE_ERROR_CODE itemDelete(const void* cookie, const std::string &key)
{
(void)cookie;
RememberingCallback<bool> delCb;
backend->del(key, delCb);;
delCb.waitForValue();
if (delCb.val) {
addDeleteEvent(key);
return ENGINE_SUCCESS;
} else {
// in case of the item being locked, we should probably
// return a more relavent return code. @TODO
return ENGINE_KEY_ENOENT;
}
}
void itemRelease(const void* cookie, item *item)
{
(void)cookie;
delete (Item*)item;
}
ENGINE_ERROR_CODE get(const void* cookie,
item** item,
const void* key,
const int nkey,
uint16_t vbucket)
{
(void)cookie;
(void)vbucket;
std::string k(static_cast<const char*>(key), nkey);
RememberingCallback<GetValue> getCb;
backend->get(k, getCb);
getCb.waitForValue();
if (getCb.val.isSuccess()) {
*item = getCb.val.getValue();
return ENGINE_SUCCESS;
} else {
return ENGINE_KEY_ENOENT;
}
}
ENGINE_ERROR_CODE getStats(const void* cookie,
const char* stat_key,
int nkey,
ADD_STAT add_stat)
{
ENGINE_ERROR_CODE rv = ENGINE_KEY_ENOENT;
if (stat_key == NULL) {
rv = doEngineStats(cookie, add_stat);
} else if (nkey == 3 && strncmp(stat_key, "tap", 3) == 0) {
rv = doTapStats(cookie, add_stat);
} else if (nkey == 4 && strncmp(stat_key, "hash", 3) == 0) {
rv = doHashStats(cookie, add_stat);
} else if (nkey > 4 && strncmp(stat_key, "key ", 4) == 0) {
// Non-validating, non-blocking version
rv = doKeyStats(cookie, add_stat, &stat_key[4], nkey-4, false);
} else if (nkey > 5 && strncmp(stat_key, "vkey ", 5) == 0) {
// Validating version; blocks
rv = doKeyStats(cookie, add_stat, &stat_key[5], nkey-5, true);
}
return rv;
}
ENGINE_ERROR_CODE store(const void *cookie,
item* itm,
uint64_t *cas,
ENGINE_STORE_OPERATION operation,
uint16_t vbucket)
{
ENGINE_ERROR_CODE ret;
BoolCallback callback;
Item *it = static_cast<Item*>(itm);
item *i;
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:
backend->set(*it, callback);
if (callback.getValue() &&
((mutation_type_t)callback.getStatus() != IS_LOCKED)) {
*cas = it->getCas();
addMutationEvent(it);
ret = ENGINE_SUCCESS;
} else {
ret = ENGINE_KEY_EEXISTS;
}
break;
case OPERATION_ADD:
// @todo this isn't atomic!
if (get(cookie, &i, it->getKey().c_str(), it->getNKey(),
vbucket) == ENGINE_SUCCESS) {
itemRelease(cookie, i);
ret = ENGINE_KEY_EEXISTS;
} else {
backend->set(*it, callback);
// unable to set if the key is locked
if ((mutation_type_t)callback.getStatus() == IS_LOCKED) {
return ENGINE_KEY_EEXISTS;
}
*cas = it->getCas();
addMutationEvent(it);
ret = ENGINE_SUCCESS;
}
break;
case OPERATION_REPLACE:
// @todo this isn't atomic!
if (get(cookie, &i, it->getKey().c_str(), it->getNKey(),
vbucket) == ENGINE_SUCCESS) {
itemRelease(cookie, i);
backend->set(*it, callback);
// unable to set if the key is locked
if ((mutation_type_t)callback.getStatus() == IS_LOCKED) {
return ENGINE_KEY_EEXISTS;
}
*cas = it->getCas();
addMutationEvent(it);
ret = ENGINE_SUCCESS;
} else {
ret = ENGINE_NOT_STORED;
}
break;
case OPERATION_APPEND:
case OPERATION_PREPEND:
do {
if ((ret = get(cookie, &i, it->getKey().c_str(),
it->getNKey(), vbucket)) == ENGINE_SUCCESS) {
Item *old = reinterpret_cast<Item*>(i);
if (operation == OPERATION_APPEND) {
if (!old->append(*it)) {
itemRelease(cookie, i);
return ENGINE_ENOMEM;
}
} else {
if (!old->prepend(*it)) {
itemRelease(cookie, i);
return ENGINE_ENOMEM;
}
}
ret = store(cookie, old, cas, OPERATION_CAS, vbucket);
itemRelease(cookie, i);
}
} while (ret == ENGINE_KEY_EEXISTS);
// Map the error code back to what memcacpable expects
if (ret == ENGINE_KEY_ENOENT) {
ret = ENGINE_NOT_STORED;
}
break;
default:
ret = ENGINE_ENOTSUP;
}
return ret;
}
ENGINE_ERROR_CODE arithmetic(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)
{
item *it = NULL;
ENGINE_ERROR_CODE ret;
ret = get(cookie, &it, key, nkey, vbucket);
if (ret == ENGINE_SUCCESS) {
Item *item = static_cast<Item*>(it);
char *endptr;
uint64_t val = strtoull(item->getData(), &endptr, 10);
if ((errno != ERANGE) && (isspace(*endptr) || (*endptr == '\0' && endptr != item->getData()))) {
if (increment) {
val += delta;
} else {
if (delta > val) {
val = 0;
} else {
val -= delta;
}
}
std::stringstream vals;
vals << val << "\r\n";
size_t nb = vals.str().length();
*result = val;
Item *nit = new Item(key, (uint16_t)nkey, item->getFlags(),
exptime, vals.str().c_str(), nb);
nit->setCas(item->getCas());
ret = store(cookie, nit, cas, OPERATION_CAS, vbucket);
delete nit;
} else {
ret = ENGINE_EINVAL;
}
delete item;
} else if (ret == ENGINE_KEY_ENOENT && create) {
std::stringstream vals;
vals << initial << "\r\n";
size_t nb = vals.str().length();
*result = initial;
Item *item = new Item(key, (uint16_t)nkey, 0, exptime,
vals.str().c_str(), nb);
ret = store(cookie, item, cas, OPERATION_ADD, vbucket);
delete item;
}
/* We had a race condition.. just call ourself recursively to retry */
if (ret == ENGINE_KEY_EEXISTS) {
return arithmetic(cookie, key, nkey, increment, create, delta,
initial, exptime, cas, result, vbucket);
}
return ret;
}
ENGINE_ERROR_CODE flush(const void *cookie, time_t when)
{
(void)cookie;
ENGINE_ERROR_CODE ret= ENGINE_ENOTSUP;
if (when == 0) {
epstore->reset();
addFlushEvent();
ret = ENGINE_SUCCESS;
}
return ret;
}
tap_event_t walkTapQueue(const void *cookie, item **itm, void **es,
uint16_t *nes, uint8_t *ttl, uint16_t *flags,
uint32_t *seqno, uint16_t *vbucket) {
LockHolder lh(tapNotifySync);
TapConnection *connection = tapConnectionMap[cookie];
assert(connection);
if (connection->doRunBackfill) {
queueBackfill(connection);
}
tap_event_t ret = TAP_PAUSE;
connection->paused = false;
*es = NULL;
*nes = 0;
*ttl = (uint8_t)-1;
*seqno = 0;
*flags = 0;
if (!connection->empty()) {
std::string key = connection->next();
lh.unlock();
ENGINE_ERROR_CODE r;
/* @todo need to fill in the vbucket id! */
*vbucket = 0;
r = get(cookie, itm, key.c_str(), (int)key.length(), 0);
if (r == ENGINE_SUCCESS) {
ret = TAP_MUTATION;
} else if (r == ENGINE_KEY_ENOENT) {
ret = TAP_DELETION;
r = itemAllocate(cookie, itm,
key.c_str(), key.length(), 0, 0, 0);
if (r != ENGINE_SUCCESS) {
EXTENSION_LOGGER_DESCRIPTOR *logger;
logger = (EXTENSION_LOGGER_DESCRIPTOR*)serverApi->extension->get_extension(EXTENSION_LOGGER);
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Failed to allocate memory for deletion of: %s\n", key.c_str());
ret = TAP_PAUSE;
}
}
} else if (connection->shouldFlush()) {
ret = TAP_FLUSH;
} else {
connection->paused = true;
}
if (ret == TAP_PAUSE && connection->complete()) {
ret = TAP_DISCONNECT;
}
return ret;
}
void createTapQueue(const void *cookie, std::string &client, uint32_t flags,
const void *userdata,
size_t nuserdata) {
// map is set-assocative, so this will create an instance here..
LockHolder lh(tapNotifySync);
purgeExpiredTapConnections_UNLOCKED();
std::string name = "eq_tapq:";
if (client.length() == 0) {
char buffer[32];
snprintf(buffer, sizeof(buffer), "%p", cookie);
name.append(buffer);
} else {
name.append(client);
}
TapConnection *tap = NULL;
std::list<TapConnection*>::iterator iter;
for (iter = allTaps.begin(); iter != allTaps.end(); ++iter) {
tap = *iter;
if (tap->client == name) {
tap->expiry_time = (rel_time_t)-1;
++tap->reconnects;
break;
} else {
tap = NULL;
}
}
// Disconnects aren't quite immediate yet, so if we see a
// connection request for a client *and* expiry_time is 0, we
// should kill this guy off.
if (tap != NULL && tapKeepAlive == 0) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"Forcing close of tap client [%s]\n",
name.c_str());
std::map<const void*, TapConnection*>::iterator miter;
for (miter = tapConnectionMap.begin();
miter != tapConnectionMap.end();
++miter) {
if (miter->second == tap) {
break;
}
}
assert(miter != tapConnectionMap.end());
tapConnectionMap.erase(miter);
purgeSingleExpiredTapConnection(tap);
tap = NULL;
}
// @todo ensure that we don't have this client alredy
// if so this should be a reconnect...
if (tap == NULL) {
TapConnection *tc = new TapConnection(name, flags);
allTaps.push_back(tc);
tapConnectionMap[cookie] = tc;
if (flags & TAP_CONNECT_FLAG_BACKFILL) { /* */
uint64_t age;
assert(nuserdata >= sizeof(age));
memcpy(&age, userdata, sizeof(age));
tc->backfillAge = ntohll(age);
}
if (tc->backfillAge < (uint64_t)time(NULL)) {
tc->doRunBackfill = true;
tc->pendingBackfill = true;
}
tc->dumpQueue = flags & TAP_CONNECT_FLAG_DUMP;
} else {
tapConnectionMap[cookie] = tap;
tap->connected = true;
}
}
ENGINE_ERROR_CODE tapNotify(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)
{
(void)engine_specific;
(void)nengine;
(void)ttl;
(void)tap_flags;
(void)tap_seqno;
if (!tapEnabled || tapClientConnectionMap[cookie] == NULL) {
return ENGINE_DISCONNECT;
}
switch (tap_event) {
case TAP_FLUSH:
return flush(cookie, 0);
case TAP_DELETION:
{
std::string k(static_cast<const char*>(key), nkey);
return itemDelete(cookie, k);
}
case TAP_MUTATION:
{
Item *item = new Item(key, (uint16_t)nkey, flags, exptime, data, ndata);
/* @TODO we don't have CAS now.. we might in the future.. */
(void)cas;
uint64_t ncas;
ENGINE_ERROR_CODE ret = store(cookie, item, &ncas, OPERATION_SET,
vbucket);
delete item;
return ret;
}
case TAP_OPAQUE:
break;
default:
abort();
}
return ENGINE_SUCCESS;
}
/**
* Visit the objects and add them to the tap connecitons queue.
* @todo this code should honor the backfill time!
*/
void queueBackfill(TapConnection *tc);
void handleDisconnect(const void *cookie) {
LockHolder lh(tapNotifySync);
std::map<const void*, TapConnection*>::iterator iter;
iter = tapConnectionMap.find(cookie);
if (iter != tapConnectionMap.end()) {
iter->second->expiry_time = serverApi->core->get_current_time()
+ (int)tapKeepAlive;
iter->second->connected = false;
tapConnectionMap.erase(iter);
}
purgeExpiredTapConnections_UNLOCKED();
{
LockHolder tm(tapMutex);
std::map<const void*, TapClientConnection*>::iterator citer;
citer = tapClientConnectionMap.find(cookie);
if (citer != tapClientConnectionMap.end()) {
TapClientConnection *tc = citer->second;
if (tc != NULL) {
tc->setFailed();
if (tapEnabled && tc->peer == tapPeer && tc->shouldRetry()) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,
"WARN: Tap connection to %s disconnected. Next retry in %d secs.\n",
tc->peer.c_str(), tc->retry_interval);
} else {
getLogger()->log(EXTENSION_LOG_WARNING, NULL,
"Tap connection to %s disconnected.\n",
tc->peer.c_str());
clientTaps.remove(citer->second);
delete citer->second;
}
}
tapClientConnectionMap.erase(citer);
}
}
}
protocol_binary_response_status stopFlusher(const char **msg) {
protocol_binary_response_status rv = PROTOCOL_BINARY_RESPONSE_SUCCESS;
*msg = NULL;
if (!epstore->pauseFlusher()) {
getLogger()->log(EXTENSION_LOG_INFO, NULL,