-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcradox.pyx.in
3895 lines (3223 loc) · 129 KB
/
cradox.pyx.in
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
# cython: embedsignature=True
"""
This module is a thin wrapper around librados.
Error codes from librados are turned into exceptions that subclass
:class:`Error`. Almost all methods may raise :class:`Error(the base class of all rados exceptions), :class:`PermissionError`
(the base class of all rados exceptions), :class:`PermissionError`
and :class:`IOError`, in addition to those documented for the
method.
"""
# Copyright 2011 Josh Durgin
# Copyright 2011, Hannu Valtonen <[email protected]>
# Copyright 2015 Hector Martin <[email protected]>
# Copyright 2016 Mehdi Abaakouk <[email protected]>
from cpython cimport PyObject, ref
from cpython.pycapsule cimport *
from libc cimport errno
from libc.stdint cimport *
from libc.stdlib cimport malloc, realloc, free
import sys
import threading
import time
from collections import Callable
from datetime import datetime
from functools import partial, wraps
from itertools import chain
# Are we running Python 2.x
if sys.version_info[0] < 3:
str_type = basestring
else:
str_type = str
cdef extern from "Python.h":
# These are in cpython/string.pxd, but use "object" types instead of
# PyObject*, which invokes assumptions in cpython that we need to
# legitimately break to implement zero-copy string buffers in Ioctx.read().
# This is valid use of the Python API and documented as a special case.
PyObject *PyBytes_FromStringAndSize(char *v, Py_ssize_t len) except NULL
char* PyBytes_AsString(PyObject *string) except NULL
int _PyBytes_Resize(PyObject **string, Py_ssize_t newsize) except -1
void PyEval_InitThreads()
cdef extern from "time.h":
ctypedef long int time_t
ctypedef long int suseconds_t
cdef extern from "sys/time.h":
cdef struct timeval:
time_t tv_sec
suseconds_t tv_usec
cdef extern from "rados/rados_types.h" nogil:
cdef char* _LIBRADOS_ALL_NSPACES "LIBRADOS_ALL_NSPACES"
cdef extern from "rados/librados.h" nogil:
enum:
_LIBRADOS_OP_FLAG_EXCL "LIBRADOS_OP_FLAG_EXCL"
_LIBRADOS_OP_FLAG_FAILOK "LIBRADOS_OP_FLAG_FAILOK"
_LIBRADOS_OP_FLAG_FADVISE_RANDOM "LIBRADOS_OP_FLAG_FADVISE_RANDOM"
_LIBRADOS_OP_FLAG_FADVISE_SEQUENTIAL "LIBRADOS_OP_FLAG_FADVISE_SEQUENTIAL"
_LIBRADOS_OP_FLAG_FADVISE_WILLNEED "LIBRADOS_OP_FLAG_FADVISE_WILLNEED"
_LIBRADOS_OP_FLAG_FADVISE_DONTNEED "LIBRADOS_OP_FLAG_FADVISE_DONTNEED"
_LIBRADOS_OP_FLAG_FADVISE_NOCACHE "LIBRADOS_OP_FLAG_FADVISE_NOCACHE"
enum:
_LIBRADOS_OPERATION_NOFLAG "LIBRADOS_OPERATION_NOFLAG"
_LIBRADOS_OPERATION_BALANCE_READS "LIBRADOS_OPERATION_BALANCE_READS"
_LIBRADOS_OPERATION_LOCALIZE_READS "LIBRADOS_OPERATION_LOCALIZE_READS"
_LIBRADOS_OPERATION_ORDER_READS_WRITES "LIBRADOS_OPERATION_ORDER_READS_WRITES"
_LIBRADOS_OPERATION_IGNORE_CACHE "LIBRADOS_OPERATION_IGNORE_CACHE"
_LIBRADOS_OPERATION_SKIPRWLOCKS "LIBRADOS_OPERATION_SKIPRWLOCKS"
_LIBRADOS_OPERATION_IGNORE_OVERLAY "LIBRADOS_OPERATION_IGNORE_OVERLAY"
_LIBRADOS_CREATE_EXCLUSIVE "LIBRADOS_CREATE_EXCLUSIVE"
_LIBRADOS_CREATE_IDEMPOTENT "LIBRADOS_CREATE_IDEMPOTENT"
cdef uint64_t _LIBRADOS_SNAP_HEAD "LIBRADOS_SNAP_HEAD"
ctypedef void* rados_t
ctypedef void* rados_config_t
ctypedef void* rados_ioctx_t
ctypedef void* rados_xattrs_iter_t
ctypedef void* rados_omap_iter_t
ctypedef void* rados_list_ctx_t
ctypedef uint64_t rados_snap_t
ctypedef void *rados_write_op_t
ctypedef void *rados_read_op_t
ctypedef void *rados_completion_t
ctypedef void (*rados_callback_t)(rados_completion_t cb, void *arg)
ctypedef void (*rados_log_callback_t)(void *arg, const char *line, const char *who,
uint64_t sec, uint64_t nsec, uint64_t seq, const char *level, const char *msg)
{% if version >= "luminous" %}
ctypedef void (*rados_log_callback2_t)(void *arg, const char *line, const char *channel, const char *who, const char *name,
uint64_t sec, uint64_t nsec, uint64_t seq, const char *level, const char *msg)
{% endif %}
cdef struct rados_cluster_stat_t:
uint64_t kb
uint64_t kb_used
uint64_t kb_avail
uint64_t num_objects
cdef struct rados_pool_stat_t:
uint64_t num_bytes
uint64_t num_kb
uint64_t num_objects
uint64_t num_object_clones
uint64_t num_object_copies
uint64_t num_objects_missing_on_primary
uint64_t num_objects_unfound
uint64_t num_objects_degraded
uint64_t num_rd
uint64_t num_rd_kb
uint64_t num_wr
uint64_t num_wr_kb
void rados_buffer_free(char *buf)
void rados_version(int *major, int *minor, int *extra)
int rados_create2(rados_t *pcluster, const char *const clustername,
const char * const name, uint64_t flags)
int rados_create_with_context(rados_t *cluster, rados_config_t cct)
int rados_connect(rados_t cluster)
void rados_shutdown(rados_t cluster)
int rados_conf_read_file(rados_t cluster, const char *path)
int rados_conf_parse_argv_remainder(rados_t cluster, int argc, const char **argv, const char **remargv)
int rados_conf_parse_env(rados_t cluster, const char *var)
int rados_conf_set(rados_t cluster, char *option, const char *value)
int rados_conf_get(rados_t cluster, char *option, char *buf, size_t len)
int rados_ioctx_pool_stat(rados_ioctx_t io, rados_pool_stat_t *stats)
int64_t rados_pool_lookup(rados_t cluster, const char *pool_name)
int rados_pool_reverse_lookup(rados_t cluster, int64_t id, char *buf, size_t maxlen)
int rados_pool_create(rados_t cluster, const char *pool_name)
int rados_pool_create_with_auid(rados_t cluster, const char *pool_name, uint64_t auid)
int rados_pool_create_with_crush_rule(rados_t cluster, const char *pool_name, uint8_t crush_rule_num)
int rados_pool_create_with_all(rados_t cluster, const char *pool_name, uint64_t auid, uint8_t crush_rule_num)
int rados_pool_get_base_tier(rados_t cluster, int64_t pool, int64_t *base_tier)
int rados_pool_list(rados_t cluster, char *buf, size_t len)
int rados_pool_delete(rados_t cluster, const char *pool_name)
{% if version >= "jewel" %}
int rados_inconsistent_pg_list(rados_t cluster, int64_t pool, char *buf, size_t len)
{% endif %}
int rados_cluster_stat(rados_t cluster, rados_cluster_stat_t *result)
int rados_cluster_fsid(rados_t cluster, char *buf, size_t len)
int rados_blacklist_add(rados_t cluster, char *client_address, uint32_t expire_seconds)
{% if version >= "luminous" %}
int rados_application_enable(rados_ioctx_t io, const char *app_name,
int force)
int rados_application_list(rados_ioctx_t io, char *values,
size_t *values_len)
int rados_application_metadata_get(rados_ioctx_t io, const char *app_name,
const char *key, char *value,
size_t *value_len)
int rados_application_metadata_set(rados_ioctx_t io, const char *app_name,
const char *key, const char *value)
int rados_application_metadata_remove(rados_ioctx_t io,
const char *app_name, const char *key)
int rados_application_metadata_list(rados_ioctx_t io,
const char *app_name, char *keys,
size_t *key_len, char *values,
size_t *value_len)
{% endif %}
int rados_ping_monitor(rados_t cluster, const char *mon_id, char **outstr, size_t *outstrlen)
int rados_mon_command(rados_t cluster, const char **cmd, size_t cmdlen,
const char *inbuf, size_t inbuflen,
char **outbuf, size_t *outbuflen,
char **outs, size_t *outslen)
{% if version >= "kraken" %}
int rados_mgr_command(rados_t cluster, const char **cmd, size_t cmdlen,
const char *inbuf, size_t inbuflen,
char **outbuf, size_t *outbuflen,
char **outs, size_t *outslen)
{% endif %}
int rados_mon_command_target(rados_t cluster, const char *name, const char **cmd, size_t cmdlen,
const char *inbuf, size_t inbuflen,
char **outbuf, size_t *outbuflen,
char **outs, size_t *outslen)
int rados_osd_command(rados_t cluster, int osdid, const char **cmd, size_t cmdlen,
const char *inbuf, size_t inbuflen,
char **outbuf, size_t *outbuflen,
char **outs, size_t *outslen)
int rados_pg_command(rados_t cluster, const char *pgstr, const char **cmd, size_t cmdlen,
const char *inbuf, size_t inbuflen,
char **outbuf, size_t *outbuflen,
char **outs, size_t *outslen)
int rados_monitor_log(rados_t cluster, const char *level, rados_log_callback_t cb, void *arg)
{% if version >= "luminous" %}
int rados_monitor_log2(rados_t cluster, const char *level, rados_log_callback2_t cb, void *arg)
{% endif %}
int rados_wait_for_latest_osdmap(rados_t cluster)
int rados_ioctx_create(rados_t cluster, const char *pool_name, rados_ioctx_t *ioctx)
void rados_ioctx_destroy(rados_ioctx_t io)
int rados_ioctx_pool_set_auid(rados_ioctx_t io, uint64_t auid)
void rados_ioctx_locator_set_key(rados_ioctx_t io, const char *key)
void rados_ioctx_set_namespace(rados_ioctx_t io, const char * nspace)
uint64_t rados_get_last_version(rados_ioctx_t io)
int rados_stat(rados_ioctx_t io, const char *o, uint64_t *psize, time_t *pmtime)
int rados_write(rados_ioctx_t io, const char *oid, const char *buf, size_t len, uint64_t off)
int rados_write_full(rados_ioctx_t io, const char *oid, const char *buf, size_t len)
int rados_append(rados_ioctx_t io, const char *oid, const char *buf, size_t len)
int rados_read(rados_ioctx_t io, const char *oid, char *buf, size_t len, uint64_t off)
int rados_remove(rados_ioctx_t io, const char *oid)
int rados_trunc(rados_ioctx_t io, const char *oid, uint64_t size)
int rados_getxattr(rados_ioctx_t io, const char *o, const char *name, char *buf, size_t len)
int rados_setxattr(rados_ioctx_t io, const char *o, const char *name, const char *buf, size_t len)
int rados_rmxattr(rados_ioctx_t io, const char *o, const char *name)
int rados_getxattrs(rados_ioctx_t io, const char *oid, rados_xattrs_iter_t *iter)
int rados_getxattrs_next(rados_xattrs_iter_t iter, const char **name, const char **val, size_t *len)
void rados_getxattrs_end(rados_xattrs_iter_t iter)
int rados_nobjects_list_open(rados_ioctx_t io, rados_list_ctx_t *ctx)
int rados_nobjects_list_next(rados_list_ctx_t ctx, const char **entry, const char **key, const char **nspace)
void rados_nobjects_list_close(rados_list_ctx_t ctx)
int rados_ioctx_snap_rollback(rados_ioctx_t io, const char * oid, const char * snapname)
int rados_ioctx_snap_create(rados_ioctx_t io, const char * snapname)
int rados_ioctx_snap_remove(rados_ioctx_t io, const char * snapname)
int rados_ioctx_snap_lookup(rados_ioctx_t io, const char * name, rados_snap_t * id)
int rados_ioctx_snap_get_name(rados_ioctx_t io, rados_snap_t id, char * name, int maxlen)
void rados_ioctx_snap_set_read(rados_ioctx_t io, rados_snap_t snap)
int rados_ioctx_snap_list(rados_ioctx_t io, rados_snap_t * snaps, int maxlen)
int rados_ioctx_snap_get_stamp(rados_ioctx_t io, rados_snap_t id, time_t * t)
int rados_lock_exclusive(rados_ioctx_t io, const char * oid, const char * name,
const char * cookie, const char * desc,
timeval * duration, uint8_t flags)
int rados_lock_shared(rados_ioctx_t io, const char * o, const char * name,
const char * cookie, const char * tag, const char * desc,
timeval * duration, uint8_t flags)
int rados_unlock(rados_ioctx_t io, const char * o, const char * name, const char * cookie)
rados_write_op_t rados_create_write_op()
void rados_release_write_op(rados_write_op_t write_op)
rados_read_op_t rados_create_read_op()
void rados_release_read_op(rados_read_op_t read_op)
int rados_aio_create_completion(void * cb_arg, rados_callback_t cb_complete, rados_callback_t cb_safe, rados_completion_t * pc)
void rados_aio_release(rados_completion_t c)
int rados_aio_stat(rados_ioctx_t io, const char *oid, rados_completion_t completion, uint64_t *psize, time_t *pmtime)
int rados_aio_write(rados_ioctx_t io, const char * oid, rados_completion_t completion, const char * buf, size_t len, uint64_t off)
int rados_aio_append(rados_ioctx_t io, const char * oid, rados_completion_t completion, const char * buf, size_t len)
int rados_aio_write_full(rados_ioctx_t io, const char * oid, rados_completion_t completion, const char * buf, size_t len)
int rados_aio_remove(rados_ioctx_t io, const char * oid, rados_completion_t completion)
int rados_aio_read(rados_ioctx_t io, const char * oid, rados_completion_t completion, char * buf, size_t len, uint64_t off)
int rados_aio_flush(rados_ioctx_t io)
int rados_aio_get_return_value(rados_completion_t c)
int rados_aio_wait_for_complete_and_cb(rados_completion_t c)
int rados_aio_wait_for_safe_and_cb(rados_completion_t c)
int rados_aio_wait_for_complete(rados_completion_t c)
int rados_aio_wait_for_safe(rados_completion_t c)
int rados_aio_is_complete(rados_completion_t c)
int rados_aio_is_safe(rados_completion_t c)
int rados_exec(rados_ioctx_t io, const char * oid, const char * cls, const char * method,
const char * in_buf, size_t in_len, char * buf, size_t out_len)
{% if version >= "kraken" %}
int rados_aio_exec(rados_ioctx_t io, const char * oid, rados_completion_t completion, const char * cls, const char * method,
const char * in_buf, size_t in_len, char * buf, size_t out_len)
{% endif %}
int rados_write_op_operate(rados_write_op_t write_op, rados_ioctx_t io, const char * oid, time_t * mtime, int flags)
int rados_aio_write_op_operate(rados_write_op_t write_op, rados_ioctx_t io, rados_completion_t completion, const char *oid, time_t *mtime, int flags)
void rados_write_op_omap_set(rados_write_op_t write_op, const char * const* keys, const char * const* vals, const size_t * lens, size_t num)
void rados_write_op_omap_rm_keys(rados_write_op_t write_op, const char * const* keys, size_t keys_len)
void rados_write_op_omap_clear(rados_write_op_t write_op)
void rados_write_op_set_flags(rados_write_op_t write_op, int flags)
void rados_write_op_create(rados_write_op_t write_op, int exclusive, const char *category)
void rados_write_op_append(rados_write_op_t write_op, const char *buffer, size_t len)
void rados_write_op_write_full(rados_write_op_t write_op, const char *buffer, size_t len)
void rados_write_op_write(rados_write_op_t write_op, const char *buffer, size_t len, uint64_t offset)
void rados_write_op_remove(rados_write_op_t write_op)
void rados_write_op_truncate(rados_write_op_t write_op, uint64_t offset)
void rados_write_op_zero(rados_write_op_t write_op, uint64_t offset, uint64_t len)
{% if version >= "luminous" %}
void rados_read_op_omap_get_vals2(rados_read_op_t read_op, const char * start_after, const char * filter_prefix, uint64_t max_return, rados_omap_iter_t * iter, unsigned char *pmore, int * prval)
void rados_read_op_omap_get_keys2(rados_read_op_t read_op, const char * start_after, uint64_t max_return, rados_omap_iter_t * iter, unsigned char *pmore, int * prval)
{% else %}
void rados_read_op_omap_get_vals(rados_read_op_t read_op, const char * start_after, const char * filter_prefix, uint64_t max_return, rados_omap_iter_t * iter, int * prval)
void rados_read_op_omap_get_keys(rados_read_op_t read_op, const char * start_after, uint64_t max_return, rados_omap_iter_t * iter, int * prval)
{% endif %}
void rados_read_op_omap_get_vals_by_keys(rados_read_op_t read_op, const char * const* keys, size_t keys_len, rados_omap_iter_t * iter, int * prval)
int rados_read_op_operate(rados_read_op_t read_op, rados_ioctx_t io, const char * oid, int flags)
int rados_aio_read_op_operate(rados_read_op_t read_op, rados_ioctx_t io, rados_completion_t completion, const char *oid, int flags)
void rados_read_op_set_flags(rados_read_op_t read_op, int flags)
int rados_omap_get_next(rados_omap_iter_t iter, const char * const* key, const char * const* val, size_t * len)
void rados_omap_get_end(rados_omap_iter_t iter)
LIBRADOS_OP_FLAG_EXCL = _LIBRADOS_OP_FLAG_EXCL
LIBRADOS_OP_FLAG_FAILOK = _LIBRADOS_OP_FLAG_FAILOK
LIBRADOS_OP_FLAG_FADVISE_RANDOM = _LIBRADOS_OP_FLAG_FADVISE_RANDOM
LIBRADOS_OP_FLAG_FADVISE_SEQUENTIAL = _LIBRADOS_OP_FLAG_FADVISE_SEQUENTIAL
LIBRADOS_OP_FLAG_FADVISE_WILLNEED = _LIBRADOS_OP_FLAG_FADVISE_WILLNEED
LIBRADOS_OP_FLAG_FADVISE_DONTNEED = _LIBRADOS_OP_FLAG_FADVISE_DONTNEED
LIBRADOS_OP_FLAG_FADVISE_NOCACHE = _LIBRADOS_OP_FLAG_FADVISE_NOCACHE
LIBRADOS_SNAP_HEAD = _LIBRADOS_SNAP_HEAD
LIBRADOS_OPERATION_NOFLAG = _LIBRADOS_OPERATION_NOFLAG
LIBRADOS_OPERATION_BALANCE_READS = _LIBRADOS_OPERATION_BALANCE_READS
LIBRADOS_OPERATION_LOCALIZE_READS = _LIBRADOS_OPERATION_LOCALIZE_READS
LIBRADOS_OPERATION_ORDER_READS_WRITES = _LIBRADOS_OPERATION_ORDER_READS_WRITES
LIBRADOS_OPERATION_IGNORE_CACHE = _LIBRADOS_OPERATION_IGNORE_CACHE
LIBRADOS_OPERATION_SKIPRWLOCKS = _LIBRADOS_OPERATION_SKIPRWLOCKS
LIBRADOS_OPERATION_IGNORE_OVERLAY = _LIBRADOS_OPERATION_IGNORE_OVERLAY
LIBRADOS_ALL_NSPACES = _LIBRADOS_ALL_NSPACES.decode('utf-8')
LIBRADOS_CREATE_EXCLUSIVE = _LIBRADOS_CREATE_EXCLUSIVE
LIBRADOS_CREATE_IDEMPOTENT = _LIBRADOS_CREATE_IDEMPOTENT
ANONYMOUS_AUID = 0xffffffffffffffff
ADMIN_AUID = 0
class Error(Exception):
""" `Error` class, derived from `Exception` """
pass
class InvalidArgumentError(Error):
pass
class OSError(Error):
""" `OSError` class, derived from `Error` """
def __init__(self, message, errno=None):
super(OSError, self).__init__(message)
self.errno = errno
def __str__(self):
msg = super(OSError, self).__str__()
if self.errno is None:
return msg
return '[errno {0}] {1}'.format(self.errno, msg)
def __reduce__(self):
return (self.__class__, (self.message, self.errno))
class InterruptedOrTimeoutError(OSError):
""" `InterruptedOrTimeoutError` class, derived from `OSError` """
pass
class PermissionError(OSError):
""" `PermissionError` class, derived from `OSError` """
pass
class PermissionDeniedError(OSError):
""" deal with EACCES related. """
pass
class ObjectNotFound(OSError):
""" `ObjectNotFound` class, derived from `OSError` """
pass
class NoData(OSError):
""" `NoData` class, derived from `OSError` """
pass
class ObjectExists(OSError):
""" `ObjectExists` class, derived from `OSError` """
pass
class ObjectBusy(OSError):
""" `ObjectBusy` class, derived from `IOError` """
pass
class IOError(OSError):
""" `ObjectBusy` class, derived from `OSError` """
pass
class NoSpace(OSError):
""" `NoSpace` class, derived from `OSError` """
pass
class RadosStateError(Error):
""" `RadosStateError` class, derived from `Error` """
pass
class IoctxStateError(Error):
""" `IoctxStateError` class, derived from `Error` """
pass
class ObjectStateError(Error):
""" `ObjectStateError` class, derived from `Error` """
pass
class LogicError(Error):
""" `` class, derived from `Error` """
pass
class TimedOut(OSError):
""" `TimedOut` class, derived from `OSError` """
pass
IF UNAME_SYSNAME == "FreeBSD":
cdef errno_to_exception = {
errno.EPERM : PermissionError,
errno.ENOENT : ObjectNotFound,
errno.EIO : IOError,
errno.ENOSPC : NoSpace,
errno.EEXIST : ObjectExists,
errno.EBUSY : ObjectBusy,
errno.ENOATTR : NoData,
errno.EINTR : InterruptedOrTimeoutError,
errno.ETIMEDOUT : TimedOut,
errno.EACCES : PermissionDeniedError,
errno.EINVAL : InvalidArgumentError,
}
ELSE:
cdef errno_to_exception = {
errno.EPERM : PermissionError,
errno.ENOENT : ObjectNotFound,
errno.EIO : IOError,
errno.ENOSPC : NoSpace,
errno.EEXIST : ObjectExists,
errno.EBUSY : ObjectBusy,
errno.ENODATA : NoData,
errno.EINTR : InterruptedOrTimeoutError,
errno.ETIMEDOUT : TimedOut,
errno.EACCES : PermissionDeniedError,
errno.EINVAL : InvalidArgumentError,
}
cdef make_ex(ret, msg):
"""
Translate a librados return code into an exception.
:param ret: the return code
:type ret: int
:param msg: the error message to use
:type msg: str
:returns: a subclass of :class:`Error`
"""
ret = abs(ret)
if ret in errno_to_exception:
return errno_to_exception[ret](msg, errno=ret)
else:
return OSError(msg, errno=ret)
# helper to specify an optional argument, where in addition to `cls`, `None`
# is also acceptable
def opt(cls):
return (cls, None)
# validate argument types of an instance method
# kwargs is an un-ordered dict, so use args instead
def requires(*types):
def is_type_of(v, t):
if t is None:
return v is None
else:
return isinstance(v, t)
def check_type(val, arg_name, arg_type):
if isinstance(arg_type, tuple):
if any(is_type_of(val, t) for t in arg_type):
return
type_names = ' or '.join('None' if t is None else t.__name__
for t in arg_type)
raise TypeError('%s must be %s' % (arg_name, type_names))
else:
if is_type_of(val, arg_type):
return
assert(arg_type is not None)
raise TypeError('%s must be %s' % (arg_name, arg_type.__name__))
def wrapper(f):
# FIXME(sileht): this stop with
# AttributeError: 'method_descriptor' object has no attribute '__module__'
# @wraps(f)
def validate_func(*args, **kwargs):
# ignore the `self` arg
pos_args = zip(args[1:], types)
named_args = ((kwargs[name], (name, spec)) for name, spec in types
if name in kwargs)
for arg_val, (arg_name, arg_type) in chain(pos_args, named_args):
check_type(arg_val, arg_name, arg_type)
return f(*args, **kwargs)
return validate_func
return wrapper
def cstr(val, name, encoding="utf-8", opt=False):
"""
Create a byte string from a Python string
:param basestring val: Python string
:param str name: Name of the string parameter, for exceptions
:param str encoding: Encoding to use
:param bool opt: If True, None is allowed
:rtype: bytes
:raises: :class:`InvalidArgument`
"""
if opt and val is None:
return None
if isinstance(val, bytes):
return val
elif isinstance(val, unicode):
return val.encode(encoding)
else:
raise TypeError('%s must be a string' % name)
def cstr_list(list_str, name, encoding="utf-8"):
return [cstr(s, name) for s in list_str]
def decode_cstr(val, encoding="utf-8"):
"""
Decode a byte string into a Python string.
:param bytes val: byte string
:rtype: unicode or None
"""
if val is None:
return None
return val.decode(encoding)
cdef char* opt_str(s) except? NULL:
if s is None:
return NULL
return s
cdef void* realloc_chk(void* ptr, size_t size) except NULL:
cdef void *ret = realloc(ptr, size)
if ret == NULL:
raise MemoryError("realloc failed")
return ret
cdef size_t * to_csize_t_array(list_int):
cdef size_t *ret = <size_t *>malloc(len(list_int) * sizeof(size_t))
if ret == NULL:
raise MemoryError("malloc failed")
for i in xrange(len(list_int)):
ret[i] = <size_t>list_int[i]
return ret
cdef char ** to_bytes_array(list_bytes):
cdef char **ret = <char **>malloc(len(list_bytes) * sizeof(char *))
if ret == NULL:
raise MemoryError("malloc failed")
for i in xrange(len(list_bytes)):
ret[i] = <char *>list_bytes[i]
return ret
cdef int __monitor_callback(void *arg, const char *line, const char *who,
uint64_t sec, uint64_t nsec, uint64_t seq,
const char *level, const char *msg) with gil:
cdef object cb_info = <object>arg
cb_info[0](cb_info[1], line, who, sec, nsec, seq, level, msg)
return 0
{% if version >= "luminous" %}
cdef int __monitor_callback2(void *arg, const char *line, const char *channel,
const char *who,
const char *name,
uint64_t sec, uint64_t nsec, uint64_t seq,
const char *level, const char *msg) with gil:
cdef object cb_info = <object>arg
cb_info[0](cb_info[1], line, channel, name, who, sec, nsec, seq, level, msg)
return 0
{% endif %}
class Version(object):
""" Version information """
def __init__(self, major, minor, extra):
self.major = major
self.minor = minor
self.extra = extra
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.extra)
cdef class Rados(object):
"""This class wraps librados functions"""
# NOTE(sileht): attributes declared in .pyd
def __init__(self, *args, **kwargs):
PyEval_InitThreads()
self.__setup(*args, **kwargs)
@requires(('rados_id', opt(str_type)), ('name', opt(str_type)), ('clustername', opt(str_type)),
('conffile', opt(str_type)))
def __setup(self, rados_id=None, name=None, clustername=None,
conf_defaults=None, conffile=None, conf=None, flags=0,
context=None):
self.monitor_callback = None
self.monitor_callback2 = None
self.parsed_args = []
self.conf_defaults = conf_defaults
self.conffile = conffile
self.rados_id = rados_id
if rados_id and name:
raise Error("Rados(): can't supply both rados_id and name")
elif rados_id:
name = 'client.' + rados_id
elif name is None:
name = 'client.admin'
if clustername is None:
{% if version >= "jewel" %}
clustername = ''
{% else %}
clustername = 'ceph'
{% endif %}
name = cstr(name, 'name')
clustername = cstr(clustername, 'clustername')
cdef:
char *_name = name
char *_clustername = clustername
int _flags = flags
int ret
if context:
# Unpack void* (aka rados_config_t) from capsule
rados_config = <rados_config_t> PyCapsule_GetPointer(context, NULL)
with nogil:
ret = rados_create_with_context(&self.cluster, rados_config)
else:
with nogil:
ret = rados_create2(&self.cluster, _clustername, _name, _flags)
if ret != 0:
raise Error("rados_initialize failed with error code: %d" % ret)
self.state = "configuring"
# order is important: conf_defaults, then conffile, then conf
if conf_defaults:
for key, value in conf_defaults.items():
self.conf_set(key, value)
if conffile is not None:
# read the default conf file when '' is given
if conffile == '':
conffile = None
self.conf_read_file(conffile)
if conf:
for key, value in conf.items():
self.conf_set(key, value)
def require_state(self, *args):
"""
Checks if the Rados object is in a special state
:raises: RadosStateError
"""
if self.state in args:
return
raise RadosStateError("You cannot perform that operation on a \
Rados object in state %s." % self.state)
def shutdown(self):
"""
Disconnects from the cluster. Call this explicitly when a
Rados.connect()ed object is no longer used.
"""
if self.state != "shutdown":
with nogil:
rados_shutdown(self.cluster)
self.state = "shutdown"
def __enter__(self):
self.connect()
return self
def __exit__(self, type_, value, traceback):
self.shutdown()
return False
def version(self):
"""
Get the version number of the ``librados`` C library.
:returns: a tuple of ``(major, minor, extra)`` components of the
librados version
"""
cdef int major = 0
cdef int minor = 0
cdef int extra = 0
with nogil:
rados_version(&major, &minor, &extra)
return Version(major, minor, extra)
@requires(('path', opt(str_type)))
def conf_read_file(self, path=None):
"""
Configure the cluster handle using a Ceph config file.
:param path: path to the config file
:type path: str
"""
self.require_state("configuring", "connected")
path = cstr(path, 'path', opt=True)
cdef:
char *_path = opt_str(path)
with nogil:
ret = rados_conf_read_file(self.cluster, _path)
if ret != 0:
raise make_ex(ret, "error calling conf_read_file")
def conf_parse_argv(self, args):
"""
Parse known arguments from args, and remove; returned
args contain only those unknown to ceph
"""
self.require_state("configuring", "connected")
if not args:
return
cargs = cstr_list(args, 'args')
cdef:
int _argc = len(args)
char **_argv = to_bytes_array(cargs)
char **_remargv = NULL
try:
_remargv = <char **>malloc(_argc * sizeof(char *))
with nogil:
ret = rados_conf_parse_argv_remainder(self.cluster, _argc,
<const char**>_argv,
<const char**>_remargv)
if ret:
raise make_ex(ret, "error calling conf_parse_argv_remainder")
# _remargv was allocated with fixed argc; collapse return
# list to eliminate any missing args
retargs = [decode_cstr(a) for a in _remargv[:_argc]
if a != NULL]
self.parsed_args = args
return retargs
finally:
free(_argv)
free(_remargv)
def conf_parse_env(self, var='CEPH_ARGS'):
"""
Parse known arguments from an environment variable, normally
CEPH_ARGS.
"""
self.require_state("configuring", "connected")
if not var:
return
var = cstr(var, 'var')
cdef:
char *_var = var
with nogil:
ret = rados_conf_parse_env(self.cluster, _var)
if ret != 0:
raise make_ex(ret, "error calling conf_parse_env")
@requires(('option', str_type))
def conf_get(self, option):
"""
Get the value of a configuration option
:param option: which option to read
:type option: str
:returns: str - value of the option or None
:raises: :class:`TypeError`
"""
self.require_state("configuring", "connected")
option = cstr(option, 'option')
cdef:
char *_option = option
size_t length = 20
char *ret_buf = NULL
try:
while True:
ret_buf = <char *>realloc_chk(ret_buf, length)
with nogil:
ret = rados_conf_get(self.cluster, _option, ret_buf, length)
if ret == 0:
return decode_cstr(ret_buf)
elif ret == -errno.ENAMETOOLONG:
length = length * 2
elif ret == -errno.ENOENT:
return None
else:
raise make_ex(ret, "error calling conf_get")
finally:
free(ret_buf)
@requires(('option', str_type), ('val', str_type))
def conf_set(self, option, val):
"""
Set the value of a configuration option
:param option: which option to set
:type option: str
:param option: value of the option
:type option: str
:raises: :class:`TypeError`, :class:`ObjectNotFound`
"""
self.require_state("configuring", "connected")
option = cstr(option, 'option')
val = cstr(val, 'val')
cdef:
char *_option = option
char *_val = val
with nogil:
ret = rados_conf_set(self.cluster, _option, _val)
if ret != 0:
raise make_ex(ret, "error calling conf_set")
def ping_monitor(self, mon_id):
"""
Ping a monitor to assess liveness
May be used as a simply way to assess liveness, or to obtain
information about the monitor in a simple way even in the
absence of quorum.
:param mon_id: the ID portion of the monitor's name (i.e., mon.<ID>)
:type mon_id: str
:returns: the string reply from the monitor
"""
self.require_state("configuring", "connected")
mon_id = cstr(mon_id, 'mon_id')
cdef:
char *_mon_id = mon_id
size_t outstrlen = 0
char *outstr
with nogil:
ret = rados_ping_monitor(self.cluster, _mon_id, &outstr, &outstrlen)
if ret != 0:
raise make_ex(ret, "error calling ping_monitor")
if outstrlen:
my_outstr = outstr[:outstrlen]
rados_buffer_free(outstr)
return decode_cstr(my_outstr)
def connect(self, timeout=0):
"""
Connect to the cluster. Use shutdown() to release resources.
"""
self.require_state("configuring")
# NOTE(sileht): timeout was supported by old python API,
# but this is not something available in C API, so ignore
# for now and remove it later
with nogil:
ret = rados_connect(self.cluster)
if ret != 0:
raise make_ex(ret, "error connecting to the cluster")
self.state = "connected"
def get_cluster_stats(self):
"""
Read usage info about the cluster
This tells you total space, space used, space available, and number
of objects. These are not updated immediately when data is written,
they are eventually consistent.
:returns: dict - contains the following keys:
- ``kb`` (int) - total space
- ``kb_used`` (int) - space used
- ``kb_avail`` (int) - free space available
- ``num_objects`` (int) - number of objects
"""
cdef:
rados_cluster_stat_t stats
with nogil:
ret = rados_cluster_stat(self.cluster, &stats)
if ret < 0:
raise make_ex(
ret, "Rados.get_cluster_stats(%s): get_stats failed" % self.rados_id)
return {'kb': stats.kb,
'kb_used': stats.kb_used,
'kb_avail': stats.kb_avail,
'num_objects': stats.num_objects}
@requires(('pool_name', str_type))
def pool_exists(self, pool_name):
"""
Checks if a given pool exists.
:param pool_name: name of the pool to check
:type pool_name: str
:raises: :class:`TypeError`, :class:`Error`
:returns: bool - whether the pool exists, false otherwise.
"""
self.require_state("connected")
pool_name = cstr(pool_name, 'pool_name')
cdef:
char *_pool_name = pool_name
with nogil:
ret = rados_pool_lookup(self.cluster, _pool_name)
if ret >= 0:
return True
elif ret == -errno.ENOENT:
return False
else:
raise make_ex(ret, "error looking up pool '%s'" % pool_name)
@requires(('pool_name', str_type))
def pool_lookup(self, pool_name):
"""
Returns a pool's ID based on its name.
:param pool_name: name of the pool to look up
:type pool_name: str
:raises: :class:`TypeError`, :class:`Error`
:returns: int - pool ID, or None if it doesn't exist
"""
self.require_state("connected")
pool_name = cstr(pool_name, 'pool_name')
cdef:
char *_pool_name = pool_name
with nogil:
ret = rados_pool_lookup(self.cluster, _pool_name)
if ret >= 0:
return int(ret)
elif ret == -errno.ENOENT:
return None
else:
raise make_ex(ret, "error looking up pool '%s'" % pool_name)
@requires(('pool_id', int))
def pool_reverse_lookup(self, pool_id):
"""
Returns a pool's name based on its ID.
:param pool_id: ID of the pool to look up
:type pool_id: int
:raises: :class:`TypeError`, :class:`Error`
:returns: string - pool name, or None if it doesn't exist
"""
self.require_state("connected")
cdef:
int64_t _pool_id = pool_id
size_t size = 512