-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpychbase.cc
3646 lines (2916 loc) · 119 KB
/
pychbase.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
#include <Python.h>
#include "structmember.h"
#include <stdio.h>
#include <unistd.h>
#include <hbase/hbase.h>
#include <pthread.h>
#include <string.h>
#include <vector>
#if defined( WIN64 ) || defined( _WIN64 ) || defined( __WIN64__ ) || defined(_WIN32)
#define __WINDOWS__
#endif
#define OOM_OBJ_RETURN_NULL(obj) \
do { \
if (!obj) { \
return PyErr_NoMemory(); \
} \
} while (0);
#define OOM_OBJ_RETURN_ERRNO(obj) \
do { \
if (!obj) { \
return 12; \
} \
} while (0);
#define OOM_ERRNO_RETURN_NULL(obj) \
do { \
if (obj == 12) { \
return PyErr_NoMemory(); \
} \
} while (0);
#define OOM_ERRNO_RETURN_ERRNO(obj) \
do { \
if (obj == 12) { \
return 12; \
} \
} while (0);
#define CHECK_FORMAT_EXC(A, exc_type, format, ...) \
do { \
if (!(A)) { \
PyErr_Format(exc_type, format, __VA_ARGS__); \
goto error; \
} \
} while (0);
#define CHECK_SET_EXC(A, exc_type, statement) \
do { \
if (!(A)) { \
PyErr_SetString(exc_type, statement); \
goto error; \
} \
} while (0);
#define CHECK_MEM_EXC(A) \
do { \
if (!(A)) { \
PyErr_SetNone(PyExc_MemoryError); \
goto error; \
} \
} while (0);
#define CHECK(A) \
do { \
if (!(A)) { \
goto error; \
} \
} while (0);
#define CHECK_ERRNO(A, errno) \
do { \
if (!(A)) { \
err = errno; \
goto error; \
} \
} while (0);
#define CHECK_MEM(A) \
do { \
if (!(A)) { \
err = 12; \
goto error; \
} \
} while (0);
static PyObject *SpamError;
static PyObject *HBaseError;
typedef struct {
// This is a macro, correct with no semi colon, which initializes fields to make it usable as a PyObject
// Why not define first and last as char * ? Is there any benefit over each way?
PyObject_HEAD
PyObject *first;
PyObject *last;
int number;
char *secret;
} Foo;
static void Foo_dealloc(Foo *self) {
//dispose of your owned references
//Py_XDECREF is sued because first/last could be NULL
Py_XDECREF(self->first);
Py_XDECREF(self->last);
//call the class tp_free function to clean up the type itself.
// Note how the Type is PyObject * insteaed of FooType * because the object may be a subclass
self->ob_type->tp_free((PyObject *) self);
// Note how there is no XDECREF on self->number
}
static PyObject *Foo_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) {
// Hm this isn't printing out?
// Ok Foo_new isn't being called for some reason
printf("In foo_new\n");
Foo *self;// == NULL;
// to_alloc allocates memory
self = (Foo *)type->tp_alloc(type, 0);
// One reason to implement a new method is to assure the initial values of instance variables
// Here we are ensuring they initial values of first and last are not NULL.
// If we don't care, we ould have used PyType_GenericNew() as the new method, which sets everything to NULL...
if (self != NULL) {
printf("in neww self is not null");
self->first = PyString_FromString("");
if (self->first == NULL) {
Py_DECREF(self);
return NULL;
}
self->last = PyString_FromString("");
if (self->last == NULL) {
Py_DECREF(self);
return NULL;
}
self->number = 0;
}
// What about self->secret ?
if (self->first == NULL) {
printf("in new self first is null\n");
} else {
printf("in new self first is not null\n");
}
return (PyObject *) self;
}
static int Foo_init(Foo *self, PyObject *args, PyObject *kwargs) {
//char *name;
printf("In foo_init\n");
PyObject *first, *last, *tmp;
// Note how we can use &self->number, but not &self->first
if (!PyArg_ParseTuple(args, "SSi", &first, &last, &self->number)) {
//return NULL;
return -1;
}
// What is the point of tmp?
// The docs say we should always reassign members before decrementing their reference counts
if (last) {
tmp = self->last;
Py_INCREF(last);
self->last = last;
Py_DECREF(tmp);
}
if (first) {
tmp = self->first;
Py_INCREF(first);
self->first = first;
//This was changed to DECREF from XDECREF once the get_first/last were set
// This is because the get_first/last guarantee that it isn't null
// but it caused a segmentation fault wtf?
// Ok that was because the new method wasn't working bug
Py_DECREF(tmp);
}
// Should I incref this?
self->secret = "secret lol";
printf("Finished foo_init");
return 0;
}
/*
import pychbase
pychbase.Foo('a','b',5)
*/
// Make data available to Python
static PyMemberDef Foo_members[] = {
//{"first", T_OBJECT_EX, offsetof(Foo, first), 0, "first name"},
//{"last", T_OBJECT_EX, offsetof(Foo, last), 0, "last name"},
{"number", T_INT, offsetof(Foo, number), 0, "number"},
{NULL}
};
static PyObject *Foo_get_first(Foo *self, void *closure) {
Py_INCREF(self->first);
return self->first;
}
static int Foo_set_first(Foo *self, PyObject *value, void *closure) {
printf("IN foo_set_first\n");
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
return -1;
}
if (!PyString_Check(value)) {
PyErr_SetString(PyExc_TypeError, "The first attribute value must be a string");
return -1;
}
Py_DECREF(self->first);
Py_INCREF(value);
self->first = value;
printf("finished foo_set_first\n");
return 0;
}
static PyObject *Foo_get_last(Foo *self, void *closure) {
Py_INCREF(self->last);
return self->last;
}
static int Foo_set_last(Foo *self, PyObject *value, void *closure) {
printf("IN foo_set_last\n");
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
return -1;
}
if (!PyString_Check(value)) {
PyErr_SetString(PyExc_TypeError, "The last attribute must be a string");
return -1;
}
Py_DECREF(self->last);
Py_INCREF(value);
self->last = value;
printf("finished foo_set_last\n");
return 0;
}
static PyGetSetDef Foo_getseters[] = {
{"first", (getter) Foo_get_first, (setter) Foo_set_first, "first name", NULL},
{"last", (getter) Foo_get_last, (setter) Foo_set_last, "last name", NULL},
{NULL}
};
static PyObject *Foo_square(Foo *self) {
return Py_BuildValue("i", self->number * self->number);
}
static PyObject * Foo_name(Foo *self) {
static PyObject *format = NULL;
PyObject *args, *result;
// We have to check for NULL, because they can be deleted, in which case they are set to NULL.
// It would be better to prevent deletion of these attributes and to restrict the attribute values to strings.
if (format == NULL) {
format = PyString_FromString("%s %s");
if (format == NULL) {
return NULL;
}
}
/*
// These checks can be removed after adding the getter/setter that guarentees it cannot be null
if (self->first == NULL) {
PyErr_SetString(PyExc_AttributeError, "first");
return NULL;
}
if (self->last == NULL) {
PyErr_SetString(PyExc_AttributeError, "last");
return NULL;
}
*/
args = Py_BuildValue("OO", self->first, self->last);
if (args == NULL) {
return NULL;
}
result = PyString_Format(format, args);
// What is the difference between XDECREF and DECREF?
// Use XDECREF if something can be null, DECREF if it is guarenteed to not be null
Py_DECREF(args);
return result;
}
// Make methods available
static PyMethodDef Foo_methods[] = {
{"square", (PyCFunction) Foo_square, METH_VARARGS, "squares an int"},
// METH_NOARGS indicates that this method should not be passed any arguments
{"name", (PyCFunction) Foo_name, METH_NOARGS, "Returns the full name"},
{NULL}
};
// Declare the type components
static PyTypeObject FooType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"pychbase.Foo", /* tp_name */
sizeof(Foo), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)Foo_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
"Foo object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
Foo_methods, /* tp_methods */
Foo_members, /* tp_members */
Foo_getseters, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Foo_init, /* tp_init */
0, /* tp_alloc */
Foo_new, /* tp_new */
};
/*
static const char *family1 = "Id";
static const char *col1_1 = "I";
static const char *family2 = "Name";
static const char *col2_1 = "First";
static const char *col2_2 = "Last";
static const char *family3 = "Address";
static const char *col3_1 = "City";
*/
/*
Given a family and a qualifier, return a fully qualified column (familiy + ":" + qualifier)
Returns NULL on failure
Caller must free the return value
*/
static char *hbase_fqcolumn(const hb_cell_t *cell) {
if (!cell) {
return NULL;
}
char *family = (char *) cell->family;
char *qualifier = (char *) cell->qualifier;
int family_len = cell->family_len;
int qualifier_len = cell->qualifier_len;
// +1 for null terminator, +1 for colon
char *fq = (char *) malloc(1 + 1 + family_len + qualifier_len);
if (!fq) {
return NULL;
}
strncpy(fq, family, family_len);
fq[family_len] = ':';
fq[family_len + 1] = '\0';
// strcat will replace the last null terminator before writing, then add a null terminator
strncat(fq, qualifier, qualifier_len);
return fq;
}
/*
import pychbase
connection = pychbase._connection("hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222")
connection.open()
table = pychbase._table(connection, '/app/SubscriptionBillingPlatform/testInteractive')
table.put("snoop", {"f:foo": "bar"})
*/
// TODO change this name of this function
/*
* Given a fully qualified column, e.g. "f:foo", split it into its family and qualifier "f" and "foo" respectively
* Caller should allocate memory for family and qualifier, and then free them later
* Returns 0 on success
* Returns 12 if given fq was null
* Returns -10 if no colon ':' was found in the string
*/
static int split(char *fq, char *family, char *qualifier) {
OOM_OBJ_RETURN_ERRNO(fq);
int i = 0;
// Initialize family to length, + 1 for null pointer, - 1 for the colon
bool found_colon = false;
// this should either be strlen(fq) - 1, or strlen(fq) without the fq[i] != '\0' right?
for (i = 0; i < strlen(fq) && fq[i] != '\0'; i++) {
if (fq[i] != ':') {
family[i] = fq[i];
} else {
found_colon = true;
break;
}
}
if (!found_colon) {
return -10;
}
family[i] = '\0';
// This works with strlen(..) + 1 or without + 1 ... why ??
int qualifier_index = 0;
for (i=i + 1; i < strlen(fq) && fq[i] != '\0'; i++) {
qualifier[qualifier_index] = fq[i];
qualifier_index += 1;
}
qualifier[qualifier_index] = '\0';
return 0;
}
/*
* Similar to split, but used for `columns` arg to Table_row or Table_delete.
* If fq doesn't have a colon, or has a colon but no more values, qualifier will be freed and set to NULL
* family needs to be strlen() + 1 for null terminator ! Note how this is different than split
*/
// TODO turn this into a private function and add to unit tests
static int split_columns(char *fq, char *family, char *qualifier) {
OOM_OBJ_RETURN_ERRNO(fq);
int i = 0;
// Initialize family to length, + 1 for null pointer, - 1 for the colon
bool found_colon = false;
// this should either be strlen(fq) - 1, or strlen(fq) without the fq[i] != '\0' right?
for (i = 0; i < strlen(fq) && fq[i] != '\0'; i++) {
if (fq[i] != ':') {
family[i] = fq[i];
} else {
found_colon = true;
break;
}
}
family[i] = '\0';
if (!found_colon) {
qualifier[0] = '\0';
return 0;
}
// This works with strlen(..) + 1 or without + 1 ... why ??
int qualifier_index = 0;
for (i=i + 1; i < strlen(fq) && fq[i] != '\0'; i++) {
qualifier[qualifier_index] = fq[i];
qualifier_index += 1;
}
qualifier[qualifier_index] = '\0';
return 0;
}
/*
* libhbase uses asyncronous threads. The data that will be sent to HBase must remain in memory until
* the callback has been executed, at which point the data can safely be cleared.
* The RowBuffer class is used to hold the data in memory.
* Make sure to clear it on exactly two conditions:
* Any exit point in the callback, including success and failures
* Any failure exit point in a function that invokes an async libhbase function, before the function is invoked
*/
struct RowBuffer {
// Vectors allow fast insert/delete from the end
std::vector<char *> allocedBufs;
RowBuffer() {
allocedBufs.clear();
}
~RowBuffer() {
while (allocedBufs.size() > 0) {
char *buf = allocedBufs.back();
allocedBufs.pop_back();
delete [] buf;
}
}
char *getBuffer(uint32_t size) {
char *newAlloc = new char[size];
allocedBufs.push_back(newAlloc);
return newAlloc;
}
};
struct BatchCallBackBuffer;
struct CallBackBuffer {
RowBuffer *rowBuf;
int err;
PyObject *ret;
uint64_t count;
pthread_mutex_t mutex;
BatchCallBackBuffer *batch_call_back_buffer;
bool include_timestamp;
bool only_rowkeys; // Used in scan call back to only return rowkeys
bool is_count; // Used in scan to not spool any rowkeys or values - only used for table.count() method
int scan_count;
int scan_limit;
//PyObject *rets;
// TODO I don't require the Table *t anymore right?
CallBackBuffer(RowBuffer *r, BatchCallBackBuffer *bcbb) {
rowBuf = r;
err = 0;
count = 0;
batch_call_back_buffer = bcbb;
mutex = PTHREAD_MUTEX_INITIALIZER;
ret = NULL;
only_rowkeys = false; // Set to true to only retrieve row key
include_timestamp = false;
is_count = false;
scan_count = 0;
scan_limit = NULL;
}
~CallBackBuffer() {
/*
* rowBuf is now being deleting inside the put/delete callbacks
* Note that the rowBuf must absolutely be deleted in all exit scenarios or else it will lead to a
* memory leak because I have removed the deletion from this destructor
*/
}
};
/*
import pychbase
connection = pychbase._connection("hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222")
connection.open()
table = pychbase._table(connection, '/app/SubscriptionBillingPlatform/testInteractive')
table.batch([], 10000)
*/
/*
* BatchCallBackBuffer is used for Table_batch to maintain references to all CallBackBuffers
*/
struct BatchCallBackBuffer {
std::vector<CallBackBuffer *> call_back_buffers;
int number_of_mutations;
int count;
int errors;
pthread_mutex_t mutex;
BatchCallBackBuffer(int i) {
number_of_mutations = i;
call_back_buffers.reserve(i);
count = 0;
errors = 0;
// TODO compiler gives warnings about this check it out
mutex = PTHREAD_MUTEX_INITIALIZER;
}
~BatchCallBackBuffer() {
while (call_back_buffers.size() > 0) {
CallBackBuffer *call_back_buffer = call_back_buffers.back();
call_back_buffers.pop_back();
pthread_mutex_lock(&call_back_buffer->mutex);
delete call_back_buffer;
//pthread_mutex_unlock(&call_back_buffer->mutex);
//free(call_back_buffers);
}
}
};
/*
import pychbase
connection = pychbase._connection("hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222")
connection.is_open()
connection.open()
connection.is_open()
connection.close()
connection.is_open()
*/
typedef struct {
PyObject_HEAD
PyObject *zookeepers;
// Add an is_open boolean
bool is_open;
hb_connection_t conn;
hb_client_t client;
hb_admin_t admin;
} Connection;
static void cl_dsc_cb(int32_t err, hb_client_t client, void *extra) {
CallBackBuffer *call_back_buffer = (CallBackBuffer *) extra;
pthread_mutex_lock(&call_back_buffer->mutex);
call_back_buffer->count = 1;
pthread_mutex_unlock(&call_back_buffer->mutex);
}
void admin_disconnection_callback(int32_t err, hb_admin_t admin, void *extra){
CallBackBuffer *call_back_buffer = (CallBackBuffer *) extra;
pthread_mutex_lock(&call_back_buffer->mutex);
call_back_buffer->count = 1;
pthread_mutex_unlock(&call_back_buffer->mutex);
}
static PyObject *Connection_close(Connection *self) {
if (self->is_open) {
// this used to cause a segfault, I'm not sure why it doesn't now
// Lol i was getting an intermittent segfault, but apparently only after adding the timestamp/wal
// now when I comment this out it apparently doesn't seg fault any more...
CallBackBuffer *call_back_buffer = new CallBackBuffer(NULL, NULL);
OOM_OBJ_RETURN_NULL(call_back_buffer);
hb_admin_destroy(self->admin, admin_disconnection_callback, call_back_buffer); // always returns 0
uint64_t local_count = 0;
while (local_count != 1) {
pthread_mutex_lock(&call_back_buffer->mutex);
local_count = call_back_buffer->count;
pthread_mutex_unlock(&call_back_buffer->mutex);
sleep(0.1);
}
call_back_buffer->count = 0;
hb_client_destroy(self->client, cl_dsc_cb, call_back_buffer);
local_count = 0;
while (local_count != 1) {
pthread_mutex_lock(&call_back_buffer->mutex);
local_count = call_back_buffer->count;
pthread_mutex_unlock(&call_back_buffer->mutex);
sleep(0.1);
}
hb_connection_destroy(self->conn);
self->is_open = false;
}
Py_RETURN_NONE;
}
static void Connection_dealloc(Connection *self) {
Connection_close(self);
Py_XDECREF(self->zookeepers);
self->ob_type->tp_free((PyObject *) self);
}
static int Connection_init(Connection *self, PyObject *args, PyObject *kwargs) {
PyObject *zookeepers, *tmp;
if (!PyArg_ParseTuple(args, "O", &zookeepers)) {
return -1;
}
// I'm not sure why tmp is necessary but it was in the docs
tmp = self->zookeepers;
Py_INCREF(zookeepers);
self->zookeepers = zookeepers;
Py_XDECREF(tmp);
return 0;
}
static PyMemberDef Connection_members[] = {
{"zookeepers", T_OBJECT_EX, offsetof(Connection, zookeepers), 0, "The zookeepers connection string"},
{NULL}
};
/*
import pychbase
connection = pychbase._connection("hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222")
connection.is_open()
connection.open()
connection.is_open()
connection.close()
connection.is_open()
connection.close()
connection = pychbase._connection("abc")
connection.open()
connection.is_open()
connection.close()
connection.zookeepers = "hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222"
connection.open()
connection.is_open()
table = pychbase._table(connection, '/app/SubscriptionBillingPlatform/testInteractive')
*/
static PyObject *Connection_open(Connection *self) {
if (!self->is_open) {
int err = 0;
err = hb_connection_create(PyString_AsString(self->zookeepers), NULL, &self->conn);
if (err != 0) {
PyErr_Format(PyExc_ValueError, "Could not connect using zookeepers '%s': %i", PyString_AsString(self->zookeepers), err);
return NULL;
}
err = hb_client_create(self->conn, &self->client);
if (err != 0) {
PyErr_SetString(HBaseError, "Could not create client from connection");
return NULL;
}// TODO destroy connection
OOM_OBJ_RETURN_NULL(self->client);
err = hb_admin_create(self->conn, &self->admin);
if (err != 0) {
PyErr_SetString(PyExc_ValueError, "Could not create admin from connection");
return NULL;
}// TODO destroy connection and client
OOM_OBJ_RETURN_NULL(self->admin);
self->is_open = true;
}
Py_RETURN_NONE;
}
static PyObject *Connection_is_open(Connection *self) {
if (self->is_open) {
return Py_True;
}
return Py_False;
}
/*
import pychbase
connection = pychbase._connection("hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222")
connection.open()
connection.create_table("/app/SubscriptionBillingPlatform/testpymaprdb21", {'f1': {}})
*/
static PyObject *Connection_delete_table(Connection *self, PyObject *args) {
char *table_name;
char *name_space = NULL;
if (!PyArg_ParseTuple(args, "s|s", &table_name, &name_space)) {
return NULL;
}
int err;
if (!self->is_open) {
Connection_open(self);
}
int table_name_length = strlen(table_name);
CHECK_SET_EXC(table_name_length <= 1000, PyExc_ValueError, "Table name is too long\n");
err = hb_admin_table_exists(self->admin, NULL, table_name);
CHECK_FORMAT_EXC(err == 0, PyExc_ValueError, "Table '%s' does not exist: %i\n", table_name, err);
err = hb_admin_table_delete(self->admin, name_space, table_name);
CHECK_FORMAT_EXC(err == 0, HBaseError, "Failed to delete table '%s': %i\n", table_name, err);
Py_RETURN_NONE;
error:
return NULL;
}
// Used to pass the different functions that can set attributes on a column family
typedef int32_t (*set_column_family_attribute)(hb_columndesc, int32_t);
static PyObject *Connection_create_table(Connection *self, PyObject *args) {
char *table_name;
PyObject *dict;
PyObject *column_family_name;
PyObject *column_family_attributes;
// To loop through dict
Py_ssize_t i = 0;
// To keep track of column families
int counter = 0;
int number_of_families;
if (!PyArg_ParseTuple(args, "sO!", &table_name, &PyDict_Type, &dict)) {
return NULL;
}
if (!self->is_open) {
Connection_open(self);
}
int err;
int table_name_length = strlen(table_name);
// TODO verify the exact length at which this becomes illegal
CHECK_SET_EXC(table_name_length <= 1000, PyExc_ValueError, "Table name is too long\n");
err = hb_admin_table_exists(self->admin, NULL, table_name);
CHECK_FORMAT_EXC(err != 0, PyExc_ValueError, "Table '%s' already exists\n", table_name);
number_of_families = PyDict_Size(dict);
CHECK_SET_EXC(number_of_families >= 1, PyExc_ValueError, "Need at least one column family\n");
hb_columndesc families[number_of_families];
while (PyDict_Next(dict, &i, &column_family_name, &column_family_attributes)) {
PyObject *key, *value;
// Used for looping over column_family_attributes
Py_ssize_t o = 0;
CHECK_SET_EXC(PyObject_TypeCheck(column_family_name, &PyBaseString_Type), PyExc_TypeError, "Key must be string\n");
CHECK_SET_EXC(PyDict_Check(column_family_attributes), PyExc_TypeError, "Attributes must be a dict\n");
char *column_family_name_char = PyString_AsString(column_family_name);
CHECK_MEM_EXC(column_family_name_char); // Is this necessary
err = hb_coldesc_create((byte_t *)column_family_name_char, strlen(column_family_name_char), &families[counter]);
CHECK_FORMAT_EXC(err == 0, PyExc_ValueError, "Failed to create column descriptor '%s'\n", column_family_name_char);
//Py_ssize_t dict_size = PyDict_Size(column_family_attributes);
while (PyDict_Next(column_family_attributes, &o, &key, &value)) {
set_column_family_attribute func;
CHECK_SET_EXC(PyObject_TypeCheck(key, &PyBaseString_Type), PyExc_TypeError, "Key must be string\n");
CHECK_SET_EXC(PyInt_Check(value), PyExc_TypeError, "Value must be int\n");
char *key_char = PyString_AsString(key);
CHECK_MEM_EXC(key_char); // Is this necessary
int value_int = PyInt_AsSsize_t(value);
// TODO these should be enums ?
if (strcmp(key_char, "max_versions") == 0) {
func = &hb_coldesc_set_maxversions;
} else if (strcmp(key_char, "min_versions") == 0) {
func = &hb_coldesc_set_minversions;
} else if (strcmp(key_char, "time_to_live") == 0) {
func = &hb_coldesc_set_ttl;
} else if (strcmp(key_char, "in_memory") == 0) {
func = &hb_coldesc_set_inmemory;
} else {
CHECK_SET_EXC(0, PyExc_ValueError, "Only max_versions, min_version, time_to_live, or in_memory permitted\n");
}
int err = (*func)(families[counter], value_int);
CHECK_FORMAT_EXC(err == 0, PyExc_ValueError, "Failed to add '%s' to column desc: %i\n", key_char, err);
}
counter++;
}
err = hb_admin_table_create(self->admin, NULL, table_name, families, number_of_families);
// TODO If there is an error above, these will never be destoryed...
for (counter = 0; counter < number_of_families; counter++) {
hb_coldesc_destroy(families[counter]);
}
if (err != 0) {
if (err == 36) {
PyErr_SetString(PyExc_ValueError, "Table name is too long\n");
} else {
PyErr_Format(PyExc_ValueError, "Failed to create table '%s': %i\n", table_name, err);
}
// Sometimes if it fails to create, the table still gets created but doesn't work?
// Attempt to delete it
PyObject *table_name_obj = Py_BuildValue("(s)", table_name);
OOM_OBJ_RETURN_NULL(table_name_obj);
// I don't care if this succeeds or not
Connection_delete_table(self, table_name_obj);
// TODO don't I need to decref table_name_obj?
//return NULL;
goto error;
}
Py_RETURN_NONE;
error:
/*
// This is throwing a segmentation fault
for (counter = 0; counter < number_of_families; counter++) {
if (hb_coldesc_destroy(families[counter])) {
hb_coldesc_destroy(families[counter]);
}
}
*/
return NULL;
}
/*
import pychbase
connection = pychbase._connection("hdnprd-c01-r03-01:7222,hdnprd-c01-r04-01:7222,hdnprd-c01-r05-01:7222")
connection.open()
for i in range(1,20):
try:
connection.delete_table("/app/SubscriptionBillingPlatform/testpymaprdb{}".format(i))
except ValueError:
pass
*/
static PyObject *Connection_is_table_enabled(Connection *self, PyObject *args) {
char *name_space = NULL;
char *table_name = NULL;
if (!PyArg_ParseTuple(args, "s|s", &table_name, &name_space)) {
return NULL;
}
if (!self->is_open) {
Connection_open(self);
}
int err = hb_admin_table_enabled(self->admin, name_space, table_name);
if (err == 0) {
return Py_True;
} else if (err == HBASE_TABLE_DISABLED) {
return Py_False;
} else {
// TODO check for bad table name and and too long table name and etc
PyErr_Format(PyExc_ValueError, "Unknown error while checking if table '%s' exists: %i", table_name, err);
return NULL;
}
}
static PyObject *Connection_enable_table(Connection *self, PyObject *args) {
char *name_space = NULL;
char *table_name = NULL;
if (!PyArg_ParseTuple(args, "s|s", &table_name, &name_space)) {
return NULL;
}
if (!self->is_open) {
Connection_open(self);
}
int err = hb_admin_table_enable(self->admin, name_space, table_name);
if (err == 0) {
Py_RETURN_NONE;
} else {
// TODO check for bad table name and and too long table name and etc
PyErr_Format(PyExc_ValueError, "Unknown error while enabling table '%s': %i", table_name, err);
return NULL;
}
}
static PyObject *Connection_disable_table(Connection *self, PyObject *args) {
char *name_space = NULL;
char *table_name = NULL;