/
cbc.cc
2441 lines (2219 loc) · 75 KB
/
cbc.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 2011-2019 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.
*/
#define NOMINMAX
#include <map>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <limits>
#include <cstddef>
#include <cerrno>
#ifdef _WIN32
#ifndef sleep
#define sleep(interval) Sleep((interval)*1000)
#endif
#else
#include <unistd.h>
#endif
#include "common/options.h"
#include "common/histogram.h"
#include "cbc-handlers.h"
#include "connspec.h"
#include "rnd.h"
#include "contrib/lcb-jsoncpp/lcb-jsoncpp.h"
#include <libcouchbase/vbucket.h>
#include <libcouchbase/utils.h>
#ifndef LCB_NO_SSL
#include <openssl/crypto.h>
#endif
#include <snappy-stubs-public.h>
#include "internalstructs.h"
using namespace cbc;
using std::map;
using std::string;
using std::stringstream;
using std::vector;
static void printEnhancedError(int cbtype, const lcb_RESPBASE *resp, const char *additional = NULL)
{
const char *ctx = lcb_resp_get_error_context(cbtype, resp);
if (ctx != NULL) {
fprintf(stderr, "%-20s %s\n", "", ctx);
}
const char *ref = lcb_resp_get_error_ref(cbtype, resp);
if (ref != NULL) {
fprintf(stderr, "%-20s Ref: %s\n", "", ref);
}
if (additional) {
fprintf(stderr, "%-20s %s\n", "", additional);
}
}
static void printKeyError(string &key, lcb_STATUS rc, int cbtype, const lcb_RESPBASE *resp,
const char *additional = NULL)
{
fprintf(stderr, "%-20s %s\n", key.c_str(), lcb_strerror_short(rc));
printEnhancedError(cbtype, resp, additional);
}
extern "C" {
static void get_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE cbtype, const lcb_RESPGET *resp)
{
const char *p;
size_t n;
lcb_respget_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_respget_status(resp);
if (rc == LCB_SUCCESS) {
const char *value;
size_t nvalue;
uint32_t flags;
uint64_t cas;
uint8_t datatype;
lcb_respget_value(resp, &value, &nvalue);
lcb_respget_flags(resp, &flags);
lcb_respget_cas(resp, &cas);
lcb_respget_datatype(resp, &datatype);
fprintf(stderr, "%-20s CAS=0x%" PRIx64 ", Flags=0x%x, Size=%lu, Datatype=0x%02x", key.c_str(), cas, flags,
(unsigned long)nvalue, (int)datatype);
if (datatype) {
int nflags = 0;
fprintf(stderr, "(");
if (datatype & LCB_VALUE_F_JSON) {
fprintf(stderr, "JSON");
nflags++;
}
if (datatype & LCB_VALUE_F_SNAPPYCOMP) {
fprintf(stderr, "%sSNAPPY", nflags > 0 ? "," : "");
nflags++;
}
fprintf(stderr, ")");
}
fprintf(stderr, "\n");
fflush(stderr);
fwrite(value, 1, nvalue, stdout);
fflush(stdout);
fprintf(stderr, "\n");
} else {
printKeyError(key, rc, cbtype, (const lcb_RESPBASE *)resp);
}
}
static void getreplica_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE cbtype, const lcb_RESPGETREPLICA *resp)
{
const char *p;
size_t n;
lcb_respgetreplica_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_respgetreplica_status(resp);
if (rc == LCB_SUCCESS) {
const char *value;
size_t nvalue;
uint32_t flags;
uint64_t cas;
uint8_t datatype;
lcb_respgetreplica_value(resp, &value, &nvalue);
lcb_respgetreplica_flags(resp, &flags);
lcb_respgetreplica_cas(resp, &cas);
lcb_respgetreplica_datatype(resp, &datatype);
fprintf(stderr, "%-20s CAS=0x%" PRIx64 ", Flags=0x%x, Size=%lu, Datatype=0x%02x", key.c_str(), cas, flags,
(unsigned long)nvalue, (int)datatype);
if (datatype) {
int nflags = 0;
fprintf(stderr, "(");
if (datatype & LCB_VALUE_F_JSON) {
fprintf(stderr, "JSON");
nflags++;
}
if (datatype & LCB_VALUE_F_SNAPPYCOMP) {
fprintf(stderr, "%sSNAPPY", nflags > 0 ? "," : "");
nflags++;
}
fprintf(stderr, ")");
}
fprintf(stderr, "\n");
fflush(stderr);
fwrite(value, 1, nvalue, stdout);
fflush(stdout);
fprintf(stderr, "\n");
} else {
printKeyError(key, rc, cbtype, (const lcb_RESPBASE *)resp);
}
}
static void storePrintSuccess(const lcb_RESPSTORE *resp, const char *message = NULL)
{
const char *key;
size_t nkey;
lcb_respstore_key(resp, &key, &nkey);
fprintf(stderr, "%-20.*s ", (int)nkey, key);
if (message != NULL) {
fprintf(stderr, "%s ", message);
}
uint64_t cas;
lcb_respstore_cas(resp, &cas);
fprintf(stderr, "CAS=0x%" PRIx64 "\n", cas);
lcb_MUTATION_TOKEN token = {0};
lcb_respstore_mutation_token(resp, &token);
if (lcb_mutation_token_is_valid(&token)) {
fprintf(stderr, "%-20s SYNCTOKEN=%u,%" PRIu64 ",%" PRIu64 "\n", "", token.vbid_, token.uuid_, token.seqno_);
}
}
static void storePrintError(const lcb_RESPSTORE *resp, const char *message = NULL)
{
size_t sz = 0;
const char *key;
lcb_respstore_key(resp, &key, &sz);
fprintf(stderr, "%-20.*s %s\n", (int)sz, key, lcb_strerror_short(lcb_respstore_status(resp)));
const lcb_KEY_VALUE_ERROR_CONTEXT *ctx = NULL;
lcb_respstore_error_context(resp, &ctx);
const char *context, *ref;
size_t ncontext, nref;
lcb_errctx_kv_context(ctx, &context, &ncontext);
lcb_errctx_kv_ref(ctx, &ref, &nref);
if (context != NULL) {
fprintf(stderr, "%-20s %.*s\n", "", (int)ncontext, context);
}
if (ref != NULL) {
fprintf(stderr, "%-20s Ref: %.*s\n", "", (int)nref, ref);
}
if (message) {
fprintf(stderr, "%-20s %s\n", "", message);
}
}
static void store_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTORE *resp)
{
lcb_STATUS rc = lcb_respstore_status(resp);
if (lcb_respstore_observe_attached(resp)) {
// Storage with durability
char buf[4096];
uint16_t npersisted, nreplicated;
lcb_respstore_observe_num_persisted(resp, &npersisted);
lcb_respstore_observe_num_replicated(resp, &nreplicated);
if (rc == LCB_SUCCESS) {
sprintf(buf, "Stored. Persisted(%u). Replicated(%u)", npersisted, nreplicated);
storePrintSuccess(resp, buf);
} else {
int store_ok;
lcb_respstore_observe_stored(resp, &store_ok);
if (store_ok) {
sprintf(buf, "Store OK, but durability failed. Persisted(%u). Replicated(%u)", npersisted, nreplicated);
} else {
sprintf(buf, "%s", "Store failed");
}
storePrintError(resp, buf);
}
} else {
if (rc == LCB_SUCCESS) {
storePrintSuccess(resp, "Stored.");
} else {
storePrintError(resp);
}
}
}
static void exists_callback(lcb_INSTANCE *, int type, const lcb_RESPEXISTS *resp)
{
const char *p;
size_t n;
lcb_respexists_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_respexists_status(resp);
if (rc != LCB_SUCCESS) {
printKeyError(key, rc, type, (const lcb_RESPBASE *)resp);
return;
}
if (lcb_respexists_is_found(resp)) {
uint64_t cas;
lcb_respexists_cas(resp, &cas);
fprintf(stderr, "%-20s FOUND, CAS=0x%" PRIx64 "\n", key.c_str(), cas);
} else {
fprintf(stderr, "%-20s NOT FOUND\n", key.c_str());
}
}
static void unlock_callback(lcb_INSTANCE *, int type, const lcb_RESPUNLOCK *resp)
{
const char *p;
size_t n;
lcb_respunlock_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_respunlock_status(resp);
if (rc != LCB_SUCCESS) {
printKeyError(key, rc, type, (const lcb_RESPBASE *)resp);
return;
}
fprintf(stderr, "%-20s Unlocked\n", key.c_str());
}
static void remove_callback(lcb_INSTANCE *, int type, const lcb_RESPREMOVE *resp)
{
const char *p;
size_t n;
lcb_respremove_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_respremove_status(resp);
if (rc != LCB_SUCCESS) {
printKeyError(key, rc, type, (const lcb_RESPBASE *)resp);
return;
}
fprintf(stderr, "%-20s Deleted\n", key.c_str());
}
static void touch_callback(lcb_INSTANCE *, int type, const lcb_RESPTOUCH *resp)
{
const char *p;
size_t n;
lcb_resptouch_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_resptouch_status(resp);
if (rc != LCB_SUCCESS) {
printKeyError(key, rc, type, (const lcb_RESPBASE *)resp);
return;
}
fprintf(stderr, "%-20s Touch\n", key.c_str());
}
static void observe_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE cbtype, const lcb_RESPOBSERVE *resp)
{
if (resp->ctx.key == 0) {
return;
}
string key((const char *)resp->ctx.key, resp->ctx.key_len);
if (resp->ctx.rc == LCB_SUCCESS) {
fprintf(stderr, "%-20s [%s] Status=0x%x, CAS=0x%" PRIx64 "\n", key.c_str(),
resp->ismaster ? "Master" : "Replica", resp->status, resp->ctx.cas);
} else {
printKeyError(key, resp->ctx.rc, cbtype, (const lcb_RESPBASE *)resp);
}
}
static void obseqno_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPOBSEQNO *resp)
{
int ix = resp->server_index;
if (resp->ctx.rc != LCB_SUCCESS) {
fprintf(stderr, "[%d] ERROR %s\n", ix, lcb_strerror_long(resp->ctx.rc));
return;
}
lcb_U64 uuid, seq_disk, seq_mem;
if (resp->old_uuid) {
seq_disk = seq_mem = resp->old_seqno;
uuid = resp->old_uuid;
} else {
uuid = resp->cur_uuid;
seq_disk = resp->persisted_seqno;
seq_mem = resp->mem_seqno;
}
fprintf(stderr, "[%d] UUID=0x%" PRIx64 ", Cache=%" PRIu64 ", Disk=%" PRIu64, ix, uuid, seq_mem, seq_disk);
if (resp->old_uuid) {
fprintf(stderr, "\n");
fprintf(stderr, " FAILOVER. New: UUID=%" PRIx64 ", Cache=%" PRIu64 ", Disk=%" PRIu64, resp->cur_uuid,
resp->mem_seqno, resp->persisted_seqno);
}
fprintf(stderr, "\n");
}
static void stats_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp)
{
if (resp->ctx.rc != LCB_SUCCESS) {
fprintf(stderr, "ERROR %s\n", lcb_strerror_long(resp->ctx.rc));
return;
}
if (resp->server == NULL || resp->ctx.key == NULL) {
return;
}
string server = resp->server;
string key((const char *)resp->ctx.key, resp->ctx.key_len);
string value;
if (resp->nvalue > 0) {
value.assign((const char *)resp->value, resp->nvalue);
}
fprintf(stdout, "%s\t%s", server.c_str(), key.c_str());
if (!value.empty()) {
if (*static_cast< bool * >(resp->cookie) && key == "key_flags") {
// Is keystats
// Flip the bits so the display formats correctly
unsigned flags_u = 0;
sscanf(value.c_str(), "%u", &flags_u);
flags_u = htonl(flags_u);
fprintf(stdout, "\t%u (cbc: converted via htonl)", flags_u);
} else {
fprintf(stdout, "\t%s", value.c_str());
}
}
fprintf(stdout, "\n");
}
static void watch_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp)
{
if (resp->ctx.rc != LCB_SUCCESS) {
fprintf(stderr, "ERROR %s\n", lcb_strerror_long(resp->ctx.rc));
return;
}
if (resp->server == NULL || resp->ctx.key == NULL) {
return;
}
string key((const char *)resp->ctx.key, resp->ctx.key_len);
if (resp->nvalue > 0) {
char *nptr = NULL;
uint64_t val =
#ifdef _WIN32
_strtoi64
#else
strtoll
#endif
((const char *)resp->value, &nptr, 10);
if (nptr != (const char *)resp->value) {
map< string, int64_t > *entry = reinterpret_cast< map< string, int64_t > * >(resp->cookie);
(*entry)[key] += val;
}
}
}
static void common_server_callback(lcb_INSTANCE *, int cbtype, const lcb_RESPSERVERBASE *sbase)
{
string msg;
if (cbtype == LCB_CALLBACK_VERBOSITY) {
msg = "Set verbosity";
} else if (cbtype == LCB_CALLBACK_VERSIONS) {
const lcb_RESPMCVERSION *resp = (const lcb_RESPMCVERSION *)sbase;
msg = string(resp->mcversion, resp->nversion);
} else {
msg = "";
}
if (!sbase->server) {
return;
}
if (sbase->ctx.rc != LCB_SUCCESS) {
fprintf(stderr, "%s failed for server %s: %s\n", msg.c_str(), sbase->server, lcb_strerror_short(sbase->ctx.rc));
} else {
fprintf(stderr, "%s: %s\n", msg.c_str(), sbase->server);
}
}
static void ping_callback(lcb_INSTANCE *, int, const lcb_RESPPING *resp)
{
lcb_STATUS rc = lcb_respping_status(resp);
if (rc != LCB_SUCCESS) {
fprintf(stderr, "failed: %s\n", lcb_strerror_short(rc));
} else {
const char *json;
size_t njson;
lcb_respping_value(resp, &json, &njson);
while (njson > 1 && json[njson - 1] == '\n') {
njson--;
}
if (njson) {
printf("%.*s", (int)njson, json);
}
}
}
static void arithmetic_callback(lcb_INSTANCE *, lcb_CALLBACK_TYPE type, const lcb_RESPCOUNTER *resp)
{
const char *p;
size_t n;
lcb_respcounter_key(resp, &p, &n);
string key(p, n);
lcb_STATUS rc = lcb_respcounter_status(resp);
if (rc != LCB_SUCCESS) {
printKeyError(key, rc, type, (lcb_RESPBASE *)resp);
} else {
uint64_t value;
lcb_respcounter_value(resp, &value);
fprintf(stderr, "%-20s Current value is %" PRIu64 ".", key.c_str(), value);
uint64_t cas;
lcb_respcounter_cas(resp, &cas);
fprintf(stderr, "CAS=0x%" PRIx64 "\n", cas);
lcb_MUTATION_TOKEN token = {0};
lcb_respcounter_mutation_token(resp, &token);
if (lcb_mutation_token_is_valid(&token)) {
fprintf(stderr, "%-20sSYNCTOKEN=%u,%" PRIu64 ",%" PRIu64 "\n", "", token.vbid_, token.uuid_, token.seqno_);
}
}
}
static void http_callback(lcb_INSTANCE *, int, const lcb_RESPHTTP *resp)
{
HttpReceiver *ctx;
lcb_resphttp_cookie(resp, (void **)&ctx);
ctx->maybeInvokeStatus(resp);
const char *body;
size_t nbody;
lcb_resphttp_body(resp, &body, &nbody);
if (nbody) {
ctx->onChunk(body, nbody);
}
if (lcb_resphttp_is_final(resp)) {
ctx->onDone();
}
}
static void view_callback(lcb_INSTANCE *, int, const lcb_RESPVIEW *resp)
{
if (lcb_respview_is_final(resp)) {
fprintf(stderr, "---> View response finished\n");
}
lcb_STATUS rc = lcb_respview_status(resp);
if (rc) {
fprintf(stderr, "---> View failed with library code %s\n", lcb_strerror_short(rc));
if (rc == LCB_ERR_HTTP) {
const lcb_RESPHTTP *http;
lcb_respview_http_response(resp, &http);
if (http != NULL) {
HttpReceiver receiver;
receiver.maybeInvokeStatus(http);
const char *body;
size_t nbody;
lcb_resphttp_body(http, &body, &nbody);
if (nbody) {
fprintf(stderr, "%.*s", (int)nbody, body);
}
}
}
}
if (lcb_respview_is_final(resp)) {
const char *value;
size_t nvalue;
lcb_respview_row(resp, &value, &nvalue);
if (value) {
fprintf(stderr, "Non-row data: %.*s\n", (int)nvalue, value);
}
const lcb_VIEW_ERROR_CONTEXT *ctx;
lcb_respview_error_context(resp, &ctx);
const char *ddoc, *view;
size_t nddoc, nview;
lcb_errctx_view_design_document(ctx, &ddoc, &nddoc);
lcb_errctx_view_view(ctx, &view, &nview);
fprintf(stderr, "---> View: %.*s/%.*s\n", (int)nddoc, ddoc, (int)nview, view);
uint32_t code;
lcb_errctx_view_http_response_code(ctx, &code);
fprintf(stderr, "---> HTTP response code: %d\n", code);
const char *err_code, *err_msg;
size_t nerr_code, nerr_msg;
lcb_errctx_view_first_error_code(ctx, &err_code, &nerr_code);
if (nerr_code != 0) {
fprintf(stderr, "---> First error code: %.*s\n", (int)nerr_code, err_code);
}
lcb_errctx_view_first_error_message(ctx, &err_msg, &nerr_msg);
if (nerr_msg != 0) {
fprintf(stderr, "---> First error message: %.*s\n", (int)nerr_msg, err_msg);
}
return;
}
const char *p;
size_t n;
lcb_respview_key(resp, &p, &n);
printf("KEY: %.*s\n", (int)n, p);
lcb_respview_row(resp, &p, &n);
printf(" VALUE: %.*s\n", (int)n, p);
lcb_respview_doc_id(resp, &p, &n);
printf(" DOCID: %.*s\n", (int)n, p);
const lcb_RESPGET *doc = NULL;
lcb_respview_document(resp, &doc);
if (doc) {
get_callback(NULL, LCB_CALLBACK_GET, doc);
}
}
}
Handler::Handler(const char *name) : parser(name), instance(NULL)
{
if (name != NULL) {
cmdname = name;
}
}
Handler::~Handler()
{
if (params.shouldDump()) {
lcb_dump(instance, stderr, LCB_DUMP_ALL);
}
if (instance) {
lcb_destroy(instance);
}
}
void Handler::execute(int argc, char **argv)
{
addOptions();
parser.default_settings.argstring = usagestr();
parser.default_settings.shortdesc = description();
parser.parse(argc, argv, true);
run();
if (instance != NULL && params.useTimings()) {
fprintf(stderr, "Output command timings as requested (--timings)\n");
hg.write();
}
}
void Handler::addOptions()
{
params.addToParser(parser);
}
void Handler::run()
{
lcb_CREATEOPTS *cropts = NULL;
params.fillCropts(cropts);
lcb_STATUS err;
err = lcb_create(&instance, cropts);
lcb_createopts_destroy(cropts);
if (err != LCB_SUCCESS) {
throw LcbError(err, "Failed to create instance");
}
params.doCtls(instance);
err = lcb_connect(instance);
if (err != LCB_SUCCESS) {
throw LcbError(err, "Failed to connect instance");
}
lcb_wait(instance);
err = lcb_get_bootstrap_status(instance);
if (err != LCB_SUCCESS) {
throw LcbError(err, "Failed to bootstrap instance");
}
if (params.useTimings()) {
hg.install(instance, stdout);
}
}
const string &Handler::getLoneArg(bool required)
{
static string empty("");
const vector< string > &args = parser.getRestArgs();
if (args.empty() || args.size() != 1) {
if (required) {
throw std::runtime_error("Command requires single argument");
}
return empty;
}
return args[0];
}
void GetHandler::addOptions()
{
Handler::addOptions();
o_exptime.abbrev('e');
if (isLock()) {
o_exptime.description("Time the lock should be held for");
} else {
o_exptime.description("Update the expiration time for the item");
o_replica.abbrev('r');
o_replica.description("Read from replica. Possible values are 'first': read from first available replica. "
"'all': read from all replicas, and <N>, where 0 < N < nreplicas");
parser.addOption(o_replica);
}
parser.addOption(o_exptime);
parser.addOption(o_scope);
parser.addOption(o_collection);
parser.addOption(o_durability);
}
void GetHandler::run()
{
Handler::run();
lcb_install_callback(instance, LCB_CALLBACK_GET, (lcb_RESPCALLBACK)get_callback);
lcb_install_callback(instance, LCB_CALLBACK_GETREPLICA, (lcb_RESPCALLBACK)getreplica_callback);
const vector< string > &keys = parser.getRestArgs();
std::string replica_mode = o_replica.result();
std::string s = o_scope.result();
std::string c = o_collection.result();
lcb_sched_enter(instance);
for (size_t ii = 0; ii < keys.size(); ++ii) {
lcb_STATUS err;
if (o_replica.passed()) {
lcb_REPLICA_MODE mode;
if (replica_mode == "first" || replica_mode == "any") {
mode = LCB_REPLICA_MODE_ANY;
} else if (replica_mode == "all") {
mode = LCB_REPLICA_MODE_ALL;
} else {
switch (std::atoi(replica_mode.c_str())) {
case 0:
mode = LCB_REPLICA_MODE_IDX0;
break;
case 1:
mode = LCB_REPLICA_MODE_IDX1;
break;
case 2:
mode = LCB_REPLICA_MODE_IDX2;
break;
default:
throw LcbError(LCB_ERR_INVALID_ARGUMENT, "invalid replica mode");
}
}
lcb_CMDGETREPLICA *cmd;
lcb_cmdgetreplica_create(&cmd, mode);
const string &key = keys[ii];
lcb_cmdgetreplica_key(cmd, key.c_str(), key.size());
if (o_collection.passed()) {
lcb_cmdgetreplica_collection(cmd, s.c_str(), s.size(), c.c_str(), c.size());
}
err = lcb_getreplica(instance, this, cmd);
} else {
lcb_CMDGET *cmd;
lcb_cmdget_create(&cmd);
const string &key = keys[ii];
lcb_cmdget_key(cmd, key.c_str(), key.size());
if (o_collection.passed()) {
lcb_cmdget_collection(cmd, s.c_str(), s.size(), c.c_str(), c.size());
}
if (o_exptime.passed()) {
if (isLock()) {
lcb_cmdget_locktime(cmd, o_exptime.result());
} else {
lcb_cmdget_expiry(cmd, o_exptime.result());
}
}
err = lcb_get(instance, this, cmd);
lcb_cmdget_destroy(cmd);
}
if (err != LCB_SUCCESS) {
throw LcbError(err);
}
}
lcb_sched_leave(instance);
lcb_wait(instance);
}
void TouchHandler::addOptions()
{
Handler::addOptions();
parser.addOption(o_exptime);
parser.addOption(o_durability);
}
void TouchHandler::run()
{
Handler::run();
lcb_install_callback(instance, LCB_CALLBACK_TOUCH, (lcb_RESPCALLBACK)touch_callback);
const vector< string > &keys = parser.getRestArgs();
lcb_STATUS err;
lcb_sched_enter(instance);
for (size_t ii = 0; ii < keys.size(); ++ii) {
const string &key = keys[ii];
lcb_CMDTOUCH *cmd;
lcb_cmdtouch_create(&cmd);
lcb_cmdtouch_key(cmd, key.c_str(), key.size());
lcb_cmdtouch_expiry(cmd, o_exptime.result());
err = lcb_touch(instance, this, cmd);
lcb_cmdtouch_destroy(cmd);
if (err != LCB_SUCCESS) {
throw LcbError(err);
}
}
lcb_sched_leave(instance);
lcb_wait(instance);
}
void SetHandler::addOptions()
{
Handler::addOptions();
parser.addOption(o_mode);
parser.addOption(o_flags);
parser.addOption(o_exp);
parser.addOption(o_add);
parser.addOption(o_persist);
parser.addOption(o_replicate);
if (!hasFileList()) {
parser.addOption(o_value);
}
parser.addOption(o_json);
parser.addOption(o_scope);
parser.addOption(o_collection);
parser.addOption(o_durability);
}
lcb_STORE_OPERATION SetHandler::mode()
{
if (o_add.passed()) {
return LCB_STORE_INSERT;
}
string s = o_mode.const_result();
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
if (s == "upsert") {
return LCB_STORE_UPSERT;
} else if (s == "replace") {
return LCB_STORE_REPLACE;
} else if (s == "insert") {
return LCB_STORE_INSERT;
} else if (s == "append") {
return LCB_STORE_APPEND;
} else if (s == "prepend") {
return LCB_STORE_PREPEND;
} else {
throw BadArg(string("Mode must be one of upsert, insert, replace. Got ") + s);
return LCB_STORE_UPSERT;
}
}
void SetHandler::storeItem(const string &key, const char *value, size_t nvalue)
{
lcb_STATUS err;
lcb_CMDSTORE *cmd;
std::string s = o_scope.result();
std::string c = o_collection.result();
lcb_cmdstore_create(&cmd, mode());
lcb_cmdstore_key(cmd, key.c_str(), key.size());
if (o_collection.passed()) {
lcb_cmdstore_collection(cmd, s.c_str(), s.size(), c.c_str(), c.size());
}
lcb_cmdstore_value(cmd, value, nvalue);
if (o_json.result()) {
lcb_cmdstore_datatype(cmd, LCB_VALUE_F_JSON);
}
if (o_exp.passed()) {
lcb_cmdstore_expiry(cmd, o_exp.result());
}
if (o_flags.passed()) {
lcb_cmdstore_flags(cmd, o_flags.result());
}
if (o_persist.passed() || o_replicate.passed()) {
lcb_cmdstore_durability_observe(cmd, o_persist.result(), o_replicate.result());
} else if (o_durability.passed()) {
lcb_cmdstore_durability(cmd, durability());
}
err = lcb_store(instance, NULL, cmd);
if (err != LCB_SUCCESS) {
throw LcbError(err);
}
lcb_cmdstore_destroy(cmd);
}
void SetHandler::storeItem(const string &key, FILE *input)
{
char tmpbuf[4096];
vector< char > vbuf;
size_t nr;
while ((nr = fread(tmpbuf, 1, sizeof tmpbuf, input))) {
vbuf.insert(vbuf.end(), tmpbuf, &tmpbuf[nr]);
}
storeItem(key, &vbuf[0], vbuf.size());
}
void SetHandler::run()
{
Handler::run();
lcb_install_callback(instance, LCB_CALLBACK_STORE, (lcb_RESPCALLBACK)store_callback);
lcb_install_callback(instance, LCB_CALLBACK_STOREDUR, (lcb_RESPCALLBACK)store_callback);
const vector< string > &keys = parser.getRestArgs();
lcb_sched_enter(instance);
if (hasFileList()) {
for (size_t ii = 0; ii < keys.size(); ii++) {
const string &key = keys[ii];
FILE *fp = fopen(key.c_str(), "rb");
if (fp == NULL) {
perror(key.c_str());
continue;
}
storeItem(key, fp);
fclose(fp);
}
} else if (keys.size() > 1 || keys.empty()) {
throw BadArg("create must be passed a single key");
} else {
const string &key = keys[0];
if (o_value.passed()) {
const string &value = o_value.const_result();
storeItem(key, value.c_str(), value.size());
} else {
storeItem(key, stdin);
}
}
lcb_sched_leave(instance);
lcb_wait(instance);
}
void HashHandler::run()
{
Handler::run();
lcbvb_CONFIG *vbc;
lcb_STATUS err;
err = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_VBCONFIG, &vbc);
if (err != LCB_SUCCESS) {
throw LcbError(err);
}
const vector< string > &args = parser.getRestArgs();
for (size_t ii = 0; ii < args.size(); ii++) {
const string &key = args[ii];
const void *vkey = (const void *)key.c_str();
int vbid, srvix;
lcbvb_map_key(vbc, vkey, key.size(), &vbid, &srvix);
fprintf(stderr, "%s: [vBucket=%d, Index=%d]", key.c_str(), vbid, srvix);
if (srvix != -1) {
fprintf(stderr, " Server: %s", lcbvb_get_hostport(vbc, srvix, LCBVB_SVCTYPE_DATA, LCBVB_SVCMODE_PLAIN));
const char *vapi = lcbvb_get_capibase(vbc, srvix, LCBVB_SVCMODE_PLAIN);
if (vapi) {
fprintf(stderr, ", CouchAPI: %s", vapi);
}
}
fprintf(stderr, "\n");
for (size_t jj = 0; jj < lcbvb_get_nreplicas(vbc); jj++) {
int rix = lcbvb_vbreplica(vbc, vbid, jj);
const char *rname = NULL;
if (rix >= 0) {
rname = lcbvb_get_hostport(vbc, rix, LCBVB_SVCTYPE_DATA, LCBVB_SVCMODE_PLAIN);
}
if (rname == NULL) {
rname = "N/A";
}
fprintf(stderr, "Replica #%d: Index=%d, Host=%s\n", (int)jj, rix, rname);
}
}
}
void ObserveHandler::run()
{
Handler::run();
lcb_install_callback(instance, LCB_CALLBACK_OBSERVE, (lcb_RESPCALLBACK)observe_callback);
const vector< string > &keys = parser.getRestArgs();
lcb_MULTICMD_CTX *mctx = lcb_observe3_ctxnew(instance);
if (mctx == NULL) {
throw std::bad_alloc();
}
lcb_STATUS err;
for (size_t ii = 0; ii < keys.size(); ii++) {
lcb_CMDOBSERVE cmd = {0};
LCB_KREQ_SIMPLE(&cmd.key, keys[ii].c_str(), keys[ii].size());
err = mctx->addcmd(mctx, (lcb_CMDBASE *)&cmd);
if (err != LCB_SUCCESS) {
throw LcbError(err);
}
}
lcb_sched_enter(instance);
err = mctx->done(mctx, NULL);
if (err == LCB_SUCCESS) {
lcb_sched_leave(instance);
lcb_wait(instance);
} else {
lcb_sched_fail(instance);
throw LcbError(err);
}
}
void ObserveSeqnoHandler::run()
{
Handler::run();
lcb_install_callback(instance, LCB_CALLBACK_OBSEQNO, (lcb_RESPCALLBACK)obseqno_callback);
const vector< string > &infos = parser.getRestArgs();
lcb_CMDOBSEQNO cmd = {0};
lcbvb_CONFIG *vbc;
lcb_STATUS rc;
rc = lcb_cntl(instance, LCB_CNTL_GET, LCB_CNTL_VBCONFIG, &vbc);
if (rc != LCB_SUCCESS) {
throw LcbError(rc);
}
lcb_sched_enter(instance);
for (size_t ii = 0; ii < infos.size(); ++ii) {
const string &cur = infos[ii];
unsigned vbid;
unsigned long long uuid;
int rv = sscanf(cur.c_str(), "%u,%llu", &vbid, &uuid);
if (rv != 2) {
throw BadArg("Must pass sequences of base10 vbid and base16 uuids");
}
cmd.uuid = uuid;
cmd.vbid = vbid;
for (size_t jj = 0; jj < lcbvb_get_nreplicas(vbc) + 1; ++jj) {
int ix = lcbvb_vbserver(vbc, vbid, jj);
if (ix < 0) {
fprintf(stderr, "Server %d unavailable (skipping)\n", ix);
}
cmd.server_index = ix;
rc = lcb_observe_seqno3(instance, NULL, &cmd);
if (rc != LCB_SUCCESS) {
throw LcbError(rc);
}
}
}
lcb_sched_leave(instance);
lcb_wait(instance);
}
void ExistsHandler::run()
{
Handler::run();
lcb_install_callback(instance, LCB_CALLBACK_EXISTS, (lcb_RESPCALLBACK)exists_callback);